repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sg26565/hott-transmitter-config | HoTT-Voice/src/main/kotlin/de/treichels/hott/voice/ADPCMCodec.kt | 1 | 5164 | package de.treichels.hott.voice
import org.apache.commons.io.IOUtils
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
import java.util.*
/**
* Codec to encode / decode ADPCM (VOX) audio data.
*
* see [http://faculty.salina.k-state.edu/tim/vox/dialogic_adpcm.pdf](http://faculty.salina.k-state.edu/tim/vox/dialogic_adpcm.pdf) for details.
*
* @author [email protected]
*/
class ADPCMCodec {
/** index into step size table */
private var index = 0
/** last PCM value */
private var last = 0
/**
* Decode an ADPCM encoded 4-bit sample to 16-bit signed PCM.
*
* @param adpcm ADPCM encoded sample (4 bit)
* @return The decoded PCM value (12 bit signed)
*/
fun decode(adpcm: Byte): Short {
// convert byte into BitSet
val bits = BitSet.valueOf(byteArrayOf(adpcm))
// current step size
val stepSize = STEP_SIZES[index]
// calculate difference
var diff = stepSize shr 3
// magnitude bit 3
if (bits[2]) diff += stepSize
// magnitude bit 2
if (bits[1]) diff += stepSize shr 1
// magnitude bit 1
if (bits[0]) diff += stepSize shr 2
// sign
if (bits[3]) diff = -diff
// new PCM value
last += diff
// clipping
if (last > MAX_PCM) last = MAX_PCM
if (last < MIN_PCM) last = MIN_PCM
// new step size
index += QUANTIZER[adpcm.toInt() and 7]
// clipping
if (index < MIN_INDEX) index = MIN_INDEX
if (index > MAX_INDEX) index = MAX_INDEX
return last.toShort()
}
/**
* Encode a 16-bit signed PCM value to 4-bit ADPCM.
*
* @param pcm
* The PCM value (12 bit signed)
* @return The ADPCM encoded sample (4 bit)
*/
fun encode(pcm: Short): Byte {
var stepSize = STEP_SIZES[index]
var diff = pcm - last
val bits = BitSet(4)
// sign
if (diff < 0) {
bits[3] = true
diff = -diff
}
// magnitude bit 3
if (diff >= stepSize) {
bits[2] = true
diff -= stepSize
}
// magnitude bit 2
stepSize = stepSize shr 1
if (diff >= stepSize) {
bits[1] = true
diff -= stepSize
}
// magnitude bit 1
stepSize = stepSize shr 1
if (diff >= stepSize) bits[0] = true
val adpcm = if (bits.isEmpty) 0 else bits.toByteArray()[0]
last = decode(adpcm).toInt()
return adpcm
}
companion object {
private val QUANTIZER = intArrayOf(-1, -1, -1, -1, 2, 4, 6, 8)
private val STEP_SIZES = intArrayOf(7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767)
private const val MIN_PCM = -2048 // 12-bit
private const val MAX_PCM = 2047 // 12-bit
private const val MIN_INDEX = 0
private val MAX_INDEX = STEP_SIZES.size - 1
/**
* Decode 4-bit ADPCM encoded data to 16-bit signed PCM (compression ratio 1:4).
*
* @param data
* ADPCM encoded data. Each byte contains two 4-bit samples.
* @return The PCM decoded data.
* @throws IOException
*/
fun decode(data: ByteArray): ByteArray {
return IOUtils.toByteArray(decode(ByteArrayInputStream(data)))
}
/**
* Decode 4-bit ADPCM encoded data to 16-bit signed PCM (compression ratio 1:4).
*
* @param source
* A stream of ADPCM encoded data. Each byte contains two 4-bit samples.
* @return A stream of PCM data.
* @throws IOException
*/
fun decode(source: InputStream): InputStream {
return DecodingInputStream(source)
}
/**
* Encode 16-bit signed PCM data to 4-bit ADPCM encoded data (compression ratio 4:1).
*
* @param data
* The PCM data.
*
* @return The ADPCM encoded data. Each byte contains two 4-bit samples.
* @throws IOException
*/
fun encode(data: ByteArray): ByteArray {
return IOUtils.toByteArray(encode(ByteArrayInputStream(data)))
}
/**
* Encode 16-bit signed PCM data to 4-bit ADPCM encoded data (compression ratio 4:1).
*
* @param source
* A stream of PCM data.
* @return A stream of ADPCM encoded data. Each byte contains two 4-bit samples.
* @throws IOException
*/
@JvmOverloads
fun encode(source: InputStream, volume: Double = 1.0): InputStream {
return EncodingInputStream(source, volume)
}
}
}
| lgpl-3.0 | 1ff0cf73f07ccda8186eb365dd4782e2 | 29.738095 | 507 | 0.560612 | 3.885628 | false | false | false | false |
breadwallet/breadwallet-android | ui/ui-gift/src/main/java/GiftBackup.kt | 1 | 3157 | /**
* BreadWallet
*
* Created by Ahsan Butt <[email protected]> on 12/09/20.
* Copyright (c) 2020 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.uigift
import android.content.SharedPreferences
import androidx.core.content.edit
private const val KEY_GIFT_PREFIX = "gift-pk-"
private const val KEY_GIFT_STATE_PREFIX = "gift-state-"
data class GiftCopy(
val address: String,
val privateKey: String,
val isUsed: Boolean = false
)
interface GiftBackup {
fun putGift(gift: GiftCopy)
fun removeUnusedGift(address: String)
fun markGiftIsUsed(address: String)
fun getAllGifts(): List<GiftCopy>
}
class SharedPrefsGiftBackup(
private val createStore: () -> SharedPreferences?
) : GiftBackup {
private val store: SharedPreferences? by lazy {
createStore()
}
override fun putGift(gift: GiftCopy) {
checkNotNull(store).edit {
putString(gift.address.giftKey(), gift.privateKey)
putBoolean(gift.address.giftStateKey(), gift.isUsed)
}
}
override fun removeUnusedGift(address: String) {
val store = checkNotNull(store)
if (!store.getBoolean(address.giftStateKey(), false)) {
store.edit {
remove(address.giftKey())
remove(address.giftStateKey())
}
}
}
override fun markGiftIsUsed(address: String) {
checkNotNull(store).edit {
putBoolean(address.giftStateKey(), true)
}
}
override fun getAllGifts(): List<GiftCopy> {
val all = checkNotNull(store).all
return all.keys
.filter { it.startsWith(KEY_GIFT_PREFIX) }
.map { key ->
val address = key.substringAfter(KEY_GIFT_PREFIX)
GiftCopy(
address,
all[key] as String,
all[address.giftStateKey()] as Boolean
)
}
}
private fun String.giftKey() = "$KEY_GIFT_PREFIX$this"
private fun String.giftStateKey() = "$KEY_GIFT_STATE_PREFIX$this"
}
| mit | ea290079b5b9b21d3452111dce82cb60 | 32.946237 | 80 | 0.664238 | 4.396936 | false | false | false | false |
koma-im/koma | src/main/kotlin/link/continuum/desktop/database/storeLatest.kt | 1 | 1891 | package link.continuum.desktop.database
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.concurrent.ConcurrentHashMap
/**
* save and and get newest values
* update names and avatar urls in real time
*/
open class LatestFlowMap<K, V>(
private val init: suspend (K)-> Pair<Long, V>,
private val save: suspend (K, V, Long) -> Unit
){
private val scope = CoroutineScope(Dispatchers.Default)
private val flows = ConcurrentHashMap<K, UpdatableValue>()
/**
* set latest value if newer than existing
*/
suspend fun update(key: K, value: V, time: Long) {
getUpdatable(key).update(key, value, time)
}
fun receiveUpdates(key: K): Flow<V?> {
val up = getUpdatable(key)
return up.observable
}
private fun getUpdatable(key: K): UpdatableValue {
return flows.computeIfAbsent(key) { UpdatableValue().also {
scope.launch {
val (t, v) = init(key)
it.update(key, v, t)
}
}}
}
private inner class UpdatableValue() {
private val mutex = Mutex()
private var timestamp = 0L
private val _observable = MutableStateFlow<V?>(null)
val observable: StateFlow<V?> get() = _observable
suspend fun update(key: K, value: V, time: Long) {
mutex.withLock {
if (time < timestamp) return
if (timestamp == time && _observable.value == value) return
timestamp = time
_observable.value = value
save(key, value, time)
}
}
}
} | gpl-3.0 | b797cbb4101c1f8603a8492111b3bd88 | 32.785714 | 75 | 0.627181 | 4.387471 | false | false | false | false |
wuan/bo-android | app/src/main/java/org/blitzortung/android/map/overlay/StrikeShape.kt | 1 | 2657 | /*
Copyright 2015 Andreas Würl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.blitzortung.android.map.overlay
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Point
import org.osmdroid.api.IGeoPoint
import org.osmdroid.views.MapView
import org.osmdroid.views.Projection
class StrikeShape(private val center: IGeoPoint) : LightningShape {
override fun isPointInside(tappedGeoPoint: IGeoPoint, projection: Projection): Boolean {
val shapeCenter = Point()
projection.toPixels(center, shapeCenter)
val tappedPoint = Point()
projection.toPixels(tappedGeoPoint, tappedPoint)
return tappedPoint.x >= shapeCenter.x - size / 2 && tappedPoint.x <= shapeCenter.x + size / 2
&& tappedPoint.y >= shapeCenter.y - size / 2 && tappedPoint.y <= shapeCenter.y + size / 2
}
private var size: Float = 0.toFloat()
private var color: Int = 0
override fun draw(canvas: Canvas, mapView: MapView, paint: Paint) {
mapView.projection.toPixels(center, centerPoint)
//Only draw it when its visible
if (canvas.quickReject(
centerPoint.x - size / 2,
centerPoint.y - size / 2,
centerPoint.x + size / 2,
centerPoint.y + size / 2,
Canvas.EdgeType.BW)) {
return
}
paint.color = color
paint.style = Paint.Style.STROKE
paint.strokeWidth = size / 4
canvas.drawLine(
centerPoint.x - size / 2,
centerPoint.y.toFloat(),
centerPoint.x + size / 2,
centerPoint.y.toFloat(),
paint)
canvas.drawLine(
centerPoint.x.toFloat(),
centerPoint.y - size / 2,
centerPoint.x.toFloat(),
centerPoint.y + size / 2,
paint)
}
fun update(size: Float, color: Int) {
this.size = size
this.color = color
}
companion object {
private val centerPoint = Point()
}
}
| apache-2.0 | 14fd7775f0be6f521836886f3086cc5f | 31 | 105 | 0.611069 | 4.667838 | false | false | false | false |
serorigundam/numeri3 | app/src/main/kotlin/net/ketc/numeri/presentation/view/activity/ui/UserInfoActivityUI.kt | 1 | 12736 | package net.ketc.numeri.presentation.view.activity.ui
import android.content.Context
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.Toolbar
import net.ketc.numeri.presentation.view.activity.UserInfoActivity
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.collapsingToolbarLayout
import org.jetbrains.anko.design.coordinatorLayout
import android.support.design.widget.AppBarLayout.LayoutParams.*
import android.support.design.widget.CollapsingToolbarLayout
import org.jetbrains.anko.*
import android.support.design.widget.CollapsingToolbarLayout.LayoutParams.*
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
import android.support.v4.widget.SwipeRefreshLayout
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewManager
import android.widget.*
import net.ketc.numeri.R
import net.ketc.numeri.util.android.*
import org.jetbrains.anko.custom.ankoView
import org.jetbrains.anko.design.tabLayout
import org.jetbrains.anko.support.v4.swipeRefreshLayout
import org.jetbrains.anko.support.v4.viewPager
class UserInfoActivityUI : IUserInfoActivityUI {
override lateinit var swipeRefresh: SwipeRefreshLayout
private set
override lateinit var appBar: AppBarLayout
private set
override lateinit var toolbar: Toolbar
private set
override lateinit var collapsingToolbar: CollapsingToolbarLayout
private set
override lateinit var headerImage: ImageView
private set
override lateinit var iconRelative: RelativeLayout
private set
override lateinit var iconImage: ImageView
private set
override lateinit var infoRelative: RelativeLayout
private set
override lateinit var userNameText: TextView
private set
override lateinit var screenNameText: TextView
private set
override lateinit var descriptionText: TextView
private set
override lateinit var locationText: TextView
private set
override lateinit var subInfoText: TextView
private set
override lateinit var userProfileTabLayout: TabLayout
private set
override lateinit var pager: ViewPager
private set
override lateinit var followButton: ImageButton
private set
override lateinit var protectedImage: ImageView
private set
override lateinit var relationInfoText: TextView
private set
override lateinit var profileEditButton: Button
private set
override fun createView(ui: AnkoContext<UserInfoActivity>) = with(ui) {
swipeRefreshLayout {
swipeRefresh = this
isEnabled = false
coordinatorLayout {
appBarLayout {
appBar = this
backgroundColor = color(R.color.colorPrimaryDark)
collapsingToolbarLayout {
collapsingToolbar = this
isTitleEnabled = false
setContentScrimColor(color(R.color.transparent))
userProfileContent(this)
userProfileHeader(this)
userProfileIcon(this)
toolbar {
toolbar = this
background = drawable(R.drawable.app_bar_gradation)
navigationIcon = drawable(resourceId(android.R.attr.homeAsUpIndicator))
}.collapsingToolbarlparams(matchParent, dimen(R.dimen.app_bar_standard_height)) {
expandedTitleGravity = Gravity.BOTTOM or Gravity.START
collapseMode = COLLAPSE_MODE_PIN
}
}.lparams(matchParent, matchParent) {
scrollFlags = SCROLL_FLAG_SCROLL or SCROLL_FLAG_EXIT_UNTIL_COLLAPSED
}
}.lparams(matchParent, wrapContent)
coordinatorLayout {
relativeLayout {
tabLayout {
userProfileTabLayout = this
id = R.id.user_profile_tab
tabMode = TabLayout.MODE_SCROLLABLE
}.lparams(matchParent, wrapContent)
viewPager {
pager = this
id = R.id.pager
offscreenPageLimit = 5
}.lparams(matchParent, matchParent) {
below(R.id.user_profile_tab)
}
}.lparams(matchParent, matchParent)
}.lparams(matchParent, matchParent) {
behavior = AppBarLayout.ScrollingViewBehavior()
}
}
}
}
//collapsingToolbarContent
private fun AnkoContext<*>.userProfileContent(manager: ViewManager) = manager.relativeLayout {
infoRelative = this
headerImageView {
id = R.id.dummy_header
visibility = View.INVISIBLE
}.lparams(matchParent, wrapContent)
relativeLayout {
id = R.id.buttons_relative
imageButton {
followButton = this
isClickable = false
background = drawable(R.drawable.ripple_frame)
scaleType = ImageView.ScaleType.CENTER_INSIDE
visibility = View.INVISIBLE
}.lparams(matchParent, matchParent)
button {
profileEditButton = this
visibility = View.GONE
text = string(R.string.edit_profile)
}.lparams(matchParent, matchParent)
}.lparams(dip(72), dip(40)) {
marginTop = dimen(R.dimen.margin_medium)
marginEnd = dimen(R.dimen.margin_medium)
below(R.id.dummy_header)
alignParentEnd()
}
relativeLayout {
textView {
userNameText = this
id = R.id.user_name_text
maxLines = 1
ellipsize = TextUtils.TruncateAt.END
textSizeDimen = R.dimen.text_size_large
textColor = color(resourceId(android.R.attr.textColorPrimary))
}.lparams(wrapContent, wrapContent) {
marginBottom = dimen(R.dimen.margin_text_small)
}
relativeLayout {
imageView {
protectedImage = this
backgroundColor = color(R.color.transparent)
image = drawable(R.drawable.ic_lock_outline_white_24dp)
scaleType = ImageView.ScaleType.CENTER_INSIDE
}.lparams(dip(16), dip(16)) {
centerVertically()
}
}.lparams(wrapContent, wrapContent) {
endOf(R.id.user_name_text)
sameTop(R.id.user_name_text)
sameBottom((R.id.user_name_text))
alignParentEnd()
marginStart = dimen(R.dimen.margin_medium)
}
textView {
screenNameText = this
id = R.id.screen_name_text
maxLines = 1
ellipsize = TextUtils.TruncateAt.END
textSizeDimen = R.dimen.text_size_small
textColor = color(resourceId(android.R.attr.textColorSecondary))
}.lparams(wrapContent, wrapContent) {
bottomOf(R.id.user_name_text)
marginBottom = dimen(R.dimen.margin_text_medium)
}
textView {
relationInfoText = this
maxLines = 1
ellipsize = TextUtils.TruncateAt.END
textSizeDimen = R.dimen.text_size_small
textColor = color(resourceId(android.R.attr.textColorSecondary))
}.lparams(wrapContent, wrapContent) {
endOf(R.id.screen_name_text)
bottomOf(R.id.user_name_text)
marginStart = dimen(R.dimen.margin_text_small)
alignParentEnd()
}
textView {
descriptionText = this
id = R.id.description_text
textSizeDimen = R.dimen.text_size_medium
textColor = color(resourceId(android.R.attr.textColorPrimary))
}.lparams(wrapContent, wrapContent) {
bottomOf(R.id.screen_name_text)
marginBottom = dimen(R.dimen.margin_text_small)
}
textView {
locationText = this
id = R.id.location_text
textSizeDimen = R.dimen.text_size_medium
ellipsize = TextUtils.TruncateAt.END
maxLines = 1
textColor = color(resourceId(android.R.attr.textColorPrimary))
}.lparams(wrapContent, wrapContent) {
bottomOf(R.id.description_text)
marginBottom = dimen(R.dimen.margin_text_small)
}
textView {
subInfoText = this
textSizeDimen = R.dimen.text_size_small
textColor = color(resourceId(android.R.attr.textColorSecondary))
}.lparams(wrapContent, wrapContent) {
bottomOf(R.id.location_text)
}
}.lparams(matchParent, matchParent) {
margin = dimen(R.dimen.margin_medium)
bottomOf(R.id.buttons_relative)
alignParentStart()
}
}.collapsingToolbarlparams(matchParent, matchParent) {
collapseMode = COLLAPSE_MODE_OFF
}
private fun AnkoContext<*>.userProfileHeader(manager: ViewManager) = manager.relativeLayout {
id = R.id.header_relative
headerImageView {
id = R.id.header_image
headerImage = this
scaleType = ImageView.ScaleType.CENTER_CROP
}.lparams(matchParent, wrapContent)
view {
this.background = drawable(R.drawable.header_image_gradation)
}.lparams(matchParent, wrapContent) {
sameBottom(R.id.header_image)
sameTop(R.id.header_image)
}
}.collapsingToolbarlparams(wrapContent, wrapContent) {
collapseMode = COLLAPSE_MODE_PIN
}
private fun AnkoContext<*>.userProfileIcon(manager: ViewManager) = manager.relativeLayout {
id = R.id.icon_frame
headerImageView {
id = R.id.dummy_header2
visibility = View.INVISIBLE
}.lparams(matchParent, wrapContent)
relativeLayout {
iconRelative = this
imageView {
iconImage = this
backgroundColor = color(R.color.image_background)
}.lparams(dip(53), dip(53)) { centerInParent() }
view {
background = drawable(R.drawable.image_frame)
}.lparams(dip(56), dip(56))
}.lparams(wrapContent, wrapContent) {
sameBottom(R.id.dummy_header2)
marginBottom = dimen(R.dimen.margin_large)
}
}.collapsingToolbarlparams(wrapContent, wrapContent) {
collapseMode = COLLAPSE_MODE_OFF
margin = dimen(R.dimen.margin_medium)
marginTop = dimen(R.dimen.app_bar_standard_height)
}
class HeaderImageView(ctx: Context) : ImageView(ctx) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightSize = widthSize / 3 //3:1
setMeasuredDimension(widthSize, heightSize)
}
}
private inline fun ViewManager.headerImageView(theme: Int = 0, init: HeaderImageView.() -> Unit): ImageView {
return ankoView(::HeaderImageView, theme) { init() }
}
}
interface IUserInfoActivityUI : AnkoComponent<UserInfoActivity> {
val swipeRefresh: SwipeRefreshLayout
val appBar: AppBarLayout
val toolbar: Toolbar
val collapsingToolbar: CollapsingToolbarLayout
val headerImage: ImageView
val iconImage: ImageView
val iconRelative: RelativeLayout
val infoRelative: RelativeLayout
val userNameText: TextView
val screenNameText: TextView
val descriptionText: TextView
val locationText: TextView
val subInfoText: TextView
val userProfileTabLayout: TabLayout
val pager: ViewPager
val followButton: ImageButton
val protectedImage: ImageView
val relationInfoText: TextView
val profileEditButton: Button
}
| mit | e22e66f5a60449fcaf78024ce21c75e1 | 36.904762 | 113 | 0.59799 | 5.389759 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/play/java/chat/rocket/android/dynamiclinks/DynamicLinksForFirebase.kt | 2 | 2464 | package chat.rocket.android.dynamiclinks
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.net.toUri
import chat.rocket.android.R
import com.google.firebase.dynamiclinks.DynamicLink
import com.google.firebase.dynamiclinks.FirebaseDynamicLinks
import com.google.firebase.dynamiclinks.ShortDynamicLink
import timber.log.Timber
import javax.inject.Inject
class DynamicLinksForFirebase @Inject constructor(private var context: Context) : DynamicLinks {
private var deepLink: Uri? = null
private var newDeepLink: String? = null
override fun getDynamicLink(intent: Intent, deepLinkCallback: (Uri?) -> Unit?) {
FirebaseDynamicLinks.getInstance()
.getDynamicLink(intent)
.addOnSuccessListener { pendingDynamicLinkData ->
if (pendingDynamicLinkData != null) {
deepLink = pendingDynamicLinkData.link
}
deepLinkCallback(deepLink)
}
.addOnFailureListener { Timber.e("getDynamicLink:onFailure : $it") }
}
override fun createDynamicLink(
username: String,
server: String,
deepLinkCallback: (String?) -> Unit?
) {
FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink("$server/direct/$username".toUri())
.setDomainUriPrefix("https://" + context.getString(R.string.dynamic_link_host_url))
.setAndroidParameters(
DynamicLink.AndroidParameters.Builder(context.packageName).build()
)
.setSocialMetaTagParameters(
DynamicLink.SocialMetaTagParameters.Builder()
.setTitle(username)
.setDescription(
context.getString(
R.string.msg_dynamic_link_description,
username,
server
)
)
.build()
)
.buildShortDynamicLink(ShortDynamicLink.Suffix.SHORT)
.addOnSuccessListener { result ->
Timber.i("DynamicLink created: $newDeepLink")
newDeepLink = result.shortLink.toString()
deepLinkCallback(newDeepLink)
}.addOnFailureListener {
Timber.e("Error creating dynamicLink.")
deepLinkCallback(null)
}
}
}
| mit | 5dbfcd44ffd01cb4effd9812b77f6ee4 | 38.111111 | 96 | 0.604708 | 5.333333 | false | false | false | false |
cloudbearings/contentful-management.java | src/test/kotlin/com/contentful/java/cma/lib/TestCallback.kt | 1 | 1329 | /*
* Copyright (C) 2014 Contentful GmbH
*
* 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.contentful.java.cma.lib
import com.contentful.java.cma.CMACallback
import retrofit.RetrofitError
import java.util.concurrent.CountDownLatch
class TestCallback<T>(val allowEmpty: Boolean = false) : CMACallback<T>() {
val cdl: CountDownLatch
var value: T = null
var error: RetrofitError? = null
init {
cdl = CountDownLatch(1)
}
override fun onSuccess(result: T) {
value = result
cdl.countDown()
}
override fun onFailure(retrofitError: RetrofitError?) {
super<CMACallback>.onFailure(retrofitError)
error = retrofitError
cdl.countDown()
}
throws(InterruptedException::class)
public fun await() {
cdl.await()
}
} | apache-2.0 | 9bca215c5c295980d131ba73ebf477f5 | 27.297872 | 75 | 0.698269 | 4.273312 | false | false | false | false |
evant/silent-support | silent-support-gradle-plugin/src/main/kotlin/me/tatarka/silentsupport/gradle/SilentSupportPlugin.kt | 1 | 1481 | package me.tatarka.silentsupport.gradle
import com.android.build.gradle.AppExtension
import com.android.build.gradle.AppPlugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
class SilentSupportPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.plugins.withType(AppPlugin::class.java) { plugin ->
val android = project.extensions.getByType(AppExtension::class.java)
val transform = SilentSupportTransform(project)
val tasks = HashSet<Task>()
android.registerTransform(transform, tasks)
android.applicationVariants.all { variant ->
transform.putVariant(variant)
val task = transform.getOrCreateSupportMetadataTask(variant)
if (task != null) {
tasks.add(task)
}
}
project.dependencies.add(
"compile",
if (isReleased) "me.tatarka.silentsupport:silent-support-lib:$version"
else project.project(":silent-support-lib")
)
android.lintOptions {
it.disable("NewApi")
it.enable("NewApiSupport")
}
}
}
private val isReleased: Boolean
get() = javaClass.getPackage().implementationVersion != null
private val version: String
get() = javaClass.getPackage().implementationVersion
}
| apache-2.0 | 47dc5725f015180abc105290cc65cead | 32.659091 | 90 | 0.607698 | 4.953177 | false | false | false | false |
Tourbillon/Android-DebuggerView | debugger/src/main/java/com/anbillon/debuggerview/ConfigAdapter.kt | 1 | 1840 | package com.anbillon.debuggerview
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
/**
* @author Cosouly ([email protected])
*/
internal abstract class ConfigAdapter : BaseAdapter() {
abstract override fun getItem(position: Int): String?
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, view: View?, container: ViewGroup): View {
val ret = view ?: LayoutInflater.from(container.context)
.inflate(android.R.layout.simple_spinner_item, container, false)
bindView(getItem(position), ret)
return ret
}
override fun getDropDownView(position: Int, view: View?, container: ViewGroup): View {
val ret = view ?: LayoutInflater.from(container.context)
.inflate(android.R.layout.simple_spinner_item, container, false)
bindView(getItem(position), ret)
return ret
}
private fun bindView(item: String?, view: View) {
val holder: ViewHolder
if (view.tag is ViewHolder) {
holder = view.tag as ViewHolder
} else {
holder = ViewHolder()
view.tag = holder
holder.textView = view.findViewById(android.R.id.text1) as? TextView
holder.textView?.let {
val padding = view.resources.getDimension(R.dimen.padding).toInt()
it.setPadding(padding, padding, padding, padding)
it.setTextSize(TypedValue.COMPLEX_UNIT_PX, view.resources.getDimension(R.dimen.font_normal))
it.setTextColor(view.resources.getColor(R.color.text_secondary))
it.gravity = Gravity.CENTER
}
}
holder.textView?.text = item
}
private class ViewHolder {
internal var textView: TextView? = null
}
}
| apache-2.0 | c9aee40bfb801d91dcd4b13eb94aad9b | 30.186441 | 100 | 0.707609 | 4.043956 | false | false | false | false |
VerifAPS/verifaps-lib | geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/print/base.kt | 1 | 5806 | package edu.kit.iti.formal.automation.testtables.print
import edu.kit.iti.formal.automation.testtables.GetetaFacade
import edu.kit.iti.formal.automation.testtables.grammar.TestTableLanguageParser
import edu.kit.iti.formal.automation.testtables.model.*
import edu.kit.iti.formal.util.CodeWriter
import java.util.*
import kotlin.collections.set
/**
* @author Alexander Weigl
* @version 1 (07.08.18)
*/
/**
*
*/
interface TablePrinter {
/**
* Prints header information needed for standalone documents.
* TeX-preamble or html head
*/
fun printPreamble()
/**
* Prints only the table.
*/
fun print()
/**
* Closing statements for the standalone document.
*/
fun printPostamble()
}
/**
* PrintCellContent holds printing information about table cells.
*/
data class PrintCellContent(
/** Content to be displayed */
var content: String = "",
/** position in a down streaming group */
var groupPosition: Int = 0,
/** signals if the cell was empty and only filled by "down streaming" */
var originalEmpty: Boolean = false,
/** signals if the cell is the end of a "down streaming" */
var endGroup: Boolean = false
) {
val beginGroup: Boolean
get() = groupPosition == 0
val singleGroup: Boolean
get() = endGroup && secondInGroup
val secondInGroup: Boolean
get() = groupPosition == 1
val inBetween: Boolean
get() = !beginGroup && !endGroup
}
/**
* A serializer for table cells.
*/
typealias CellPrinter = (TestTableLanguageParser.CellContext) -> String
/**
* This class helps printer with serialization of the table cell contents.
*/
class PrinterHelper(gtt: GeneralizedTestTable,
val cellPrinter: CellPrinter) {
val states = gtt.region.flat()
val columns = LinkedHashMap<String, List<PrintCellContent>>()
init {
gtt.programVariables.forEach { columns[it.name] = calculateColumn(it) }
}
fun calculateColumn(column: ColumnVariable): List<PrintCellContent> {
var previousContent = GetetaFacade.parseCell("-").cell()!!
val seq = states.map { PrintCellContent() }
var currentGroupDuration = 0
for (i in 0 until seq.size) {
val v = states[i].rawFields[column]
val c = seq[i]
if (v != null) {
previousContent = v
c.content = cellPrinter(v)
c.groupPosition = 0
currentGroupDuration = 0
if (i != 0) {
seq[i - 1].endGroup = true
}
} else {
c.originalEmpty = true
c.content = cellPrinter(previousContent)
c.groupPosition = ++currentGroupDuration
}
}
return seq
}
}
/**
* [Counter] offers a multiple counters identified by a string
*/
class Counter {
private val counter = LinkedHashMap<String, Int>()
fun peek(s: String): Int =
counter.computeIfAbsent(s) { _ -> 0 }
fun getAndIncrement(s: String): Int {
val peek = peek(s)
counter[s] = peek + 1
return peek
}
}
/**
* Base class for TablePrinter.
*
* This class provides visitor functions that get called during table visialization.
*/
abstract class AbstractTablePrinter(protected val gtt: GeneralizedTestTable,
protected val stream: CodeWriter) : TablePrinter {
protected lateinit var helper: PrinterHelper
protected var currentRow = 0
val input = gtt.programVariables.filter { it.isAssumption }
val output = gtt.programVariables.filter { it.isAssertion }
val durations = Stack<Pair<Duration, Int>>()
val depth = gtt.region.depth()
fun init() {
helper = PrinterHelper(gtt, this::cellFormatter)
}
override fun printPreamble() {}
override fun printPostamble() {}
protected open fun contentBegin() {}
protected open fun tableBegin() {}
protected open fun tableEnd() {}
protected open fun contentEnd() {}
protected open fun regionEnd() {}
protected open fun regionBegin() {}
protected open fun rowBegin() {}
protected open fun rowEnd() {}
protected open fun printGroupDuration(dur: Duration, rowSpan: Int) {}
protected open fun printCell(v: ColumnVariable, row: TableRow) {
if(v is ProjectionVariable) printCell(v, row)
if(v is ProgramVariable) printCell(v, row)
}
protected open fun printCell(v: ProgramVariable, row: TableRow) {}
protected open fun printCell(v: ProjectionVariable, row: TableRow) {}
protected open fun printRowDuration(duration: Duration) {}
override fun print() {
contentBegin()
tableBegin()
printRegion(gtt.region.children)
tableEnd()
contentEnd()
}
private fun printRegion(region: List<TableNode>) {
region.forEach { o ->
when (o) {
is TableRow -> printStep(o)
is Region -> {
regionBegin()
printRegion(o)
regionEnd()
}
}
}
}
private fun printRegion(b: Region) {
durations.push(b.duration to b.count())
printRegion(b.children)
}
private fun printStep(s: TableRow) {
rowBegin()
input.forEach { v -> printCell(v, s) }
output.forEach { v -> printCell(v, s) }
printRowDuration(s.duration)
while (!durations.empty()) {
val (dur, rowSpan) = durations.pop()
printGroupDuration(dur, rowSpan)
}
rowEnd()
currentRow++
}
abstract fun cellFormatter(c: TestTableLanguageParser.CellContext): String
}
| gpl-3.0 | a1639ab458c52475bd23eccc153da438 | 27.885572 | 86 | 0.607131 | 4.42868 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/business/demo/fragment/DemoFragment.kt | 1 | 4170 | package com.binlly.fastpeak.business.demo.fragment
import android.view.View
import com.binlly.fastpeak.R
import com.binlly.fastpeak.base.glide.progress.OnGlideImageViewListener
import com.binlly.fastpeak.base.mvp.BaseMvpFragment
import com.binlly.fastpeak.base.rx.RxObserver
import com.binlly.fastpeak.business.demo.model.DemoModel
import com.binlly.fastpeak.ext.load
import com.binlly.fastpeak.ext.loadCircle
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.GlideException
import kotlinx.android.synthetic.main.fragment_demo.*
import org.jetbrains.anko.coroutines.experimental.bg
import org.jetbrains.anko.toast
/**
* Created by yy on 2017/8/25.
*/
class DemoFragment: BaseMvpFragment<DemoFragmentPresenter>(), DemoFragmentContract.View {
private var count = 0
override fun getContentViewId(): Int {
return R.layout.fragment_demo
}
private lateinit var images: ArrayList<String>
override fun initView() {
// setPageEmpty()
setPageSucceed()
images = arrayListOf("http://www.sogoupc.com/uploads/allimg/120309/1-1203091U601.jpg",
"http://pic4.bbzhi.com/fengjingbizhi/gaoqingkuanpingfengjingbizhixiazai/gaoqingkuanpingfengjingbizhixiazai_404987_10.jpg",
"http://www.sogoupc.com/uploads/allimg/120309/1-1203091U525.jpg",
"http://www.1tong.com/uploads/wallpaper/landscapes/404-2-1440x900.jpg",
"http://pic1.win4000.com/wallpaper/b/51fb21b44fcc6.jpg")
P.requestImageList(object: RxObserver<DemoFragmentModel>() {
override fun onNext(result: DemoFragmentModel) {
super.onNext(result)
images = result.image_list
}
})
image_1.loadCircle(R.color.colorPrimary)
image_1.setOnClickListener {
Glide.get(context).clearMemory()
bg { Glide.get(context).clearDiskCache() }
context.toast("清空图片缓存")
}
image_2.load(images[0])
image_2.setOnClickListener {
image_2.load(images[++count % images.size],
listener = object: OnGlideImageViewListener {
override fun onProgress(percent: Int, isDone: Boolean,
exception: GlideException?) {
println("下载中:$percent")
progress.visibility = if (isDone) View.GONE else View.VISIBLE
progress.progress = percent
}
})
}
// refresh()
}
private fun refresh() {
setPageLoading()
P.requestDemo(object: RxObserver<DemoModel>() {
override fun onNext(model: DemoModel) {
setPageSucceed()
context.toast(model.toString())
}
override fun onError(e: Throwable) {
super.onError(e)
setPageError()
e.message ?: return
context.toast(e.message.toString())
}
override fun onComplete() {
super.onComplete()
context.toast("onComplete")
}
})
P.requestImageList(object: RxObserver<DemoFragmentModel>() {
override fun onNext(result: DemoFragmentModel) {
super.onNext(result)
images = result.image_list
image_2.load(images[count % images.size],
listener = object: OnGlideImageViewListener {
override fun onProgress(percent: Int, isDone: Boolean,
exception: GlideException?) {
println("下载中:$percent")
progress.visibility = if (isDone) View.GONE else View.VISIBLE
progress.progress = percent
}
})
}
})
}
override fun onReload() {
super.onReload()
context.toast("reload")
refresh()
}
} | mit | e6b2d3619784a5d4681ab9f6e6e1e905 | 35.663717 | 138 | 0.569049 | 4.638298 | false | false | false | false |
pie-flavor/Kludge | src/main/kotlin/flavor/pie/kludge/files.kt | 1 | 10070 | package flavor.pie.kludge
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStream
import java.io.OutputStream
import java.nio.channels.SeekableByteChannel
import java.nio.charset.Charset
import java.nio.file.CopyOption
import java.nio.file.DirectoryStream
import java.nio.file.FileStore
import java.nio.file.FileVisitOption
import java.nio.file.FileVisitor
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.OpenOption
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.FileAttribute
import java.nio.file.attribute.FileAttributeView
import java.nio.file.attribute.FileTime
import java.nio.file.attribute.PosixFilePermission
import java.nio.file.attribute.UserPrincipal
import java.util.function.BiPredicate
import kotlin.streams.asSequence
/**
* @see Files.newInputStream
*/
fun Path.newInputStream(vararg options: OpenOption): InputStream = Files.newInputStream(this, *options)
/**
* @see Files.newOutputStream
*/
fun Path.newOutputStream(vararg options: OpenOption): OutputStream = Files.newOutputStream(this, *options)
/**
* @see Files.newByteChannel
*/
fun Path.newByteChannel(vararg options: OpenOption): SeekableByteChannel = Files.newByteChannel(this, *options)
/**
* @see Files.newByteChannel
*/
fun Path.newByteChannel(options: Set<OpenOption>, vararg attributes: FileAttribute<*>): SeekableByteChannel =
Files.newByteChannel(this, options, *attributes)
/**
* @see Files.newDirectoryStream
*/
fun Path.newDirectoryStream(): DirectoryStream<Path> = Files.newDirectoryStream(this)
/**
* @see Files.newDirectoryStream
*/
fun Path.newDirectoryStream(glob: String): DirectoryStream<Path> = Files.newDirectoryStream(this, glob)
/**
* @see Files.newDirectoryStream
*/
fun Path.newDirectoryStream(filter: DirectoryStream.Filter<in Path>): DirectoryStream<Path> =
Files.newDirectoryStream(this, filter)
/**
* @see Files.createFile
*/
fun Path.createFile(vararg attrs: FileAttribute<*>): Path = Files.createFile(this, *attrs)
/**
* @see Files.createDirectory
*/
fun Path.createDirectory(vararg attrs: FileAttribute<*>): Path = Files.createDirectory(this, *attrs)
/**
* @see Files.createDirectories
*/
fun Path.createDirectories(vararg attrs: FileAttribute<*>): Path = Files.createDirectories(this, *attrs)
/**
* @see Files.createTempFile
*/
fun Path.createTempFile(prefix: String, suffix: String, vararg attrs: FileAttribute<*>): Path =
Files.createTempFile(this, prefix, suffix, *attrs)
/**
* @see Files.createTempDirectory
*/
fun Path.createTempDirectory(prefix: String, vararg attrs: FileAttribute<*>): Path =
Files.createTempDirectory(this, prefix, *attrs)
/**
* @see Files.createSymbolicLink
*/
fun Path.createSymbolicLink(target: Path, vararg attrs: FileAttribute<*>): Path =
Files.createSymbolicLink(this, target, *attrs)
/**
* @see Files.createLink
*/
fun Path.createLink(existing: Path): Path = Files.createLink(this, existing)
/**
* @see Files.delete
*/
fun Path.delete() = Files.delete(this)
/**
* @see Files.deleteIfExists
*/
fun Path.deleteIfExists() = Files.deleteIfExists(this)
/**
* @see Files.copy
*/
fun Path.copy(target: Path, vararg options: CopyOption): Path = Files.copy(this, target, *options)
/**
* @see Files.move
*/
fun Path.move(target: Path, vararg options: CopyOption): Path = Files.copy(this, target, *options)
/**
* @see Files.readSymbolicLink
*/
fun Path.readSymbolicLink(): Path = Files.readSymbolicLink(this)
/**
* @see Files.getFileStore
*/
fun Path.getFileStore(): FileStore = Files.getFileStore(this)
/**
* @see Files.isSameFile
*/
fun Path.isSameFile(path2: Path): Boolean = Files.isSameFile(this, path2)
/**
* @see Files.isHidden
*/
fun Path.isHidden(): Boolean = Files.isHidden(this)
/**
* @see Files.probeContentType
*/
fun Path.probeContentType(): String? = Files.probeContentType(this)
/**
* @see Files.getFileAttributeView
*/
inline fun <reified V : FileAttributeView> Path.getFileAttributeView(vararg options: LinkOption): V? =
Files.getFileAttributeView(this, V::class.java, *options)
/**
* @see Files.readAttributes
*/
inline fun <reified A : BasicFileAttributes> Path.readAttributes(vararg options: LinkOption): A =
Files.readAttributes(this, A::class.java, *options)
/**
* @see Files.setAttribute
*/
fun Path.setAttribute(attribute: String, value: Any, vararg options: LinkOption): Path =
Files.setAttribute(this, attribute, value, *options)
/**
* @see Files.getAttribute
*/
fun Path.getAttribute(attribute: String, vararg options: LinkOption): Any =
Files.getAttribute(this, attribute, *options)
/**
* @see Files.readAttributes
*/
fun Path.readAttributes(attributes: String, vararg options: LinkOption): Map<String, Any> =
Files.readAttributes(this, attributes, *options)
/**
* @see Files.getPosixFilePermissions
*/
fun Path.getPosixFilePermissions(vararg options: LinkOption): Set<PosixFilePermission> =
Files.getPosixFilePermissions(this, *options)
/**
* @see Files.getPosixFilePermissions
* @see Files.setPosixFilePermissions
*/
var Path.posixFilePermissions: Set<PosixFilePermission>
get() = Files.getPosixFilePermissions(this)
set(value) {
Files.setPosixFilePermissions(this, value)
}
/**
* @see Files.getOwner
*/
fun Path.getOwner(vararg options: LinkOption): UserPrincipal = Files.getOwner(this, *options)
/**
* @see Files.getOwner
* @see Files.setOwner
*/
var Path.owner: UserPrincipal
get() = Files.getOwner(this)
set(value) {
Files.setOwner(this, value)
}
/**
* @see Files.isSymbolicLink
*/
val Path.isSymbolicLink: Boolean get() = Files.isSymbolicLink(this)
/**
* @see Files.isDirectory
*/
val Path.isDirectory: Boolean get() = Files.isDirectory(this)
/**
* @see Files.isDirectory
*/
fun Path.isDirectory(vararg options: LinkOption): Boolean = Files.isDirectory(this, *options)
/**
* @see Files.isRegularFile
*/
val Path.isRegularFile: Boolean get() = Files.isRegularFile(this)
/**
* @see Files.isRegularFile
*/
fun Path.isRegularFile(vararg options: LinkOption): Boolean = Files.isRegularFile(this, *options)
/**
* @see Files.getLastModifiedTime
*/
fun Path.getLastModifiedTime(vararg options: LinkOption): FileTime = Files.getLastModifiedTime(this, *options)
/**
* @see Files.getLastModifiedTime
* @see Files.setLastModifiedTime
*/
var Path.lastModifiedTime: FileTime
get() = Files.getLastModifiedTime(this)
set(value) {
Files.setLastModifiedTime(this, value)
}
/**
* @see Files.size
*/
val Path.size: Long get() = Files.size(this)
/**
* @see Files.exists
*/
fun Path.exists(vararg options: LinkOption): Boolean = Files.exists(this, *options)
/**
* @see Files.exists
*/
val Path.exists: Boolean get() = Files.exists(this)
/**
* @see Files.notExists
*/
fun Path.notExists(vararg options: LinkOption): Boolean = Files.notExists(this, *options)
/**
* @see Files.notExists
*/
val Path.notExists: Boolean get() = Files.notExists(this)
/**
* @see Files.isReadable
*/
val Path.isReadable: Boolean get() = Files.isReadable(this)
/**
* @see Files.isWritable
*/
val Path.isWritable: Boolean get() = Files.isWritable(this)
/**
* @see Files.isExecutable
*/
val Path.isExecutable: Boolean get() = Files.isExecutable(this)
/**
* @see Files.walkFileTree
*/
fun Path.walkFileTree(options: Set<FileVisitOption>, maxDepth: Int, visitor: FileVisitor<in Path>): Path =
Files.walkFileTree(this, options, maxDepth, visitor)
/**
* @see Files.walkFileTree
*/
fun Path.walkFileTree(visitor: FileVisitor<in Path>): Path = Files.walkFileTree(this, visitor)
/**
* @see Files.newBufferedReader
*/
fun Path.newBufferedReader(cs: Charset): BufferedReader = Files.newBufferedReader(this, cs)
/**
* @see Files.newBufferedReader
*/
fun Path.newBufferedReader(): BufferedReader = Files.newBufferedReader(this)
/**
* @see Files.newBufferedWriter
*/
fun Path.newBufferedWriter(cs: Charset, vararg options: OpenOption): BufferedWriter =
Files.newBufferedWriter(this, cs, *options)
/**
* @see Files.newBufferedWriter
*/
fun Path.newBufferedWriter(vararg options: OpenOption): BufferedWriter = Files.newBufferedWriter(this, *options)
/**
* @see Files.copy
*/
fun Path.copy(`in`: InputStream, vararg options: CopyOption): Long = Files.copy(`in`, this, *options)
/**
* @see Files.copy
*/
fun Path.copy(out: OutputStream): Long = Files.copy(this, out)
/**
* @see Files.readAllBytes
*/
fun Path.readAllBytes(): ByteArray = Files.readAllBytes(this)
/**
* @see Files.readAllLines
*/
fun Path.readAllLines(): List<String> = Files.readAllLines(this)
/**
* @see Files.readAllLines
*/
fun Path.readAllLines(cs: Charset): List<String> = Files.readAllLines(this, cs)
/**
* @see Files.write
*/
fun Path.write(bytes: ByteArray, vararg options: OpenOption): Path = Files.write(this, bytes, *options)
/**
* @see Files.write
*/
fun Path.write(lines: Iterable<CharSequence>, cs: Charset, vararg options: OpenOption): Path =
Files.write(this, lines, cs, *options)
/**
* @see Files.write
*/
fun Path.write(lines: Iterable<CharSequence>, vararg options: OpenOption): Path = Files.write(this, lines, *options)
/**
* @see Files.list
*/
fun Path.list(): Sequence<Path> = Files.list(this).asSequence()
/**
* @see Files.walk
*/
fun Path.walk(maxDepth: Int, vararg options: FileVisitOption): Sequence<Path> =
Files.walk(this, maxDepth, *options).asSequence()
/**
* @see Files.walk
*/
fun Path.walk(vararg options: FileVisitOption): Sequence<Path> = Files.walk(this, *options).asSequence()
/**
* @see Files.find
*/
fun Path.find(
maxDepth: Int,
matcher: (Path, BasicFileAttributes) -> Boolean,
vararg options: FileVisitOption
): Sequence<Path> = Files.find(this, maxDepth, BiPredicate(matcher), *options).asSequence()
/**
* @see Files.lines
*/
fun Path.lines(cs: Charset): Sequence<String> = Files.lines(this, cs).asSequence()
/**
* @see Files.lines
*/
fun Path.lines(): Sequence<String> = Files.lines(this).asSequence()
| mit | 7076d729af612ec0c6abe20f6e2a5a10 | 24.493671 | 116 | 0.725323 | 3.778612 | false | false | false | false |
fython/shadowsocks-android | mobile/src/main/java/com/github/shadowsocks/database/ProfileManager.kt | 1 | 4329 | /*******************************************************************************
* *
* Copyright (C) 2017 by Max Lv <[email protected]> *
* Copyright (C) 2017 by Mygod Studio <[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.github.shadowsocks.database
import android.util.Log
import com.github.shadowsocks.App.Companion.app
import com.github.shadowsocks.ProfilesFragment
import com.github.shadowsocks.preference.DataStore
import com.github.shadowsocks.utils.DirectBoot
import java.sql.SQLException
/**
* SQLExceptions are not caught (and therefore will cause crash) for insert/update transactions
* to ensure we are in a consistent state.
*/
object ProfileManager {
private const val TAG = "ProfileManager"
@Throws(SQLException::class)
fun createProfile(p: Profile? = null): Profile {
val profile = p ?: Profile()
profile.id = 0
val oldProfile = app.currentProfile
if (oldProfile != null) {
// Copy Feature Settings from old profile
profile.route = oldProfile.route
profile.ipv6 = oldProfile.ipv6
profile.proxyApps = oldProfile.proxyApps
profile.bypass = oldProfile.bypass
profile.individual = oldProfile.individual
profile.udpdns = oldProfile.udpdns
}
val last = PrivateDatabase.profileDao.queryRaw(PrivateDatabase.profileDao.queryBuilder()
.selectRaw("MAX(userOrder)").prepareStatementString()).firstResult
if (last != null && last.size == 1 && last[0] != null) profile.userOrder = last[0].toLong() + 1
PrivateDatabase.profileDao.createOrUpdate(profile)
ProfilesFragment.instance?.profilesAdapter?.add(profile)
return profile
}
/**
* Note: It's caller's responsibility to update DirectBoot profile if necessary.
*/
@Throws(SQLException::class)
fun updateProfile(profile: Profile) = PrivateDatabase.profileDao.update(profile)
fun getProfile(id: Int): Profile? = try {
PrivateDatabase.profileDao.queryForId(id)
} catch (ex: SQLException) {
Log.e(TAG, "getProfile", ex)
app.track(ex)
null
}
@Throws(SQLException::class)
fun delProfile(id: Int) {
PrivateDatabase.profileDao.deleteById(id)
ProfilesFragment.instance?.profilesAdapter?.removeId(id)
if (id == DataStore.profileId && DataStore.directBootAware) DirectBoot.clean()
}
fun getFirstProfile(): Profile? = try {
PrivateDatabase.profileDao.query(PrivateDatabase.profileDao.queryBuilder().limit(1L).prepare()).singleOrNull()
} catch (ex: SQLException) {
Log.e(TAG, "getFirstProfile", ex)
app.track(ex)
null
}
fun getAllProfiles(): List<Profile>? = try {
PrivateDatabase.profileDao.query(PrivateDatabase.profileDao.queryBuilder().orderBy("userOrder", true).prepare())
} catch (ex: SQLException) {
Log.e(TAG, "getAllProfiles", ex)
app.track(ex)
null
}
}
| gpl-3.0 | 923b078e926a779678475c1b3ea7bc9f | 44.568421 | 120 | 0.566182 | 4.970149 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/ToggleTrackingCommand.kt | 1 | 3265 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.essentials.bukkit.command
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.essentials.bukkit.RPKEssentialsBukkit
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.tracking.bukkit.tracking.RPKTrackingService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class ToggleTrackingCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (!sender.hasPermission("rpkit.essentials.command.toggletracking")) {
sender.sendMessage(plugin.messages["no-permission-toggle-tracking"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val trackingService = Services[RPKTrackingService::class.java]
if (trackingService == null) {
sender.sendMessage(plugin.messages["no-tracking-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
if (character == null) {
sender.sendMessage(plugin.messages["no-character-self"])
return true
}
trackingService.isTrackable(character).thenAccept { isTrackable ->
val newIsTrackable = !isTrackable
trackingService.setTrackable(character, newIsTrackable).thenRun {
if (newIsTrackable) {
sender.sendMessage(plugin.messages["toggle-tracking-on-valid"])
} else {
sender.sendMessage(plugin.messages["toggle-tracking-off-valid"])
}
}
}
return true
}
}
| apache-2.0 | 3e4ec8411b7b8f4935490e27537410f9 | 41.402597 | 114 | 0.683308 | 4.880419 | false | false | false | false |
universum-studios/gradle_github_plugin | plugin/src/releases/kotlin/universum/studios/gradle/github/release/data/model/Asset.kt | 1 | 4774 | /*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* 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 universum.studios.gradle.github.release.data.model
import org.gradle.api.artifacts.PublishArtifact
import java.io.File
/**
* Simple model containing properties describing asset associated with a specific release used locally
* by the GitHub plugin.
*
* @author Martin Albedinsky
* @since 1.0
*
* @property id Id of the asset.
* @property name Name of the asset.
* @property file File that the asset represents.
* @property fileContentType Type of the content that the asset file represents.
* @property baseUploadUrl Base url that should be used to build full url for upload.
* @constructor Creates a new instance of Asset with the specified property values.
*/
data class Asset(
val id: Int = 0,
val name: String,
val file: File,
val fileContentType: String = Asset.CONTENT_TYPE,
val baseUploadUrl: String = Asset.BASE_UPLOAD_URL) {
/**
*/
companion object Contract {
/**
* Default content type of asset file.
*/
const val CONTENT_TYPE = "application/octet-stream"
/**
* Default value for base upload url.
*/
const val BASE_UPLOAD_URL = "https://uploads.github.com/"
}
/**
* Builder which may be used to build a name for a specific [Asset] using properties of the
* corresponding [PublishArtifact] and of the specified release name.
*
* @author Martin Albedinsky
* @since 1.0
*/
class NameBuilder {
/**
*
*/
private var name: String? = null
/**
*
*/
private var version: String? = null
/**
*
*/
private var classifier: String? = null
/**
*
*/
private var type: String? = null
/**
* Specifies a name of asset of which full name to build.
*
* @param name The desired name.
* @return This builder to allow methods chaining.
*/
fun name(name: String?): NameBuilder {
this.name = name
return this
}
/**
* Specifies a version name of asset of which full name to build.
*
* @param version The desired version name.
* @return This builder to allow methods chaining.
*/
fun version(version: String?) : NameBuilder {
this.version = version
return this
}
/**
* Specifies a classifier of asset of which full name to build.
*
* @param classifier The desired classifier.
* @return This builder to allow methods chaining.
*/
fun classifier(classifier: String?): NameBuilder {
this.classifier = classifier
return this
}
/**
* Specifies a type of asset of which full name to build.
*
* @param type The desired type.
* @return This builder to allow methods chaining.
*/
fun type(type: String?): NameBuilder {
this.type = type
return this
}
/**
* Builds name property for [Asset] from the properties specified for this builder.
*
* @return The appropriate asset name.
*/
fun build(): String {
var assetName = name ?: return ""
if (!version.isNullOrEmpty()) {
assetName += "-$version"
}
if (!classifier.isNullOrEmpty()) {
assetName += "-$classifier"
}
if (!type.isNullOrEmpty()) {
assetName += ".$type"
}
return assetName
}
}
} | apache-2.0 | b03d1e5cd7f93970d57cfd3c6e57d816 | 30.414474 | 102 | 0.521366 | 5.269316 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/database/table/RPKLockedBlockTable.kt | 1 | 5278 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.locks.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.core.location.RPKBlockLocation
import com.rpkit.locks.bukkit.RPKLocksBukkit
import com.rpkit.locks.bukkit.database.create
import com.rpkit.locks.bukkit.database.jooq.Tables.RPKIT_LOCKED_BLOCK
import com.rpkit.locks.bukkit.database.jooq.tables.records.RpkitLockedBlockRecord
import com.rpkit.locks.bukkit.lock.RPKLockedBlock
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
class RPKLockedBlockTable(private val database: Database, private val plugin: RPKLocksBukkit) : Table {
private data class BlockCacheKey(
val worldName: String,
val x: Int,
val y: Int,
val z: Int
)
private val cache = if (plugin.config.getBoolean("caching.rpkit_locked_block.block.enabled")) {
database.cacheManager.createCache("rpk-locks-bukkit.rpkit_locked_block.block",
BlockCacheKey::class.javaObjectType,
RPKLockedBlock::class.java,
plugin.config.getLong("caching.rpkit_locked_block.block.size")
)
} else {
null
}
fun insert(entity: RPKLockedBlock): CompletableFuture<Void> {
val block = entity.block
val cacheKey = BlockCacheKey(block.world, block.x, block.y, block.z)
return CompletableFuture.runAsync {
database.create
.insertInto(
RPKIT_LOCKED_BLOCK,
RPKIT_LOCKED_BLOCK.WORLD,
RPKIT_LOCKED_BLOCK.X,
RPKIT_LOCKED_BLOCK.Y,
RPKIT_LOCKED_BLOCK.Z
)
.values(
block.world,
block.x,
block.y,
block.z
)
.execute()
cache?.set(cacheKey, entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to insert locked block", exception)
throw exception
}
}
operator fun get(block: RPKBlockLocation): CompletableFuture<RPKLockedBlock?> {
val cacheKey = BlockCacheKey(block.world, block.x, block.y, block.z)
if (cache?.containsKey(cacheKey) == true) {
return CompletableFuture.completedFuture(cache[cacheKey])
}
return CompletableFuture.supplyAsync {
database.create
.select(
RPKIT_LOCKED_BLOCK.WORLD,
RPKIT_LOCKED_BLOCK.X,
RPKIT_LOCKED_BLOCK.Y,
RPKIT_LOCKED_BLOCK.Z
)
.from(RPKIT_LOCKED_BLOCK)
.where(RPKIT_LOCKED_BLOCK.WORLD.eq(block.world))
.and(RPKIT_LOCKED_BLOCK.X.eq(block.x))
.and(RPKIT_LOCKED_BLOCK.Y.eq(block.y))
.and(RPKIT_LOCKED_BLOCK.Z.eq(block.z))
.fetchOne() ?: return@supplyAsync null
val lockedBlock = RPKLockedBlock(block)
cache?.set(cacheKey, lockedBlock)
return@supplyAsync lockedBlock
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get locked block", exception)
throw exception
}
}
fun getAll(): CompletableFuture<List<RPKLockedBlock>> {
return CompletableFuture.supplyAsync {
return@supplyAsync database.create
.selectFrom(RPKIT_LOCKED_BLOCK)
.fetch()
.mapNotNull { it.toDomain() }
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get locked blocks", exception)
throw exception
}
}
private fun RpkitLockedBlockRecord.toDomain(): RPKLockedBlock {
return RPKLockedBlock(
block = RPKBlockLocation(world, x, y, z)
)
}
fun delete(entity: RPKLockedBlock): CompletableFuture<Void> {
val block = entity.block
val cacheKey = BlockCacheKey(block.world, block.x, block.y, block.z)
return CompletableFuture.runAsync {
database.create
.deleteFrom(RPKIT_LOCKED_BLOCK)
.where(RPKIT_LOCKED_BLOCK.WORLD.eq(block.world))
.and(RPKIT_LOCKED_BLOCK.X.eq(block.x))
.and(RPKIT_LOCKED_BLOCK.Y.eq(block.y))
.and(RPKIT_LOCKED_BLOCK.Z.eq(block.z))
.execute()
cache?.remove(cacheKey)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to delete locked block", exception)
throw exception
}
}
} | apache-2.0 | 1b0f7ef0bf3f777119f316444b4c74b3 | 36.707143 | 103 | 0.606859 | 4.573657 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/action/PsiElementTranslateAction.kt | 1 | 2148 | package cn.yiiguxing.plugin.translate.action
import cn.yiiguxing.plugin.translate.util.w
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
abstract class PsiElementTranslateAction : AnAction() {
final override fun update(e: AnActionEvent) {
val editor = e.editor
val psiFile = e.psiFile
e.presentation.isEnabledAndVisible = if (editor != null && psiFile != null && psiFile.isValid) {
val dataContext = e.dataContext
val element = try {
pickPsiElement(editor, psiFile, dataContext)
} catch (e: Throwable) {
LOG.w("Failed to pick PSI element", e)
null
}
element?.let { it.isValid && isEnabledForElement(editor, it, dataContext) } ?: false
} else {
false
}
}
protected open fun pickPsiElement(editor: Editor, psiFile: PsiFile, dataContext: DataContext): PsiElement? {
return dataContext.getData(LangDataKeys.PSI_ELEMENT)
}
protected abstract fun isEnabledForElement(editor: Editor, element: PsiElement, dataContext: DataContext): Boolean
final override fun actionPerformed(e: AnActionEvent) {
val editor = e.editor ?: return
val psiFile = e.psiFile ?: return
val dataContext = e.dataContext
val element = try {
pickPsiElement(editor, psiFile, dataContext) ?: return
} catch (e: Throwable) {
LOG.w("Failed to pick PSI element", e)
return
}
doTranslate(editor, element, dataContext)
}
protected abstract fun doTranslate(editor: Editor, element: PsiElement, dataContext: DataContext)
companion object {
private val LOG = Logger.getInstance(PsiElementTranslateAction::class.java)
private val AnActionEvent.editor: Editor?
get() = getData(CommonDataKeys.EDITOR)
private val AnActionEvent.psiFile: PsiFile?
get() = getData(LangDataKeys.PSI_FILE)
}
} | mit | 7fdcd6db9e474fd6de521e0a73efe932 | 34.229508 | 118 | 0.653631 | 4.837838 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/ModelFunctions.kt | 5 | 4122 | import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.category.CategoryItem
import fr.free.nrw.commons.location.LatLng
import fr.free.nrw.commons.nearby.Label
import fr.free.nrw.commons.nearby.Place
import fr.free.nrw.commons.nearby.Sitelinks
import fr.free.nrw.commons.upload.structure.depictions.DepictedItem
import fr.free.nrw.commons.wikidata.model.DepictSearchItem
import org.wikipedia.wikidata.*
import java.util.*
fun depictedItem(
name: String = "label",
description: String = "desc",
imageUrl: String = "",
instanceOfs: List<String> = listOf(),
commonsCategories: List<CategoryItem> = listOf(),
isSelected: Boolean = false,
id: String = "entityId"
) = DepictedItem(
name = name,
description = description,
imageUrl = imageUrl,
instanceOfs = instanceOfs,
commonsCategories = commonsCategories,
isSelected = isSelected,
id = id
)
fun categoryItem(name: String = "name", description: String = "desc",
thumbUrl: String = "thumbUrl", selected: Boolean = false) =
CategoryItem(name, description, thumbUrl, selected)
fun media(
thumbUrl: String? = "thumbUrl",
imageUrl: String? = "imageUrl",
filename: String? = "filename",
fallbackDescription: String? = "fallbackDescription",
dateUploaded: Date? = Date(),
license: String? = "license",
licenseUrl: String? = "licenseUrl",
author: String? = "creator",
user:String?="user",
pageId: String = "pageId",
categories: List<String>? = listOf("categories"),
coordinates: LatLng? = LatLng(0.0, 0.0, 0.0f),
captions: Map<String, String> = mapOf("en" to "caption"),
descriptions: Map<String, String> = mapOf("en" to "description"),
depictionIds: List<String> = listOf("depictionId")
) = Media(
pageId,
thumbUrl,
imageUrl,
filename,
fallbackDescription,
dateUploaded,
license,
licenseUrl,
author,
user,
categories,
coordinates,
captions,
descriptions,
depictionIds
)
fun depictSearchItem(
id: String = "id",
pageId: String = "pageid",
url: String = "url",
label: String = "label",
description: String = "description"
) = DepictSearchItem(id, pageId, url, label, description)
fun place(
name: String = "name",
lang: String = "en",
label: Label? = null,
longDescription: String = "longDescription",
latLng: LatLng? = null,
category: String = "category",
siteLinks: Sitelinks? = null,
pic: String = "pic",
exists: Boolean = false
): Place {
return Place(lang, name, label, longDescription, latLng, category, siteLinks, pic, exists)
}
fun entityId(wikiBaseEntityValue: WikiBaseEntityValue = wikiBaseEntityValue()) =
DataValue.EntityId(wikiBaseEntityValue)
fun wikiBaseEntityValue(
entityType: String = "type",
id: String = "id",
numericId: Long = 0
) = WikiBaseEntityValue(entityType, id, numericId)
fun statement(
mainSnak: Snak_partial = snak(),
rank: String = "rank",
type: String = "type"
) = Statement_partial(mainSnak, type, rank)
fun snak(
snakType: String = "type",
property: String = "property",
dataValue: DataValue = valueString("")
) = Snak_partial(snakType, property, dataValue)
fun valueString(value: String) = DataValue.ValueString(value)
fun entity(
labels: Map<String, String> = emptyMap(),
descriptions: Map<String, String> = emptyMap(),
statements: Map<String, List<Statement_partial>>? = emptyMap(),
id: String = "id"
) = mock<Entities.Entity>().apply {
val mockedLabels = labels.mockLabels()
whenever(labels()).thenReturn(mockedLabels)
val mockedDescriptions = descriptions.mockLabels()
whenever(descriptions()).thenReturn(mockedDescriptions)
whenever(this.statements).thenReturn(statements)
whenever(id()).thenReturn(id)
}
private fun Map<String, String>.mockLabels(): Map<String, Entities.Label> {
return mapValues { entry ->
mock<Entities.Label>().also { whenever(it.value()).thenReturn(entry.value) }
}
}
| apache-2.0 | 4b0d26a35efa11d3cb0e90bbc613f9e0 | 29.992481 | 94 | 0.683406 | 3.892351 | false | false | false | false |
pratikbutani/AppIntro | appintro/src/main/java/com/github/paolorotolo/appintro/indicator/DotIndicatorController.kt | 2 | 2913 | package com.github.paolorotolo.appintro.indicator
import android.content.Context
import android.graphics.PorterDuff
import android.view.Gravity
import android.view.Gravity.CENTER
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.github.paolorotolo.appintro.R
/**
* An [IndicatorController] that shows a list of dots and highlight the selected dot.
* Use this when the number of page you're dealing with is not too high.
*/
class DotIndicatorController(context: Context) : IndicatorController, LinearLayout(context) {
override var selectedIndicatorColor = -1
set(value) {
field = value
selectPosition(currentPosition)
}
override var unselectedIndicatorColor = -1
set(value) {
field = value
selectPosition(currentPosition)
}
private var currentPosition = 0
private var slideCount = 0
override fun newInstance(context: Context): View {
val newLayoutParams = LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT
)
newLayoutParams.gravity = Gravity.CENTER_VERTICAL
layoutParams = newLayoutParams
orientation = HORIZONTAL
gravity = CENTER
return this
}
override fun initialize(slideCount: Int) {
this.slideCount = slideCount
for (i in 0 until slideCount) {
val dot = ImageView(this.context)
dot.setImageDrawable(
ContextCompat.getDrawable(
this.context,
R.drawable.ic_appintro_indicator_unselected
)
)
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
this.addView(dot, params)
}
selectPosition(0)
}
override fun selectPosition(index: Int) {
currentPosition = index
for (i in 0 until slideCount) {
val drawableId = if (i == index)
R.drawable.ic_appintro_indicator_selected
else
R.drawable.ic_appintro_indicator_unselected
val drawable = ContextCompat.getDrawable(this.context, drawableId)
if (selectedIndicatorColor != DEFAULT_COLOR && i == index)
drawable!!.mutate().setColorFilter(
selectedIndicatorColor,
PorterDuff.Mode.SRC_IN
)
if (unselectedIndicatorColor != DEFAULT_COLOR && i != index)
drawable!!.mutate().setColorFilter(
unselectedIndicatorColor,
PorterDuff.Mode.SRC_IN
)
(getChildAt(i) as ImageView).setImageDrawable(drawable)
}
}
}
| apache-2.0 | ce9e68655b9b9d1f7a4b0092923ab076 | 32.102273 | 93 | 0.61792 | 5.277174 | false | false | false | false |
androidx/constraintlayout | demoProjects/ExamplesComposeMotionLayout/app/src/main/java/com/example/examplescomposemotionlayout/MainActivity.kt | 2 | 3615 | package com.example.examplescomposemotionlayout
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
private val composeKey = "USE_COMPOSE"
private var cmap = listOf(
get("CollapsingToolbar DSL") { ToolBarExampleDsl() },
get("CollapsingToolbar JSON") { ToolBarExample() },
get("ToolBarLazyExample DSL") { ToolBarLazyExampleDsl() },
get("ToolBarLazyExample JSON") { ToolBarLazyExample() },
get("MotionInLazyColumn Dsl") { MotionInLazyColumnDsl() },
get("MotionInLazyColumn JSON") { MotionInLazyColumn() },
get("DynamicGraph") { ManyGraphs() },
get("ReactionSelector") { ReactionSelector() },
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val extra = intent.extras
var cfunc: ComposeFunc? = null
if (extra != null) {
val composeName = extra.getString(composeKey)
for (composeFunc in cmap) {
if (composeFunc.toString() == composeName) {
cfunc = composeFunc
break
}
}
}
val com = ComposeView(this)
setContentView(com)
com.setContent {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color(0xFFF0E7FC)
) {
if (cfunc != null) {
Log.v("MAIN", " running $cfunc")
cfunc.Run()
} else {
ComposableMenu(map = cmap) { act -> launch(act) }
}
}
}
}
private fun launch(to_run: ComposeFunc) {
Log.v("MAIN", " launch $to_run")
val intent = Intent(this, MainActivity::class.java)
intent.putExtra(composeKey, to_run.toString())
startActivity(intent)
}
}
@Composable
fun ComposableMenu(map: List<ComposeFunc>, act: (act: ComposeFunc) -> Unit) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
) {
for (i in 0..(map.size-1)/2) {
val cFunc1 = map[i*2]
val cFunc2 = if ((i*2+1 < map.size)) map[i*2+1] else null
Row(modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween) {
Button(onClick = { act(cFunc1) }) {
Text(cFunc1.toString(), modifier = Modifier.padding(2.dp))
}
if (cFunc2 != null) {
Button(onClick = { act(cFunc2) }) {
val s = cFunc2.toString().substring(cFunc2.toString().indexOf(' ')+1)
Text(s, modifier = Modifier.padding(2.dp))
}
}
}
}
}
}
fun get(name: String, cRun: @Composable () -> Unit): ComposeFunc {
return object : ComposeFunc {
@Composable
override fun Run() {
cRun()
}
override fun toString(): String {
return name
}
}
}
interface ComposeFunc {
@Composable
fun Run()
override fun toString(): String
}
| apache-2.0 | 97b4b7091f243d2c9e81f37d57637396 | 30.434783 | 88 | 0.568465 | 4.45197 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-appcompat-v7/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v7/widget/ToolbarEvent.kt | 1 | 1119 | package com.github.kittinunf.reactiveandroid.support.v7.widget
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.view.View
import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription
import io.reactivex.Observable
//================================================================================
// Events
//================================================================================
fun Toolbar.rx_navigationClick(): Observable<View> {
return Observable.create { subscriber ->
setNavigationOnClickListener {
subscriber.onNext(it)
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setNavigationOnClickListener(null)
})
}
}
fun Toolbar.rx_menuItemClick(consumed: Boolean): Observable<MenuItem> {
return Observable.create { subscriber ->
setOnMenuItemClickListener {
subscriber.onNext(it)
consumed
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setOnMenuItemClickListener(null)
})
}
}
| mit | f5b14eb904c115c8c1eb239fc34acb1d | 29.243243 | 86 | 0.604111 | 6.048649 | false | false | false | false |
BracketCove/PosTrainer | app/src/main/java/com/bracketcove/postrainer/movement/MovementLogic.kt | 1 | 2556 | package com.bracketcove.postrainer.movement
import com.bracketcove.postrainer.BaseLogic
import com.bracketcove.postrainer.ERROR_GENERIC
import com.bracketcove.postrainer.dependencyinjection.AndroidMovementProvider
import com.wiseassblog.common.ResultWrapper
import com.wiseassblog.domain.domainmodel.Movement
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
class MovementLogic(
private val view: MovementContract.View,
private val viewModel: MovementContract.ViewModel,
private val provider: AndroidMovementProvider,
dispatcher: CoroutineDispatcher
) : BaseLogic<MovementEvent>(dispatcher) {
override val coroutineContext: CoroutineContext
get() = main + jobTracker
override fun handleEvent(eventType: MovementEvent) {
when (eventType){
is MovementEvent.OnStart -> getMovement(eventType.movementId)
is MovementEvent.OnImageClick -> onImageClick()
}
}
private fun onImageClick() {
val imageList = viewModel.getMovement()!!.imageResourceNames
val index = viewModel.getCurrentIndex()
if (imageList.lastIndex == index) updateViewImage(viewModel.getImageResource(0))
else updateViewImage(viewModel.getImageResource(index + 1))
}
private fun updateViewImage(imageResource: String) {
view.setParallaxImage(imageResource)
}
private fun getMovement(movementId: String?) = launch {
if (movementId != null && movementId != ""){
val result = provider.movementRepository.getMovementById(movementId)
when (result) {
is ResultWrapper.Success -> {
viewModel.setMovement(result.value)
updateView(result.value)
}
is ResultWrapper.Error -> handleError()
}
} else {
handleError()
}
}
private fun handleError() {
view.showMessage(ERROR_GENERIC)
view.startMovementListView()
}
private fun updateView(mov: Movement) {
view.setTootlbarTitle(mov.name)
view.setParallaxImage(mov.imageResourceNames[0])
view.setTargets(mov.targets)
view.setFrequency(mov.frequency)
view.setIsTimed(mov.isTimeBased)
view.setTimeOrRepetitions(mov.timeOrRepetitions)
view.setDifficulty(mov.difficulty)
view.setDescription(mov.description)
view.setInstructions(mov.instructions)
view.hideProgressBar()
}
} | apache-2.0 | 889d993313afa154563adc4a0d6ce043 | 32.207792 | 88 | 0.688185 | 5.031496 | false | false | false | false |
darakeon/dfm | android/Lib/src/main/kotlin/com/darakeon/dfm/lib/extensions/View.kt | 1 | 2568 | package com.darakeon.dfm.lib.extensions
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.ACTION_MOVE
import android.view.MotionEvent.ACTION_UP
import android.view.View
import android.widget.GridLayout
import com.darakeon.dfm.lib.Log
import kotlin.math.abs
fun View.changeColSpan(size: Int) {
val layoutParams = layoutParams as GridLayout.LayoutParams
layoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, size, size.toFloat())
}
fun View.swipe(direction: Direction, action: () -> Unit) {
swipe(direction, 1, action)
}
fun View.swipe(direction: Direction, fingers: Int, action: () -> Unit) {
val actions = touches
.getOrAdd(this, mutableMapOf())
actions.getOrAdd(
direction, mutableMapOf()
)[fingers] = action
setOnTouchListener { view, event ->
if (event.action == ACTION_UP && event.pointerCount == 1)
view.performClick()
touch(view, event, actions)
}
}
private fun <K, V> MutableMap<K, V>.getOrAdd(key: K, defaultValue: V): V {
if (this[key] == null)
this[key] = defaultValue
return this[key]!!
}
private var x = mutableMapOf<View, Float>()
private var y = mutableMapOf<View, Float>()
private var finger = mutableMapOf<View, Int>()
private var touches = mutableMapOf<
View, MutableMap<Direction, MutableMap<Int, () -> Unit>>
>()
enum class Direction {
None, Up, Left, Down, Right
}
private fun touch(view: View, event: MotionEvent, moves: MutableMap<Direction, MutableMap<Int, () -> Unit>>): Boolean {
when(event.action) {
ACTION_DOWN -> {
x[view] = event.rawX
y[view] = event.rawY
finger[view] = event.pointerCount
}
ACTION_MOVE -> {
if (!x.containsKey(view)) x[view] = event.rawX
if (!y.containsKey(view)) y[view] = event.rawY
if (!finger.containsKey(view)) finger[view] = event.pointerCount
}
ACTION_UP -> {
val diffX = event.rawX - (x[view]?:0f)
val diffY = event.rawY - (y[view]?:0f)
val direction = getDirection(diffX, diffY)
Log.record(direction)
Log.record(finger[view])
moves[direction]
?.get(finger[view])
?.invoke()
x.remove(view)
y.remove(view)
finger.remove(view)
}
}
return false
}
private fun getDirection(diffX: Float, diffY: Float): Direction {
val absX = abs(diffX)
val absY = abs(diffY)
return when {
absX > absY -> when {
diffX > 0 -> Direction.Right
diffX < 0 -> Direction.Left
else -> Direction.None
}
absX < absY -> when {
diffY > 0 -> Direction.Down
diffY < 0 -> Direction.Up
else -> Direction.None
}
else -> Direction.None
}
}
| gpl-3.0 | 3aa348d783bdf1b70a02a01db1fdb2bc | 23 | 119 | 0.686137 | 3.242424 | false | false | false | false |
eugeis/ee | ee-design/src/main/kotlin/ee/design/gen/angular/DesignAngularGenerator.kt | 1 | 1410 | package ee.design.gen.angular
import ee.design.gen.DesignGeneratorFactory
import ee.lang.StructureUnitI
import ee.lang.gen.ts.prepareForTsGeneration
import java.nio.file.Path
open class DesignAngularGenerator(val model: StructureUnitI<*>) {
fun generate(target: Path) {
val generatorFactory = DesignGeneratorFactory()
model.prepareForTsGeneration()
val generatorContextsApiBase = generatorFactory.typeScriptApiBase("", model)
val generatorApiBase = generatorContextsApiBase.generator
val generatorContextsComponent = generatorFactory.angularTypeScriptComponent("", model)
val generatorComponent = generatorContextsComponent.generator
val generatorAngularModule = generatorFactory.angularModules("", model)
val generatorModule = generatorAngularModule.generator
val generatorAngularHtmlAndScss = generatorFactory.angularHtmlAndScssComponent("", model)
val generatorHtmlAndScss = generatorAngularHtmlAndScss.generator
generatorApiBase.delete(target, model)
generatorComponent.delete(target, model)
generatorModule.delete(target, model)
generatorHtmlAndScss.delete(target, model)
generatorApiBase.generate(target, model)
generatorComponent.generate(target, model)
generatorModule.generate(target, model)
generatorHtmlAndScss.generate(target, model)
}
}
| apache-2.0 | 1415bae5dd49ac0c50c2d9e5bc63e407 | 39.285714 | 97 | 0.758156 | 5.261194 | false | false | false | false |
luoyuan800/NeverEnd | dataModel/src/cn/luo/yuan/maze/model/gift/SkillMaster.kt | 1 | 674 | package cn.luo.yuan.maze.model.gift
import cn.luo.yuan.maze.model.effect.original.SkillRateEffect
import cn.luo.yuan.maze.service.InfoControlInterface
/**
* Created by luoyuan on 2017/9/15.
*/
class SkillMaster:GiftHandler {
override fun handler(control: InfoControlInterface?) {
val pre = SkillRateEffect()
pre.skillRate = 10f
pre.tag = this.javaClass.simpleName
control?.hero?.effects?.add(pre)
}
override fun unHandler(control: InfoControlInterface?) {
val e = control?.hero?.effects?.find { it.tag == this.javaClass.simpleName }
if(e!=null){
control?.hero?.effects?.remove(e)
}
}
} | bsd-3-clause | f7e38c6c627ff9027ecb707a10a7c29a | 28.347826 | 84 | 0.663205 | 3.723757 | false | false | false | false |
kotlintest/kotlintest | kotest-assertions/kotest-assertions-arrow/src/jvmTest/kotlin/io/kotest/assertions/arrow/TestData.kt | 1 | 1482 | //package io.kotest.assertions.arrow
//
//import arrow.Kind
//import arrow.core.Tuple2
//import arrow.data.Nel
//import arrow.data.NonEmptyList
//import arrow.data.Validated
//import arrow.data.ValidatedPartialOf
//import arrow.data.extensions.nonemptylist.semigroup.semigroup
//import arrow.data.extensions.validated.applicativeError.applicativeError
//import arrow.extension
//import arrow.product
//import arrow.typeclasses.Applicative
//import arrow.validation.RefinedPredicateException
//import arrow.validation.Refinement
//import io.kotest.properties.Gen
//
///**
// * Marker [Throwable] used to generate random [arrow.core.Failure] cases
// */
//object Ex : RuntimeException("BOOM")
//
//@product
//data class Person(val id: Long, val name: String) {
// companion object
//}
//
//interface NonEmptyPerson<F> : Refinement<F, Person> {
// override fun invalidValueMsg(a: Person): String =
// "$a should have a name"
//
// override fun Person.refinement(): Boolean =
// name.isNotEmpty()
//}
//
//@extension
//interface ValidatedNonEmptyPerson :
// NonEmptyPerson<ValidatedPartialOf<Nel<RefinedPredicateException>>> {
// override fun applicativeError() =
// Validated.applicativeError(NonEmptyList.semigroup<RefinedPredicateException>())
//}
//
//fun Person.Companion.gen(): Gen<Person> =
// map(
// Gen.long(),
// Gen.string(),
// Tuple2<Long, String>::toPerson
// )
//
//fun <F> Applicative<F>.helloWorldPoly(): Kind<F, String> = just("Hello World")
| apache-2.0 | 42362c990d048176e931d77f3833d030 | 28.64 | 85 | 0.727395 | 3.462617 | false | false | false | false |
mastizada/focus-android | app/src/main/java/org/mozilla/focus/utils/Settings.kt | 2 | 2552 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.utils
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Resources
import android.preference.PreferenceManager
import org.mozilla.focus.R
import org.mozilla.focus.fragment.FirstrunFragment
import org.mozilla.focus.search.SearchEngine
/**
* A simple wrapper for SharedPreferences that makes reading preference a little bit easier.
*/
class Settings private constructor(context: Context) {
companion object {
private var instance: Settings? = null
@JvmStatic
@Synchronized
fun getInstance(context: Context): Settings {
if (instance == null) {
instance = Settings(context.applicationContext)
}
return instance ?: throw AssertionError("Instance cleared")
}
}
private val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
private val resources: Resources = context.resources
val defaultSearchEngineName: String?
get() = preferences.getString(getPreferenceKey(R.string.pref_key_search_engine), null)
fun shouldBlockImages(): Boolean =
// Not shipping in v1 (#188)
/* preferences.getBoolean(
resources.getString(R.string.pref_key_performance_block_images),
false); */
false
fun shouldShowFirstrun(): Boolean =
!preferences.getBoolean(FirstrunFragment.FIRSTRUN_PREF, false)
fun shouldUseSecureMode(): Boolean =
preferences.getBoolean(getPreferenceKey(R.string.pref_key_secure), false)
fun setDefaultSearchEngine(searchEngine: SearchEngine) {
preferences.edit()
.putString(getPreferenceKey(R.string.pref_key_search_engine), searchEngine.name)
.apply()
}
fun shouldAutocompleteFromShippedDomainList() =
preferences.getBoolean(
getPreferenceKey(R.string.pref_key_autocomplete_preinstalled),
true)
fun shouldAutocompleteFromCustomDomainList() =
preferences.getBoolean(
getPreferenceKey(R.string.pref_key_autocomplete_custom),
false)
private fun getPreferenceKey(resourceId: Int): String =
resources.getString(resourceId)
}
| mpl-2.0 | e9bbd3d48ce1ddc738cbf327c50789b7 | 35.457143 | 103 | 0.674765 | 4.964981 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/onboarding/UserFeedWithStoriesKComponent.kt | 1 | 2132 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.samples.litho.onboarding
import androidx.recyclerview.widget.RecyclerView.HORIZONTAL
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Row
import com.facebook.litho.Style
import com.facebook.litho.core.height
import com.facebook.litho.core.padding
import com.facebook.litho.dp
import com.facebook.litho.px
import com.facebook.litho.view.backgroundColor
import com.facebook.litho.widget.collection.CrossAxisWrapMode
import com.facebook.litho.widget.collection.LazyList
import com.facebook.samples.litho.onboarding.model.Post
import com.facebook.samples.litho.onboarding.model.User
// start_example
class UserFeedWithStoriesKComponent(
private val posts: List<Post>,
private val usersWithStories: List<User>
) : KComponent() {
override fun ComponentScope.render(): Component {
return LazyList {
child(
LazyList(
orientation = HORIZONTAL,
crossAxisWrapMode = CrossAxisWrapMode.MatchFirstChild,
startPadding = 4.dp,
topPadding = 4.dp,
style = Style.padding(vertical = 6.dp)) {
usersWithStories.forEach { user -> child(StoryKComponent(user = user)) }
})
child(Row(style = Style.height(1.px).backgroundColor(0x22888888)))
posts.forEach { post ->
child(id = post.id, component = PostWithActionsKComponent(post = post))
}
}
}
}
// end_example
| apache-2.0 | 1737445d743c1b5684c88ea0ebfd4267 | 34.533333 | 88 | 0.724672 | 4.164063 | false | false | false | false |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/internal/activity/db/LeakTable.kt | 2 | 6051 | package leakcanary.internal.activity.db
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import org.intellij.lang.annotations.Language
import shark.Leak
import shark.LibraryLeak
internal object LeakTable {
@Language("RoomSql")
const val create = """
CREATE TABLE leak
(
id INTEGER PRIMARY KEY,
signature TEXT UNIQUE,
short_description TEXT,
is_library_leak INTEGER,
is_read INTEGER
)"""
@Language("RoomSql")
const val createSignatureIndex = """
CREATE INDEX leak_signature
on leak (signature)
"""
@Language("RoomSql")
const val drop = "DROP TABLE IF EXISTS leak"
fun insert(
db: SQLiteDatabase,
heapAnalysisId: Long,
leak: Leak
): Long {
val values = ContentValues()
values.put("signature", leak.signature)
values.put("short_description", leak.shortDescription)
values.put("is_library_leak", if (leak is LibraryLeak) 1 else 0)
values.put("is_read", 0)
db.insertWithOnConflict("leak", null, values, SQLiteDatabase.CONFLICT_IGNORE)
val leakId =
db.rawQuery("SELECT id from leak WHERE signature = '${leak.signature}' LIMIT 1", null)
.use { cursor ->
if (cursor.moveToFirst()) cursor.getLong(0) else throw IllegalStateException(
"No id found for leak with signature '${leak.signature}'"
)
}
leak.leakTraces.forEachIndexed { index, leakTrace ->
LeakTraceTable.insert(
db = db,
leakId = leakId,
heapAnalysisId = heapAnalysisId,
leakTraceIndex = index,
leakingObjectClassSimpleName = leakTrace.leakingObject.classSimpleName
)
}
return leakId
}
fun retrieveLeakReadStatuses(
db: SQLiteDatabase,
signatures: Set<String>
): Map<String, Boolean> {
return db.rawQuery(
"""
SELECT
signature
, is_read
FROM leak
WHERE signature IN (${signatures.joinToString { "'$it'" }})
""", null
)
.use { cursor ->
val leakReadStatuses = mutableMapOf<String, Boolean>()
while (cursor.moveToNext()) {
val signature = cursor.getString(0)
val isRead = cursor.getInt(1) == 1
leakReadStatuses[signature] = isRead
}
leakReadStatuses
}
}
class AllLeaksProjection(
val signature: String,
val shortDescription: String,
val createdAtTimeMillis: Long,
val leakTraceCount: Int,
val isLibraryLeak: Boolean,
val isNew: Boolean
)
fun retrieveAllLeaks(
db: SQLiteDatabase
): List<AllLeaksProjection> {
return db.rawQuery(
"""
SELECT
l.signature
, MIN(l.short_description)
, MAX(h.created_at_time_millis) as created_at_time_millis
, COUNT(*) as leak_trace_count
, MIN(l.is_library_leak) as is_library_leak
, MAX(l.is_read) as is_read
FROM leak_trace lt
LEFT JOIN leak l on lt.leak_id = l.id
LEFT JOIN heap_analysis h ON lt.heap_analysis_id = h.id
GROUP BY 1
ORDER BY leak_trace_count DESC, created_at_time_millis DESC
""", null
)
.use { cursor ->
val all = mutableListOf<AllLeaksProjection>()
while (cursor.moveToNext()) {
val group = AllLeaksProjection(
signature = cursor.getString(0),
shortDescription = cursor.getString(1),
createdAtTimeMillis = cursor.getLong(2),
leakTraceCount = cursor.getInt(3),
isLibraryLeak = cursor.getInt(4) == 1,
isNew = cursor.getInt(5) == 0
)
all.add(group)
}
all
}
}
fun markAsRead(
db: SQLiteDatabase,
signature: String
) {
val values = ContentValues().apply { put("is_read", 1) }
db.update("leak", values, "signature = ?", arrayOf(signature))
}
class LeakProjection(
val shortDescription: String,
val isNew: Boolean,
val isLibraryLeak: Boolean,
val leakTraces: List<LeakTraceProjection>
)
class LeakTraceProjection(
val leakTraceIndex: Int,
val heapAnalysisId: Long,
val classSimpleName: String,
val createdAtTimeMillis: Long
)
fun retrieveLeakBySignature(
db: SQLiteDatabase,
signature: String
): LeakProjection? {
return db.rawQuery(
"""
SELECT
lt.leak_trace_index
, lt.heap_analysis_id
, lt.class_simple_name
, h.created_at_time_millis
, l.short_description
, l.is_read
, l.is_library_leak
FROM leak_trace lt
LEFT JOIN leak l on lt.leak_id = l.id
LEFT JOIN heap_analysis h ON lt.heap_analysis_id = h.id
WHERE l.signature = ?
ORDER BY h.created_at_time_millis DESC
""", arrayOf(signature)
)
.use { cursor ->
return if (cursor.moveToFirst()) {
val leakTraces = mutableListOf<LeakTraceProjection>()
val leakProjection = LeakProjection(
shortDescription = cursor.getString(4),
isNew = cursor.getInt(5) == 0,
isLibraryLeak = cursor.getInt(6) == 1,
leakTraces = leakTraces
)
leakTraces.addAll(generateSequence(cursor) {
if (cursor.moveToNext()) cursor else null
}.map {
LeakTraceProjection(
leakTraceIndex = cursor.getInt(0),
heapAnalysisId = cursor.getLong(1),
classSimpleName = cursor.getString(2),
createdAtTimeMillis = cursor.getLong(3)
)
})
leakProjection
} else {
null
}
}
}
fun deleteByHeapAnalysisId(
db: SQLiteDatabase,
heapAnalysisId: Long
) {
LeakTraceTable.deleteByHeapAnalysisId(db, heapAnalysisId)
db.execSQL(
"""
DELETE
FROM leak
WHERE NOT EXISTS (
SELECT *
FROM leak_trace lt
WHERE leak.id = lt.leak_id)
"""
)
}
}
| apache-2.0 | e28c97746beb877b9ce1253c01767b4a | 26.630137 | 92 | 0.594778 | 4.452539 | false | false | false | false |
android/camera-samples | Camera2SlowMotion/app/src/main/java/com/example/android/camera2/slowmo/fragments/PermissionsFragment.kt | 1 | 2920 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.camera2.slowmo.fragments
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import com.example.android.camera2.slowmo.R
private const val PERMISSIONS_REQUEST_CODE = 10
private val PERMISSIONS_REQUIRED = arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO)
/**
* This [Fragment] requests permissions and, once granted, it will navigate to the next fragment
*/
class PermissionsFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (hasPermissions(requireContext())) {
// If permissions have already been granted, proceed
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
PermissionsFragmentDirections.actionPermissionsToSelector())
} else {
// Request camera-related permissions
requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSIONS_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Takes the user to the success fragment when permission is granted
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
PermissionsFragmentDirections.actionPermissionsToSelector())
} else {
Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show()
}
}
}
companion object {
/** Convenience method used to check if all permissions required by this app are granted */
fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all {
ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
}
}
| apache-2.0 | c1c87db72a06d630ca4b53919ee9e6ab | 39 | 99 | 0.709932 | 5.060659 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/util/lifecycle.kt | 1 | 1395 | package app.lawnchair.util
import android.content.Context
import android.content.ContextWrapper
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
private val LocalLifecycleState = compositionLocalOf<Lifecycle.State> {
error("CompositionLocal LocalLifecycleState not present")
}
@Composable
fun lifecycleState(): Lifecycle.State = LocalLifecycleState.current
@Composable
fun ProvideLifecycleState(content: @Composable () -> Unit) {
CompositionLocalProvider(LocalLifecycleState provides observeLifecycleState()) {
content()
}
}
@Composable
private fun observeLifecycleState(): Lifecycle.State {
val lifecycle = LocalLifecycleOwner.current.lifecycle
var state by remember(lifecycle) { mutableStateOf(lifecycle.currentState) }
DisposableEffect(lifecycle) {
val observer = LifecycleEventObserver { _, event ->
state = event.targetState
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
return state
}
fun Context.lookupLifecycleOwner(): LifecycleOwner? {
return when (this) {
is LifecycleOwner -> this
is ContextWrapper -> baseContext.lookupLifecycleOwner()
else -> null
}
}
| gpl-3.0 | 40a10620f5ab96c4181a9dbc262041cf | 28.680851 | 84 | 0.751254 | 5.284091 | false | false | false | false |
greggigon/Home-Temperature-Controller | temperature-sensor-and-rest/src/main/kotlin/io/dev/temperature/verticles/ScheduleVerticle.kt | 1 | 4971 | package io.dev.temperature.verticles
import io.dev.temperature.BusAddresses
import io.dev.temperature.model.NextScheduledTemp
import io.dev.temperature.model.Schedule
import io.vertx.core.AbstractVerticle
import io.vertx.core.Vertx
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
class ScheduleVerticle(val scheduleFilePath: String = "./schedule.json") : AbstractVerticle() {
val log: Logger = LoggerFactory.getLogger(ScheduleVerticle::class.java)
val EMPTY_SCHEDULE = JsonObject().
put("active", false).
put("days", JsonArray().
add(JsonObject().
put("name", "Mon").
put("hours", JsonArray())).
add(JsonObject().
put("name", "Tue").
put("hours", JsonArray())).
add(JsonObject().
put("name", "Wed").
put("hours", JsonArray())).
add(JsonObject().
put("name", "Thu").
put("hours", JsonArray())).
add(JsonObject().
put("name", "Fri").
put("hours", JsonArray())).
add(JsonObject().
put("name", "Sat").
put("hours", JsonArray())).
add(JsonObject().
put("name", "Sun").
put("hours", JsonArray()))
)
var currentSchedule: JsonObject? = null
var scheduleFile: File? = null
var currentTimer: Long = 0
var nextTemperatureSetup: NextScheduledTemp? = null
override fun start() {
scheduleFile = File(scheduleFilePath)
if (!scheduleFile!!.exists()) {
scheduleFile!!.createNewFile()
scheduleFile!!.writeText(EMPTY_SCHEDULE.encodePrettily())
}
currentSchedule = JsonObject(scheduleFile!!.readText())
vertx.eventBus().consumer<JsonObject>(BusAddresses.Schedule.SCHEDULE_GET_CURRENT, { message ->
message.reply(currentSchedule)
})
vertx.eventBus().consumer<JsonObject>(BusAddresses.Schedule.SCHEDULE_SAVE, { message ->
currentSchedule = message.body()
message.reply(currentSchedule)
vertx.eventBus().publish(BusAddresses.Schedule.SCHEDULE_UPDATED, currentSchedule)
})
vertx.eventBus().consumer<JsonObject>(BusAddresses.Schedule.SCHEDULE_GET_NEXT_UPDATE, { message ->
message.reply(nextTemperatureSetup?.toJson())
})
vertx.eventBus().consumer<JsonObject>(BusAddresses.Schedule.SCHEDULE_UPDATED, { message ->
val newSchedule = message.body()
if (scheduleFile == null) {
scheduleFile = File(scheduleFilePath)
}
scheduleFile!!.writeText(newSchedule.encodePrettily())
log.info("Saved new Schedule to file [${scheduleFile?.absolutePath}]")
if (!currentTimer.equals(0)) {
log.info("Canceling previously scheduled temperature setup")
vertx.cancelTimer(currentTimer)
currentTimer = 0
nextTemperatureSetup = null
}
if (shouldScheduleNextJob(currentSchedule)) {
currentTimer = scheduleNextJob(currentSchedule, vertx)
}
})
if (shouldScheduleNextJob(currentSchedule)) {
currentTimer = scheduleNextJob(currentSchedule, vertx)
} else {
log.info("There is no Active schedule at the moment.")
}
log.info("Started Schedule verticle")
}
private fun shouldScheduleNextJob(schedule: JsonObject?): Boolean {
return (schedule != null && schedule.getBoolean("active", false))
}
private fun scheduleNextJob(scheduleJson: JsonObject?, vertx: Vertx): Long {
val schedule = Schedule.fromJson(scheduleJson!!)
val now = LocalDateTime.now()
val nextScheduledTemp = schedule.nextScheduledTemp(now) ?: return 0
nextTemperatureSetup = nextScheduledTemp
val delay = now.until(nextScheduledTemp.time, ChronoUnit.MILLIS)
log.info("Scheduling next temperature setup [${nextScheduledTemp}]")
return vertx.setTimer(delay, {
vertx.eventBus().send<Float>(BusAddresses.Serial.SET_TEMPERATURE_IN_ARDUINO, nextScheduledTemp.temp, { responseMessage ->
if (responseMessage.failed()) {
log.error("Unable to send new temperature setup", responseMessage.cause())
}
currentTimer = scheduleNextJob(currentSchedule, vertx)
})
})
}
} | mit | 38a08dfa54c67c760f7f694d01532bb4 | 37.542636 | 133 | 0.578354 | 5.32227 | false | false | false | false |
youlookwhat/CloudReader | app/src/main/java/com/example/jingbin/cloudreader/bean/CoinLogBean.kt | 1 | 574 | package com.example.jingbin.cloudreader.bean
/**
* Created by jingbin on 2020/12/3.
*/
class CoinLogBean {
/**
* coinCount : 12
* date : 1569468233000
* desc : 2019-09-26 11:23:53 分享文章 , 积分:10 + 2
* id : 53889
* reason : 分享文章
* type : 3
* userId : 1534
* userName : jingbin
*/
val coinCount = 0
val date: Long = 0
val desc: String? = null
val id = 0
val reason: String? = null
val type = 0
val userId = 0
val username: String? = null
val nickname: String? = null
} | apache-2.0 | 6f0e1a1960d318b1cdc028c3b5ab7b41 | 20.269231 | 50 | 0.559783 | 3.209302 | false | false | false | false |
ajmirB/Messaging | app/src/main/java/com/xception/messaging/features/channels/fragments/ChannelListFragment.kt | 1 | 4357 | package com.xception.messaging.features.channels.fragments
import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.TextInputEditText
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.airbnb.epoxy.EpoxyModel
import com.airbnb.epoxy.EpoxyRecyclerView
import com.sendbird.android.OpenChannel
import com.xception.messaging.R
import com.xception.messaging.features.channels.items.ChannelModel_
import com.xception.messaging.features.channels.presenters.ChannelItemData
import com.xception.messaging.features.channels.presenters.ChannelListPresenter
import com.xception.messaging.features.channels.presenters.ChannelListView
import com.xception.messaging.features.commons.BaseFragment
class ChannelListFragment : BaseFragment(), ChannelListView {
lateinit var mChannelListPresenter: ChannelListPresenter
lateinit var mRecyclerView: EpoxyRecyclerView
lateinit var mFragmentListener: Listener
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is Listener) {
mFragmentListener = context
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.fragment_channel_list, container, false)
mChannelListPresenter = ChannelListPresenter(this)
mRecyclerView = view.findViewById(R.id.channel_list_epoxy_recycler_view)
mRecyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
val mCreateChannelButton : FloatingActionButton = view.findViewById(R.id.channel_list_create_channel_button)
mCreateChannelButton.setOnClickListener({ mChannelListPresenter.onAskToCreateChannelClicked()})
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mChannelListPresenter.onViewCreated()
}
override fun onResume() {
super.onResume()
mChannelListPresenter.onViewResumed()
}
override fun onDestroyView() {
super.onDestroyView()
mChannelListPresenter.onViewDestroyed()
}
// region ChannelListView
override fun showContent(channels: List<ChannelItemData>) {
mRecyclerView.buildModelsWith { controller ->
channels.forEach {
ChannelModel_()
.id(it.url)
.channel(it)
.addTo(controller)
}
}
}
override fun updateContent(channels: List<ChannelItemData>) {
// Generate the new models
val channelModels = ArrayList<EpoxyModel<View>>(channels.size)
channels.forEach {
channelModels.add(
ChannelModel_()
.id(it.url)
.channel(it)
)
}
// Update the models in the recycler view
mRecyclerView.setModels(channelModels)
}
override fun showChannelCreationForm() {
// Edit text to enter the channel name
val input = TextInputEditText(activity)
input.setHint(R.string.channel_creation_input_hint)
input.maxLines = 1
input.inputType = InputType.TYPE_CLASS_TEXT
// Dialog to let the user enter its channel name
AlertDialog.Builder(activity)
.setTitle(R.string.channel_creation_title)
.setView(input)
.setPositiveButton(R.string.channel_creation_create_button, { _, _ -> mChannelListPresenter.onCreateChannelConfirmationClicked(input.text.toString()) })
.setNegativeButton(R.string.channel_creation_cancel_button, { dialog, _ -> dialog.cancel() })
.show()
}
override fun goToConversation(channel: OpenChannel) {
mFragmentListener.showConversation(channel)
}
// endregion
companion object {
fun newInstance() = ChannelListFragment()
}
interface Listener {
fun showConversation(channel: OpenChannel)
}
} | apache-2.0 | af02443c84417bf3c5d9898ada65253f | 34.145161 | 168 | 0.692219 | 5.125882 | false | false | false | false |
reime005/splintersweets | core/src/de/reimerm/splintersweets/actors/scene2d/AudioButton.kt | 1 | 2076 | /*
* Copyright (c) 2017. Marius Reimer
*
* 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 de.reimerm.splintersweets.actors.scene2d
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener
import com.badlogic.gdx.scenes.scene2d.utils.Drawable
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import de.reimerm.splintersweets.utils.AssetsManager
import de.reimerm.splintersweets.utils.AudioUtils
import de.reimerm.splintersweets.utils.Resources
/**
* Created by Marius Reimer on 05-Oct-16.
*/
class AudioButton : ImageButton {
private var imageOn: Drawable
private var imageOff: Drawable
constructor(imageUp: Drawable) : super(imageUp) {
imageOn = TextureRegionDrawable(AssetsManager.textureMap[Resources.RegionNames.BUTTON_AUDIO_ON.name])
imageOff = TextureRegionDrawable(AssetsManager.textureMap[Resources.RegionNames.BUTTON_AUDIO_OFF.name])
addListener(object : ChangeListener() {
override fun changed(event: ChangeEvent?, actor: Actor?) {
if (AudioUtils.isMusicOn() == true) {
AudioUtils.stopMusic()
}
AudioUtils.toggleMusicPreference()
AudioUtils.playBackgroundMusic()
if (AudioUtils.isMusicPreferenceTrue()) {
style.imageUp = imageOn
} else {
style.imageUp = imageOff
}
}
})
}
} | apache-2.0 | 386bb7e5be614e259137dd1b23789eb7 | 35.438596 | 111 | 0.69316 | 4.152 | false | false | false | false |
beyama/winter | winter-compiler/src/test/resources/FactoryTypeAnnotation_WinterFactory.kt | 1 | 657 | package test
import io.jentz.winter.Component
import io.jentz.winter.Graph
import io.jentz.winter.TypeKey
import io.jentz.winter.inject.Factory
import java.util.concurrent.atomic.AtomicBoolean
import javax.annotation.Generated
import kotlin.Boolean
@Generated(
value = ["io.jentz.winter.compiler.WinterProcessor"],
date = "2019-02-10T14:52Z"
)
class FactoryTypeAnnotation_WinterFactory : Factory<AtomicBoolean> {
override fun invoke(graph: Graph): AtomicBoolean = FactoryTypeAnnotation()
override fun register(builder: Component.Builder, override: Boolean): TypeKey<AtomicBoolean> =
builder.prototype(override = override, factory = this)
}
| apache-2.0 | b3b18ffaee7cbd39cad27819ed679ee1 | 31.85 | 96 | 0.792998 | 4.006098 | false | false | false | false |
jara0705/PolyShareByKotlin | kotlin_myshare/src/main/java/com/jara/kotlin_myshare/channel/ShareBySystemK.kt | 1 | 1369 | package com.jara.kotlin_myshare.channel
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import com.jara.kotlin_myshare.R
import com.jara.kotlin_myshare.bean.Constant
import com.jara.kotlin_myshare.bean.ShareEntity
import com.jara.kotlin_myshare.interfaces.OnShareListener
import com.jara.kotlin_myshare.utils.ShareUtil
/**
* Created by jara on 2017-9-19.
*/
class ShareBySystemK(context: Context) : ShareBaseK(context) {
override fun share(entity: ShareEntity, listener: OnShareListener) {
if (entity == null || TextUtils.isEmpty(entity.content)) {
return
}
val content = if (TextUtils.isEmpty(entity.content))
entity.title + entity.url
else entity.content + entity.url
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_TEXT, content)
intent.type = "text/plain"
if (ShareUtil.startActivity(context
, Intent.createChooser(intent, context.getString(R.string.share_to)))) {
if (null != listener) {
listener.onShare(Constant.SHARE_CHANNEL_SYSTEM, Constant.SHARE_STATUS_COMPLETE)
}
} else {
if (null != listener) {
listener.onShare(Constant.SHARE_CHANNEL_SYSTEM, Constant.SHARE_STATUS_FAILED)
}
}
}
} | mit | 9af3c1f0117c7eb0eef95313c489b3c4 | 36.027027 | 95 | 0.664719 | 4.050296 | false | false | false | false |
astir-trotter/mobile-android | projects/AndroidCustomer/atcustom/src/main/java/com/astir_trotter/atcustom/singleton/Cache.kt | 1 | 1309 | package com.astir_trotter.atcustom.singleton
import android.content.Context
import com.astir_trotter.atcustom.component.AppInfo
import com.astir_trotter.atcustom.singleton.lang.base.Language
import com.astir_trotter.atcustom.singleton.theme.base.Theme
/**
* @author - Saori Sugiyama
* *
* @contact - [email protected]
* *
* @date - 4/11/17
*/
class Cache private constructor() {
////////////////////////////////////////////////////////////////////////////////////////////////
var isDebug: Boolean = false
var context: Context? = null
get() {
if (field == null)
throw IllegalStateException("No context registered yet.")
return field
}
var appInfo: AppInfo? = null
get() {
if (field == null)
throw IllegalStateException("No app info registered yet.")
return field
}
var language: Language = Language.English
var theme: Theme = Theme.Light
companion object {
private val TAG = Cache::class.java.simpleName
private var _instance: Cache? = null
val instance: Cache
get() {
if (_instance == null)
_instance = Cache()
return _instance!!
}
}
}
| mit | 787980690e8f6ea5cff3f785437148a3 | 24.173077 | 100 | 0.542399 | 4.513793 | false | false | false | false |
LordAkkarin/Beacon | ui/src/main/kotlin/tv/dotstart/beacon/ui/util/ErrorReporter.kt | 1 | 3621 | /*
* Copyright 2020 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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 tv.dotstart.beacon.ui.util
import com.mindscapehq.raygun4java.core.RaygunClient
import com.mindscapehq.raygun4java.core.messages.RaygunBreadcrumbLevel
import tv.dotstart.beacon.ui.BeaconUiMetadata
/**
* Exports error reports to an external service provider if available.
*
* Authentication information is provided as part of the `raygun.token` resource file in the root
* of the application Class-Path.
*
* @author Johannes Donath
* @date 02/12/2020
*/
object ErrorReporter {
private val logger = ErrorReporter::class.logger
/**
* Permanently stores the authentication token which is to be transmitted for all requests to
* the error reporting backend.
*
* When no authentication token has been configured, null is stored within this property instead.
*/
private val token = System.getProperty("raygun.token")
?.takeIf(String::isNotBlank)
?: this::class.java.getResourceAsStream("/raygun.token")
?.readAllBytes()
?.toString(Charsets.UTF_8)
?.takeIf(String::isNotBlank)
?.trim()
/**
* Evaluates whether error reporting is available.
*/
val available: Boolean by lazy { token != null }
/**
* Caches the error reporting client once initialized.
*/
private val client by lazy {
token?.let {
RaygunClient(it)
.apply {
setVersion(BeaconUiMetadata.version)
withData("javaVersion", System.getProperty("java.version", "unknown"))
withData("javaVendor", System.getProperty("java.vendor", "unknown"))
withData("javaBytecodeVersion", System.getProperty("java.class.version", "unknown"))
}
}
}
/**
* Submits an application error if authentication is present within the application Class-Path.
*
* When no authentication is given, this method simply acts as a no-op.
*/
operator fun invoke(ex: Throwable) {
val client = client
if (client == null) {
logger.error("Cannot submit error report without valid authentication", ex)
return
}
val responseCode = client.send(ex)
logger.info("Submitted error report (server responded with code $responseCode)")
}
/**
* Records a trace of an action performed within the application.
*
* This information is transmitted along with error records if submitted thus providing additional
* information on how to reproduce a given error within the application.
*/
fun trace(category: String,
message: String,
level: RaygunBreadcrumbLevel = RaygunBreadcrumbLevel.INFO,
data: Map<String, Any?> = emptyMap()) {
val client = client
if (client == null) {
logger.debug("Ignoring breadcrumb of level $level for category \"$category\": $message")
return
}
client.recordBreadcrumb(message)
.withLevel(level)
.withCategory(category)
.withCustomData(data)
}
}
| apache-2.0 | 250b23036fec01550d01f7ce70719511 | 32.527778 | 100 | 0.690417 | 4.486989 | false | false | false | false |
vovagrechka/k2php | k2php/src/org/jetbrains/kotlin/js/inline/FunctionInlineMutator.kt | 2 | 6928 | /*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.jetbrains.kotlin.js.inline
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.backend.ast.metadata.isSuspend
import org.jetbrains.kotlin.js.backend.ast.metadata.staticRef
import org.jetbrains.kotlin.js.backend.ast.metadata.synthetic
import org.jetbrains.kotlin.js.inline.clean.removeDefaultInitializers
import org.jetbrains.kotlin.js.inline.context.InliningContext
import org.jetbrains.kotlin.js.inline.util.*
import org.jetbrains.kotlin.js.inline.util.rewriters.ReturnReplacingVisitor
import org.jetbrains.kotlin.js.translate.context.Namer
class FunctionInlineMutator
private constructor(
private val call: JsInvocation,
private val inliningContext: InliningContext
) {
private val invokedFunction: JsFunction
private val namingContext = inliningContext.newNamingContext()
private val body: JsBlock
private var resultExpr: JsExpression? = null
private var resultName: JsName? = null
private var breakLabel: JsLabel? = null
private val currentStatement = inliningContext.statementContext.currentNode
init {
val functionContext = inliningContext.functionContext
invokedFunction = uncoverClosure(functionContext.getFunctionDefinition(call).deepCopy())
body = invokedFunction.body
}
private fun process() {
val arguments = getArguments()
val parameters = getParameters()
removeDefaultInitializers(arguments, parameters, body)
aliasArgumentsIfNeeded(namingContext, arguments, parameters)
renameLocalNames(namingContext, invokedFunction)
processReturns()
namingContext.applyRenameTo(body)
resultExpr = resultExpr?.let {
namingContext.applyRenameTo(it) as JsExpression
}
}
private fun uncoverClosure(invokedFunction: JsFunction): JsFunction {
val innerFunction = invokedFunction.getInnerFunction()
val innerCall = getInnerCall(call.qualifier)
return if (innerCall != null && innerFunction != null) {
innerFunction.apply {
replaceThis(body)
applyCapturedArgs(innerCall, this, invokedFunction)
}
}
else {
invokedFunction.apply { replaceThis(body) }
}
}
private fun getInnerCall(qualifier: JsExpression): JsInvocation? {
return when (qualifier) {
is JsInvocation -> qualifier
is JsNameRef -> {
val callee = if (qualifier.ident == Namer.CALL_FUNCTION) qualifier.qualifier else (qualifier.name?.staticRef as? JsExpression)
callee?.let { getInnerCall(it) }
}
else -> null
}
}
private fun applyCapturedArgs(call: JsInvocation, inner: JsFunction, outer: JsFunction) {
val namingContext = inliningContext.newNamingContext()
val arguments = call.arguments
val parameters = outer.parameters
aliasArgumentsIfNeeded(namingContext, arguments, parameters)
namingContext.applyRenameTo(inner)
}
private fun replaceThis(block: JsBlock) {
if (!hasThisReference(block)) return
var thisReplacement = getThisReplacement(call)
if (thisReplacement == null || thisReplacement is JsLiteral.JsThisRef) return
val thisName = namingContext.getFreshName(getThisAlias())
namingContext.newVar(thisName, thisReplacement)
thisReplacement = thisName.makeRef()
replaceThisReference(block, thisReplacement)
}
private fun processReturns() {
resultExpr = getResultReference()
val breakName = namingContext.getFreshName(getBreakLabel())
this.breakLabel = JsLabel(breakName).apply { synthetic = true }
val visitor = ReturnReplacingVisitor(resultExpr as? JsNameRef, breakName.makeRef(), invokedFunction, call.isSuspend)
visitor.accept(body)
}
private fun getResultReference(): JsNameRef? {
if (!isResultNeeded(call)) return null
val resultName = namingContext.getFreshName(getResultLabel())
this.resultName = resultName
namingContext.newVar(resultName, null)
return resultName.makePHPVarRef()
}
private fun getArguments(): List<JsExpression> {
val arguments = call.arguments
if (isCallInvocation(call)) {
return arguments.subList(1, arguments.size)
}
return arguments
}
private fun isResultNeeded(call: JsInvocation): Boolean {
return currentStatement !is JsExpressionStatement || call != currentStatement.expression
}
private fun getParameters(): List<JsParameter> {
return invokedFunction.parameters
}
private fun getResultLabel(): String {
return getLabelPrefix() + "result"
}
private fun getBreakLabel(): String {
return getLabelPrefix() + "break"
}
private fun getThisAlias(): String {
return "\$this"
}
fun getLabelPrefix(): String {
val ident = getSimpleIdent(call)
val labelPrefix = ident ?: "inline$"
if (labelPrefix.endsWith("$")) {
return labelPrefix
}
return labelPrefix + "$"
}
companion object {
@JvmStatic fun getInlineableCallReplacement(call: JsInvocation, inliningContext: InliningContext): InlineableResult {
val mutator = FunctionInlineMutator(call, inliningContext)
mutator.process()
var inlineableBody: JsStatement = mutator.body
val breakLabel = mutator.breakLabel
if (breakLabel != null) {
breakLabel.statement = inlineableBody
inlineableBody = breakLabel
}
return InlineableResult(inlineableBody, mutator.resultExpr)
}
@JvmStatic
private fun getThisReplacement(call: JsInvocation): JsExpression? {
if (isCallInvocation(call)) {
return call.arguments[0]
}
if (hasCallerQualifier(call)) {
return getCallerQualifier(call)
}
return null
}
private fun hasThisReference(body: JsBlock): Boolean {
val thisRefs = collectInstances(JsLiteral.JsThisRef::class.java, body)
return !thisRefs.isEmpty()
}
}
}
| apache-2.0 | 773fb530d21b8fc491527a6d8a72a365 | 33.29703 | 142 | 0.671334 | 4.945039 | false | false | false | false |
hotshotmentors/Yeng-App-Android | app/src/main/java/in/yeng/user/helpers/AnimUtil.kt | 2 | 2419 | package `in`.yeng.user.helpers
import android.animation.ObjectAnimator
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
object AnimUtil {
fun fadeDown(view: View, duration: Long = 1200, initialOffset: Float = 100f, scaleValue: Float = 0.9f) {
val translate = ObjectAnimator.ofFloat(view, "translationY", -initialOffset, 0f)
translate.duration = duration
translate.interpolator = DecelerateInterpolator(2f)
translate.start()
val alpha = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f)
alpha.duration = duration * 8 / 10
alpha.interpolator = AccelerateInterpolator(0.9f)
alpha.start()
val scale = ObjectAnimator.ofFloat(view, "scaleX", scaleValue, 1f)
scale.duration = duration * 8 / 10
scale.interpolator = DecelerateInterpolator(2f)
scale.start()
}
fun fadeUp(view: View, duration: Long = 1200, initialOffset: Float = 100f, scaleValue: Float = 0.9f) {
val translate = ObjectAnimator.ofFloat(view, "translationY", initialOffset, 0f)
translate.duration = duration
translate.interpolator = DecelerateInterpolator(2f)
translate.start()
val alpha = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f)
alpha.duration = duration * 8 / 10
alpha.interpolator = AccelerateInterpolator(0.9f)
alpha.start()
val scale = ObjectAnimator.ofFloat(view, "scaleX", scaleValue, 1f)
scale.duration = duration * 8 / 10
scale.interpolator = DecelerateInterpolator(2f)
scale.start()
}
fun fadeIn(view: View, duration: Long = 1200, scaleValue: Float = 0.95f) {
val alpha = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f)
alpha.duration = duration
alpha.interpolator = AccelerateInterpolator(0.9f)
alpha.start()
val scale = ObjectAnimator.ofFloat(view, "scaleX", scaleValue, 1f)
scale.duration = duration * 8 / 10
scale.interpolator = DecelerateInterpolator(2f)
scale.start()
}
fun clickAnimation(view: View) {
val scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.95f, 1f)
scaleX.duration = 200
scaleX.start()
val scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.95f, 1f)
scaleY.duration = 300
scaleY.start()
}
} | gpl-3.0 | 9c503fa7f60eccfef60b9e9dd290c8e6 | 34.588235 | 108 | 0.658537 | 4.236427 | false | false | false | false |
EvidentSolutions/apina | apina-core/src/main/kotlin/fi/evident/apina/ApinaProcessor.kt | 1 | 2408 | package fi.evident.apina
import fi.evident.apina.java.reader.Classpath
import fi.evident.apina.model.settings.Platform.*
import fi.evident.apina.model.settings.TranslationSettings
import fi.evident.apina.output.swift.SwiftGenerator
import fi.evident.apina.output.ts.TypeScriptAngularGenerator
import fi.evident.apina.output.ts.TypeScriptES6Generator
import fi.evident.apina.spring.SpringModelReader
import org.slf4j.LoggerFactory
class ApinaProcessor(private val classpath: Classpath) {
val settings = TranslationSettings()
fun process(): String {
val api = SpringModelReader.readApiDefinition(classpath, settings)
log.debug("Loaded {} endpoint groups with {} endpoints.", api.endpointGroupCount, api.endpointCount)
log.trace("Loaded endpoint groups: {}", api.endpointGroups)
if (api.endpointCount == 0) {
log.warn("Apina could not find any endpoints to process")
}
log.debug("Loaded {} class definitions", api.classDefinitionCount)
log.trace("Loaded class definitions: {}", api.classDefinitions)
log.debug("Loaded {} enum definitions", api.enumDefinitionCount)
log.trace("Loaded enum definitions: {}", api.enumDefinitions)
val unknownTypes = api.unknownTypeReferences
if (!unknownTypes.isEmpty()) {
log.warn("Writing {} unknown class definitions as black boxes: {}", unknownTypes.size, unknownTypes)
}
@Suppress("DEPRECATION")
return when (settings.platform) {
ANGULAR -> TypeScriptAngularGenerator(api, settings).run {
writeApi()
output
}
ANGULAR2 -> {
log.warn("Platform.ANGULAR2 is deprecated, use Platform.ANGULAR instead")
TypeScriptAngularGenerator(api, settings).run {
writeApi()
output
}
}
ES6 -> TypeScriptES6Generator(api, settings).run {
writeApi()
output
}
SWIFT -> SwiftGenerator(api, settings).run {
log.warn("Apina's Swift-support is incubating and will have breaking changes in minor releases")
writeApi()
output
}
}
}
companion object {
private val log = LoggerFactory.getLogger(ApinaProcessor::class.java)
}
}
| mit | a5aa057522774617d3c369f5c89ab46b | 36.046154 | 112 | 0.633306 | 4.740157 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/engine/XmlActivity.kt | 1 | 3720 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel.engine
import kotlinx.serialization.Serializable
import kotlinx.serialization.Serializer
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import nl.adaptivity.process.ProcessConsts
import nl.adaptivity.process.processModel.*
import nl.adaptivity.process.processModel.ProcessModel.BuildHelper
import nl.adaptivity.serialutil.DelegatingSerializer
import nl.adaptivity.xmlutil.serialization.XmlDefault
import nl.adaptivity.xmlutil.serialization.XmlSerialName
/**
* Class representing an activity in a process engine. Activities are expected
* to invoke one (and only one) web service. Some services are special in that
* they either invoke another process (and the process engine can treat this
* specially in later versions), or set interaction with the user. Services can
* use the ActivityResponse soap header to indicate support for processes and
* what the actual state of the task after return should be (instead of
*
* @author Paul de Vrieze
*/
class XmlActivity : ActivityBase, XmlProcessNode, CompositeActivity, MessageActivity {
override var message: IXmlMessage?
get() = field
private set(value) {
field = XmlMessage.from(value)
}
override val childModel: ChildProcessModel<ProcessNode>?
val childId: String?
private var xmlCondition: XmlCondition? = null
override val condition: Condition?
get() = xmlCondition
constructor(
builder: MessageActivity.Builder,
newOwner: ProcessModel<*>,
otherNodes: Iterable<ProcessNode.Builder>
) : super(builder.ensureExportable(), newOwner, otherNodes) {
childModel = null
childId = null
message = builder.message
}
constructor(
builder: CompositeActivity.ModelBuilder,
buildHelper: BuildHelper<*, *, *, *>,
otherNodes: Iterable<ProcessNode.Builder>
) : super(builder.ensureExportable(), buildHelper.newOwner, otherNodes) {
childModel = buildHelper.childModel(builder)
childId = builder.childId
message = null
}
constructor(
builder: CompositeActivity.ReferenceBuilder,
buildHelper: BuildHelper<*, *, *, *>,
otherNodes: Iterable<ProcessNode.Builder>
) : super(builder.ensureExportable(), buildHelper.newOwner, otherNodes) {
val id = builder.childId
childModel = id?.let { buildHelper.childModel(it) }
childId = id
message = null
}
override fun builder(): Activity.Builder = when {
childId == null -> MessageActivityBase.Builder(this)
else -> ReferenceActivityBuilder(this)
}
override fun <R> visit(visitor: ProcessNode.Visitor<R>): R = when {
childModel == null -> visitor.visitActivity(messageActivity = this)
else -> visitor.visitActivity(compositeActivity = this)
}
}
| lgpl-3.0 | 770c7545fe9555f3112d743ab6dff21b | 35.470588 | 112 | 0.71828 | 4.888305 | false | false | false | false |
BasinMC/Basin | faucet/src/main/kotlin/org/basinmc/faucet/math/Vector3Int.kt | 1 | 3476 | /*
* Copyright 2019 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.basinmc.faucet.math
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* @author <a href="mailto:[email protected]">Johannes Donath</a>
*/
data class Vector3Int(override val x: Int = 0, override val y: Int = 0, override val z: Int = 0) :
Vector3<Int> {
override val length: Double by lazy {
sqrt(Math.pow(this.x.toDouble(), 2.0) + Math.pow(this.y.toDouble(), 2.0) + Math.pow(
this.z.toDouble(), 2.0))
}
override val normalized: Vector3Int by lazy {
Vector3Int((this.x / this.length).roundToInt(), (this.y / this.length).roundToInt(),
(this.z / this.length).roundToInt())
}
override val int: Vector3Int
get() = this
override fun plus(addend: Int) = Vector3Int(this.x + addend, this.y + addend, this.z + addend)
override fun plus(addend: Vector2<Int>) = Vector3Int(this.x + addend.x, this.y + addend.y, this.z)
override fun plus(addend: Vector3<Int>) = Vector3Int(this.x + addend.x, this.y + addend.y,
this.z + addend.z)
override fun minus(subtrahend: Int) = Vector3Int(this.x - subtrahend, this.y - subtrahend,
this.z - subtrahend)
override fun minus(subtrahend: Vector2<Int>) = Vector3Int(this.x - subtrahend.x,
this.y - subtrahend.y, this.z)
override fun minus(subtrahend: Vector3<Int>) = Vector3Int(this.x - subtrahend.x,
this.y - subtrahend.y, this.z - subtrahend.z)
override fun times(factor: Int) = Vector3Int(this.x * factor, this.y * factor, this.z * factor)
override fun times(factor: Vector2<Int>) = Vector3Int(this.x * factor.x, this.y * factor.y,
this.z)
override fun times(factor: Vector3<Int>) = Vector3Int(this.x * factor.x, this.y * factor.y,
this.z * factor.z)
override fun div(divisor: Int) = Vector3Int(this.x / divisor, this.y / divisor, this.z / divisor)
override fun div(divisor: Vector2<Int>) = Vector3Int(this.x / divisor.x, this.y / divisor.y,
this.z)
override fun div(divisor: Vector3<Int>) = Vector3Int(this.x / divisor.x, this.y / divisor.y,
this.z / divisor.z)
override fun rem(divisor: Int) = Vector3Int(this.x % divisor, this.y % divisor, this.z % divisor)
override fun rem(divisor: Vector2<Int>) = Vector3Int(this.x % divisor.x, this.y % divisor.y,
this.z)
override fun rem(divisor: Vector3<Int>) = Vector3Int(this.x % divisor.x, this.y % divisor.y,
this.z % divisor.z)
companion object : Vector3.Definition<Int> {
override val zero = Vector3Int()
override val one = Vector3Int(1, 1, 1)
override val up = Vector3Int(0, 1, 0)
override val right = Vector3Int(1, 0, 0)
override val down = Vector3Int(0, -1, 0)
override val left = Vector3Int(-1, 0, 0)
override val forward = Vector3Int(0, 0, 1)
override val backward = Vector3Int(0, 0, -1)
}
}
| apache-2.0 | 0275654f7391aed85a74086c7b862525 | 39.418605 | 100 | 0.68153 | 3.257732 | false | false | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/ui/widget/LetterIcon.kt | 1 | 3105 | package me.shkschneider.skeleton.ui.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorInt
import androidx.annotation.IntRange
import me.shkschneider.skeleton.helperx.Logger
import me.shkschneider.skeleton.helperx.Metrics
import me.shkschneider.skeleton.ui.ThemeHelper
// <https://github.com/IvBaranov/MaterialLetterIcon>
class LetterIcon : View {
private var shapePaint = Paint()
private var letterPaint = Paint()
private var shapeColor = Color.BLACK
private var letter = DEFAULT
private var letterColor = Color.WHITE
private var letterSize = 26 // R.dimen.textSizeBig
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr)
init {
shapePaint = Paint()
shapePaint.style = Paint.Style.FILL
shapePaint.isAntiAlias = true
letterPaint = Paint()
letterPaint.isAntiAlias = true
setShapeColor(ThemeHelper.accentColor())
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val layoutParams = layoutParams ?: run {
Logger.warning("ViewGroup.LayoutParams was NULL")
return
}
if (layoutParams.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
val dp = Metrics.pixelsFromDp(DP.toFloat())
layoutParams.width = dp
layoutParams.height = dp
invalidate()
}
}
override fun onDraw(canvas: Canvas) {
val width = measuredWidth / 2
val height = measuredHeight / 2
val radius = if (width > height) height else width
shapePaint.run {
color = shapeColor
canvas.drawCircle(width.toFloat(), height.toFloat(), radius.toFloat(), this)
}
letterPaint.run {
color = letterColor
textSize = Metrics.pixelsFromSp(letterSize.toFloat()).toFloat()
getTextBounds(letter, 0, letter.length, RECT)
canvas.drawText(letter, width - RECT.exactCenterX(), height - RECT.exactCenterY(), this)
}
}
fun setShapeColor(@ColorInt color: Int) {
shapeColor = color
invalidate()
}
fun setLetter(string: String) {
letter = string.replace("\\s+".toRegex(), "").toUpperCase()
letter = if (letter.isNotEmpty()) letter.first().toString() else DEFAULT
invalidate()
}
fun setLetterColor(@ColorInt color: Int) {
letterColor = color
invalidate()
}
fun setLetterSize(@IntRange(from = 0) size: Int) {
letterSize = size
invalidate()
}
fun setLetterTypeface(typeface: Typeface) {
letterPaint.typeface = typeface
invalidate()
}
companion object {
private val DEFAULT = "#"
private val DP = 40
private val RECT = Rect()
}
}
| apache-2.0 | b871e372eb1276c9a7cc6bbd0574f783 | 29.145631 | 123 | 0.650242 | 4.740458 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/action/wizard/ipsum/InsertDummyTextDialogWrapper.kt | 1 | 8280 | package nl.hannahsten.texifyidea.action.wizard.ipsum
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.JBIntSpinner
import com.intellij.ui.components.*
import nl.hannahsten.texifyidea.util.addLabeledComponent
import nl.hannahsten.texifyidea.util.hbox
import nl.hannahsten.texifyidea.util.text.Ipsum
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.*
import javax.swing.border.EmptyBorder
import kotlin.random.Random
/**
* @author Hannah Schellekens
*/
open class InsertDummyTextDialogWrapper : DialogWrapper(true) {
/**
* What type of blind text to generate.
*/
private val cboxBlindType = ComboBox(DummyTextData.BlindtextType.values()).apply {
selectedItem = DummyTextData.BlindtextType.PARAGRAPH
addItemListener { updateUi() }
}
/**
* The amount of repetitions of blind text.
*/
private val intBlindRepetitions = JBIntSpinner(1, 1, 99999)
/**
* The amount of paragraphs of blind text.
*/
private val intBlindParagraphs = JBIntSpinner(1, 1, 99999)
/**
* The level of the blind itemize/enumerate/description.
*/
private val intBlindLevel = JBIntSpinner(1, 1, 999)
/**
* Panel containing options for the blindtext package.
*/
private val panelBlindtext = JPanel().apply {
border = EmptyBorder(8, 0, 8, 16)
layout = BoxLayout(this, BoxLayout.Y_AXIS).apply {
// Flush left.
alignmentX = 0.0f
}
val labelWidth = 140
addLabeledComponent(cboxBlindType, "Type of text:", labelWidth)
addLabeledComponent(hbox(8, intBlindParagraphs, JLabel("Repetitions:"), intBlindRepetitions), "Paragraphs:", labelWidth)
addLabeledComponent(intBlindLevel, "List level:", labelWidth)
add(Box.createRigidArea(Dimension(0, 28)))
}
/**
* Contains the lipsum start paragraph number (1-150).
*/
private val intLipsumParagraphsMin = JBIntSpinner(1, 1, 150)
/**
* Contains the lipsum end paragraph number (1-150).
*/
private val intLipsumParagraphsMax = JBIntSpinner(7, 1, 150)
/**
* Contains the lipsum start sentence number.
*/
private val intLipsumSentencesMin = JBIntSpinner(1, 1, 999)
/**
* Contains the lipsum end sentence number.
*/
private val intLipsumSentencesMax = JBIntSpinner(999, 1, 999)
/**
* How to separate the lipsum paragraphs.
*/
private val cboxLipsumSeparator = ComboBox(DummyTextData.LipsumParagraphSeparation.values()).apply {
selectedItem = DummyTextData.LipsumParagraphSeparation.PARAGRAPH
}
/**
* Panel containing options for the lipsum package.
*/
private val panelLipsum = JPanel().apply {
border = EmptyBorder(8, 0, 8, 16)
layout = BoxLayout(this, BoxLayout.Y_AXIS).apply {
// Flush left.
alignmentX = 0.0f
}
val labelWidth = 192
addLabeledComponent(hbox(8, intLipsumParagraphsMin, JLabel("to"), intLipsumParagraphsMax), "Paragraph numbers:", labelWidth)
addLabeledComponent(hbox(8, intLipsumSentencesMin, JLabel("to"), intLipsumSentencesMax), "Sentence numbers:", labelWidth)
addLabeledComponent(cboxLipsumSeparator, "Paragraph separation:", labelWidth)
add(Box.createRigidArea(Dimension(0, 28)))
}
/**
* Which dummy text teplate to use.
*/
private val cboxRawTemplate = ComboBox(Ipsum.values()).apply {
selectedItem = Ipsum.TEXIFY_IDEA_IPSUM
}
/**
* The minimum number of raw paragraphs to generate.
*/
private val intRawParagraphsMin = JBIntSpinner(3, 1, 99999)
/**
* The maximum number of raw paragraphs to generate.
*/
private val intRawParagraphsMax = JBIntSpinner(7, 1, 99999)
/**
* The minimum number of raw sentences in a paragraph.
*/
private val intRawSentencesMin = JBIntSpinner(2, 1, 99999)
/**
* The maximum number of raw sentences in a paragraph.
*/
private val intRawSentencessMax = JBIntSpinner(14, 1, 99999)
/**
* Contains the seed to generate random numbers.
*/
private val txtRawSeed = JBTextField(Random.nextInt().toString())
/**
* Panel containing options for raw text.
*/
private val panelRaw = JPanel().apply {
border = EmptyBorder(8, 0, 8, 16)
layout = BoxLayout(this, BoxLayout.Y_AXIS).apply {
// Flush left.
alignmentX = 0.0f
}
val labelWidth = 192
addLabeledComponent(cboxRawTemplate, "Dummy text template:", labelWidth)
addLabeledComponent(hbox(8, intRawParagraphsMin, JLabel("to"), intRawParagraphsMax), "Number of paragraphs:", labelWidth)
addLabeledComponent(hbox(8, intRawSentencesMin, JLabel("to"), intRawSentencessMax), "Sentences per paragraph:", labelWidth)
addLabeledComponent(txtRawSeed, "Seed:", labelWidth)
}
private val tabPane = JBTabbedPane().apply {
insertTab(DummyTextData.IpsumType.BLINDTEXT.description, null, panelBlindtext, null, 0)
insertTab(DummyTextData.IpsumType.LIPSUM.description, null, panelLipsum, null, 1)
insertTab(DummyTextData.IpsumType.RAW.description, null, panelRaw, null, 2)
}
init {
super.init()
title = "Insert dummy text"
}
/**
* Get the data that has been entered into the UI.
*/
fun extractData() = when (tabPane.selectedIndex) {
0 -> DummyTextData(
ipsumType = DummyTextData.IpsumType.BLINDTEXT,
blindtextType = cboxBlindType.selectedItem as DummyTextData.BlindtextType,
blindtextRepetitions = intBlindRepetitions.number,
blindtextParagraphs = intBlindParagraphs.number,
blindtextLevel = intBlindLevel.number
)
1 -> DummyTextData(
ipsumType = DummyTextData.IpsumType.LIPSUM,
lipsumParagraphs = intLipsumParagraphsMin.number..intLipsumParagraphsMax.number,
lipsumSentences = intLipsumSentencesMin.number..intLipsumSentencesMax.number,
lipsumParagraphSeparator = cboxLipsumSeparator.selectedItem as DummyTextData.LipsumParagraphSeparation
)
else -> DummyTextData(
ipsumType = DummyTextData.IpsumType.RAW,
rawDummyTextType = cboxRawTemplate.selectedItem as Ipsum,
rawParagraphs = intRawParagraphsMin.number..intRawParagraphsMax.number,
rawSentencesPerParagraph = intRawSentencesMin.number..intRawSentencessMax.number,
rawSeed = txtRawSeed.text.toInt()
)
}
private fun updateUi() {
intBlindLevel.isEnabled = cboxBlindType.item == DummyTextData.BlindtextType.ITEMIZE ||
cboxBlindType.item == DummyTextData.BlindtextType.DESCRIPTION ||
cboxBlindType.item == DummyTextData.BlindtextType.ENUMERATE
intBlindRepetitions.isEnabled = cboxBlindType.item == DummyTextData.BlindtextType.PARAGRAPH
intBlindParagraphs.isEnabled = cboxBlindType.item == DummyTextData.BlindtextType.PARAGRAPH
}
override fun createCenterPanel() = JPanel(BorderLayout()).apply {
add(tabPane, BorderLayout.CENTER)
updateUi()
}
override fun doValidate() = if (intLipsumParagraphsMax.number < intLipsumParagraphsMin.number) {
ValidationInfo("Maximum must be greater than or equal to the minimum.", intLipsumParagraphsMax)
}
else if (intLipsumSentencesMax.number < intLipsumSentencesMin.number) {
ValidationInfo("Maximum must be greater than or equal to the minimum.", intLipsumSentencesMax)
}
else if (intRawParagraphsMax.number < intRawParagraphsMin.number) {
ValidationInfo("Maximum must be greater than or equal to the minimum.", intRawParagraphsMax)
}
else if (intRawSentencessMax.number < intRawSentencesMin.number) {
ValidationInfo("Maximum must be greater than or equal to the minimum.", intRawSentencessMax)
}
else if (txtRawSeed.text.toIntOrNull() == null) {
ValidationInfo("Invalid seed: must be an integer in range -2147483648 to 2147483647.", txtRawSeed)
}
else null
} | mit | 9fe35662197d4e28a76d8bdd55b4f943 | 36.301802 | 132 | 0.680918 | 4.899408 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/services/SessionTracker.kt | 1 | 9450 | package io.rover.sdk.experiences.services
import android.os.Handler
import android.os.Looper
import io.rover.sdk.core.data.graphql.safeGetString
import io.rover.sdk.core.data.graphql.safeOptInt
import io.rover.sdk.experiences.data.events.RoverEvent
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.platform.LocalStorage
import io.rover.sdk.experiences.platform.debugExplanation
import io.rover.sdk.experiences.platform.whenNotNull
import org.json.JSONObject
import java.util.Date
import java.util.UUID
import kotlin.math.max
internal class SessionTracker(
private val eventEmitter: EventEmitter,
private val sessionStore: SessionStore,
/**
* The number of seconds to leave the session open for in the event that the user leaves
* temporarily.
*/
private val keepAliveTime: Int
) {
private val timerHandler = Handler(Looper.getMainLooper())
/**
* Indicate a session is opening for the given session key. The Session Key should be a value
* object (a Kotlin data class, a string, etc.) that properly implements hashcode, equals, and
* an exhaustive version of toString(). This value object should describe the given semantic
* item the user is looking at (a given experience, a given view, etc.).
*
* Note that the values need to be unique amongst the different event sources in the app, so be
* particularly careful with string values or data class class names.
*
* A [sessionEventName] must be provided so that the Session Tracker can emit session viewed
* after the timeout completes.
*/
fun enterSession(
sessionKey: Any,
sessionStartEvent: RoverEvent,
sessionEvent: RoverEvent
) {
log.v("Entering session $sessionKey")
sessionStore.enterSession(sessionKey, sessionEvent)
eventEmitter.trackEvent(
sessionStartEvent
)
}
/**
* Indicate a session is being left. See [enterSession] for an explanation of session key.
*/
private fun updateTimer() {
timerHandler.removeCallbacksAndMessages(this::timerCallback)
sessionStore.soonestExpiryInSeconds(keepAliveTime).whenNotNull { soonestExpiry ->
if (soonestExpiry == 0) {
// execute the timer callback directly.
timerCallback()
} else {
timerHandler.postDelayed(
this::timerCallback,
soonestExpiry * 1000L
)
}
}
}
private fun timerCallback() {
log.v("Emitting events for expired sessions.")
sessionStore.collectExpiredSessions(keepAliveTime).forEach { expiredSession ->
log.v("Session closed: ${expiredSession.sessionKey}")
val eventToSend: RoverEvent = when (val event = expiredSession.sessionEvent) {
is RoverEvent.ScreenViewed -> {
event.copy(duration = expiredSession.durationSeconds)
}
is RoverEvent.ExperienceViewed -> {
event.copy(duration = expiredSession.durationSeconds)
}
else -> event
}
eventEmitter.trackEvent(eventToSend)
}
updateTimer()
}
fun leaveSession(
sessionKey: Any,
sessionEndEvent: RoverEvent
) {
log.v("Leaving session $sessionKey")
sessionStore.leaveSession(sessionKey)
eventEmitter.trackEvent(sessionEndEvent)
updateTimer()
}
}
internal class SessionStore(
localStorage: LocalStorage
) {
private val store = localStorage.getKeyValueStorageFor(STORAGE_IDENTIFIER)
init {
gc()
}
/**
* Enters a session.
*
* Returns the new session's UUID, or, if a session is already active, null.
*/
fun enterSession(sessionKey: Any, sessionEvent: RoverEvent) {
val session = getEntry(sessionKey)?.copy(
// clear closedAt to avoid expiring the session if it is being re-opened.
closedAt = null
) ?: SessionEntry(
UUID.randomUUID(),
Date(),
sessionEvent,
null
)
setEntry(sessionKey, session)
}
fun leaveSession(sessionKey: Any) {
val existingEntry = getEntry(sessionKey)
if (existingEntry != null) {
// there is indeed a session open for the given key, mark it as expiring.
setEntry(
sessionKey,
existingEntry.copy(
closedAt = Date()
)
)
}
}
private fun getEntry(sessionKey: Any): SessionEntry? {
val entryJson = store[sessionKey.toString()].whenNotNull { JSONObject(it) }
return entryJson.whenNotNull {
try {
SessionEntry.decodeJson(it)
} catch (exception: Exception) {
log.w("Invalid JSON appeared in Session Store, ignoring: ${exception.debugExplanation()}")
null
}
}
}
private fun setEntry(sessionKey: Any, sessionEntry: SessionEntry) {
store[sessionKey.toString()] = sessionEntry.encodeJson().toString()
}
/**
* Returns the soonest time that a session is going to expire.
*/
fun soonestExpiryInSeconds(keepAliveSeconds: Int): Int? {
// gather stale expiring session entries that have passed.
val earliestExpiry = store.keys
.mapNotNull { key -> getEntry(key) }
.mapNotNull { entry -> entry.closedAt?.time }
.map { closedAt -> closedAt + (keepAliveSeconds * 1000L) }
// differential from current time in seconds, assuming expiry in the future.
.map { expiryTimeMsEpoch ->
((expiryTimeMsEpoch - Date().time) / 1000).toInt()
}
.minOrNull()
// if there's a negative number, return 0 because there's already expired entries that need
// to be dealt with now.
return earliestExpiry.whenNotNull { earliest ->
max(earliest, 0)
}
}
/**
* Returns the sessions that are expired and should have their event emitted.
*
* Such sessions will only be returned once; they are deleted.
*/
fun collectExpiredSessions(keepAliveSeconds: Int): List<ExpiredSession> {
val expiringEntries = store.keys
.mapNotNull { key ->
getEntry(key).whenNotNull { Pair(key, it) }
}
.filter { it.second.closedAt != null }
.filter { entry ->
entry.second.closedAt!!.before(
Date(
Date().time + keepAliveSeconds * 1000L
)
)
}
expiringEntries.map { it.first }.forEach { key ->
log.v("Removing now expired session entry $key from store.")
store.unset(key)
}
return expiringEntries.map { (key, entry) ->
ExpiredSession(
key,
entry.uuid,
entry.sessionEvent,
((entry.closedAt?.time!! - entry.startedAt.time) / 1000L).toInt()
)
}
}
private fun gc() {
log.v("Garbage collecting any expired sessions.")
store.keys.forEach { key ->
val entry = getEntry(key)
if (entry == null) {
log.e("GC: '$key' was missing or invalid. Deleting it.")
store[key] = null
return@forEach
}
if (entry.startedAt.before(Date(Date().time - CLEANUP_TIME))) {
log.w("Cleaning up stale session store key: $key/$entry")
}
}
}
data class ExpiredSession(
val sessionKey: Any,
val uuid: UUID,
val sessionEvent: RoverEvent,
val durationSeconds: Int
)
data class SessionEntry(
val uuid: UUID,
/**
* When was this session started?
*/
val startedAt: Date,
/**
* Any other attributes to include with the session event.
*/
val sessionEvent: RoverEvent,
/**
* When was the session closed?
*/
val closedAt: Date?
) {
fun encodeJson(): JSONObject {
return JSONObject().apply {
put("uuid", uuid.toString())
put("started-at", startedAt.time / 1000)
put("session-attributes", sessionEvent.encodeJson())
if (closedAt != null) {
put("closed-at", closedAt.time / 1000)
}
}
}
companion object {
fun decodeJson(jsonObject: JSONObject): SessionEntry {
return SessionEntry(
UUID.fromString(jsonObject.safeGetString("uuid")),
Date(jsonObject.getInt("started-at") * 1000L),
RoverEvent.decodeJson(jsonObject.getJSONObject("session-attributes")),
jsonObject.safeOptInt("closed-at").whenNotNull { Date(it * 1000L) }
)
}
}
}
companion object {
const val STORAGE_IDENTIFIER = "session-store"
const val CLEANUP_TIME = 3600 * 1000L // 1 hour.
}
}
| apache-2.0 | 73f8c37c50d2afcec4321329659bb103 | 31.25256 | 106 | 0.573545 | 5.002647 | false | false | false | false |
AcapellaSoft/Aconite | aconite-core/src/io/aconite/Data.kt | 1 | 1355 | package io.aconite
data class Request (
val method: String = "",
val path: Map<String, String> = emptyMap(),
val query: Map<String, String> = emptyMap(),
val headers: Map<String, String> = emptyMap(),
val body: BodyBuffer? = null
)
data class Response (
val code: Int? = null,
val headers: Map<String, String> = emptyMap(),
val body: BodyBuffer? = null
) {
operator fun plus(other: Response) = Response(
code = other.code ?: this.code,
headers = this.headers + other.headers,
body = other.body ?: this.body
)
}
data class BodyBuffer(
val content: Buffer,
val contentType: String
)
interface Buffer {
val string: String
val bytes: ByteArray
companion object Factory {
fun wrap(string: String) = object: Buffer {
override val string = string
override val bytes by lazy { string.toByteArray() }
}
fun wrap(bytes: ByteArray) = object: Buffer {
override val string by lazy { String(bytes) }
override val bytes = bytes
}
}
}
fun HttpException.toResponse() = Response(
code = this.code,
body = BodyBuffer(
content = Buffer.wrap(this.message ?: ""),
contentType = "text/plain"
)
) | mit | e0b7c0534df53bbc701141d3df9d09e7 | 25.588235 | 63 | 0.56679 | 4.399351 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/filesystem/ftpserver/RootFtpFile.kt | 1 | 4648 | /*
* Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.filesystem.ftpserver
import com.topjohnwu.superuser.io.SuFile
import com.topjohnwu.superuser.io.SuFileInputStream
import com.topjohnwu.superuser.io.SuFileOutputStream
import org.apache.ftpserver.ftplet.FtpFile
import org.apache.ftpserver.ftplet.User
import org.apache.ftpserver.usermanager.impl.WriteRequest
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.InputStream
import java.io.OutputStream
class RootFtpFile(
private val fileName: String,
private val backingFile: SuFile,
private val user: User
) : FtpFile {
companion object {
@JvmStatic
private val logger: Logger = LoggerFactory.getLogger(RootFtpFile::class.java)
}
override fun getAbsolutePath(): String = backingFile.absolutePath
override fun getName(): String = backingFile.name
override fun isHidden(): Boolean = backingFile.isHidden
override fun isDirectory(): Boolean = backingFile.isDirectory
override fun isFile(): Boolean = backingFile.isFile
override fun doesExist(): Boolean = backingFile.exists()
override fun isReadable(): Boolean = backingFile.canRead()
override fun isWritable(): Boolean {
logger.debug("Checking authorization for $absolutePath")
if (user.authorize(WriteRequest(absolutePath)) == null) {
logger.debug("Not authorized")
return false
}
logger.debug("Checking if file exists")
if (backingFile.exists()) {
logger.debug("Checking can write: " + backingFile.canWrite())
return backingFile.canWrite()
}
logger.debug("Authorized")
return true
}
override fun isRemovable(): Boolean {
// root cannot be deleted
if ("/" == fileName) {
return false
}
val fullName = absolutePath
// we check FTPServer's write permission for this file.
if (user.authorize(WriteRequest(fullName)) == null) {
return false
}
// In order to maintain consistency, when possible we delete the last '/' character in the String
val indexOfSlash = fullName.lastIndexOf('/')
val parentFullName: String = if (indexOfSlash == 0) {
"/"
} else {
fullName.substring(0, indexOfSlash)
}
// we check if the parent FileObject is writable.
return backingFile.absoluteFile.parentFile?.run {
RootFtpFile(
parentFullName,
this,
user
).isWritable
} ?: false
}
override fun getOwnerName(): String = "user"
override fun getGroupName(): String = "user"
override fun getLinkCount(): Int = if (backingFile.isDirectory) 3 else 1
override fun getLastModified(): Long = backingFile.lastModified()
override fun setLastModified(time: Long): Boolean = backingFile.setLastModified(time)
override fun getSize(): Long = backingFile.length()
override fun getPhysicalFile(): Any = backingFile
override fun mkdir(): Boolean = backingFile.mkdirs()
override fun delete(): Boolean = backingFile.delete()
override fun move(destination: FtpFile): Boolean =
backingFile.renameTo(destination.physicalFile as SuFile)
override fun listFiles(): MutableList<out FtpFile> = backingFile.listFiles()?.map {
RootFtpFile(it.name, it, user)
}?.toMutableList() ?: emptyList<FtpFile>().toMutableList()
override fun createOutputStream(offset: Long): OutputStream =
SuFileOutputStream.open(backingFile.absolutePath)
override fun createInputStream(offset: Long): InputStream =
SuFileInputStream.open(backingFile.absolutePath)
}
| gpl-3.0 | dbd2b9971d25d048f0e66bba59e007a0 | 33.42963 | 107 | 0.686532 | 4.826584 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/widget/WidgetFilterSelectionActivity.kt | 1 | 2105 | package org.tasks.widget
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import com.todoroo.astrid.api.Filter
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.LocalBroadcastManager
import org.tasks.dialogs.FilterPicker.Companion.EXTRA_FILTER
import org.tasks.dialogs.FilterPicker.Companion.SELECT_FILTER
import org.tasks.dialogs.FilterPicker.Companion.newFilterPicker
import org.tasks.injection.InjectingAppCompatActivity
import org.tasks.preferences.DefaultFilterProvider
import org.tasks.preferences.Preferences
import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint
class WidgetFilterSelectionActivity : InjectingAppCompatActivity() {
@Inject lateinit var preferences: Preferences
@Inject lateinit var defaultFilterProvider: DefaultFilterProvider
@Inject lateinit var localBroadcastManager: LocalBroadcastManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)
if (widgetId == -1) {
Timber.e("Missing ${AppWidgetManager.EXTRA_APPWIDGET_ID}")
finish()
}
supportFragmentManager
.setFragmentResultListener(SELECT_FILTER, this) { _, result ->
val filter: Filter? = result.getParcelable(EXTRA_FILTER)
if (filter == null) {
finish()
return@setFragmentResultListener
}
WidgetPreferences(this, preferences, widgetId)
.setFilter(defaultFilterProvider.getFilterPreferenceValue(filter))
localBroadcastManager.reconfigureWidget(widgetId)
setResult(RESULT_OK, Intent().putExtras(result))
finish()
}
newFilterPicker(intent.getParcelableExtra(EXTRA_FILTER))
.show(supportFragmentManager, FRAG_TAG_FILTER_PICKER)
}
companion object {
private const val FRAG_TAG_FILTER_PICKER = "frag_tag_filter_picker"
}
} | gpl-3.0 | 59d2c9c83d7e7af1be45a195d9180144 | 40.294118 | 86 | 0.712114 | 5.210396 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/options/Option.kt | 1 | 6620 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.options
import com.eclipsesource.json.Json
import com.eclipsesource.json.JsonArray
import com.eclipsesource.json.JsonObject
import javafx.scene.input.DataFormat
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.input.KeyCombination
import uk.co.nickthecoder.paratask.Tool
import uk.co.nickthecoder.paratask.JsonHelper
import java.io.Externalizable
import java.io.ObjectInput
import java.io.ObjectOutput
interface Option : Externalizable, Comparable<Option> {
var code: String
var aliases: MutableList<String>
var label: String
var isRow: Boolean
var isMultiple: Boolean
var refresh: Boolean
var newTab: Boolean
var prompt: Boolean
var shortcut: KeyCodeCombination?
fun run(tool: Tool, row: Any): Any?
fun runNonRow(tool: Tool): Any?
fun runMultiple(tool: Tool, rows: List<Any>): Any?
fun copy(): Option
fun toJson(): JsonObject {
val joption = JsonObject()
when (this) {
is GroovyOption -> {
joption.set("type", "groovy")
joption.set("script", script)
}
is TaskOption -> {
joption.set("type", "task")
joption.set("task", task.creationString())
}
else -> {
throw RuntimeException("Unknown Option : $javaClass")
}
}
with(joption) {
set("code", code)
set("label", label)
set("isRow", isRow)
set("isMultiple", isMultiple)
set("prompt", prompt)
set("newTab", newTab)
set("refresh", refresh)
shortcut?.let {
set("keyCode", it.code.toString())
saveModifier(joption, "shift", it.shift)
saveModifier(joption, "control", it.control)
saveModifier(joption, "alt", it.alt)
}
}
if (aliases.size > 0) {
val jaliases = JsonArray()
aliases.forEach { alias ->
jaliases.add(alias)
}
joption.add("aliases", jaliases)
}
if (this is TaskOption) {
val jparameters = JsonHelper.parametersAsJsonArray(task)
joption.add("parameters", jparameters)
}
return joption
}
override fun readExternal(input: ObjectInput) {
val jsonString = input.readObject() as String
val jsonObject = Json.parse(jsonString) as JsonObject
val option = fromJson(jsonObject)
code = option.code
aliases = option.aliases
label = option.label
isRow = option.isRow
isMultiple = option.isMultiple
refresh = option.refresh
newTab = option.newTab
prompt = option.prompt
shortcut = option.shortcut
if (this is TaskOption && option is TaskOption) {
task = option.task
}
if (this is GroovyOption && option is GroovyOption) {
script = option.script
}
}
override fun writeExternal(out: ObjectOutput) {
val jsonString = toJson().toString()
out.writeObject(jsonString)
}
companion object {
val dataFormat = DataFormat("application/x-java-paratask-option-list")
private fun saveModifier(joption: JsonObject, name: String, mod: KeyCombination.ModifierValue) {
if (mod != KeyCombination.ModifierValue.UP) {
joption.set(name, mod.toString())
}
}
fun fromJson(joption: JsonObject): Option {
val type = joption.getString("type", "groovy")
val option: Option
when (type) {
"groovy" -> {
option = GroovyOption(joption.getString("script", ""))
}
"task" -> {
option = TaskOption(joption.getString("task", ""))
}
else -> {
throw RuntimeException("Unknown option type : " + type)
}
}
with(option) {
code = joption.getString("code", "?")
label = joption.getString("label", "")
isRow = joption.getBoolean("isRow", false)
isMultiple = joption.getBoolean("isMultiple", false)
newTab = joption.getBoolean("newTab", false)
prompt = joption.getBoolean("prompt", false)
refresh = joption.getBoolean("refresh", false)
}
val keyCodeS = joption.getString("keyCode", "")
if (keyCodeS == "") {
option.shortcut = null
} else {
val keyCode = KeyCode.valueOf(keyCodeS)
val shiftS = joption.getString("shift", "UP")
val controlS = joption.getString("control", "UP")
val altS = joption.getString("alt", "UP")
val shift = KeyCombination.ModifierValue.valueOf(shiftS)
val control = KeyCombination.ModifierValue.valueOf(controlS)
val alt = KeyCombination.ModifierValue.valueOf(altS)
option.shortcut = KeyCodeCombination(keyCode, shift, control, alt, KeyCombination.ModifierValue.UP, KeyCombination.ModifierValue.UP)
}
val jaliases = joption.get("aliases")
jaliases?.let {
option.aliases = jaliases.asArray().map { it.asString() }.toMutableList()
}
// Load parameter values/expressions for TaskOption
if (option is TaskOption) {
val jparameters = joption.get("parameters").asArray()
JsonHelper.read(jparameters, option.task)
}
return option
}
}
override fun compareTo(other: Option): Int {
return this.label.compareTo(other.label)
}
}
| gpl-3.0 | f6b67d85f8573af47ee7b5b2a7db7fd4 | 31.45098 | 148 | 0.582931 | 4.889217 | false | false | false | false |
wiltonlazary/kotlin-native | utilities/cli-runner/src/main/kotlin/org/jetbrains/kotlin/cli/utilities/InteropCompiler.kt | 1 | 3490 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.cli.utilities
import org.jetbrains.kotlin.cli.bc.SHORT_MODULE_NAME_ARG
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.target.PlatformManager
import org.jetbrains.kotlin.konan.util.KonanHomeProvider
import org.jetbrains.kotlin.native.interop.gen.jvm.InternalInteropOptions
import org.jetbrains.kotlin.native.interop.gen.jvm.interop
import org.jetbrains.kotlin.native.interop.tool.*
// TODO: this function should eventually be eliminated from 'utilities'.
// The interaction of interop and the compiler should be streamlined.
/**
* @return null if there is no need in compiler invocation.
* Otherwise returns array of compiler args.
*/
fun invokeInterop(flavor: String, args: Array<String>): Array<String>? {
val arguments = if (flavor == "native") CInteropArguments() else JSInteropArguments()
arguments.argParser.parse(args)
val outputFileName = arguments.output
val noDefaultLibs = arguments.nodefaultlibs || arguments.nodefaultlibsDeprecated
val noEndorsedLibs = arguments.noendorsedlibs
val purgeUserLibs = arguments.purgeUserLibs
val nopack = arguments.nopack
val temporaryFilesDir = arguments.tempDir
val moduleName = (arguments as? CInteropArguments)?.moduleName
val shortModuleName = (arguments as? CInteropArguments)?.shortModuleName
val buildDir = File("$outputFileName-build")
val generatedDir = File(buildDir, "kotlin")
val nativesDir = File(buildDir,"natives")
val manifest = File(buildDir, "manifest.properties")
val cstubsName ="cstubs"
val libraries = arguments.library
val repos = arguments.repo
val targetRequest = if (arguments is CInteropArguments) arguments.target
else (arguments as JSInteropArguments).target
val target = PlatformManager(KonanHomeProvider.determineKonanHome()).targetManager(targetRequest).target
val cinteropArgsToCompiler = interop(flavor, args,
InternalInteropOptions(generatedDir.absolutePath,
nativesDir.absolutePath,manifest.path,
cstubsName.takeIf { flavor == "native" }
)
) ?: return null // There is no need in compiler invocation if we're generating only metadata.
val nativeStubs =
if (flavor == "wasm")
arrayOf("-include-binary", File(nativesDir, "js_stubs.js").path)
else
arrayOf("-native-library", File(nativesDir, "$cstubsName.bc").path)
return arrayOf(
generatedDir.path,
"-produce", "library",
"-o", outputFileName,
"-target", target.visibleName,
"-manifest", manifest.path,
"-Xtemporary-files-dir=$temporaryFilesDir") +
nativeStubs +
cinteropArgsToCompiler +
libraries.flatMap { listOf("-library", it) } +
repos.flatMap { listOf("-repo", it) } +
(if (noDefaultLibs) arrayOf("-$NODEFAULTLIBS") else emptyArray()) +
(if (noEndorsedLibs) arrayOf("-$NOENDORSEDLIBS") else emptyArray()) +
(if (purgeUserLibs) arrayOf("-$PURGE_USER_LIBS") else emptyArray()) +
(if (nopack) arrayOf("-$NOPACK") else emptyArray()) +
moduleName?.let { arrayOf("-module-name", it) }.orEmpty() +
shortModuleName?.let { arrayOf("$SHORT_MODULE_NAME_ARG=$it") }.orEmpty() +
arguments.kotlincOption
}
| apache-2.0 | d3ecf19e5d81b322dc4998f80996a93f | 43.74359 | 108 | 0.700287 | 4.384422 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/portfolio/IndicatorPortfolioServiceImpl.kt | 1 | 6181 | package net.nemerosa.ontrack.extension.indicators.portfolio
import net.nemerosa.ontrack.extension.indicators.acl.IndicatorPortfolioManagement
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategory
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategoryListener
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategoryService
import net.nemerosa.ontrack.model.labels.Label
import net.nemerosa.ontrack.model.labels.LabelManagementService
import net.nemerosa.ontrack.model.labels.ProjectLabelManagementService
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.StructureService
import net.nemerosa.ontrack.model.support.StorageService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class IndicatorPortfolioServiceImpl(
private val structureService: StructureService,
private val securityService: SecurityService,
private val storageService: StorageService,
private val labelManagementService: LabelManagementService,
private val projectLabelManagementService: ProjectLabelManagementService,
private val indicatorCategoryService: IndicatorCategoryService
) : IndicatorPortfolioService, IndicatorCategoryListener {
init {
indicatorCategoryService.registerCategoryListener(this)
}
override fun onCategoryDeleted(category: IndicatorCategory) {
findAll().forEach { portfolio ->
if (category.id in portfolio.categories) {
val newCategories = portfolio.categories - category.id
updatePortfolio(
portfolio.id,
PortfolioUpdateForm(
categories = newCategories
)
)
}
}
}
override fun createPortfolio(id: String, name: String): IndicatorPortfolio {
securityService.checkGlobalFunction(IndicatorPortfolioManagement::class.java)
val existing = findPortfolioById(id)
if (existing != null) {
throw IndicatorPortfolioIdAlreadyExistingException(id)
} else {
val portfolio = IndicatorPortfolio(
id = id,
name = name,
label = null,
categories = emptyList()
)
storageService.store(STORE, id, portfolio)
return portfolio
}
}
override fun updatePortfolio(id: String, input: PortfolioUpdateForm): IndicatorPortfolio {
securityService.checkGlobalFunction(IndicatorPortfolioManagement::class.java)
val existing = findPortfolioById(id) ?: throw IndicatorPortfolioNotFoundException(id)
val name = if (!input.name.isNullOrBlank()) {
input.name
} else {
existing.name
}
val label = input.label ?: existing.label
val categories = input.categories ?: existing.categories
val newRecord = IndicatorPortfolio(
id = id,
name = name,
label = label,
categories = categories
)
storageService.store(STORE, id, newRecord)
return newRecord
}
override fun deletePortfolio(id: String) {
securityService.checkGlobalFunction(IndicatorPortfolioManagement::class.java)
storageService.delete(STORE, id)
}
override fun getPortfolioLabel(portfolio: IndicatorPortfolio): Label? =
portfolio.label?.let {
labelManagementService.findLabelById(it)
}
override fun getPortfolioProjects(portfolio: IndicatorPortfolio): List<Project> =
getPortfolioLabel(portfolio)?.let { label ->
projectLabelManagementService.getProjectsForLabel(label)
}?.map {
structureService.getProject(it)
} ?: emptyList()
override fun findPortfolioById(id: String): IndicatorPortfolio? {
return storageService.retrieve(STORE, id, IndicatorPortfolio::class.java).orElse(null)
}
override fun findAll(): List<IndicatorPortfolio> {
return storageService.getKeys(STORE).mapNotNull { key ->
storageService.retrieve(STORE, key, IndicatorPortfolio::class.java).orElse(null)
}.sortedBy { it.name }
}
override fun getPortfolioOfPortfolios(): IndicatorPortfolioOfPortfolios {
// Checks we have access to the projects
structureService.projectList
return storageService.retrieve(STORE_PORTFOLIO_OF_PORTFOLIOS, PORTFOLIO_OF_PORTFOLIOS, IndicatorPortfolioOfPortfolios::class.java)
.orElse(IndicatorPortfolioOfPortfolios(
categories = emptyList()
))
}
override fun savePortfolioOfPortfolios(input: PortfolioGlobalIndicators): IndicatorPortfolioOfPortfolios {
val portfolio = IndicatorPortfolioOfPortfolios(
input.categories.filter {
indicatorCategoryService.findCategoryById(it) != null
}
)
storageService.store(STORE_PORTFOLIO_OF_PORTFOLIOS, PORTFOLIO_OF_PORTFOLIOS, portfolio)
return portfolio
}
override fun findPortfolioByProject(project: Project): List<IndicatorPortfolio> {
// Gets the labels for this project
val labels = projectLabelManagementService.getLabelsForProject(project).map { it.id }.toSet()
// Gets all portfolios and filter on label
return if (labels.isEmpty()) {
emptyList()
} else {
findAll().filter { portfolio ->
portfolio.label != null && portfolio.label in labels
}
}
}
companion object {
private val STORE = IndicatorPortfolio::class.java.name
@Deprecated("Use views")
private val STORE_PORTFOLIO_OF_PORTFOLIOS = IndicatorPortfolioOfPortfolios::class.java.name
@Deprecated("Use views")
private const val PORTFOLIO_OF_PORTFOLIOS = "0"
}
} | mit | fbfc63c7e29dea274e4b91f6dd5b3b51 | 40.213333 | 138 | 0.669956 | 5.665445 | false | false | false | false |
jraska/github-client | feature/users/src/main/java/com/jraska/github/client/users/model/GitHubUserRepo.kt | 1 | 618 | package com.jraska.github.client.users.model
import androidx.annotation.Keep
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
@Keep
internal class GitHubUserRepo {
@SerializedName("id")
@Expose
var id: Int? = null
@SerializedName("name")
@Expose
var name: String? = null
@SerializedName("owner")
@Expose
var owner: GitHubUser? = null
@SerializedName("html_url")
@Expose
var description: String? = null
@SerializedName("stargazers_count")
@Expose
var stargazersCount: Int? = null
@SerializedName("forks")
@Expose
var forks: Int? = null
}
| apache-2.0 | 3a37f5959daad63a7d2f12d39da25c08 | 21.888889 | 49 | 0.728155 | 3.838509 | false | false | false | false |
ohmae/mmupnp | mmupnp/src/main/java/net/mm2d/upnp/internal/server/SsdpMessageValidator.kt | 1 | 1735 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.server
import net.mm2d.upnp.Http
import net.mm2d.upnp.SsdpMessage
import net.mm2d.upnp.log.Logger
import java.io.IOException
import java.net.InetAddress
import java.net.URL
internal val DEFAULT_SSDP_MESSAGE_FILTER: (SsdpMessage) -> Boolean = { true }
/**
* A normal URL is described in the Location of SsdpMessage,
* and it is checked whether there is a mismatch between the description address and the packet source address.
*
* @receiver SsdpMessage to check
* @param sourceAddress source address
* @return true: if there is an invalid Location, such as a mismatch with the sender. false: otherwise
*/
internal fun SsdpMessage.hasInvalidLocation(sourceAddress: InetAddress): Boolean =
(!hasValidLocation(sourceAddress)).also {
if (it) Logger.w { "Location: $location is invalid from $sourceAddress" }
}
private fun SsdpMessage.hasValidLocation(sourceAddress: InetAddress): Boolean {
val location = location ?: return false
if (!Http.isHttpUrl(location)) return false
try {
return sourceAddress == InetAddress.getByName(URL(location).host)
} catch (ignored: IOException) {
}
return false
}
internal fun SsdpMessage.isNotUpnp(): Boolean {
if (getHeader("X-TelepathyAddress.sony.com") != null) {
// Sony telepathy service(urn:schemas-sony-com:service:X_Telepathy:1) send ssdp packet,
// but its location address refuses connection. Since this is not correct as UPnP, ignore it.
Logger.v("ignore sony telepathy service")
return true
}
return false
}
| mit | dafcd651777e3d0fbe0cd8c136253319 | 33.54 | 111 | 0.723798 | 3.89842 | false | false | false | false |
samtstern/quickstart-android | auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GoogleSignInActivity.kt | 1 | 6331 | package com.google.firebase.quickstart.auth.kotlin
import android.content.Intent
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import android.util.Log
import android.view.View
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.R
import com.google.firebase.quickstart.auth.databinding.ActivityGoogleBinding
/**
* Demonstrate Firebase Authentication using a Google ID Token.
*/
class GoogleSignInActivity : BaseActivity(), View.OnClickListener {
// [START declare_auth]
private lateinit var auth: FirebaseAuth
// [END declare_auth]
private lateinit var binding: ActivityGoogleBinding
private lateinit var googleSignInClient: GoogleSignInClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityGoogleBinding.inflate(layoutInflater)
setContentView(binding.root)
setProgressBar(binding.progressBar)
// Button listeners
binding.signInButton.setOnClickListener(this)
binding.signOutButton.setOnClickListener(this)
binding.disconnectButton.setOnClickListener(this)
// [START config_signin]
// Configure Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
// [END config_signin]
googleSignInClient = GoogleSignIn.getClient(this, gso)
// [START initialize_auth]
// Initialize Firebase Auth
auth = Firebase.auth
// [END initialize_auth]
}
// [START on_start_check_user]
override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
// [END on_start_check_user]
// [START onactivityresult]
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
// [START_EXCLUDE]
updateUI(null)
// [END_EXCLUDE]
}
}
}
// [END onactivityresult]
// [START auth_with_google]
private fun firebaseAuthWithGoogle(idToken: String) {
// [START_EXCLUDE silent]
showProgressBar()
// [END_EXCLUDE]
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
// [START_EXCLUDE]
val view = binding.mainLayout
// [END_EXCLUDE]
Snackbar.make(view, "Authentication Failed.", Snackbar.LENGTH_SHORT).show()
updateUI(null)
}
// [START_EXCLUDE]
hideProgressBar()
// [END_EXCLUDE]
}
}
// [END auth_with_google]
// [START signin]
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
// [END signin]
private fun signOut() {
// Firebase sign out
auth.signOut()
// Google sign out
googleSignInClient.signOut().addOnCompleteListener(this) {
updateUI(null)
}
}
private fun revokeAccess() {
// Firebase sign out
auth.signOut()
// Google revoke access
googleSignInClient.revokeAccess().addOnCompleteListener(this) {
updateUI(null)
}
}
private fun updateUI(user: FirebaseUser?) {
hideProgressBar()
if (user != null) {
binding.status.text = getString(R.string.google_status_fmt, user.email)
binding.detail.text = getString(R.string.firebase_status_fmt, user.uid)
binding.signInButton.visibility = View.GONE
binding.signOutAndDisconnect.visibility = View.VISIBLE
} else {
binding.status.setText(R.string.signed_out)
binding.detail.text = null
binding.signInButton.visibility = View.VISIBLE
binding.signOutAndDisconnect.visibility = View.GONE
}
}
override fun onClick(v: View) {
when (v.id) {
R.id.signInButton -> signIn()
R.id.signOutButton -> signOut()
R.id.disconnectButton -> revokeAccess()
}
}
companion object {
private const val TAG = "GoogleActivity"
private const val RC_SIGN_IN = 9001
}
}
| apache-2.0 | 2c6b97f3e9042625719fbb764ca8166d | 34.768362 | 99 | 0.61728 | 4.896365 | false | false | false | false |
material-components/material-components-android-motion-codelab | app/src/main/java/com/materialstudies/reply/ui/email/EmailFragment.kt | 1 | 2866 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.email
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.GridLayoutManager
import com.materialstudies.reply.data.EmailStore
import com.materialstudies.reply.databinding.FragmentEmailBinding
import kotlin.LazyThreadSafetyMode.NONE
private const val MAX_GRID_SPANS = 3
/**
* A [Fragment] which displays a single, full email.
*/
class EmailFragment : Fragment() {
private val args: EmailFragmentArgs by navArgs()
private val emailId: Long by lazy(NONE) { args.emailId }
private lateinit var binding: FragmentEmailBinding
private val attachmentAdapter = EmailAttachmentGridAdapter(MAX_GRID_SPANS)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// TODO: Set up MaterialContainerTransform transition as sharedElementEnterTransition.
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentEmailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.navigationIcon.setOnClickListener {
findNavController().navigateUp()
}
val email = EmailStore.get(emailId)
if (email == null) {
showError()
return
}
binding.run {
this.email = email
// Set up the staggered/masonry grid recycler
attachmentRecyclerView.layoutManager = GridLayoutManager(
requireContext(),
MAX_GRID_SPANS
).apply {
spanSizeLookup = attachmentAdapter.variableSpanSizeLookup
}
attachmentRecyclerView.adapter = attachmentAdapter
attachmentAdapter.submitList(email.attachments)
}
}
private fun showError() {
// Do nothing
}
} | apache-2.0 | ca040bcee161f5ad8c8a20dd9cfbcc6b | 30.855556 | 94 | 0.701326 | 4.993031 | false | false | false | false |
cashapp/sqldelight | sqldelight-gradle-plugin/src/test/kotlin/app/cash/sqldelight/tests/CompilationUnitTests.kt | 1 | 20031 | package app.cash.sqldelight.tests
import app.cash.sqldelight.gradle.SqlDelightCompilationUnitImpl
import app.cash.sqldelight.gradle.SqlDelightDatabasePropertiesImpl
import app.cash.sqldelight.gradle.SqlDelightSourceFolderImpl
import app.cash.sqldelight.withTemporaryFixture
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import java.io.File
class CompilationUnitTests {
@Test
fun `JVM kotlin`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'org.jetbrains.kotlin.jvm'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).hasSize(1)
val database = properties.databases[0]
assertThat(database.className).isEqualTo("CommonDb")
assertThat(database.packageName).isEqualTo("com.sample")
assertThat(database.compilationUnits).containsExactly(
SqlDelightCompilationUnitImpl(
name = "main",
sourceFolders = listOf(SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false)),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb"),
),
)
}
}
}
@Test
fun `JVM kotlin with multiple databases`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'org.jetbrains.kotlin.jvm'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|
| OtherDb {
| packageName = "com.sample.otherdb"
| sourceFolders = ["sqldelight", "otherdb"]
| treatNullAsUnknownForEquality = true
| }
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).containsExactly(
SqlDelightDatabasePropertiesImpl(
className = "CommonDb",
packageName = "com.sample",
compilationUnits = listOf(
SqlDelightCompilationUnitImpl(
name = "main",
sourceFolders = listOf(SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false)),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb"),
),
),
dependencies = emptyList(),
rootDirectory = fixtureRoot,
),
SqlDelightDatabasePropertiesImpl(
className = "OtherDb",
packageName = "com.sample.otherdb",
compilationUnits = listOf(
SqlDelightCompilationUnitImpl(
name = "main",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/otherdb"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/OtherDb"),
),
),
dependencies = emptyList(),
rootDirectory = fixtureRoot,
treatNullAsUnknownForEquality = true,
),
)
}
}
}
@Test
fun `Multiplatform project with multiple targets`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'org.jetbrains.kotlin.multiplatform'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|}
|
|kotlin {
| targetFromPreset(presets.jvm, 'jvm')
| targetFromPreset(presets.js, 'js')
| targetFromPreset(presets.iosArm32, 'iosArm32')
| targetFromPreset(presets.iosArm64, 'iosArm64')
| targetFromPreset(presets.iosX64, 'iosX64')
| targetFromPreset(presets.macosX64, 'macosX64')
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).hasSize(1)
val database = properties.databases[0]
assertThat(database.className).isEqualTo("CommonDb")
assertThat(database.packageName).isEqualTo("com.sample")
assertThat(database.compilationUnits).containsExactly(
SqlDelightCompilationUnitImpl(
name = "commonMain",
sourceFolders = listOf(SqlDelightSourceFolderImpl(File(fixtureRoot, "src/commonMain/sqldelight"), false)),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb"),
),
)
}
}
}
@Test
fun `Multiplatform project with android and ios targets`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'org.jetbrains.kotlin.multiplatform'
|apply plugin: 'com.android.application'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|}
|
|android {
| compileSdk libs.versions.compileSdk.get() as int
|
| buildTypes {
| release {}
| sqldelight {}
| }
|
| flavorDimensions "api", "mode"
|
| productFlavors {
| demo {
| applicationIdSuffix ".demo"
| dimension "mode"
| }
| full {
| applicationIdSuffix ".full"
| dimension "mode"
| }
| minApi21 {
| dimension "api"
| }
| minApi23 {
| dimension "api"
| }
| }
|}
|
|kotlin {
| targetFromPreset(presets.iosX64, 'iosX64')
| targetFromPreset(presets.android, 'androidLib')
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).hasSize(1)
val database = properties.databases[0]
assertThat(database.className).isEqualTo("CommonDb")
assertThat(database.packageName).isEqualTo("com.sample")
assertThat(database.compilationUnits).containsExactly(
SqlDelightCompilationUnitImpl(
name = "commonMain",
sourceFolders = listOf(SqlDelightSourceFolderImpl(File(fixtureRoot, "src/commonMain/sqldelight"), false)),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb"),
),
)
}
}
}
@Test
fun `android project with multiple flavors`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'com.android.application'
|apply plugin: 'org.jetbrains.kotlin.android'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|}
|
|android {
| compileSdk libs.versions.compileSdk.get() as int
|
| buildTypes {
| release {}
| sqldelight {}
| }
|
| flavorDimensions "api", "mode"
|
| productFlavors {
| demo {
| applicationIdSuffix ".demo"
| dimension "mode"
| }
| full {
| applicationIdSuffix ".full"
| dimension "mode"
| }
| minApi21 {
| dimension "api"
| }
| minApi23 {
| dimension "api"
| }
| }
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).hasSize(1)
val database = properties.databases[0]
assertThat(database.className).isEqualTo("CommonDb")
assertThat(database.packageName).isEqualTo("com.sample")
assertThat(database.compilationUnits).containsExactly(
SqlDelightCompilationUnitImpl(
name = "minApi23DemoDebug",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23DemoDebug/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23DemoDebug"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23DemoRelease",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23DemoRelease/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23DemoRelease"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23DemoSqldelight",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23DemoSqldelight/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/sqldelight/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23DemoSqldelight"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23FullDebug",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23FullDebug/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23FullDebug"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23FullRelease",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23FullRelease/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23FullRelease"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23FullSqldelight",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23FullSqldelight/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/sqldelight/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23FullSqldelight"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21DemoDebug",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21DemoDebug/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21DemoDebug"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21DemoRelease",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21DemoRelease/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21DemoRelease"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21DemoSqldelight",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21DemoSqldelight/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/sqldelight/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21DemoSqldelight"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21FullDebug",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21FullDebug/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21FullDebug"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21FullRelease",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21FullRelease/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21FullRelease"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21FullSqldelight",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21FullSqldelight/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/sqldelight/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21FullSqldelight"),
),
)
}
}
}
}
| apache-2.0 | d3fb29c96f202a53ea0682a93b3f32e3 | 42.263499 | 119 | 0.608607 | 5.360182 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/RxAutoImageView.kt | 1 | 1492 | package com.tamsiree.rxui.view
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.ImageView
import com.tamsiree.rxui.R
/**
* @author tamsiree
* 自动左右平滑移动的ImageView
*/
class RxAutoImageView : FrameLayout {
private var mImageView: ImageView? = null
var resId = 0
constructor(context: Context?) : super(context!!)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
//导入布局
initView(context, attrs)
}
private fun initView(context: Context, attrs: AttributeSet?) {
LayoutInflater.from(context).inflate(R.layout.layout_auto_imageview, this)
mImageView = findViewById(R.id.img_backgroud)
//获得这个控件对应的属性。
val a = getContext().obtainStyledAttributes(attrs, R.styleable.RxAutoImageView)
resId = try {
//获得属性值
a.getResourceId(R.styleable.RxAutoImageView_ImageSrc, 0)
} finally {
//回收这个对象
a.recycle()
}
if (resId != 0) {
mImageView?.setImageResource(resId)
}
Handler().postDelayed({
val animation = AnimationUtils.loadAnimation(context, R.anim.translate_anim)
mImageView?.startAnimation(animation)
}, 200)
}
} | apache-2.0 | 9da98b20d1b32f87f3581e5ea9b86bec | 29.234043 | 88 | 0.664789 | 4.264264 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/model/parsers/SourceCardDataJsonParser.kt | 1 | 2443 | package com.stripe.android.model.parsers
import com.stripe.android.core.model.StripeJsonUtils
import com.stripe.android.core.model.parsers.ModelJsonParser
import com.stripe.android.model.Card
import com.stripe.android.model.CardFunding
import com.stripe.android.model.SourceTypeModel
import com.stripe.android.model.TokenizationMethod
import org.json.JSONObject
internal class SourceCardDataJsonParser : ModelJsonParser<SourceTypeModel.Card> {
override fun parse(json: JSONObject): SourceTypeModel.Card {
return SourceTypeModel.Card(
addressLine1Check = StripeJsonUtils.optString(json, FIELD_ADDRESS_LINE1_CHECK),
addressZipCheck = StripeJsonUtils.optString(json, FIELD_ADDRESS_ZIP_CHECK),
brand = Card.getCardBrand(StripeJsonUtils.optString(json, FIELD_BRAND)),
country = StripeJsonUtils.optString(json, FIELD_COUNTRY),
cvcCheck = StripeJsonUtils.optString(json, FIELD_CVC_CHECK),
dynamicLast4 = StripeJsonUtils.optString(json, FIELD_DYNAMIC_LAST4),
expiryMonth = StripeJsonUtils.optInteger(json, FIELD_EXP_MONTH),
expiryYear = StripeJsonUtils.optInteger(json, FIELD_EXP_YEAR),
funding = CardFunding.fromCode(StripeJsonUtils.optString(json, FIELD_FUNDING)),
last4 = StripeJsonUtils.optString(json, FIELD_LAST4),
threeDSecureStatus = SourceTypeModel.Card.ThreeDSecureStatus.fromCode(
StripeJsonUtils.optString(json, FIELD_THREE_D_SECURE)
),
tokenizationMethod = TokenizationMethod.fromCode(
StripeJsonUtils.optString(json, FIELD_TOKENIZATION_METHOD)
)
)
}
internal companion object {
private const val FIELD_ADDRESS_LINE1_CHECK = "address_line1_check"
private const val FIELD_ADDRESS_ZIP_CHECK = "address_zip_check"
private const val FIELD_BRAND = "brand"
private const val FIELD_COUNTRY = "country"
private const val FIELD_CVC_CHECK = "cvc_check"
private const val FIELD_DYNAMIC_LAST4 = "dynamic_last4"
private const val FIELD_EXP_MONTH = "exp_month"
private const val FIELD_EXP_YEAR = "exp_year"
private const val FIELD_FUNDING = "funding"
private const val FIELD_LAST4 = "last4"
private const val FIELD_THREE_D_SECURE = "three_d_secure"
private const val FIELD_TOKENIZATION_METHOD = "tokenization_method"
}
}
| mit | e55c62549f273627ba88fe92558743fe | 50.978723 | 91 | 0.704462 | 4.385996 | false | false | false | false |
stripe/stripe-android | financial-connections/src/test/java/com/stripe/android/financialconnections/analytics/DefaultConnectionsEventReportTest.kt | 1 | 4764 | package com.stripe.android.financialconnections.analytics
import android.app.Application
import androidx.test.core.app.ApplicationProvider
import com.stripe.android.core.networking.AnalyticsRequestExecutor
import com.stripe.android.core.networking.AnalyticsRequestFactory
import com.stripe.android.financialconnections.ApiKeyFixtures
import com.stripe.android.financialconnections.FinancialConnectionsSheet
import com.stripe.android.financialconnections.launcher.FinancialConnectionsSheetActivityResult
import com.stripe.android.financialconnections.model.FinancialConnectionsAccountList
import com.stripe.android.financialconnections.model.FinancialConnectionsSession
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.argWhere
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.robolectric.RobolectricTestRunner
@ExperimentalCoroutinesApi
@RunWith(RobolectricTestRunner::class)
class DefaultConnectionsEventReportTest {
private val testDispatcher = UnconfinedTestDispatcher()
private val application = ApplicationProvider.getApplicationContext<Application>()
private val analyticsRequestExecutor = mock<AnalyticsRequestExecutor>()
private val analyticsRequestFactory = AnalyticsRequestFactory(
packageManager = application.packageManager,
packageName = application.packageName.orEmpty(),
packageInfo = application.packageManager.getPackageInfo(application.packageName, 0),
publishableKeyProvider = { ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY }
)
private val eventReporter = DefaultFinancialConnectionsEventReporter(
analyticsRequestExecutor,
analyticsRequestFactory,
testDispatcher
)
private val configuration = FinancialConnectionsSheet.Configuration(
ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET,
ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY
)
private val financialConnectionsSession = FinancialConnectionsSession(
clientSecret = "las_1234567890",
id = ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET,
accountsNew = FinancialConnectionsAccountList(
data = emptyList(),
hasMore = false,
url = "url",
count = 0
),
livemode = true
)
@Test
fun `onPresented() should fire analytics request with expected event value`() {
eventReporter.onPresented(configuration)
verify(analyticsRequestExecutor).executeAsync(
argWhere { req ->
req.params["event"] == "stripe_android.connections.sheet.presented" &&
req.params["las_client_secret"] == ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET
}
)
}
@Test
fun `onResult() should fire analytics request with expected event value for success`() {
eventReporter.onResult(
configuration,
FinancialConnectionsSheetActivityResult.Completed(
financialConnectionsSession = financialConnectionsSession
)
)
verify(analyticsRequestExecutor).executeAsync(
argWhere { req ->
req.params["event"] == "stripe_android.connections.sheet.closed" &&
req.params["session_result"] == "completed" &&
req.params["las_client_secret"] == ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET
}
)
}
@Test
fun `onResult() should fire analytics request with expected event value for cancelled`() {
eventReporter.onResult(configuration, FinancialConnectionsSheetActivityResult.Canceled)
verify(analyticsRequestExecutor).executeAsync(
argWhere { req ->
req.params["event"] == "stripe_android.connections.sheet.closed" &&
req.params["session_result"] == "cancelled" &&
req.params["las_client_secret"] == ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET
}
)
}
@Test
fun `onResult() should fire analytics request with expected event value for failure`() {
eventReporter.onResult(configuration, FinancialConnectionsSheetActivityResult.Failed(Exception()))
verify(analyticsRequestExecutor).executeAsync(
argWhere { req ->
req.params["event"] == "stripe_android.connections.sheet.failed" &&
req.params["session_result"] == "failure" &&
req.params["las_client_secret"] == ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET
}
)
}
}
| mit | ccb362b0eb5cd2a1480679dcd2affea7 | 42.706422 | 114 | 0.707599 | 5.664685 | false | true | false | false |
stripe/stripe-android | stripe-core/src/main/java/com/stripe/android/core/networking/ConnectionFactory.kt | 1 | 2722 | package com.stripe.android.core.networking
import androidx.annotation.RestrictTo
import com.stripe.android.core.exception.InvalidRequestException
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Factory to create [StripeConnection], which encapsulates an [HttpURLConnection], triggers the
* request and parses the response with different body type as [StripeResponse].
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
interface ConnectionFactory {
/**
* Creates an [StripeConnection] which attempts to parse the http response body as a [String].
*/
@Throws(IOException::class, InvalidRequestException::class)
fun create(request: StripeRequest): StripeConnection<String>
/**
* Creates an [StripeConnection] which attempts to parse the http response body as a [File].
*/
@Throws(IOException::class, InvalidRequestException::class)
fun createForFile(request: StripeRequest, outputFile: File): StripeConnection<File>
object Default : ConnectionFactory {
@Throws(IOException::class, InvalidRequestException::class)
@JvmSynthetic
override fun create(request: StripeRequest): StripeConnection<String> {
return StripeConnection.Default(openConnectionAndApplyFields(request))
}
override fun createForFile(
request: StripeRequest,
outputFile: File
): StripeConnection<File> {
return StripeConnection.FileConnection(
openConnectionAndApplyFields(request),
outputFile
)
}
private fun openConnectionAndApplyFields(request: StripeRequest): HttpURLConnection {
return (URL(request.url).openConnection() as HttpURLConnection).apply {
connectTimeout = CONNECT_TIMEOUT
readTimeout = READ_TIMEOUT
useCaches = request.shouldCache
requestMethod = request.method.code
request.headers.forEach { (key, value) ->
setRequestProperty(key, value)
}
if (StripeRequest.Method.POST == request.method) {
doOutput = true
request.postHeaders?.forEach { (key, value) ->
setRequestProperty(key, value)
}
outputStream.use { output -> request.writePostBody(output) }
}
}
}
}
private companion object {
private val CONNECT_TIMEOUT = TimeUnit.SECONDS.toMillis(30).toInt()
private val READ_TIMEOUT = TimeUnit.SECONDS.toMillis(80).toInt()
}
}
| mit | bb7846c6051c0061379995bd58c9ac26 | 36.805556 | 98 | 0.649155 | 5.32681 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/model/PaymentIntent.kt | 1 | 14960 | package com.stripe.android.model
import androidx.annotation.RestrictTo
import com.stripe.android.core.model.StripeJsonUtils
import com.stripe.android.core.model.StripeModel
import com.stripe.android.model.PaymentIntent.CaptureMethod
import com.stripe.android.model.PaymentIntent.ConfirmationMethod
import com.stripe.android.model.parsers.PaymentIntentJsonParser
import kotlinx.parcelize.Parcelize
import org.json.JSONObject
import java.util.regex.Pattern
/**
* A [PaymentIntent] tracks the process of collecting a payment from your customer.
*
* - [Payment Intents Overview](https://stripe.com/docs/payments/payment-intents)
* - [PaymentIntents API Reference](https://stripe.com/docs/api/payment_intents)
*/
@Parcelize
data class PaymentIntent internal constructor(
/**
* Unique identifier for the object.
*/
override val id: String?,
/**
* The list of payment method types (e.g. card) that this [PaymentIntent] is allowed to
* use.
*/
override val paymentMethodTypes: List<String>,
/**
* Amount intended to be collected by this [PaymentIntent]. A positive integer
* representing how much to charge in the smallest currency unit (e.g., 100 cents to charge
* $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or
* equivalent in charge currency. The amount value supports up to eight digits (e.g., a value
* of 99999999 for a USD charge of $999,999.99).
*/
val amount: Long?,
/**
* Populated when `status` is `canceled`, this is the time at which the [PaymentIntent]
* was canceled. Measured in seconds since the Unix epoch. If unavailable, will return 0.
*/
val canceledAt: Long = 0L,
/**
* Reason for cancellation of this [PaymentIntent].
*/
val cancellationReason: CancellationReason? = null,
/**
* Controls when the funds will be captured from the customer’s account.
* See [CaptureMethod].
*/
val captureMethod: CaptureMethod = CaptureMethod.Automatic,
/**
* The client secret of this [PaymentIntent]. Used for client-side retrieval using a
* publishable key.
*
* The client secret can be used to complete a payment from your frontend.
* It should not be stored, logged, embedded in URLs, or exposed to anyone other than the
* customer. Make sure that you have TLS enabled on any page that includes the client
* secret.
*/
override val clientSecret: String?,
/**
* One of automatic (default) or manual. See [ConfirmationMethod].
*
* When [confirmationMethod] is `automatic`, a [PaymentIntent] can be confirmed
* using a publishable key. After `next_action`s are handled, no additional
* confirmation is required to complete the payment.
*
* When [confirmationMethod] is `manual`, all payment attempts must be made
* using a secret key. The [PaymentIntent] returns to the
* [RequiresConfirmation][StripeIntent.Status.RequiresConfirmation]
* state after handling `next_action`s, and requires your server to initiate each
* payment attempt with an explicit confirmation.
*/
val confirmationMethod: ConfirmationMethod = ConfirmationMethod.Automatic,
/**
* Country code of the user.
*/
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
val countryCode: String?,
/**
* Time at which the object was created. Measured in seconds since the Unix epoch.
*/
override val created: Long,
/**
* Three-letter ISO currency code, in lowercase. Must be a supported currency.
*/
val currency: String?,
/**
* An arbitrary string attached to the object. Often useful for displaying to users.
*/
override val description: String? = null,
/**
* Has the value `true` if the object exists in live mode or the value
* `false` if the object exists in test mode.
*/
override val isLiveMode: Boolean,
override val paymentMethod: PaymentMethod? = null,
/**
* ID of the payment method (a PaymentMethod, Card, BankAccount, or saved Source object)
* to attach to this [PaymentIntent].
*/
override val paymentMethodId: String? = null,
/**
* Email address that the receipt for the resulting payment will be sent to.
*/
val receiptEmail: String? = null,
/**
* Status of this [PaymentIntent].
*/
override val status: StripeIntent.Status? = null,
val setupFutureUsage: StripeIntent.Usage? = null,
/**
* The payment error encountered in the previous [PaymentIntent] confirmation.
*/
val lastPaymentError: Error? = null,
/**
* Shipping information for this [PaymentIntent].
*/
val shipping: Shipping? = null,
/**
* Payment types that have not been activated in livemode, but have been activated in testmode.
*/
override val unactivatedPaymentMethods: List<String>,
/**
* Payment types that are accepted when paying with Link.
*/
override val linkFundingSources: List<String> = emptyList(),
override val nextActionData: StripeIntent.NextActionData? = null,
private val paymentMethodOptionsJsonString: String? = null
) : StripeIntent {
fun getPaymentMethodOptions() = paymentMethodOptionsJsonString?.let {
StripeJsonUtils.jsonObjectToMap(JSONObject(it))
} ?: emptyMap()
override val nextActionType: StripeIntent.NextActionType?
get() = when (nextActionData) {
is StripeIntent.NextActionData.SdkData -> {
StripeIntent.NextActionType.UseStripeSdk
}
is StripeIntent.NextActionData.RedirectToUrl -> {
StripeIntent.NextActionType.RedirectToUrl
}
is StripeIntent.NextActionData.DisplayOxxoDetails -> {
StripeIntent.NextActionType.DisplayOxxoDetails
}
is StripeIntent.NextActionData.VerifyWithMicrodeposits -> {
StripeIntent.NextActionType.VerifyWithMicrodeposits
}
is StripeIntent.NextActionData.UpiAwaitNotification -> {
StripeIntent.NextActionType.UpiAwaitNotification
}
is StripeIntent.NextActionData.AlipayRedirect,
is StripeIntent.NextActionData.BlikAuthorize,
is StripeIntent.NextActionData.WeChatPayRedirect,
null -> {
null
}
}
override val isConfirmed: Boolean
get() = setOf(
StripeIntent.Status.Processing,
StripeIntent.Status.RequiresCapture,
StripeIntent.Status.Succeeded
).contains(status)
override val lastErrorMessage: String?
get() = lastPaymentError?.message
override fun requiresAction(): Boolean {
return status === StripeIntent.Status.RequiresAction
}
override fun requiresConfirmation(): Boolean {
return status === StripeIntent.Status.RequiresConfirmation
}
/**
* SetupFutureUsage is considered to be set if it is on or off session.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
private fun isTopLevelSetupFutureUsageSet() =
when (setupFutureUsage) {
StripeIntent.Usage.OnSession -> true
StripeIntent.Usage.OffSession -> true
StripeIntent.Usage.OneTime -> false
null -> false
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun isLpmLevelSetupFutureUsageSet(code: PaymentMethodCode): Boolean {
return isTopLevelSetupFutureUsageSet() || paymentMethodOptionsJsonString?.let {
JSONObject(paymentMethodOptionsJsonString)
.optJSONObject(code)
?.optString("setup_future_usage")?.let {
true
} ?: false
} ?: false
}
/**
* The payment error encountered in the previous [PaymentIntent] confirmation.
*
* See [last_payment_error](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error).
*/
@Parcelize
data class Error internal constructor(
/**
* For card errors, the ID of the failed charge.
*/
val charge: String?,
/**
* For some errors that could be handled programmatically, a short string indicating the
* [error code](https://stripe.com/docs/error-codes) reported.
*/
val code: String?,
/**
* For card errors resulting from a card issuer decline, a short string indicating the
* [card issuer’s reason for the decline](https://stripe.com/docs/declines#issuer-declines)
* if they provide one.
*/
val declineCode: String?,
/**
* A URL to more information about the
* [error code](https://stripe.com/docs/error-codes) reported.
*/
val docUrl: String?,
/**
* A human-readable message providing more details about the error. For card errors,
* these messages can be shown to your users.
*/
val message: String?,
/**
* If the error is parameter-specific, the parameter related to the error.
* For example, you can use this to display a message near the correct form field.
*/
val param: String?,
/**
* The PaymentMethod object for errors returned on a request involving a PaymentMethod.
*/
val paymentMethod: PaymentMethod?,
/**
* The type of error returned.
*/
val type: Type?
) : StripeModel {
enum class Type(val code: String) {
ApiConnectionError("api_connection_error"),
ApiError("api_error"),
AuthenticationError("authentication_error"),
CardError("card_error"),
IdempotencyError("idempotency_error"),
InvalidRequestError("invalid_request_error"),
RateLimitError("rate_limit_error");
internal companion object {
fun fromCode(typeCode: String?) = values().firstOrNull { it.code == typeCode }
}
}
internal companion object {
internal const val CODE_AUTHENTICATION_ERROR = "payment_intent_authentication_failure"
}
}
/**
* Shipping information for this [PaymentIntent].
*
* See [shipping](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping)
*/
@Parcelize
data class Shipping(
/**
* Shipping address.
*
* See [shipping.address](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-address)
*/
val address: Address,
/**
* The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.
*
* See [shipping.carrier](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-carrier)
*/
val carrier: String? = null,
/**
* Recipient name.
*
* See [shipping.name](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-name)
*/
val name: String? = null,
/**
* Recipient phone (including extension).
*
* See [shipping.phone](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-phone)
*/
val phone: String? = null,
/**
* The tracking number for a physical product, obtained from the delivery service.
* If multiple tracking numbers were generated for this purchase, please separate them
* with commas.
*
* See [shipping.tracking_number](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-tracking_number)
*/
val trackingNumber: String? = null
) : StripeModel
internal data class ClientSecret(internal val value: String) {
internal val paymentIntentId: String =
value.split("_secret".toRegex())
.dropLastWhile { it.isEmpty() }.toTypedArray()[0]
init {
require(isMatch(value)) {
"Invalid Payment Intent client secret: $value"
}
}
internal companion object {
private val PATTERN = Pattern.compile("^pi_[^_]+_secret_[^_]+$")
fun isMatch(value: String) = PATTERN.matcher(value).matches()
}
}
/**
* Reason for cancellation of this [PaymentIntent], either user-provided (duplicate, fraudulent,
* requested_by_customer, or abandoned) or generated by Stripe internally (failed_invoice,
* void_invoice, or automatic).
*/
enum class CancellationReason(private val code: String) {
Duplicate("duplicate"),
Fraudulent("fraudulent"),
RequestedByCustomer("requested_by_customer"),
Abandoned("abandoned"),
FailedInvoice("failed_invoice"),
VoidInvoice("void_invoice"),
Automatic("automatic");
internal companion object {
fun fromCode(code: String?) = values().firstOrNull { it.code == code }
}
}
/**
* Controls when the funds will be captured from the customer’s account.
*/
enum class CaptureMethod(private val code: String) {
/**
* (Default) Stripe automatically captures funds when the customer authorizes the payment.
*/
Automatic("automatic"),
/**
* Place a hold on the funds when the customer authorizes the payment, but don’t capture
* the funds until later. (Not all payment methods support this.)
*/
Manual("manual");
internal companion object {
fun fromCode(code: String?) = values().firstOrNull { it.code == code } ?: Automatic
}
}
enum class ConfirmationMethod(private val code: String) {
/**
* (Default) PaymentIntent can be confirmed using a publishable key. After `next_action`s
* are handled, no additional confirmation is required to complete the payment.
*/
Automatic("automatic"),
/**
* All payment attempts must be made using a secret key. The PaymentIntent returns to the
* `requires_confirmation` state after handling `next_action`s, and requires your server to
* initiate each payment attempt with an explicit confirmation.
*/
Manual("manual");
internal companion object {
fun fromCode(code: String?) = values().firstOrNull { it.code == code } ?: Automatic
}
}
companion object {
@JvmStatic
fun fromJson(jsonObject: JSONObject?): PaymentIntent? {
return jsonObject?.let {
PaymentIntentJsonParser().parse(it)
}
}
}
}
| mit | 0b72e9c308ea7f331913f3187513082f | 33.932243 | 140 | 0.632199 | 4.840078 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/intentions/AddRemainingArmsIntention.kt | 3 | 2182 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.ide.inspections.fixes.AddRemainingArmsFix
import org.rust.ide.utils.checkMatch.Pattern
import org.rust.ide.utils.checkMatch.checkExhaustive
import org.rust.lang.core.psi.RsMatchBody
import org.rust.lang.core.psi.RsMatchExpr
open class AddRemainingArmsIntention : RsElementBaseIntentionAction<AddRemainingArmsIntention.Context>() {
override fun getText(): String = AddRemainingArmsFix.NAME
override fun getFamilyName(): String = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val matchExpr = when (val parent = element.context) {
is RsMatchExpr -> parent
is RsMatchBody -> parent.context as? RsMatchExpr
else -> null
} ?: return null
val textRange = matchExpr.match.textRange
val caretOffset = editor.caretModel.offset
// `RsNonExhaustiveMatchInspection` register its quick fixes only for `match` keyword.
// At the same time, platform shows these quick fixes even when caret is located just after the keyword,
// i.e. `match/*caret*/`.
// So disable this intention for such range not to provide two the same actions to a user
if (caretOffset >= textRange.startOffset && caretOffset <= textRange.endOffset) return null
val patterns = matchExpr.checkExhaustive() ?: return null
return Context(matchExpr, patterns)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (matchExpr, patterns) = ctx
createQuickFix(matchExpr, patterns).invoke(project, matchExpr.containingFile, matchExpr, matchExpr)
}
protected open fun createQuickFix(matchExpr: RsMatchExpr, patterns: List<Pattern>): AddRemainingArmsFix {
return AddRemainingArmsFix(matchExpr, patterns)
}
data class Context(val matchExpr: RsMatchExpr, val patterns: List<Pattern>)
}
| mit | afbf6d2fffaffc6f1aecf72824f113d2 | 41.784314 | 112 | 0.726856 | 4.652452 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/dialogs/WonChallengeDialog.kt | 1 | 1769 | package com.habitrpg.android.habitica.ui.views.dialogs
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.fromHtml
import com.habitrpg.android.habitica.models.notifications.ChallengeWonData
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
class WonChallengeDialog(context: Context) : HabiticaAlertDialog(context) {
fun configure(data: ChallengeWonData?) {
val imageView = additionalContentView?.findViewById<ImageView>(R.id.achievement_view)
DataBindingUtils.loadImage(imageView, "achievement-karaoke-2x")
if (data?.name != null) {
additionalContentView?.findViewById<TextView>(R.id.description_view)?.text = context.getString(R.string.won_achievement_description, data.name).fromHtml()
}
if ((data?.prize ?: 0) > 0) {
addButton(context.getString(R.string.claim_x_gems, data?.prize), true)
additionalContentView?.findViewById<ImageView>(R.id.achievement_confetti_left)?.visibility = View.GONE
additionalContentView?.findViewById<ImageView>(R.id.achievement_confetti_right)?.visibility = View.GONE
} else {
addButton(R.string.hurray, true)
additionalContentView?.findViewById<ImageView>(R.id.achievement_confetti_view)?.visibility = View.GONE
}
}
init {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as? LayoutInflater
val view = inflater?.inflate(R.layout.dialog_won_challenge, null)
setTitle(R.string.you_won_challenge)
setAdditionalContentView(view)
}
}
| gpl-3.0 | 9023bc59e7495209ac1aa2296d45caf1 | 46.810811 | 166 | 0.733748 | 4.325183 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/exercise-solutions/card-game/part-08/cards/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/cards/CardCollection.kt | 2 | 2995 | package org.tsdes.advanced.exercises.cardgame.cards
import org.tsdes.advanced.exercises.cardgame.cards.dto.CardDto
import org.tsdes.advanced.exercises.cardgame.cards.dto.CollectionDto
import org.tsdes.advanced.exercises.cardgame.cards.dto.Rarity.*
object CardCollection{
fun get() : CollectionDto{
val dto = CollectionDto()
dto.prices.run {
put(BRONZE, 100)
put(SILVER, 500)
put(GOLD, 1_000)
put(PINK_DIAMOND, 100_000)
}
dto.prices.forEach { dto.millValues[it.key] = it.value / 4 }
dto.rarityProbabilities.run {
put(SILVER, 0.10)
put(GOLD, 0.01)
put(PINK_DIAMOND, 0.001)
put(BRONZE, 1 - get(SILVER)!! - get(GOLD)!! - get(PINK_DIAMOND)!!)
}
addCards(dto)
return dto
}
private fun addCards(dto: CollectionDto){
dto.cards.run {
add(CardDto("c000", "Green Mold", "lore ipsum", BRONZE, "035-monster.svg"))
add(CardDto("c001", "Opera Singer", "lore ipsum", BRONZE, "056-monster.svg"))
add(CardDto("c002", "Not Stitch", "lore ipsum", BRONZE, "070-monster.svg"))
add(CardDto("c003", "Assault Hamster", "lore ipsum", BRONZE, "100-monster.svg"))
add(CardDto("c004", "WTF?!?", "lore ipsum", BRONZE, "075-monster.svg"))
add(CardDto("c005", "Stupid Lump", "lore ipsum", BRONZE, "055-monster.svg"))
add(CardDto("c006", "Sad Farter", "lore ipsum", BRONZE, "063-monster.svg"))
add(CardDto("c007", "Smelly Tainter", "lore ipsum", BRONZE, "050-monster.svg"))
add(CardDto("c008", "Hårboll", "lore ipsum", BRONZE, "019-monster.svg"))
add(CardDto("c009", "Blue Horned", "lore ipsum", BRONZE, "006-monster.svg"))
add(CardDto("c010", "Børje McTrumf", "lore ipsum", SILVER, "081-monster.svg"))
add(CardDto("c011", "Exa Nopass", "lore ipsum", SILVER, "057-monster.svg"))
add(CardDto("c012", "Dick Tracy", "lore ipsum", SILVER, "028-monster.svg"))
add(CardDto("c013", "Marius Mario", "lore ipsum", SILVER, "032-monster.svg"))
add(CardDto("c014", "Patrick Stew", "lore ipsum", SILVER, "002-monster.svg"))
add(CardDto("c015", "Fluffy The Hugger of Death", "lore ipsum", GOLD, "036-monster.svg"))
add(CardDto("c016", "Gary The Wise", "lore ipsum", GOLD, "064-monster.svg"))
add(CardDto("c017", "Grump-Grump The Grumpy One", "lore ipsum", GOLD, "044-monster.svg"))
add(CardDto("c018", "Bert-ho-met The Polite Guy", "lore ipsum", GOLD, "041-monster.svg"))
add(CardDto("c019", "Bengt The Destroyer", "lore ipsum", PINK_DIAMOND, "051-monster.svg"))
}
assert(dto.cards.size == dto.cards.map { it.cardId }.toSet().size)
assert(dto.cards.size == dto.cards.map { it.name }.toSet().size)
assert(dto.cards.size == dto.cards.map { it.imageId }.toSet().size)
}
} | lgpl-3.0 | f5fcfb67b0cd15c0b4e82088e8275f17 | 45.061538 | 102 | 0.589041 | 3.397276 | false | false | false | false |
cqjjjzr/Laplacian | Laplacian.Essential.Desktop/src/main/kotlin/charlie/laplacian/plugin/essential/EssentialDesktop.kt | 1 | 1244 | package charlie.laplacian.plugin.essential
//import charlie.laplacian.decoder.essential.FFmpegDecoderFactory
import charlie.laplacian.decoder.DecoderRegistry
import charlie.laplacian.decoder.essential.FFmpegDecoder
import charlie.laplacian.output.OutputMethodRegistry
import charlie.laplacian.output.essential.JavaSoundOutputMethod
import charlie.laplacian.source.SourceRegistry
import charlie.laplacian.source.essential.FileSource
import ro.fortsoft.pf4j.Plugin
import ro.fortsoft.pf4j.PluginWrapper
class EssentialDesktop(wrapper: PluginWrapper?) : Plugin(wrapper) {
companion object {
val VERSION = 1
val AUTHOR = "Charlie Jiang"
}
private val decoder = FFmpegDecoder()
private val outputMethod = JavaSoundOutputMethod()
private val fileSource = FileSource()
override fun start() {
DecoderRegistry.registerDecoderFactory(decoder)
FFmpegDecoder.init()
OutputMethodRegistry.registerOutputMethod(outputMethod)
SourceRegistry.registerSource(fileSource)
}
override fun stop() {
DecoderRegistry.unregisterDecoderFactory(decoder)
OutputMethodRegistry.unregisterOutputMethod(outputMethod)
SourceRegistry.unregisterSource(fileSource)
}
} | apache-2.0 | a78eabe1b8524850e3e4baba44b3997c | 34.571429 | 67 | 0.780547 | 4.730038 | false | false | false | false |
c4akarl/Escalero | app/src/main/java/com/androidheads/vienna/escalero/Preferences.kt | 1 | 13874 | /*
Escalero - An Android dice program.
Copyright (C) 2016-2021 Karl Schreiner, [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.androidheads.vienna.escalero
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.*
import androidx.core.content.ContextCompat
class Preferences : Activity() {
private lateinit var prefs: SharedPreferences
internal var dice = 0 // 0 : result entry, 1 : dice
private var isPlayOnline = true
private var isPlayerColumn = false
private var isDiceBoard = true
private var diceSize = 2 // 1 small, 2 medium, 3 large
private var icons = 1
private lateinit var cbLogging: CheckBox
private lateinit var cbMainDialog: CheckBox
private lateinit var diceIcon1: ImageView
private lateinit var diceIcon2: ImageView
private lateinit var diceIcon3: ImageView
private lateinit var col1: TextView
private lateinit var col2: TextView
private lateinit var col3: TextView
private lateinit var bon: TextView
private lateinit var multiplier: TextView
private lateinit var unit: TextView
private lateinit var bonusServed: TextView
private lateinit var bonusServedGrande: TextView
private lateinit var cbSummation: CheckBox
private lateinit var cbNewGame: CheckBox
private lateinit var cbSounds: CheckBox
private lateinit var cbFlipScreen: CheckBox
private lateinit var cbAdvertising: CheckBox
private lateinit var rbDiceManuel: RadioButton
private lateinit var rbDiceAutomatic: RadioButton
private lateinit var rbSizeSmall: RadioButton
private lateinit var rbSizeMedium: RadioButton
private lateinit var rbSizeLarge: RadioButton
private lateinit var rbAccountingPlayer: RadioButton
private lateinit var rbAccountingColumns: RadioButton
private lateinit var rbDimension3D: RadioButton
private lateinit var rbDimension2D: RadioButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.prefs)
cbLogging = findViewById<View>(R.id.cbLogging) as CheckBox
cbMainDialog = findViewById<View>(R.id.cbMainDialog) as CheckBox
diceIcon1 = findViewById<View>(R.id.dice_icon_1) as ImageView
diceIcon2 = findViewById<View>(R.id.dice_icon_2) as ImageView
diceIcon3 = findViewById<View>(R.id.dice_icon_3) as ImageView
col1 = findViewById<View>(R.id.col1) as TextView
col2 = findViewById<View>(R.id.col2) as TextView
col3 = findViewById<View>(R.id.col3) as TextView
bon = findViewById<View>(R.id.bon) as TextView
multiplier = findViewById<View>(R.id.multiplier) as TextView
unit = findViewById<View>(R.id.unit) as TextView
bonusServed = findViewById<View>(R.id.bonusServed) as TextView
bonusServedGrande = findViewById<View>(R.id.bonusServedGrande) as TextView
cbSummation = findViewById<View>(R.id.cbSummation) as CheckBox
cbNewGame = findViewById<View>(R.id.cbNewGame) as CheckBox
cbSounds = findViewById<View>(R.id.cbSounds) as CheckBox
cbFlipScreen = findViewById<View>(R.id.cbFlipScreen) as CheckBox
cbAdvertising = findViewById<View>(R.id.cbAdvertising) as CheckBox
rbDiceManuel = findViewById<View>(R.id.rbDiceManuel) as RadioButton
rbDiceAutomatic = findViewById<View>(R.id.rbDiceAutomatic) as RadioButton
rbSizeSmall = findViewById<View>(R.id.rbSizeSmall) as RadioButton
rbSizeMedium = findViewById<View>(R.id.rbSizeMedium) as RadioButton
rbSizeLarge = findViewById<View>(R.id.rbSizeLarge) as RadioButton
rbAccountingPlayer = findViewById<View>(R.id.rbAccountingPlayer) as RadioButton
rbAccountingColumns = findViewById<View>(R.id.rbAccountingColumns) as RadioButton
rbDimension3D = findViewById<View>(R.id.rbDimension3D) as RadioButton
rbDimension2D = findViewById<View>(R.id.rbDimension2D) as RadioButton
prefs = getSharedPreferences("prefs", 0)
isPlayOnline = prefs.getBoolean("playOnline", true)
cbLogging!!.isChecked = prefs.getBoolean("logging", false)
cbMainDialog!!.isChecked = prefs.getBoolean("mainDialog", true)
dice = prefs.getInt("dice", 1)
isDiceBoard = prefs.getBoolean("isDiceBoard", true)
diceSize = prefs.getInt("diceSize", 2)
icons = prefs.getInt("icons", 1)
if (prefs.getInt("icons", 1) == 1)
diceIcon1.setImageBitmap(getHoldBitmap(R.drawable._1_4, true))
if (prefs.getInt("icons", 1) == 2)
diceIcon2.setImageBitmap(getHoldBitmap(R.drawable._2_4, true))
if (prefs.getInt("icons", 1) == 3)
diceIcon3.setImageBitmap(getHoldBitmap(R.drawable._3_4, true))
col1.setText(String.format("%d", prefs.getInt("pointsCol1", 1)))
col2.setText(String.format("%d", prefs.getInt("pointsCol2", 2)))
col3.setText(String.format("%d", prefs.getInt("pointsCol3", 4)))
bon.setText(String.format("%d", prefs.getInt("pointsBon", 3)))
multiplier.setText(String.format("%d", prefs.getInt("multiplier", 1)))
unit.setText(prefs.getString("unit", resources.getString(R.string.points)))
bonusServed.setText(String.format("%d", prefs.getInt("bonusServed", 5)))
bonusServedGrande.setText(String.format("%d", prefs.getInt("bonusServedGrande", 30)))
isPlayerColumn = prefs.getBoolean("isPlayerColumn", true)
cbSummation!!.isChecked = prefs.getBoolean("isSummation", false)
cbSounds!!.isChecked = prefs.getBoolean("sounds", true)
cbFlipScreen!!.isChecked = prefs.getBoolean("computeFlipScreen", false)
cbAdvertising!!.isChecked = prefs.getBoolean("advertising", true)
cbNewGame!!.isChecked = false
if (isPlayOnline)
cbNewGame.visibility = CheckBox.INVISIBLE
if (dice == 0)
rbDiceManuel.isChecked = true
if (dice == 1)
rbDiceAutomatic.isChecked = true
if (diceSize == 1)
rbSizeSmall.isChecked = true
if (diceSize == 2)
rbSizeMedium.isChecked = true
if (diceSize == 3)
rbSizeLarge.isChecked = true
if (isPlayerColumn)
rbAccountingPlayer.isChecked = true
else
rbAccountingColumns.isChecked = true
if (isDiceBoard)
rbDimension3D.isChecked = true
else
rbDimension2D.isChecked = true
var msg = getString(R.string.player)
msg = msg.replace("0", "")
msg = msg.replace(" ", "")
rbAccountingPlayer.text = Editable.Factory.getInstance().newEditable(msg)
if (isPlayOnline) {
col1.isClickable = false
col1.isFocusable = false
col2.isClickable = false
col2.isFocusable = false
col3.isClickable = false
col3.isFocusable = false
bon.isClickable = false
bon.isFocusable = false
multiplier.isClickable = false
multiplier.isFocusable = false
unit.isClickable = false
unit.isFocusable = false
bonusServed.isClickable = false
bonusServed.isFocusable = false
bonusServedGrande.isClickable = false
bonusServedGrande.isFocusable = false
}
//karl
cbMainDialog.visibility = View.INVISIBLE
cbAdvertising.visibility = View.INVISIBLE
}
fun onRadioButtonClicked(view: View) {
val checked = view as RadioButton
if (rbDiceManuel == checked) {
dice = 0
if (isPlayOnline) {
dice = 1
rbDiceManuel.isChecked = false
rbDiceAutomatic.isChecked = true
Toast.makeText(applicationContext, getString(R.string.disabledOnline), Toast.LENGTH_SHORT).show()
}
}
if (rbDiceAutomatic == checked) { dice = 1 }
if (rbAccountingPlayer == checked) { isPlayerColumn = true }
if (rbAccountingColumns == checked) { isPlayerColumn = false }
if (rbDimension3D == checked) { isDiceBoard = true }
if (rbDimension2D == checked) { isDiceBoard = false }
if (rbSizeSmall == checked) { diceSize = 1 }
if (rbSizeMedium == checked) { diceSize = 2 }
if (rbSizeLarge == checked) { diceSize = 3 }
}
fun myClickHandler(view: View) {
val returnIntent: Intent
when (view.id) {
R.id.btnOk -> {
setPrefs()
returnIntent = Intent()
setResult(RESULT_OK, returnIntent)
finish()
}
R.id.dice_icon_1 -> {
icons = 1
diceIcon1.setImageBitmap(getHoldBitmap(R.drawable._1_4, true))
diceIcon2.setImageBitmap(getHoldBitmap(R.drawable._2_4, false))
diceIcon3.setImageBitmap(getHoldBitmap(R.drawable._3_4, false))
}
R.id.dice_icon_2 -> {
icons = 2
diceIcon2.setImageBitmap(getHoldBitmap(R.drawable._2_4, true))
diceIcon1.setImageBitmap(getHoldBitmap(R.drawable._1_4, false))
diceIcon3.setImageBitmap(getHoldBitmap(R.drawable._3_4, false))
}
R.id.dice_icon_3 -> {
icons = 3
diceIcon3.setImageBitmap(getHoldBitmap(R.drawable._3_4, true))
diceIcon1.setImageBitmap(getHoldBitmap(R.drawable._1_4, false))
diceIcon2.setImageBitmap(getHoldBitmap(R.drawable._2_4, false))
}
}
}
private fun getHoldBitmap(imageId: Int, isDrawRect: Boolean): Bitmap {
// hold BORDER
val bm = BitmapFactory.decodeResource(this.resources, imageId).copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas()
canvas.setBitmap(bm)
val paint = Paint()
val stroke = canvas.width / 6
paint.strokeWidth = stroke.toFloat()
paint.color = ContextCompat.getColor(this, R.color.colorHold)
paint.style = Paint.Style.STROKE
val width = canvas.width.toFloat()
val height = canvas.height.toFloat()
if (isDrawRect)
canvas.drawRect(0f, 0f, width, height, paint)
return bm
}
private fun setPrefs() {
val ed = prefs.edit()
ed.putInt("dice", dice)
ed.putBoolean("isDiceBoard", isDiceBoard)
ed.putInt("diceSize", diceSize)
ed.putInt("icons", icons)
ed.putBoolean("isPlayerColumn", isPlayerColumn)
if (!col1.text.isNullOrEmpty())
ed.putInt("pointsCol1", Integer.parseInt(col1.text.toString()))
if (!col2.text.isNullOrEmpty())
ed.putInt("pointsCol2", Integer.parseInt(col2.text.toString()))
if (!col3.text.isNullOrEmpty())
ed.putInt("pointsCol3", Integer.parseInt(col3.text.toString()))
if (!bon.text.isNullOrEmpty())
ed.putInt("pointsBon", Integer.parseInt(bon.text.toString()))
if (!multiplier.text.isNullOrEmpty())
ed.putInt("multiplier", Integer.parseInt(multiplier.text.toString()))
if (unit.text != null)
ed.putString("unit", unit.text.toString())
if (!bonusServed.text.isNullOrEmpty())
ed.putInt("bonusServed", Integer.parseInt(bonusServed.text.toString()))
if (!bonusServedGrande.text.isNullOrEmpty())
ed.putInt("bonusServedGrande", Integer.parseInt(bonusServedGrande.text.toString()))
if (cbSummation != null)
ed.putBoolean("isSummation", cbSummation!!.isChecked)
if (cbSounds != null)
ed.putBoolean("sounds", cbSounds!!.isChecked)
if (cbFlipScreen != null) {
if (isPlayOnline)
ed.putBoolean("computeFlipScreen", false)
else
ed.putBoolean("computeFlipScreen", cbFlipScreen!!.isChecked)
}
if (cbLogging != null)
ed.putBoolean("logging", cbLogging!!.isChecked)
ed.putBoolean("mainDialog", false)
ed.putBoolean("advertising", true)
if (cbNewGame != null)
ed.putBoolean("cbNewGame", cbNewGame!!.isChecked)
ed.apply()
var col1 = prefs.getInt("pointsCol1", 1)
var col2 = prefs.getInt("pointsCol2", 2)
var col3 = prefs.getInt("pointsCol3", 4)
for (i in 0..1) {
if (col1 > col2) {
val tmp = col2
col2 = col1
col1 = tmp
}
if (col2 > col3) {
val tmp = col3
col3 = col2
col2 = tmp
}
}
ed.putInt("pointsCol1", col1)
ed.putInt("pointsCol2", col2)
ed.putInt("pointsCol3", col3)
ed.apply()
}
companion object {
const val TAG = "Preferences"
}
}
| mit | 7e741b96e2b6c2477e3699cb13673ff3 | 42.086957 | 113 | 0.63464 | 4.595561 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui-test/testData/wordSelection/selectEnclosing/StatementsWithWindowsDelimiter/7.kt | 1 | 478 | fun main(args : Array<String>) {
for (i in 1..100) {
when {
i%3 == 0 -> {print("Fizz"); continue;}
i%5 == 0 -> {print("Buzz"); continue;}
(i%3 != 0 && i%5 != 0) -> {print(i); continue;}
else -> println()
}
}
}
fun foo() : Unit <selection>{
println() {
println()
pr<caret>intln()
println()
}
println(array(1, 2, 3))
println()
}</selection> | apache-2.0 | 4cb718eea7442bb3983d64ed6cffeacb | 18 | 59 | 0.39749 | 3.567164 | false | false | false | false |
edx/edx-app-android | OpenEdXMobile/src/main/java/org/edx/mobile/view/PaymentsBannerFragment.kt | 1 | 5059 | package org.edx.mobile.view
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.google.inject.Inject
import kotlinx.android.synthetic.main.fragment_payments_banner.*
import org.edx.mobile.R
import org.edx.mobile.base.BaseFragment
import org.edx.mobile.core.IEdxEnvironment
import org.edx.mobile.databinding.FragmentPaymentsBannerBinding
import org.edx.mobile.model.api.CourseUpgradeResponse
import org.edx.mobile.model.api.EnrolledCoursesResponse
import org.edx.mobile.model.course.CourseComponent
class PaymentsBannerFragment : BaseFragment() {
@Inject
var environment: IEdxEnvironment? = null
companion object {
private const val EXTRA_SHOW_INFO_BUTTON = "show_info_button"
private fun newInstance(courseData: EnrolledCoursesResponse,
courseUnit: CourseComponent?,
courseUpgradeData: CourseUpgradeResponse,
showInfoButton: Boolean): Fragment {
val fragment = PaymentsBannerFragment()
val bundle = Bundle()
bundle.putSerializable(Router.EXTRA_COURSE_DATA, courseData)
bundle.putSerializable(Router.EXTRA_COURSE_UNIT, courseUnit)
bundle.putParcelable(Router.EXTRA_COURSE_UPGRADE_DATA, courseUpgradeData)
bundle.putBoolean(EXTRA_SHOW_INFO_BUTTON, showInfoButton)
fragment.arguments = bundle
return fragment
}
fun loadPaymentsBannerFragment(containerId: Int,
courseData: EnrolledCoursesResponse,
courseUnit: CourseComponent?,
courseUpgradeData: CourseUpgradeResponse, showInfoButton: Boolean,
childFragmentManager: FragmentManager, animate: Boolean) {
val frag: Fragment? = childFragmentManager.findFragmentByTag("payment_banner_frag")
if (frag != null) {
// Payment banner already exists
return
}
val fragment: Fragment = newInstance(courseData, courseUnit, courseUpgradeData, showInfoButton)
// This activity will only ever hold this lone fragment, so we
// can afford to retain the instance during activity recreation
fragment.retainInstance = true
val fragmentTransaction: FragmentTransaction = childFragmentManager.beginTransaction()
if (animate) {
fragmentTransaction.setCustomAnimations(R.anim.slide_up, android.R.anim.fade_out)
}
fragmentTransaction.replace(containerId, fragment, "payment_banner_frag")
fragmentTransaction.disallowAddToBackStack()
fragmentTransaction.commitAllowingStateLoss()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding: FragmentPaymentsBannerBinding =
DataBindingUtil.inflate(inflater, R.layout.fragment_payments_banner, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
populateCourseUpgradeBanner(view.context)
}
private fun populateCourseUpgradeBanner(context: Context) {
val courseUpgradeData: CourseUpgradeResponse =
arguments?.getParcelable(Router.EXTRA_COURSE_UPGRADE_DATA) as CourseUpgradeResponse
val courseData: EnrolledCoursesResponse =
arguments?.getSerializable(Router.EXTRA_COURSE_DATA) as EnrolledCoursesResponse
val showInfoButton: Boolean = arguments?.getBoolean(EXTRA_SHOW_INFO_BUTTON) ?: false
upgrade_to_verified_footer.visibility = View.VISIBLE
if (showInfoButton) {
info.visibility = View.VISIBLE
info.setOnClickListener {
environment?.router?.showPaymentsInfoActivity(context, courseData, courseUpgradeData)
}
} else {
info.visibility = View.GONE
}
if (!TextUtils.isEmpty(courseUpgradeData.price)) {
tv_upgrade_price.text = courseUpgradeData.price
} else {
tv_upgrade_price.visibility = View.GONE
}
val courseUnit: CourseComponent? = arguments?.getSerializable(Router.EXTRA_COURSE_UNIT) as CourseComponent?
courseUpgradeData.basketUrl?.let { basketUrl ->
ll_upgrade_button.setOnClickListener {
environment?.router?.showCourseUpgradeWebViewActivity(
context, basketUrl, courseData, courseUnit)
}
}
}
}
| apache-2.0 | a6a0f225efc64b06b7bd42ffd3d1903b | 45.412844 | 115 | 0.668116 | 5.565457 | false | false | false | false |
pdvrieze/darwinlib | src/main/java/nl/adaptivity/android/darwin/AuthenticatedWebClientV14.kt | 1 | 6833 | /*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with Foobar. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.android.darwin
import android.accounts.Account
import android.accounts.AccountManager
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.os.Build
import android.support.annotation.WorkerThread
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import nl.adaptivity.android.coroutines.CoroutineActivity
import nl.adaptivity.android.coroutines.getAuthToken
import java.io.IOException
import java.net.*
/**
* A class making it easier to make authenticated requests to darwin.
*
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
internal class AuthenticatedWebClientV14(override val account: Account, override val authBase: URI?) : AuthenticatedWebClient {
private var token: String? = null
private val cookieManager: CookieManager by lazy<CookieManager> {
CookieManager(MyCookieStore(), CookiePolicy.ACCEPT_ORIGINAL_SERVER).also {
CookieHandler.setDefault(it)
}
}
@WorkerThread
@Throws(IOException::class)
override fun execute(context: Context, request: AuthenticatedWebClient.WebRequest): HttpURLConnection? {
return execute(context, request, false)
}
suspend fun execute(activity: Activity, request: AuthenticatedWebClient.WebRequest): HttpURLConnection? {
val am = AccountManager.get(activity)
@Suppress("DEPRECATION")
val token = am.getAuthToken(activity, account, AuthenticatedWebClient.ACCOUNT_TOKEN_TYPE)
if (token!=null) {
val cookieUri = request.uri
val cookieStore = cookieManager.cookieStore
for(repeat in 0..1) {
val cookie = HttpCookie(AuthenticatedWebClient.DARWIN_AUTH_COOKIE, token)
if ("https" == request.uri.scheme.toLowerCase()) {
cookie.secure = true
}
removeConflictingCookies(cookieStore, cookie)
cookieStore.add(cookieUri, cookie)
request.setHeader(AuthenticatedWebClient.DARWIN_AUTH_COOKIE, token)
val connection = request.connection
when {
connection.responseCode == HttpURLConnection.HTTP_UNAUTHORIZED && repeat==0 -> {
try {
connection.errorStream.use { errorStream ->
errorStream.skip(Int.MAX_VALUE.toLong())
}
} finally {
connection.disconnect()
}
Log.d(TAG, "execute: Invalidating auth token")
am.invalidateAuthToken(AuthenticatedWebClient.ACCOUNT_TYPE, token)
}
else -> return connection
}
}
}
return null
}
override fun <A> A.execute(
request: AuthenticatedWebClient.WebRequest,
currentlyInRetry: Boolean,
onError: RequestFailure,
onSuccess: RequestSuccess
): Job where A : Activity, A : CoroutineScope {
return launch {
val connection = execute(this@execute, request)
when {
connection==null -> onError(null)
connection.responseCode in 200..399 -> try { onSuccess(connection) } finally { connection.disconnect() }
else -> try { onError(connection) } finally { connection.disconnect() }
}
}
}
@WorkerThread
@Throws(IOException::class)
private fun execute(context: Context, request: AuthenticatedWebClient.WebRequest, currentlyInRetry: Boolean): HttpURLConnection? {
Log.d(TAG, "execute() called with: request = [$request], currentlyInRetry = [$currentlyInRetry]")
val accountManager = AccountManager.get(context)
token = getAuthToken(context, accountManager)
if (token == null) {
return null
}
val cookieUri = request.uri
// cookieUri = cookieUri.resolve("/");
val cookie = HttpCookie(AuthenticatedWebClient.DARWIN_AUTH_COOKIE, token)
// cookie.setDomain(cookieUri.getHost());
// cookie.setVersion(1);
// cookie.setPath("/");
if ("https" == request.uri.scheme.toLowerCase()) {
cookie.secure = true
}
val cookieStore = cookieManager.cookieStore
removeConflictingCookies(cookieStore, cookie)
cookieStore.add(cookieUri, cookie)
request.setHeader(AuthenticatedWebClient.DARWIN_AUTH_COOKIE, token!!)
val connection = request.connection
try {
if (connection.responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
connection.errorStream.use { errorStream ->
errorStream.skip(Int.MAX_VALUE.toLong())
}
Log.d(TAG, "execute: Invalidating auth token")
accountManager.invalidateAuthToken(AuthenticatedWebClient.ACCOUNT_TYPE, token)
if (!currentlyInRetry) { // Do not repeat retry
return execute(context, request, true)
}
}
return connection
} catch (e: Throwable) { // Catch exception as there would be no way for a caller to disconnect
connection.disconnect()
throw e
}
}
private fun removeConflictingCookies(cookieStore: CookieStore, refCookie: HttpCookie) {
val toRemove = cookieStore.cookies.filter { it.name == refCookie.name }
for (c in toRemove) {
for (url in cookieStore.urIs) {
cookieStore.remove(url, c)
}
}
}
@WorkerThread
private fun getAuthToken(context: Context, accountManager: AccountManager): String? {
if (token != null) return token
return AuthenticatedWebClientFactory.getAuthToken(accountManager, context, this.authBase, this.account)
}
companion object {
private val TAG = AuthenticatedWebClientV14::class.java.name
}
} | lgpl-2.1 | 08e932cca4020798f599767f94e9087b | 35.940541 | 134 | 0.633397 | 5.153092 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-api-okhttp3/src/main/java/org/ccci/gto/android/common/api/okhttp3/interceptor/SessionInterceptor.kt | 1 | 3885 | package org.ccci.gto.android.common.api.okhttp3.interceptor
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.CallSuper
import androidx.annotation.VisibleForTesting
import java.io.IOException
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Request
import okhttp3.Response
import org.ccci.gto.android.common.api.Session
import org.ccci.gto.android.common.api.okhttp3.EstablishSessionApiException
import org.ccci.gto.android.common.api.okhttp3.InvalidSessionApiException
private const val DEFAULT_RETURN_INVALID_SESSION_RESPONSES = false
abstract class SessionInterceptor<S : Session> @JvmOverloads protected constructor(
context: Context,
private val returnInvalidSessionResponses: Boolean = DEFAULT_RETURN_INVALID_SESSION_RESPONSES,
prefFile: String? = null
) : Interceptor {
protected val context: Context = context.applicationContext
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal val prefFileName = prefFile?.also { require(it.isNotEmpty()) { "prefFile cannot be an empty string" } }
?: generateSequence<Class<*>>(javaClass) { it.superclass }
.mapNotNull { it.simpleName.takeUnless { it.isEmpty() } }
.first()
protected val prefs by lazy { this.context.getSharedPreferences(prefFileName, Context.MODE_PRIVATE) }
protected val lockSession = Any()
@JvmField
@Deprecated("Since v3.10.0, use lockSession property instead", ReplaceWith("lockSession"))
protected val mLockSession = lockSession
@JvmField
@Deprecated("Since v3.10.0, use context property instead", ReplaceWith("context"))
protected val mContext = this.context
@Deprecated("Since v3.10.0, use named parameters for the constructor instead.")
protected constructor(context: Context, prefFile: String?) :
this(context, DEFAULT_RETURN_INVALID_SESSION_RESPONSES, prefFile)
@Throws(IOException::class)
override fun intercept(chain: Chain): Response {
val session = synchronized(lockSession) {
// load a valid session
loadSession()?.takeIf { it.isValid }
// otherwise try establishing a session
?: try {
establishSession()?.takeIf { it.isValid }?.also { saveSession(it) }
} catch (e: IOException) {
throw EstablishSessionApiException(e)
}
} ?: throw InvalidSessionApiException()
return processResponse(chain.proceed(attachSession(chain.request(), session)), session)
}
protected abstract fun attachSession(request: Request, session: S): Request
@CallSuper
@Throws(IOException::class)
protected open fun processResponse(response: Response, session: S): Response {
if (isSessionInvalid(response)) {
// reset the session if this is still the same session
synchronized(lockSession) {
loadSession()?.takeIf { it == session }?.apply { deleteSession(this) }
}
if (!returnInvalidSessionResponses) throw InvalidSessionApiException()
}
return response
}
@Throws(IOException::class)
open fun isSessionInvalid(response: Response) = false
private fun loadSession() = synchronized(lockSession) { loadSession(prefs) }?.takeIf { it.isValid }
protected abstract fun loadSession(prefs: SharedPreferences): S?
@Throws(IOException::class)
protected open fun establishSession(): S? = null
private fun saveSession(session: Session) {
val changes = prefs.edit().apply { session.save(this) }
synchronized(lockSession) { changes.apply() }
}
private fun deleteSession(session: Session) {
val changes = prefs.edit().apply { session.delete(this) }
synchronized(lockSession) { changes.apply() }
}
}
| mit | daa5515b27210ea72da628637017cc9d | 39.894737 | 116 | 0.698069 | 4.737805 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/stubs/LuaLocalFuncDefStub.kt | 2 | 3691 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.stubs
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IndexSink
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.intellij.util.io.StringRef
import com.tang.intellij.lua.psi.LuaLocalFuncDef
import com.tang.intellij.lua.psi.LuaParamInfo
import com.tang.intellij.lua.psi.impl.LuaLocalFuncDefImpl
import com.tang.intellij.lua.psi.overloads
import com.tang.intellij.lua.psi.tyParams
import com.tang.intellij.lua.ty.IFunSignature
import com.tang.intellij.lua.ty.ITy
import com.tang.intellij.lua.ty.TyParameter
class LuaLocalFuncDefElementType
: LuaStubElementType<LuaLocalFuncDefStub, LuaLocalFuncDef>("LOCAL_FUNC_DEF") {
override fun serialize(stub: LuaLocalFuncDefStub, stream: StubOutputStream) {
stream.writeName(stub.name)
stream.writeTyNullable(stub.returnDocTy)
stream.writeTyNullable(stub.varargTy)
stream.writeParamInfoArray(stub.params)
stream.writeTyParams(stub.tyParams)
stream.writeSignatures(stub.overloads)
}
override fun shouldCreateStub(node: ASTNode): Boolean {
val psi = node.psi as LuaLocalFuncDef
return createStubIfParentIsStub(node) && psi.name != null
}
override fun createStub(def: LuaLocalFuncDef, parentStub: StubElement<*>?): LuaLocalFuncDefStub {
val retDocTy = def.comment?.tagReturn?.type
val params = def.params
val tyParams = def.tyParams
val overloads = def.overloads
return LuaLocalFuncDefStub(def.name!!,
retDocTy,
def.varargType,
params,
tyParams,
overloads,
parentStub,
this)
}
override fun deserialize(stream: StubInputStream, parentStub: StubElement<*>?): LuaLocalFuncDefStub {
val name = stream.readName()
val retDocTy = stream.readTyNullable()
val varargTy = stream.readTyNullable()
val params = stream.readParamInfoArray()
val tyParams = stream.readTyParams()
val overloads = stream.readSignatures()
return LuaLocalFuncDefStub(StringRef.toString(name),
retDocTy,
varargTy,
params,
tyParams,
overloads,
parentStub,
this)
}
override fun indexStub(stub: LuaLocalFuncDefStub, sink: IndexSink) {
}
override fun createPsi(stub: LuaLocalFuncDefStub): LuaLocalFuncDef {
return LuaLocalFuncDefImpl(stub, this)
}
}
class LuaLocalFuncDefStub(
val name: String,
override val returnDocTy: ITy?,
override val varargTy: ITy?,
override val params: Array<LuaParamInfo>,
override val tyParams: Array<TyParameter>,
override val overloads: Array<IFunSignature>,
parent: StubElement<*>?,
type: LuaStubElementType<*, *>
) : LuaStubBase<LuaLocalFuncDef>(parent, type), LuaFuncBodyOwnerStub<LuaLocalFuncDef> | apache-2.0 | 9353624b258926fc839466e2992db98e | 35.92 | 105 | 0.689515 | 4.50122 | false | false | false | false |
MaTriXy/android-topeka | app/src/androidTest/java/com/google/samples/apps/topeka/activity/SignInActivityTest.kt | 1 | 5838 | /*
* Copyright 2017 Google 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.google.samples.apps.topeka.activity
import android.support.test.InstrumentationRegistry
import android.support.test.espresso.Espresso.onData
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.action.ViewActions.closeSoftKeyboard
import android.support.test.espresso.action.ViewActions.typeText
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.assertThat
import android.support.test.espresso.matcher.ViewMatchers.isChecked
import android.support.test.espresso.matcher.ViewMatchers.isClickable
import android.support.test.espresso.matcher.ViewMatchers.isDisplayed
import android.support.test.espresso.matcher.ViewMatchers.isEnabled
import android.support.test.espresso.matcher.ViewMatchers.isFocusable
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.espresso.matcher.ViewMatchers.withText
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.view.View
import com.google.samples.apps.topeka.R
import com.google.samples.apps.topeka.helper.isSignedIn
import com.google.samples.apps.topeka.helper.signOut
import com.google.samples.apps.topeka.model.Avatar
import com.google.samples.apps.topeka.model.TEST_AVATAR
import com.google.samples.apps.topeka.model.TEST_FIRST_NAME
import com.google.samples.apps.topeka.model.TEST_LAST_INITIAL
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.isEmptyOrNullString
import org.hamcrest.Matchers.not
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class SignInActivityTest {
@Suppress("unused") // actually used by Espresso
val activityRule @Rule get() = object :
ActivityTestRule<SignInActivity>(SignInActivity::class.java) {
override fun beforeActivityLaunched() {
InstrumentationRegistry.getTargetContext().signOut()
}
}
@Before fun clearPreferences() {
InstrumentationRegistry.getTargetContext().signOut()
}
@Test fun checkFab_initiallyNotDisplayed() {
onView(withId(R.id.done)).check(matches(not(isDisplayed())))
}
@Test fun signIn_withoutFirstNameFailed() {
inputData(null, TEST_LAST_INITIAL, TEST_AVATAR)
onDoneView().check(matches(not(isDisplayed())))
}
@Test fun signIn_withoutLastInitialFailed() {
inputData(TEST_FIRST_NAME, null, TEST_AVATAR)
onDoneView().check(matches(not(isDisplayed())))
}
@Test fun signIn_withoutAvatarFailed() {
inputData(TEST_FIRST_NAME, TEST_LAST_INITIAL, null)
onDoneView().check(matches(not(isDisplayed())))
}
@Test fun signIn_withAllPlayerPreferencesSuccessfully() {
inputData(TEST_FIRST_NAME, TEST_LAST_INITIAL, TEST_AVATAR)
onDoneView().check(matches(isDisplayed()))
}
@Test fun signIn_performSignIn() {
inputData(TEST_FIRST_NAME, TEST_LAST_INITIAL, TEST_AVATAR)
onDoneView().perform(click())
assertThat(InstrumentationRegistry.getTargetContext().isSignedIn(), `is`(true))
}
private fun onDoneView() = onView(withId(R.id.done))
@Test fun signIn_withLongLastName() {
typeAndHideKeyboard(R.id.last_initial, TEST_FIRST_NAME)
val expectedValue = TEST_FIRST_NAME[0].toString()
onView(withId(R.id.last_initial)).check(matches(withText(expectedValue)))
}
private fun inputData(firstName: String?, lastInitial: String?, avatar: Avatar?) {
if (firstName != null) typeAndHideKeyboard(R.id.first_name, firstName)
if (lastInitial != null) typeAndHideKeyboard(R.id.last_initial, lastInitial)
if (avatar != null) clickAvatar(avatar)
}
private fun typeAndHideKeyboard(targetViewId: Int, text: String) {
onView(withId(targetViewId)).perform(typeText(text), closeSoftKeyboard())
}
private fun clickAvatar(avatar: Avatar) {
onData(equalTo(avatar))
.inAdapterView(withId(R.id.avatars))
.perform(click())
}
@Test fun firstName_isInitiallyEmpty() = editTextIsEmpty(R.id.first_name)
@Test fun lastInitial_isInitiallyEmpty() = editTextIsEmpty(R.id.last_initial)
private fun editTextIsEmpty(id: Int) {
onView(withId(id)).check(matches(withText(isEmptyOrNullString())))
}
@Test fun avatar_allDisplayed() = checkOnAvatar(isDisplayed())
@Test fun avatar_isEnabled() = checkOnAvatar(isEnabled())
@Test fun avatar_notFocusable() = checkOnAvatar(not(isFocusable()))
@Test fun avatar_notClickable() = checkOnAvatar(not(isClickable()))
@Test fun avatar_noneChecked() = checkOnAvatar(not(isChecked()))
private fun checkOnAvatar(matcher: Matcher<View>) {
(0 until Avatar.values().size).forEach {
onData(equalTo(Avatar.values()[it]))
.inAdapterView(withId(R.id.avatars))
.check(matches(matcher))
}
}
}
| apache-2.0 | 62bae3a2a84e84613406955ec1f98834 | 37.92 | 87 | 0.734327 | 4.248908 | false | true | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/translator/overview/TranslatorOverviewPresenter.kt | 2 | 2480 | package ru.fantlab.android.ui.modules.translator.overview
import android.os.Bundle
import android.view.View
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.Nomination
import ru.fantlab.android.data.dao.model.Translator
import ru.fantlab.android.data.dao.response.TranslatorResponse
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getTranslatorInformationPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class TranslatorOverviewPresenter : BasePresenter<TranslatorOverviewMvp.View>(), TranslatorOverviewMvp.Presenter {
override fun onFragmentCreated(bundle: Bundle) {
val translatorId = bundle.getInt(BundleConstant.EXTRA)
makeRestCall(
retrieveTranslatorInfoInternal(translatorId).toObservable(),
Consumer { (translator, awards) ->
sendToView { it.onTranslatorInformationRetrieved(translator, awards) }
}
)
}
override fun onItemClick(position: Int, v: View?, item: Nomination) {
sendToView { it.onItemClicked(item) }
}
override fun onItemLongClick(position: Int, v: View?, item: Nomination) {
}
private fun retrieveTranslatorInfoInternal(translatorId: Int) =
retrieveTranslatorInfoFromServer(translatorId)
.onErrorResumeNext { retrieveTranslatorInfoFromDb(translatorId) }
private fun retrieveTranslatorInfoFromServer(translatorId: Int): Single<Pair<Translator, ArrayList<Translator.TranslationAward>>> =
DataManager.getTranslatorInformation(translatorId, showBio = true, showAwards = true)
.map { getTranslator(it) }
private fun retrieveTranslatorInfoFromDb(translatorId: Int): Single<Pair<Translator, ArrayList<Translator.TranslationAward>>> =
DbProvider.mainDatabase
.responseDao()
.get(getTranslatorInformationPath(translatorId, showBio = true, showAwards = true))
.map { it.response }
.map { TranslatorResponse.Deserializer().deserialize(it) }
.map { getTranslator(it) }
private fun getTranslator(response: TranslatorResponse): Pair<Translator, ArrayList<Translator.TranslationAward>> =
Pair(response.translator, response.awards)
} | gpl-3.0 | ee075769cc0405280f176e430ac3eda0 | 44.944444 | 135 | 0.722581 | 5.061224 | false | false | false | false |
google/cross-device-sdk | crossdevice/src/main/kotlin/com/google/ambient/crossdevice/discovery/Discovery.kt | 1 | 4487 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ambient.crossdevice.discovery
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Parcelable
import android.util.Log
import androidx.activity.result.ActivityResultCaller
import androidx.annotation.RequiresApi
import com.google.ambient.crossdevice.Participant
import com.google.ambient.crossdevice.ParticipantImpl
import com.google.android.gms.dtdi.Dtdi as GmsDtdi
import com.google.android.gms.dtdi.analytics.CorrelationData
import com.google.android.gms.dtdi.core.AnalyticsInfo
import com.google.android.gms.dtdi.core.DtdiClient
import com.google.android.gms.dtdi.core.SelectedDevice
/** Entry point for discovering devices. */
@RequiresApi(Build.VERSION_CODES.O)
interface Discovery {
/**
* Gets the participant from an incoming [Intent]. Used to begin the process of accepting a remote
* connection with a [Participant]. Returns null if the [Intent] is not valid for getting a
* [Participant].
*/
fun getParticipantFromIntent(intent: Intent): Participant?
/**
* Registers a callback for discovery.
*
* @param caller The calling activity or fragment.
* @param callback The callback to be called when devices are selected by a user.
* @return The launcher to use to show a device picker UI to the user.
*/
fun registerForResult(
caller: ActivityResultCaller,
callback: OnDevicePickerResultListener,
): DevicePickerLauncher
/** Interface to receive the result from the device picker, for use with [registerForResult]. */
fun interface OnDevicePickerResultListener {
/**
* Called when the user has selected the devices to connect to, and the receiving component has
* been successfully started.
*/
fun onDevicePickerResult(participants: Collection<Participant>)
}
companion object {
internal const val ORIGIN_DEVICE = "com.google.android.gms.dtdi.extra.ORIGIN_DEVICE"
internal const val ANALYTICS_INFO = "com.google.android.gms.dtdi.extra.ANALYTICS_INFO"
/** Creates an instance of [Discovery]. */
@JvmStatic
fun create(context: Context): Discovery = DiscoveryImpl(context, GmsDtdi.getClient(context))
}
}
private const val TAG = "CrossDeviceDiscovery"
/**
* Not intended for external usage. Please use [Discovery.create].
*
* @hide
*/
// TODO: Move Impl classes into internal packages with visibility/strict deps.
@RequiresApi(Build.VERSION_CODES.O)
class DiscoveryImpl(private val context: Context, private val dtdiClient: DtdiClient) : Discovery {
@SuppressWarnings("GmsCoreFirstPartyApiChecker")
override fun getParticipantFromIntent(intent: Intent): Participant? {
val device =
intent.getParcelable<SelectedDevice>(Discovery.ORIGIN_DEVICE)
?: run {
Log.w(TAG, "Unable to get participant token from intent")
return null
}
val analyticsInfo =
intent.getParcelable<AnalyticsInfo>(Discovery.ANALYTICS_INFO)
?: run {
Log.w(TAG, "Unable to get analytics info from intent")
return null
}
return ParticipantImpl(
device.displayName,
device.token,
CorrelationData.createFromAnalyticsInfo(analyticsInfo),
dtdiClient,
)
}
private inline fun <reified T : Parcelable> Intent.getParcelable(key: String): T? {
// TODO: Use the non-deprecated Bundle.getParcelable(String, Class) instead on T or
// above when b/232589966 is fixed.
@Suppress("DEPRECATION") return extras?.getParcelable(key)
}
override fun registerForResult(
caller: ActivityResultCaller,
callback: Discovery.OnDevicePickerResultListener,
): DevicePickerLauncher {
return DevicePickerLauncherImpl(
context = context,
launcher =
caller.registerForActivityResult(DevicePickerResultContract(dtdiClient)) {
callback.onDevicePickerResult(it)
}
)
}
}
| apache-2.0 | 6a9ce23ae20b5bbfb00166f5099d7c78 | 34.896 | 100 | 0.735235 | 4.364786 | false | false | false | false |
fython/NHentai-android | app/src/main/kotlin/moe/feng/nhentai/model/Picture.kt | 3 | 512 | package moe.feng.nhentai.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class Picture {
@Expose @SerializedName("h") var height: Int = 0
@Expose @SerializedName("w") var width: Int = 0
private @Expose @SerializedName("t") var type: String = "j"
val isJpg: Boolean get() = type == "j"
val isPng: Boolean get() = type == "p"
val fileType: String get() = if (isJpg) "jpg" else "png"
fun setIsJpg() {
type = "j"
}
fun setIsPng() {
type = "p"
}
} | gpl-3.0 | ff2669451a6748b3199374b21fd6e832 | 21.304348 | 60 | 0.667969 | 2.925714 | false | false | false | false |
laurentvdl/sqlbuilder | src/main/kotlin/sqlbuilder/impl/mappers/DoubleMapper.kt | 1 | 963 | package sqlbuilder.impl.mappers
import sqlbuilder.mapping.BiMapper
import sqlbuilder.mapping.ToObjectMappingParameters
import sqlbuilder.mapping.ToSQLMappingParameters
import java.sql.Types
/**
* @author Laurent Van der Linden.
*/
class DoubleMapper : BiMapper {
override fun toObject(params: ToObjectMappingParameters): Double? {
val value = params.resultSet.getDouble(params.index)
return if (params.resultSet.wasNull()) {
null
} else {
value
}
}
override fun toSQL(params: ToSQLMappingParameters) {
if (params.value != null) {
params.preparedStatement.setDouble(params.index, params.value as Double)
} else {
params.preparedStatement.setNull(params.index, Types.DECIMAL)
}
}
override fun handles(targetType: Class<*>): Boolean {
return targetType == Double::class.java || targetType == java.lang.Double::class.java
}
} | apache-2.0 | 2d0f39de2056c6224de50cf005f6aa5f | 29.125 | 93 | 0.67082 | 4.629808 | false | false | false | false |
slelyuk/circle-avatar-view | circle-avatar/src/main/kotlin/com/slelyuk/android/circleavatarview/CircleAvatarView.kt | 1 | 4223 | package com.slelyuk.android.circleavatarview
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.Config
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.Style.FILL
import android.graphics.PorterDuff.Mode.SRC_IN
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatImageView
import android.util.AttributeSet
import com.slelyuk.android.circleavatarview.R.color
import com.slelyuk.android.circleavatarview.R.dimen
import com.slelyuk.android.circleavatarview.R.styleable
/**
* Circle image view that could use defined name's abbreviation as a placeholder.
*/
class CircleAvatarView : AppCompatImageView {
internal var circleRadius = 0f
internal var circleCenterXValue = 0f
internal var circleCenterYValue = 0f
private var borderColor = 0
private var borderWidth = 0
private var viewSize = 0
private val borderPaint = Paint()
private val mainPaint = Paint()
private var circleDrawable: Drawable? = null
private val circleRect = Rect()
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs,
defStyleAttr) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
val defaultBorderColor = ContextCompat.getColor(context, color.default_border_color)
val defaultBorderWidth = context.resources.getDimensionPixelSize(dimen.default_border_width)
val arr = obtainStyledAttributes(attrs, styleable.CircleAvatarView)
try {
borderColor = arr.getColor(styleable.CircleAvatarView_av_border_color, defaultBorderColor)
borderWidth = arr.getDimensionPixelSize(styleable.CircleAvatarView_av_border_width,
defaultBorderWidth)
} finally {
arr.recycle()
}
borderPaint.let {
it.isAntiAlias = true
it.style = FILL
//it.color = borderColor
}
mainPaint.let {
it.isAntiAlias = true
it.xfermode = PorterDuffXfermode(SRC_IN)
}
}
public override fun onDraw(canvas: Canvas) {
updateViewParams(canvas)
if (viewSize == 0) {
return
}
val bitmap = cutIntoCircle(drawableToBitmap(circleDrawable)) ?: return
//Draw Border
canvas.let {
//val radius = circleRadius + borderWidth
it.translate(circleCenterXValue, circleCenterYValue)
//it.drawCircle(radius, radius, radius, borderPaint)
it.drawBitmap(bitmap, 0f, 0f, null)
}
}
private fun drawableToBitmap(drawable: Drawable?): Bitmap? {
if (viewSize == 0) {
return null
}
val bitmap = Bitmap.createBitmap(viewSize, viewSize, Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable?.let {
it.setBounds(0, 0, viewSize, viewSize)
it.draw(canvas)
}
return bitmap
}
private fun cutIntoCircle(bitmap: Bitmap?): Bitmap? {
if (viewSize == 0) {
return null
}
val output = Bitmap.createBitmap(viewSize, viewSize, Config.ARGB_8888)
val canvas = Canvas(output)
canvas.let {
val radiusWithBorder = (circleRadius + borderWidth)
//it.drawARGB(0, 0, 0, 0)
it.drawCircle(radiusWithBorder, radiusWithBorder, circleRadius, borderPaint)
it.drawBitmap(bitmap, circleRect, circleRect, mainPaint)
}
return output
}
private fun updateViewParams(canvas: Canvas) {
val viewHeight = canvas.height
val viewWidth = canvas.width
viewSize = Math.min(viewWidth, viewHeight)
circleCenterXValue = (viewWidth - viewSize) / 2f
circleCenterYValue = (viewHeight - viewSize) / 2f
circleRadius = (viewSize - borderWidth * 2) / 2f
circleRect.set(Rect(0, 0, viewSize, viewSize))
borderWidth = Math.min(viewSize / 3, borderWidth)
if (viewSize != 0) {
circleDrawable = this.drawable
}
}
override fun drawableStateChanged() {
super.drawableStateChanged()
invalidate()
}
} | mit | 1030402236b3f39bfed9962069074962 | 27.16 | 96 | 0.714184 | 4.252769 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/completion/property/XPathVersion.kt | 1 | 2307 | /*
* Copyright (C) 2019 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.completion.property
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import uk.co.reecedunn.intellij.plugin.core.completion.CompletionProperty
import uk.co.reecedunn.intellij.plugin.intellij.lang.Version
import uk.co.reecedunn.intellij.plugin.intellij.lang.XPathSpec
import uk.co.reecedunn.intellij.plugin.intellij.lang.XQuerySpec
import uk.co.reecedunn.intellij.plugin.xpath.completion.property.XPathCompletionProperty
object XPathVersion : CompletionProperty {
override fun computeProperty(element: PsiElement, context: ProcessingContext) {
if (context[XPathCompletionProperty.XPATH_VERSION] == null) {
XQueryVersion.computeProperty(element, context)
val xquery = context[XQueryCompletionProperty.XQUERY_VERSION]
context.put(XPathCompletionProperty.XPATH_VERSION, get(xquery))
}
}
fun get(element: PsiElement): Version = get(XQueryVersion.get(element))
private fun get(xqueryVersion: Version): Version = when (xqueryVersion) {
XQuerySpec.REC_1_0_20070123 -> XPathSpec.REC_2_0_20070123
XQuerySpec.REC_1_0_20101214 -> XPathSpec.REC_2_0_20101214
XQuerySpec.WD_1_0_20030502 -> XPathSpec.WD_2_0_20030502
XQuerySpec.REC_3_0_20140408 -> XPathSpec.REC_3_0_20140408
XQuerySpec.CR_3_1_20151217 -> XPathSpec.CR_3_1_20151217
XQuerySpec.REC_3_1_20170321 -> XPathSpec.REC_3_1_20170321
XQuerySpec.ED_4_0_20210113 -> XPathSpec.ED_4_0_20210113
XQuerySpec.MARKLOGIC_0_9 -> XPathSpec.WD_2_0_20030502
XQuerySpec.MARKLOGIC_1_0 -> XPathSpec.REC_3_0_20140408
else -> XPathSpec.REC_3_1_20170321
}
}
| apache-2.0 | 77efe3dff98cab3516d85e4d7447387e | 45.14 | 88 | 0.738622 | 3.73301 | false | false | false | false |
pkleimann/livingdoc | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/collection/Tokenizer.kt | 3 | 695 | package org.livingdoc.converters.collection
import org.livingdoc.api.conversion.ConversionException
internal object Tokenizer {
fun tokenizeToStringList(value: String, delimiter: String = ",") = value.split(delimiter).map { it.trim() }
fun tokenizeToMap(value: String, pairDelimiter: String = ";", valueDelimiter: String = ","): Map<String, String> {
val pairs = tokenizeToStringList(value, pairDelimiter)
return pairs.map { pairString ->
val split = tokenizeToStringList(pairString, valueDelimiter)
if (split.size != 2) throw ConversionException("'$pairString' is not a valid Pair")
split[0] to split[1]
}.toMap()
}
}
| apache-2.0 | dc3a211299f2cc9d25b774824cc8bfa4 | 39.882353 | 118 | 0.679137 | 4.483871 | false | false | false | false |
Akjir/WiFabs | src/main/kotlin/net/kejira/wifabs/ui/fabric/edit/FabricEditMultiAttributeBox.kt | 1 | 4218 | /*
* Copyright (c) 2017 Stefan Neubert
*
* 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 net.kejira.wifabs.ui.fabric.edit
import javafx.collections.ObservableList
import javafx.geometry.Insets
import javafx.geometry.Orientation
import javafx.scene.control.Button
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import javafx.scene.layout.FlowPane
import org.controlsfx.control.textfield.TextFields
class FabricEditMultiAttributeBox(private val name_list: ObservableList<String>) : FlowPane(Orientation.HORIZONTAL) {
private val list = hashSetOf<String>()
init {
style =
"-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border), linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);" +
"-fx-background-insets: 0, 1;" +
"-fx-background-radius: 3, 2;"
padding = Insets(5.0)
minHeight = 35.0
hgap = 5.0
vgap = 5.0
this.setOnMouseReleased { mouse_event ->
if (mouse_event.button == javafx.scene.input.MouseButton.PRIMARY) {
createTextField()
}
}
}
private fun add(attribute: String) {
var text = attribute.trim().capitalize()
if (text.isNotEmpty()) {
if (text.length > 35) {
text = text.substring(0, 35)
}
if (!list.contains(text)) {
createButton(text)
list.add(text)
}
}
}
fun get(): Set<String> = list.toSet()
fun set(attributes: Set<String>) {
this.list.clear()
this.children.clear()
attributes.forEach {
createButton(it)
list.add(it)
}
}
private fun remove(attribute: String) {
list.remove(attribute)
}
private fun createButton(text: String) {
val button = Button(text)
button.setOnMouseClicked {
remove(button.text)
this.children.remove(button)
}
this.children.add(button)
}
private fun createTextField() {
val text_field = FabricEditAttributeTextField()
/* enter */
text_field.setOnKeyPressed { ke ->
if (ke.code == KeyCode.ESCAPE) {
text_field.createButton = false
super.requestFocus()
} else if (ke.code == KeyCode.ENTER) {
super.requestFocus()
}
}
/* focus lost */
text_field.focusedProperty().addListener { _, _, new ->
if (!new) {
this.children.remove(text_field)
if (text_field.createButton) add(text_field.text)
}
}
/* auto completion */
val autoCompletion = TextFields.bindAutoCompletion(text_field, name_list)
autoCompletion.setOnAutoCompleted { super.requestFocus() }
this.children.add(text_field)
text_field.requestFocus()
}
}
class FabricEditAttributeTextField : TextField() {
@JvmField var createButton = true
init {
maxWidth = 85.0
}
} | mit | f66901736433c41d83624a806f8dd0f3 | 30.485075 | 232 | 0.630156 | 4.326154 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/enhancedlist/BaseEnhancedListActivity.kt | 1 | 7422 | package org.walleth.enhancedlist
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.SearchView
import androidx.core.animation.doOnEnd
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.LEFT
import androidx.recyclerview.widget.ItemTouchHelper.RIGHT
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_list.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.android.ext.android.inject
import org.ligi.kaxt.startActivityFromURL
import org.walleth.R
import org.walleth.base_activities.BaseSubActivity
import org.walleth.chains.getFaucetURL
import org.walleth.chains.hasFaucetWithAddressSupport
import org.walleth.data.AppDatabase
import org.walleth.data.addresses.CurrentAddressProvider
import org.walleth.data.chaininfo.ChainInfo
import org.walleth.util.question
import timber.log.Timber
interface Deletable {
var deleted: Boolean
}
interface ListItem : Deletable {
val name: String
}
@SuppressLint("Registered")
abstract class BaseEnhancedListActivity<T : ListItem> : BaseSubActivity() {
abstract val enhancedList: EnhancedListInterface<T>
abstract val adapter: EnhancedListAdapter<T>
private var currentSnack: Snackbar? = null
internal var searchTerm = ""
fun T.changeDeleteState(state: Boolean) {
val changedEntity = apply { deleted = state }
lifecycleScope.launch(Dispatchers.Main) {
withContext(Dispatchers.Default) {
enhancedList.upsert(changedEntity)
if (state) {
currentSnack = Snackbar.make(coordinator, "Deleted " + changedEntity.name, Snackbar.LENGTH_INDEFINITE)
.setAction(getString(R.string.undo)) { changeDeleteState(false) }
.apply { show() }
}
refreshAdapter()
invalidateOptionsMenu()
}
}
}
internal fun View.deleteWithAnimation(t: T) {
ObjectAnimator.ofFloat(this, "translationX", this.width.toFloat()).apply {
duration = 333
start()
doOnEnd {
t.changeDeleteState(true)
handler.postDelayed({
translationX = 0f
}, 333)
}
}
}
fun AppCompatImageView.prepareFaucetButton(chainInfo: ChainInfo?,
currentAddressProvider: CurrentAddressProvider,
postAction: () -> Unit = {}) {
visibility = if (chainInfo?.faucets?.isNotEmpty() == true) {
setImageResource(if (chainInfo.hasFaucetWithAddressSupport()) R.drawable.ic_flash_on_black_24dp else R.drawable.ic_redeem_black_24dp)
View.VISIBLE
} else {
View.INVISIBLE
}
setOnClickListener {
chainInfo?.getFaucetURL(currentAddressProvider.getCurrentNeverNull())?.let { url ->
context.startActivityFromURL(url)
postAction.invoke()
}
}
}
internal fun MenuItem.filterToggle(updater: (value: Boolean) -> Unit) = true.also {
isChecked = !isChecked
updater(isChecked)
refreshAdapter()
}
val appDatabase: AppDatabase by inject()
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val anySoftDeletedExists = adapter.list.any { it.deleted }
menu.findItem(R.id.menu_undelete).isVisible = anySoftDeletedExists
menu.findItem(R.id.menu_delete_forever).isVisible = anySoftDeletedExists
return super.onPrepareOptionsMenu(menu)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_enhanced_list, menu)
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem.actionView as SearchView
Timber.i("setting search term $searchTerm")
searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(p0: MenuItem?) = true
override fun onMenuItemActionCollapse(p0: MenuItem?) = true.also {
searchTerm = ""
}
})
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(newSearchTerm: String) = true.also {
searchTerm = newSearchTerm
Timber.i("setting search term 2 $newSearchTerm")
refreshAdapter()
}
override fun onQueryTextSubmit(query: String?) = false
})
searchView.setQuery(searchTerm, true)
return super.onCreateOptionsMenu(menu)
}
fun checkForSearchTerm(vararg terms: String) = terms.any { it.toLowerCase().contains(searchTerm, ignoreCase = true) }
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.menu_undelete -> true.also {
lifecycleScope.launch(Dispatchers.Main) {
currentSnack?.dismiss()
enhancedList.undeleteAll()
refreshAdapter()
}
}
R.id.menu_delete_forever -> true.also {
question(configurator = {
setIcon(R.drawable.ic_warning_orange_24dp)
setTitle(R.string.are_you_sure)
setMessage(R.string.permanent_delete_question)
}, action = {
currentSnack?.dismiss()
lifecycleScope.launch {
enhancedList.deleteAllSoftDeleted()
refreshAdapter()
}
})
}
else -> super.onOptionsItemSelected(item)
}
internal fun refreshAdapter() = lifecycleScope.launch(Dispatchers.Main) {
adapter.filter(enhancedList.getAll(),
filter = { enhancedList.filter(it) },
onChange = { invalidateOptionsMenu() },
areEqual = { t1, t2 -> enhancedList.compare(t1, t2) })
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.adapter = adapter
val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, LEFT or RIGHT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder) = false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
adapter.displayList[viewHolder.adapterPosition].changeDeleteState(true)
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(recycler_view)
}
override fun onResume() {
super.onResume()
refreshAdapter()
}
} | gpl-3.0 | c9b183d0e94df3ff5ddec2404e24f1c3 | 35.387255 | 145 | 0.652654 | 5.11157 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceWithAnnotationAnalyzer.kt | 3 | 11534 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.replaceWith
import com.intellij.openapi.diagnostic.ControlFlowException
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInliner.CodeToInline
import org.jetbrains.kotlin.idea.codeInliner.CodeToInlineBuilder
import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.utils.chainImportingScopes
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
data class ReplaceWithData(val pattern: String, val imports: List<String>, val replaceInWholeProject: Boolean)
@OptIn(FrontendInternals::class)
object ReplaceWithAnnotationAnalyzer {
fun analyzeCallableReplacement(
replaceWith: ReplaceWithData,
symbolDescriptor: CallableDescriptor,
resolutionFacade: ResolutionFacade,
reformat: Boolean
): CodeToInline? {
val originalDescriptor = symbolDescriptor.unwrapIfFakeOverride().original
return analyzeOriginal(replaceWith, originalDescriptor, resolutionFacade, reformat)
}
private fun analyzeOriginal(
replaceWith: ReplaceWithData,
symbolDescriptor: CallableDescriptor,
resolutionFacade: ResolutionFacade,
reformat: Boolean
): CodeToInline? {
val psiFactory = KtPsiFactory(resolutionFacade.project)
val expression = psiFactory.createExpressionIfPossible(replaceWith.pattern) ?: return null
val module = resolutionFacade.moduleDescriptor
val scope = buildScope(resolutionFacade, replaceWith, symbolDescriptor) ?: return null
val expressionTypingServices = resolutionFacade.getFrontendService(module, ExpressionTypingServices::class.java)
fun analyzeExpression(ignore: KtExpression) = expression.analyzeInContext(
scope,
expressionTypingServices = expressionTypingServices
)
return CodeToInlineBuilder(symbolDescriptor, resolutionFacade, originalDeclaration = null).prepareCodeToInline(
expression,
emptyList(),
::analyzeExpression,
reformat,
)
}
fun analyzeClassifierReplacement(
replaceWith: ReplaceWithData,
symbolDescriptor: ClassifierDescriptorWithTypeParameters,
resolutionFacade: ResolutionFacade
): KtUserType? {
val psiFactory = KtPsiFactory(resolutionFacade.project)
val typeReference = try {
psiFactory.createType(replaceWith.pattern)
} catch (e: Exception) {
if (e is ControlFlowException) throw e
return null
}
if (typeReference.typeElement !is KtUserType) return null
val scope = buildScope(resolutionFacade, replaceWith, symbolDescriptor) ?: return null
val typeResolver = resolutionFacade.getFrontendService(TypeResolver::class.java)
val bindingTrace = BindingTraceContext()
typeResolver.resolvePossiblyBareType(TypeResolutionContext(scope, bindingTrace, false, true, false), typeReference)
val typesToQualify = ArrayList<Pair<KtNameReferenceExpression, FqName>>()
typeReference.forEachDescendantOfType<KtNameReferenceExpression> { expression ->
val parentType = expression.parent as? KtUserType ?: return@forEachDescendantOfType
if (parentType.qualifier != null) return@forEachDescendantOfType
val targetClass = bindingTrace.bindingContext[BindingContext.REFERENCE_TARGET, expression] as? ClassDescriptor
?: return@forEachDescendantOfType
val fqName = targetClass.fqNameUnsafe
if (fqName.isSafe) {
typesToQualify.add(expression to fqName.toSafe())
}
}
for ((nameExpression, fqName) in typesToQualify) {
nameExpression.mainReference.bindToFqName(fqName, KtSimpleNameReference.ShorteningMode.NO_SHORTENING)
}
return typeReference.typeElement as KtUserType
}
private fun buildScope(
resolutionFacade: ResolutionFacade,
replaceWith: ReplaceWithData,
symbolDescriptor: DeclarationDescriptor
): LexicalScope? {
val module = resolutionFacade.moduleDescriptor
val explicitImportsScope = buildExplicitImportsScope(importFqNames(replaceWith), resolutionFacade, module)
val languageVersionSettings = resolutionFacade.languageVersionSettings
val defaultImportsScopes = buildDefaultImportsScopes(resolutionFacade, module, languageVersionSettings)
return getResolutionScope(
symbolDescriptor, symbolDescriptor, listOf(explicitImportsScope), defaultImportsScopes, languageVersionSettings
)
}
private fun buildDefaultImportsScopes(
resolutionFacade: ResolutionFacade,
module: ModuleDescriptor,
languageVersionSettings: LanguageVersionSettings
): List<ImportingScope> {
val allDefaultImports =
resolutionFacade.frontendService<TargetPlatform>().findAnalyzerServices(resolutionFacade.project)
.getDefaultImports(languageVersionSettings, includeLowPriorityImports = true)
val (allUnderImports, aliasImports) = allDefaultImports.partition { it.isAllUnder }
// this solution doesn't support aliased default imports with a different alias
// TODO: Create import directives from ImportPath, create ImportResolver, create LazyResolverScope, see FileScopeProviderImpl
return listOf(buildExplicitImportsScope(aliasImports.map { it.fqName }, resolutionFacade, module)) +
allUnderImports.map { module.getPackage(it.fqName).memberScope.memberScopeAsImportingScope() }.asReversed()
}
private fun buildExplicitImportsScope(
importFqNames: List<FqName>,
resolutionFacade: ResolutionFacade,
module: ModuleDescriptor
): ExplicitImportsScope {
val importedSymbols = importFqNames.flatMap { resolutionFacade.resolveImportReference(module, it) }
return ExplicitImportsScope(importedSymbols)
}
private fun importFqNames(annotation: ReplaceWithData): List<FqName> {
val result = ArrayList<FqName>()
for (fqName in annotation.imports) {
if (!FqNameUnsafe.isValid(fqName)) continue
result += FqNameUnsafe(fqName).takeIf { it.isSafe }?.toSafe() ?: continue
}
return result
}
private fun getResolutionScope(
descriptor: DeclarationDescriptor,
ownerDescriptor: DeclarationDescriptor,
explicitScopes: Collection<ExplicitImportsScope>,
additionalScopes: Collection<ImportingScope>,
languageVersionSettings: LanguageVersionSettings
): LexicalScope? {
return when (descriptor) {
is PackageFragmentDescriptor -> {
val moduleDescriptor = descriptor.containingDeclaration
getResolutionScope(
moduleDescriptor.getPackage(descriptor.fqName),
ownerDescriptor,
explicitScopes,
additionalScopes,
languageVersionSettings
)
}
is PackageViewDescriptor -> {
val memberAsImportingScope = descriptor.memberScope.memberScopeAsImportingScope()
LexicalScope.Base(
chainImportingScopes(explicitScopes + listOf(memberAsImportingScope) + additionalScopes)!!,
ownerDescriptor
)
}
is ClassDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
ClassResolutionScopesSupport(
descriptor,
LockBasedStorageManager.NO_LOCKS,
languageVersionSettings
) { outerScope }.scopeForMemberDeclarationResolution()
}
is TypeAliasDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
LexicalScopeImpl(
outerScope,
descriptor,
false,
null,
emptyList(),
LexicalScopeKind.TYPE_ALIAS_HEADER,
LocalRedeclarationChecker.DO_NOTHING
) {
for (typeParameter in descriptor.declaredTypeParameters) {
addClassifierDescriptor(typeParameter)
}
}
}
is FunctionDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
FunctionDescriptorUtil.getFunctionInnerScope(outerScope, descriptor, LocalRedeclarationChecker.DO_NOTHING)
}
is PropertyDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
val propertyHeader = ScopeUtils.makeScopeForPropertyHeader(outerScope, descriptor)
LexicalScopeImpl(
propertyHeader,
descriptor,
false,
descriptor.extensionReceiverParameter,
descriptor.contextReceiverParameters,
LexicalScopeKind.PROPERTY_ACCESSOR_BODY
)
}
else -> return null // something local, should not work with ReplaceWith
}
}
}
| apache-2.0 | 64bbe101fdead511097fb34d3521f93c | 45.136 | 158 | 0.695422 | 6.39357 | false | false | false | false |
romanoid/buck | src/com/facebook/buck/multitenant/service/Types.kt | 1 | 3254 | /*
* Copyright 2019-present Facebook, 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.facebook.buck.multitenant.service
import com.facebook.buck.core.model.UnconfiguredBuildTarget
import com.facebook.buck.core.model.targetgraph.raw.RawTargetNode
import java.nio.file.Path
import java.util.*
typealias Commit = String
internal typealias BuildTargetId = Int
/**
* The values in the array must be sorted in ascending order or else [equals_BuildTargetSet] and
* [hashCode_BuildTargetSet] will not work properly.
*/
internal typealias BuildTargetSet = IntArray
/**
* This is a RawTargetNode paired with its deps as determined by configuring the RawTargetNode with
* the empty configuration.
*/
data class RawBuildRule(val targetNode: RawTargetNode, val deps: Set<UnconfiguredBuildTarget>)
/**
* @param[deps] must be sorted in ascending order!!!
*/
internal data class InternalRawBuildRule(val targetNode: RawTargetNode, val deps: BuildTargetSet) {
/*
* Because RawTargetNodeAndDeps contains an IntArray field, which does not play well with
* `.equals()` (or `hashCode()`, for that matter), we have to do a bit of work to implement
* these methods properly when the default implementations for a data class are not appropriate.
*/
override fun equals(other: Any?): Boolean {
if (other !is InternalRawBuildRule) {
return false
}
return targetNode == other.targetNode && equals_BuildTargetSet(deps, other.deps)
}
override fun hashCode(): Int {
return 31 * Objects.hash(targetNode) + hashCode_BuildTargetSet(deps)
}
}
private fun equals_BuildTargetSet(set1: BuildTargetSet, set2: BuildTargetSet): Boolean {
return set1.contentEquals(set2)
}
private fun hashCode_BuildTargetSet(set: BuildTargetSet): Int {
return set.contentHashCode()
}
/**
* By construction, the name for each rule in rules should be distinct across all of the rules in
* the set.
*/
data class BuildPackage(val buildFileDirectory: Path, val rules: Set<RawBuildRule>)
internal data class InternalBuildPackage(val buildFileDirectory: Path, val rules: Set<InternalRawBuildRule>)
/**
* By construction, the Path for each BuildPackage should be distinct across all of the
* collections of build packages.
*/
data class Changes(val addedBuildPackages: List<BuildPackage>,
val modifiedBuildPackages: List<BuildPackage>,
val removedBuildPackages: List<Path>)
internal data class InternalChanges(val addedBuildPackages: List<InternalBuildPackage>,
val modifiedBuildPackages: List<InternalBuildPackage>,
val removedBuildPackages: List<Path>)
| apache-2.0 | f4d95bc2b505f47040e73b7721781e51 | 35.977273 | 108 | 0.72772 | 4.729651 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/Shape.kt | 1 | 1364 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.simplemath.ndarray
import java.io.Serializable
/**
* The shape of an bi-dimensional NDArray containing its dimensions (first and second).
*/
data class Shape(val dim1: Int, val dim2: Int = 1) : Serializable {
companion object {
/**
* Private val used to serialize the class (needed by Serializable).
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
}
/**
* The inverse [Shape] of this.
*/
val inverse: Shape get() = Shape(this.dim2, this.dim1)
/**
* @param other any object
*
* @return a Boolean indicating if this [Shape] is equal to the given [other] object
*/
override fun equals(other: Any?): Boolean {
return (other is Shape && other.dim1 == this.dim1 && other.dim2 == this.dim2)
}
/**
* @return the hash code representation of this [Shape]
*/
override fun hashCode(): Int {
var hash = 7
hash = 83 * hash + this.dim1
hash = 83 * hash + this.dim2
return hash
}
}
| mpl-2.0 | e4ed458f9c8ae6977be60d1513f2e058 | 25.745098 | 87 | 0.622434 | 3.930836 | false | false | false | false |
ingokegel/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/LocalHistoryLesson.kt | 1 | 15167 | // 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 training.learn.lesson.general.assistance
import com.intellij.CommonBundle
import com.intellij.history.integration.ui.actions.LocalHistoryGroup
import com.intellij.history.integration.ui.actions.ShowHistoryAction
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.ui.components.JBLoadingPanelListener
import com.intellij.ui.table.JBTable
import com.intellij.ui.tabs.impl.SingleHeightTabs
import com.intellij.util.DocumentUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.ui.UIUtil
import org.assertj.swing.core.MouseButton
import org.assertj.swing.data.TableCell
import org.assertj.swing.fixture.JTableFixture
import org.jetbrains.annotations.Nls
import training.FeaturesTrainerIcons
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.learn.course.LessonProperties
import training.learn.course.LessonType
import training.learn.lesson.LessonManager
import training.ui.LearningUiHighlightingManager
import training.ui.LearningUiHighlightingManager.HighlightingOptions
import training.ui.LearningUiUtil
import training.util.LessonEndInfo
import java.awt.Component
import java.awt.Point
import java.awt.Rectangle
import java.util.concurrent.CompletableFuture
import javax.swing.JFrame
class LocalHistoryLesson : KLesson("CodeAssistance.LocalHistory", LessonsBundle.message("local.history.lesson.name")) {
override val languageId = "yaml"
override val lessonType = LessonType.SCRATCH
override val properties = LessonProperties(availableSince = "212.5284")
private val lineToDelete = 14
private val revisionInd = 2
private val sample = parseLessonSample("""
cat:
name: Pelmen
gender: male
breed: sphinx
fur_type: hairless
fur_pattern: solid
fur_colors: [ white ]
tail_length: long
eyes_colors: [ green ]
favourite_things:
- three plaids
- pile of clothes
- castle of boxes
- toys scattered all over the place
behavior:
- play:
condition: boring
actions:
- bring one of the favourite toys to the human
- run all over the house
- eat:
condition: want to eat
actions:
- shout to the whole house
- sharpen claws by the sofa
- wake up a human in the middle of the night""".trimIndent())
private val textToDelete = """
| - play:
| condition: boring
| actions:
| - bring one of the favourite toys to the human
| - run all over the house
""".trimMargin()
private val textAfterDelete = """
| behavior:
|
| - eat:
""".trimMargin()
private val textToAppend = """
| - sleep:
| condition: want to sleep
| action:
| - bury himself in a human's blanket
| - bury himself in a favourite plaid
""".trimMargin()
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
caret(textToDelete, select = true)
prepareRuntimeTask(ModalityState.NON_MODAL) {
FileDocumentManager.getInstance().saveDocument(editor.document)
}
val localHistoryActionText = ActionsBundle.groupText("LocalHistory").dropMnemonic()
task {
text(LessonsBundle.message("local.history.remove.code",
strong(localHistoryActionText),
action(IdeActions.ACTION_EDITOR_BACKSPACE)))
stateCheck {
editor.document.charsSequence.contains(textAfterDelete)
}
restoreIfModifiedOrMoved()
test { invokeActionViaShortcut("DELETE") }
}
setEditorHint(LessonsBundle.message("local.history.editor.hint"))
waitBeforeContinue(500)
prepareRuntimeTask {
if (!TaskTestContext.inTestMode) {
val userDecision = Messages.showOkCancelDialog(
LessonsBundle.message("local.history.dialog.message"),
LessonsBundle.message("recent.files.dialog.title"),
CommonBundle.message("button.ok"),
LearnBundle.message("learn.stop.lesson"),
FeaturesTrainerIcons.PluginIcon
)
if (userDecision != Messages.OK) {
LessonManager.instance.stopLesson()
}
}
}
modifyFile()
lateinit var invokeMenuTaskId: TaskContext.TaskId
task {
invokeMenuTaskId = taskId
text(LessonsBundle.message("local.history.imagine.restore", strong(ActionsBundle.message("action.\$Undo.text"))))
text(LessonsBundle.message("local.history.invoke.context.menu", strong(localHistoryActionText)))
triggerAndBorderHighlight().component { ui: EditorComponentImpl -> ui.editor == editor }
triggerAndFullHighlight().component { ui: ActionMenu ->
isClassEqual(ui.anAction, LocalHistoryGroup::class.java)
}
test {
ideFrame { robot().rightClick(editor.component) }
}
}
task("LocalHistory.ShowHistory") {
val showHistoryActionText = ActionsBundle.actionText(it).dropMnemonic()
text(LessonsBundle.message("local.history.show.history", strong(localHistoryActionText), strong(showHistoryActionText)))
triggerAndFullHighlight { clearPreviousHighlights = false }.component { ui: ActionMenuItem ->
isClassEqual(ui.anAction, ShowHistoryAction::class.java)
}
trigger(it)
restoreByUi()
test {
ideFrame {
jMenuItem { item: ActionMenu -> isClassEqual(item.anAction, LocalHistoryGroup::class.java) }.click()
jMenuItem { item: ActionMenuItem -> isClassEqual(item.anAction, ShowHistoryAction::class.java) }.click()
}
}
}
var revisionsTable: JBTable? = null
task {
triggerAndBorderHighlight().componentPart { ui: JBTable ->
if (checkInsideLocalHistoryFrame(ui)) {
revisionsTable = ui
ui.getCellRect(revisionInd, 0, false)
}
else null
}
}
lateinit var selectRevisionTaskId: TaskContext.TaskId
task {
selectRevisionTaskId = taskId
text(LessonsBundle.message("local.history.select.revision", strong(localHistoryActionText), strong(localHistoryActionText)))
val step = CompletableFuture<Boolean>()
addStep(step)
triggerUI { clearPreviousHighlights = false }.component l@{ ui: JBLoadingPanel ->
if (!checkInsideLocalHistoryFrame(ui)) return@l false
ui.addListener(object : JBLoadingPanelListener {
override fun onLoadingStart() {
// do nothing
}
override fun onLoadingFinish() {
val revisions = revisionsTable ?: return
if (revisions.selectionModel.selectedIndices.let { it.size == 1 && it[0] == revisionInd }) {
ui.removeListener(this)
step.complete(true)
}
}
})
true
}
restoreByUi(invokeMenuTaskId, delayMillis = defaultRestoreDelay)
test {
ideFrame {
Thread.sleep(1000)
val table = revisionsTable ?: error("revisionsTable is not initialized")
JTableFixture(robot(), table).click(TableCell.row(revisionInd).column(0), MouseButton.LEFT_BUTTON)
}
}
}
task {
triggerAndBorderHighlight().componentPart { ui: EditorGutterComponentEx -> findDiffGutterRect(ui) }
}
task {
text(LessonsBundle.message("local.history.restore.code", icon(AllIcons.Diff.ArrowRight)))
text(LessonsBundle.message("local.history.restore.code.balloon"),
LearningBalloonConfig(Balloon.Position.below, 0, cornerToPointerDistance = 50))
stateCheck {
editor.document.charsSequence.contains(textToDelete)
}
restoreByUi(invokeMenuTaskId)
restoreState(selectRevisionTaskId) l@{
val revisions = revisionsTable ?: return@l false
revisions.selectionModel.selectedIndices.let { it.size != 1 || it[0] != revisionInd }
}
test {
ideFrame {
val gutterComponent = previous.ui as? EditorGutterComponentEx ?: error("Failed to find gutter component")
val gutterRect = findDiffGutterRect(gutterComponent) ?: error("Failed to find required gutter")
robot().click(gutterComponent, Point(gutterRect.x + gutterRect.width / 2, gutterRect.y + gutterRect.height / 2))
}
}
}
task {
before { LearningUiHighlightingManager.clearHighlights() }
text(LessonsBundle.message("local.history.close.window", action("EditorEscape")))
stateCheck {
val focusedEditor = focusOwner as? EditorComponentImpl
// check that it is editor from main IDE frame
focusedEditor != null && UIUtil.getParentOfType(SingleHeightTabs::class.java, focusedEditor) != null
}
test {
invokeActionViaShortcut("ESCAPE")
// sometimes some small popup appears at mouse position so the first Escape may close just that popup
invokeActionViaShortcut("ESCAPE")
}
}
setEditorHint(null)
text(LessonsBundle.message("local.history.congratulations"))
}
override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) {
if (!lessonEndInfo.lessonPassed) return
ApplicationManager.getApplication().executeOnPooledThread {
val editorComponent = LearningUiUtil.findComponentOrNull(project, EditorComponentImpl::class.java) { editor ->
UIUtil.getParentOfType(SingleHeightTabs::class.java, editor) != null
} ?: error("Failed to find editor component")
invokeLater {
val lines = textToDelete.lines()
val rightColumn = lines.maxOf { it.length }
LearningUiHighlightingManager.highlightPartOfComponent(editorComponent, HighlightingOptions(highlightInside = false)) {
val editor = editorComponent.editor
val textToFind = lines[0].trim()
val offset = editor.document.charsSequence.indexOf(textToFind)
if (offset == -1) error("Failed to find '$textToFind' in the editor")
val leftPosition = editor.offsetToLogicalPosition(offset)
val leftPoint = editor.logicalPositionToXY(leftPosition)
val rightPoint = editor.logicalPositionToXY(LogicalPosition(leftPosition.line, rightColumn))
Rectangle(leftPoint.x - 3, leftPoint.y, rightPoint.x - leftPoint.x + 6, editor.lineHeight * lines.size)
}
}
}
}
private fun isClassEqual(value: Any, expectedClass: Class<*>): Boolean {
return value.javaClass.name == expectedClass.name
}
private fun findDiffGutterRect(ui: EditorGutterComponentEx): Rectangle? {
val editor = CommonDataKeys.EDITOR.getData(ui as DataProvider) ?: return null
val offset = editor.document.charsSequence.indexOf(textToDelete)
return if (offset != -1) {
val lineIndex = editor.document.getLineNumber(offset)
invokeAndWaitIfNeeded {
val y = editor.visualLineToY(lineIndex)
Rectangle(ui.width - ui.whitespaceSeparatorOffset, y, ui.width - 26, editor.lineHeight)
}
}
else null
}
private fun TaskRuntimeContext.checkInsideLocalHistoryFrame(component: Component): Boolean {
val frame = UIUtil.getParentOfType(JFrame::class.java, component)
return frame?.title == FileUtil.toSystemDependentName(virtualFile.path)
}
// If message is null it will remove the existing hint and allow file modification
private fun LessonContext.setEditorHint(@Nls message: String?) {
prepareRuntimeTask {
EditorModificationUtil.setReadOnlyHint(editor, message)
(editor as EditorEx).isViewer = message != null
}
}
private fun LessonContext.modifyFile() {
task {
addFutureStep {
val editor = this.editor
runBackgroundableTask(LessonsBundle.message("local.history.file.modification.progress"), project, cancellable = false) {
val document = editor.document
invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) }
removeLineWithAnimation(editor)
invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) }
Thread.sleep(50)
insertStringWithAnimation(editor, textToAppend, editor.document.textLength)
taskInvokeLater {
editor.caretModel.moveToOffset(document.textLength)
FileDocumentManager.getInstance().saveDocument(document)
completeStep()
}
}
}
}
}
@RequiresBackgroundThread
private fun removeLineWithAnimation(editor: Editor) {
val document = editor.document
val startOffset = document.getLineStartOffset(lineToDelete)
val endOffset = document.getLineEndOffset(lineToDelete)
for (ind in endOffset downTo startOffset) {
invokeAndWaitIfNeeded {
DocumentUtil.writeInRunUndoTransparentAction {
editor.caretModel.moveToOffset(ind)
document.deleteString(ind - 1, ind)
}
}
Thread.sleep(10)
}
}
@RequiresBackgroundThread
private fun insertStringWithAnimation(editor: Editor, text: String, offset: Int) {
val document = editor.document
for (ind in text.indices) {
invokeAndWaitIfNeeded {
DocumentUtil.writeInRunUndoTransparentAction {
document.insertString(offset + ind, text[ind].toString())
editor.caretModel.moveToOffset(offset + ind)
}
}
Thread.sleep(10)
}
}
override val suitableTips = listOf("local_history")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("local.history.help.link"),
LessonUtil.getHelpLink("local-history.html")),
)
} | apache-2.0 | 3c5e261ef2aed9ab15543c461a1609b7 | 37.792839 | 158 | 0.699611 | 4.89732 | false | false | false | false |
Major-/Vicis | legacy/src/main/kotlin/rs/emulate/legacy/title/font/FontDecoder.kt | 1 | 2979 | package rs.emulate.legacy.title.font
import rs.emulate.legacy.IndexedFileSystem
import rs.emulate.legacy.archive.Archive
import rs.emulate.legacy.graphics.GraphicsDecoder
import rs.emulate.legacy.graphics.ImageFormat
/**
* A [GraphicsDecoder] for [Font]s.
*
* @param graphics The [Archive] containing the font.
* @param name The name of the [Font] to decode.
*/
class FontDecoder(graphics: Archive, name: String) : GraphicsDecoder(graphics, name) {
/**
* Decodes the [Font].
*/
fun decode(): Font {
index.readerIndex(data.readUnsignedShort() + 4)
val offset = index.readUnsignedByte()
if (offset > 0) {
index.readerIndex(3 * (offset - 1))
}
val glyphs = Array(GLYPHS_PER_FONT) { decodeGlyph() }
return Font(name, glyphs)
}
/**
* Decodes a single [Glyph].
*/
private fun decodeGlyph(): Glyph {
var horizontalOffset = index.readUnsignedByte()
val verticalOffset = index.readUnsignedByte()
val width = index.readUnsignedShort()
val height = index.readUnsignedShort()
val format = ImageFormat.valueOf(index.readUnsignedByte().toInt())
val raster = decodeRaster(width, height, format)
var spacing = width + SPACING
var left = 0
var right = 0
for (y in height / 7 until height) {
left += raster[y * width].toInt()
right += raster[(y + 1) * width - 1].toInt()
}
if (left <= height / 7) {
spacing--
horizontalOffset = 0
}
if (right <= height / 7) {
spacing--
}
return Glyph(format, raster, height, width, horizontalOffset.toInt(), verticalOffset.toInt(), spacing)
}
/**
* Decodes the raster of a single [Glyph].
*/
private fun decodeRaster(width: Int, height: Int, format: ImageFormat): ByteArray {
val count = width * height
val raster = ByteArray(count)
when (format) {
ImageFormat.COLUMN_ORDERED -> data.readBytes(raster)
ImageFormat.ROW_ORDERED -> for (x in 0 until width) {
for (y in 0 until height) {
raster[x + y * width] = data.readByte()
}
}
}
return raster
}
companion object {
/**
* The amount of Glyphs in a font.
*/
private const val GLYPHS_PER_FONT = 256
/**
* The default spacing offset.
*/
private const val SPACING = 2
/**
* The file id of the title archive.
*/
private const val TITLE_FILE_ID = 1
/**
* Creates a new FontDecoder for the Font with the specified name, using the specified [IndexedFileSystem].
*/
fun create(fs: IndexedFileSystem, name: String): FontDecoder {
return FontDecoder(fs.getArchive(0, TITLE_FILE_ID), name)
}
}
}
| isc | a48c06f4ccabc653ba102da83199eb76 | 26.841121 | 115 | 0.568312 | 4.413333 | false | false | false | false |
android/nowinandroid | core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/NewsResourceCard.kt | 1 | 11193 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.google.samples.apps.nowinandroid.core.designsystem.R as DesignsystemR
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopicTag
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
import com.google.samples.apps.nowinandroid.core.model.data.Author
import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
import com.google.samples.apps.nowinandroid.core.model.data.Topic
import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import kotlinx.datetime.Instant
import kotlinx.datetime.toJavaInstant
/**
* [NewsResource] card used on the following screens: For You, Saved
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NewsResourceCardExpanded(
newsResource: NewsResource,
isBookmarked: Boolean,
onToggleBookmark: () -> Unit,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
val clickActionLabel = stringResource(R.string.card_tap_action)
Card(
onClick = onClick,
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
// Use custom label for accessibility services to communicate button's action to user.
// Pass null for action to only override the label and not the actual action.
modifier = modifier.semantics {
onClick(label = clickActionLabel, action = null)
}
) {
Column {
if (!newsResource.headerImageUrl.isNullOrEmpty()) {
Row {
NewsResourceHeaderImage(newsResource.headerImageUrl)
}
}
Box(
modifier = Modifier.padding(16.dp)
) {
Column {
Row {
NewsResourceAuthors(newsResource.authors)
}
Spacer(modifier = Modifier.height(12.dp))
Row {
NewsResourceTitle(
newsResource.title,
modifier = Modifier.fillMaxWidth((.8f))
)
Spacer(modifier = Modifier.weight(1f))
BookmarkButton(isBookmarked, onToggleBookmark)
}
Spacer(modifier = Modifier.height(12.dp))
NewsResourceDate(newsResource.publishDate)
Spacer(modifier = Modifier.height(12.dp))
NewsResourceShortDescription(newsResource.content)
Spacer(modifier = Modifier.height(12.dp))
NewsResourceTopics(newsResource.topics)
}
}
}
}
}
@Composable
fun NewsResourceHeaderImage(
headerImageUrl: String?
) {
AsyncImage(
placeholder = if (LocalInspectionMode.current) {
painterResource(DesignsystemR.drawable.ic_placeholder_default)
} else {
// TODO b/228077205, show specific loading image visual
null
},
modifier = Modifier
.fillMaxWidth()
.height(180.dp),
contentScale = ContentScale.Crop,
model = headerImageUrl,
// TODO b/226661685: Investigate using alt text of image to populate content description
contentDescription = null // decorative image
)
}
@Composable
fun NewsResourceAuthors(
authors: List<Author>
) {
if (authors.isNotEmpty()) {
// display all authors
val authorNameFormatted =
authors.joinToString(separator = ", ") { author -> author.name }
.uppercase(Locale.getDefault())
val authorImageUrl = authors[0].imageUrl
val authorImageModifier = Modifier
.clip(CircleShape)
.size(24.dp)
Row(verticalAlignment = Alignment.CenterVertically) {
if (authorImageUrl.isNotEmpty()) {
AsyncImage(
modifier = authorImageModifier,
contentScale = ContentScale.Crop,
model = authorImageUrl,
contentDescription = null // decorative image
)
} else {
Icon(
modifier = authorImageModifier
.background(MaterialTheme.colorScheme.surface)
.padding(4.dp),
imageVector = NiaIcons.Person,
contentDescription = null // decorative image
)
}
Spacer(modifier = Modifier.width(8.dp))
Text(authorNameFormatted, style = MaterialTheme.typography.labelSmall)
}
}
}
@Composable
fun NewsResourceTitle(
newsResourceTitle: String,
modifier: Modifier = Modifier
) {
Text(newsResourceTitle, style = MaterialTheme.typography.headlineSmall, modifier = modifier)
}
@Composable
fun BookmarkButton(
isBookmarked: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
NiaToggleButton(
checked = isBookmarked,
onCheckedChange = { onClick() },
modifier = modifier,
icon = {
Icon(
painter = painterResource(NiaIcons.BookmarkBorder),
contentDescription = stringResource(R.string.bookmark)
)
},
checkedIcon = {
Icon(
painter = painterResource(NiaIcons.Bookmark),
contentDescription = stringResource(R.string.unbookmark)
)
}
)
}
@Composable
private fun dateFormatted(publishDate: Instant): String {
var zoneId by remember { mutableStateOf(ZoneId.systemDefault()) }
val context = LocalContext.current
DisposableEffect(context) {
val receiver = TimeZoneBroadcastReceiver(
onTimeZoneChanged = { zoneId = ZoneId.systemDefault() }
)
receiver.register(context)
onDispose {
receiver.unregister(context)
}
}
return DateTimeFormatter.ofPattern("MMM d, yyyy")
.withZone(zoneId).format(publishDate.toJavaInstant())
}
@Composable
fun NewsResourceDate(
publishDate: Instant
) {
Text(dateFormatted(publishDate), style = MaterialTheme.typography.labelSmall)
}
@Composable
fun NewsResourceLink(
newsResource: NewsResource
) {
TODO()
}
@Composable
fun NewsResourceShortDescription(
newsResourceShortDescription: String
) {
Text(newsResourceShortDescription, style = MaterialTheme.typography.bodyLarge)
}
@Composable
fun NewsResourceTopics(
topics: List<Topic>,
modifier: Modifier = Modifier
) {
// Store the ID of the Topic which has its "following" menu expanded, if any.
// To avoid UI confusion, only one topic can have an expanded menu at a time.
var expandedTopicId by remember { mutableStateOf<String?>(null) }
Row(
modifier = modifier.horizontalScroll(rememberScrollState()), // causes narrow chips
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
for (topic in topics) {
NiaTopicTag(
expanded = expandedTopicId == topic.id,
followed = true, // ToDo: Check if topic is followed
onDropMenuToggle = { show ->
expandedTopicId = if (show) topic.id else null
},
onFollowClick = { }, // ToDo
onUnfollowClick = { }, // ToDo
onBrowseClick = { }, // ToDo
text = { Text(text = topic.name.uppercase(Locale.getDefault())) }
)
}
}
}
@Preview("Bookmark Button")
@Composable
fun BookmarkButtonPreview() {
NiaTheme {
Surface {
BookmarkButton(isBookmarked = false, onClick = { })
}
}
}
@Preview("Bookmark Button Bookmarked")
@Composable
fun BookmarkButtonBookmarkedPreview() {
NiaTheme {
Surface {
BookmarkButton(isBookmarked = true, onClick = { })
}
}
}
@Preview("NewsResourceCardExpanded")
@Composable
fun ExpandedNewsResourcePreview() {
NiaTheme {
Surface {
NewsResourceCardExpanded(
newsResource = previewNewsResources[0],
isBookmarked = true,
onToggleBookmark = {},
onClick = {}
)
}
}
}
| apache-2.0 | f24b59f7d03bcdc575870cc6bd9547ac | 33.021277 | 97 | 0.659877 | 4.985746 | false | false | false | false |
datarank/tempest | src/main/java/com/simplymeasured/elasticsearch/plugins/tempest/balancer/ShardSizeCalculator.kt | 1 | 10178 | /*
* The MIT License (MIT)
* Copyright (c) 2016 DataRank, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.simplymeasured.elasticsearch.plugins.tempest.balancer
import com.simplymeasured.elasticsearch.plugins.tempest.balancer.IndexSizingGroup.*
import org.eclipse.collections.api.RichIterable
import org.eclipse.collections.api.list.MutableList
import org.eclipse.collections.api.map.MapIterable
import org.eclipse.collections.impl.factory.Lists
import org.eclipse.collections.impl.factory.Maps
import org.eclipse.collections.impl.list.mutable.CompositeFastList
import org.eclipse.collections.impl.list.mutable.FastList
import org.eclipse.collections.impl.tuple.Tuples.pair
import org.eclipse.collections.impl.utility.LazyIterate
import org.elasticsearch.cluster.metadata.IndexMetaData
import org.elasticsearch.cluster.metadata.MetaData
import org.elasticsearch.cluster.routing.ShardRouting
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation
import org.elasticsearch.common.component.AbstractComponent
import org.elasticsearch.common.inject.Inject
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.index.shard.ShardId
import org.joda.time.DateTime
/**
* Shard Size Calculator and Estimator used for preemptive balancing
*
* Users define index groups by writing regexes that match index names. When the balancer asks for a shard's size
* this class will either report the actual size of the shard or an estimate for how big the shard will get in the near
* future.
*
* The estimation step only occurs if the index in question is young and if it belongs to a group with indexes that are
* not young. Also, if the actual size of a shard is ever larger than the actual size, the estimation is ignored.
*
* Estimates come in two flavors, homogeneous and non-homogeneous. Homogeneous estimation occurs when the new index and
* all non-young indexes in a group have the same number of shards. In this case the estimated size of a shard is the
* average of all like-id shards in the group. For non-homogeneous groups, the average of all shards in the group is
* used.
*
* Note, any indexes not matching a pattern are placed into a "default" group
*/
class ShardSizeCalculator
@Inject constructor(
settings: Settings,
private val indexGroupPartitioner: IndexGroupPartitioner)
: AbstractComponent(settings) {
// should follow settings for tempest.balancer.modelAgeMinutes
var modelAgeInMinutes = 60*12
fun buildShardSizeInfo(allocation: RoutingAllocation) : MapIterable<ShardId, ShardSizeInfo> {
val shards = LazyIterate.concatenate(
allocation.routingNodes().flatMap { it },
allocation.routingNodes().unassigned())
val indexSizingGroupMap = buildIndexGroupMap(allocation.metaData())
return shards
.groupBy { it.shardId() }
.toMap()
.keyValuesView()
.collect { pair(it.one, it.two.collect { buildShardSizingInfo(allocation, it, indexSizingGroupMap) })}
.toMap({ it.one }, { it.two.maxBy { it.estimatedSize } })
}
private fun buildShardSizingInfo(allocation: RoutingAllocation, it: ShardRouting, indexSizingGroupMap: MapIterable<String, IndexSizingGroup>): ShardSizeInfo {
return ShardSizeInfo(
actualSize = allocation.clusterInfo().getShardSize(it) ?: 0,
estimatedSize = estimateShardSize(allocation, indexSizingGroupMap[it.index]!!, it))
}
private fun buildIndexGroupMap(metaData: MetaData): MapIterable<String, IndexSizingGroup> {
val modelTimestampThreshold = DateTime().minusMinutes(modelAgeInMinutes)
val indexGroups = indexGroupPartitioner.partition(metaData)
val indexSizingGroups = FastList.newWithNValues(indexGroups.size(), {IndexSizingGroup()})
return Maps.mutable.empty<String, IndexSizingGroup>().apply {
metaData.forEach { indexMetaData ->
val indexGroup = indexGroups
.indexOfFirst { it.contains(indexMetaData) }
.let { indexSizingGroups[it] }
when {
modelTimestampThreshold.isAfter(indexMetaData.creationDate) -> indexGroup.addModel(indexMetaData)
else -> indexGroup.addYoungIndex(indexMetaData)
}
this.put(indexMetaData.index, indexGroup)
}
}
}
private fun estimateShardSize(
routingAllocation: RoutingAllocation,
indexSizingGroup: IndexSizingGroup,
shardRouting: ShardRouting) : Long {
return arrayOf(routingAllocation.clusterInfo().getShardSize(shardRouting) ?: 0,
shardRouting.expectedShardSize,
calculateEstimatedShardSize(
routingAllocation,
indexSizingGroup,
shardRouting)).max()
?: 0L
}
private fun calculateEstimatedShardSize(
routingAllocation: RoutingAllocation,
indexSizingGroup: IndexSizingGroup,
shardRouting: ShardRouting): Long {
when {
indexSizingGroup.modelIndexes.anySatisfy { it.index == shardRouting.index() } ->
// for older indexes we can usually trust the actual shard size but not when the shard is being initialized
// from a dead node. In those cases we need to "guess" the size by looking at started replicas with the
// same shard id on that index
return Math.max(routingAllocation.clusterInfo().getShardSize(shardRouting) ?: 0,
routingAllocation.findLargestReplicaSize(shardRouting))
!indexSizingGroup.hasModelIndexes() ->
// it's possible for a newly created index to have no models (or for older versions of the index to be
// nuked). In these cases the best guess we have is the actual shard size
return routingAllocation.clusterInfo().getShardSize(shardRouting) ?: 0
indexSizingGroup.isHomogeneous() ->
// this is an ideal case where we see that the new (young) index and one or more model (old) indexes
// look alike. So we want to use the older indexes as a "guess" to the new size. Note that we do an
// average just in case multiple models exists (rare but useful)
return indexSizingGroup.modelIndexes
.map { routingAllocation.findLargestShardSizeById(it.index, shardRouting.id) }
.average()
.toLong()
else ->
// this is a less ideal case where we see a new index with no good model to fall back on. We can still
// make an educated guess on the shard size by averaging the size of the shards in the models
return indexSizingGroup.modelIndexes
.flatMap { routingAllocation.routingTable().index(it.index).shards.values() }
.map { routingAllocation.findLargestShardSizeById(it.value.shardId().index, it.value.shardId.id) }
.average()
.toLong()
}
}
fun youngIndexes(metaData: MetaData) : RichIterable<String> =
buildIndexGroupMap(metaData)
.valuesView()
.toSet()
.flatCollect { it.youngIndexes }
.collect { it.index }
}
// considers both primaries and replicas in order to worst case scenario for shard size estimation
fun RoutingAllocation.findLargestShardSizeById(index: String, id: Int) : Long =
routingTable()
.index(index)
.shard(id)
.map { clusterInfo().getShardSize(it) ?: 0 }
.max() ?: 0
fun RoutingAllocation.findLargestReplicaSize(shardRouting: ShardRouting): Long =
findLargestShardSizeById(shardRouting.index(), shardRouting.id)
class IndexSizingGroup {
val modelIndexes: MutableList<IndexMetaData> = Lists.mutable.empty<IndexMetaData>()
val youngIndexes: MutableList<IndexMetaData> = Lists.mutable.empty<IndexMetaData>()
fun addModel(indexMetadata: IndexMetaData) {
modelIndexes.add(indexMetadata)
}
fun addYoungIndex(indexMetadata: IndexMetaData) {
youngIndexes.add(indexMetadata)
}
fun hasModelIndexes(): Boolean {
return modelIndexes.isNotEmpty()
}
fun isHomogeneous(): Boolean {
val allIndexes = allIndexes()
if (allIndexes.isEmpty) { return false; }
val value = allIndexes.first.numberOfShards
return allIndexes.all { it.numberOfShards == value }
}
fun allIndexes(): CompositeFastList<IndexMetaData> {
val allIndexes = CompositeFastList<IndexMetaData>()
allIndexes.addComposited(modelIndexes)
allIndexes.addComposited(youngIndexes)
return allIndexes
}
data class ShardSizeInfo(val actualSize: Long, val estimatedSize: Long)
} | mit | 6cd5dea565faeb7ec6221707126c8f68 | 46.125 | 162 | 0.681568 | 4.921663 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/friends/usecase/SavePostsUseCase.kt | 1 | 9868 | package io.ipoli.android.friends.usecase
import io.ipoli.android.achievement.Achievement
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.challenge.entity.SharingPreference
import io.ipoli.android.challenge.persistence.ChallengeRepository
import io.ipoli.android.common.UseCase
import io.ipoli.android.common.datetime.days
import io.ipoli.android.common.datetime.daysBetween
import io.ipoli.android.common.datetime.minutes
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.friends.feed.persistence.ImageRepository
import io.ipoli.android.friends.feed.persistence.PostRepository
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.persistence.PlayerRepository
import io.ipoli.android.quest.Quest
import org.threeten.bp.LocalDate
/**
* Created by Venelin Valkov <[email protected]>
* on 07/16/2018.
*/
open class SavePostsUseCase(
private val postRepository: PostRepository,
private val playerRepository: PlayerRepository,
private val challengeRepository: ChallengeRepository,
private val imageRepository: ImageRepository
) : UseCase<SavePostsUseCase.Params, Unit> {
override fun execute(parameters: Params) {
val player = parameters.player ?: playerRepository.find()!!
if (!player.isLoggedIn()) {
return
}
val isAutoPostingEnabled = player.preferences.isAutoPostingEnabled
when (parameters) {
is Params.LevelUp -> {
if (isAutoPostingEnabled && parameters.newLevel % 5 == 0) {
postRepository.save(
Post(
playerId = player.id,
playerAvatar = player.avatar,
playerDisplayName = player.displayName ?: "Unknown Hero",
playerUsername = player.username!!,
playerLevel = parameters.newLevel,
data = Post.Data.LevelUp(parameters.newLevel),
description = null,
reactions = emptyList(),
comments = emptyList(),
status = Post.Status.APPROVED,
isFromCurrentPlayer = true
)
)
}
}
is Params.DailyChallengeComplete -> {
val stats = player.statistics
if (isAutoPostingEnabled && stats.dailyChallengeCompleteStreak.count > 1 && stats.dailyChallengeCompleteStreak.count % 5 == 0L) {
savePost(
player = player,
data = Post.Data.DailyChallengeCompleted(
streak = stats.dailyChallengeCompleteStreak.count.toInt(),
bestStreak = stats.dailyChallengeBestStreak.toInt()
)
)
}
}
is Params.AchievementUnlocked -> {
if (isAutoPostingEnabled && parameters.achievement.level > 1) {
savePost(
player = player,
data = Post.Data.AchievementUnlocked(parameters.achievement)
)
}
}
is Params.QuestComplete -> {
val quest = parameters.quest
savePost(
player = player,
data = if (quest.hasPomodoroTimer) {
Post.Data.QuestWithPomodoroShared(
quest.id,
quest.name,
quest.totalPomodoros!!
)
} else {
Post.Data.QuestShared(
quest.id,
quest.name,
if (quest.hasTimer) quest.actualDuration.asMinutes else 0.minutes
)
},
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
is Params.QuestFromChallengeComplete -> {
val q = parameters.quest
val challenge = parameters.challenge
savePost(
player = player,
data = if (q.hasPomodoroTimer) {
Post.Data.QuestWithPomodoroFromChallengeCompleted(
questId = q.id,
challengeId = challenge.id,
questName = q.name,
challengeName = challenge.name,
pomodoroCount = q.totalPomodoros!!
)
} else {
Post.Data.QuestFromChallengeCompleted(
questId = q.id,
challengeId = challenge.id,
questName = q.name,
challengeName = challenge.name,
durationTracked = if (q.hasTimer) q.actualDuration.asMinutes else 0.minutes
)
},
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
is Params.ChallengeShared -> {
val challenge = parameters.challenge
challengeRepository.save(challenge.copy(sharingPreference = SharingPreference.FRIENDS))
savePost(
player = player,
data = Post.Data.ChallengeShared(challenge.id, challenge.name),
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
is Params.ChallengeComplete -> {
val c = parameters.challenge
savePost(
player = player,
data = Post.Data.ChallengeCompleted(
c.id,
c.name,
c.startDate.daysBetween(c.completedAtDate!!).days
),
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
is Params.HabitCompleted -> {
val habit = parameters.habit
val challenge = parameters.challenge
savePost(
player = player,
data = Post.Data.HabitCompleted(
habitId = habit.id,
habitName = habit.name,
habitDate = LocalDate.now(),
challengeId = challenge?.id,
challengeName = challenge?.name,
isGood = habit.isGood,
streak = habit.streak.current,
bestStreak = habit.streak.best
),
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
}
}
private fun saveImageIfAdded(imageData: ByteArray?) =
imageData?.let {
imageRepository.savePostImage(it)
}
private fun savePost(
player: Player,
data: Post.Data,
imageUrl: String? = null,
description: String? = null
) {
postRepository.save(
Post(
playerId = player.id,
playerAvatar = player.avatar,
playerDisplayName = player.displayName ?: "Unknown Hero",
playerUsername = player.username!!,
playerLevel = player.level,
data = data,
imageUrl = imageUrl,
description = description,
reactions = emptyList(),
comments = emptyList(),
status = imageUrl?.let { Post.Status.PENDING } ?: Post.Status.APPROVED,
isFromCurrentPlayer = true
)
)
}
sealed class Params {
abstract val player: Player?
data class LevelUp(val newLevel: Int, override val player: Player?) : Params()
data class DailyChallengeComplete(override val player: Player? = null) : Params()
data class AchievementUnlocked(val achievement: Achievement, override val player: Player?) :
Params()
data class QuestComplete(
val quest: Quest,
val description: String?,
val imageData: ByteArray?,
override val player: Player?
) : Params()
data class QuestFromChallengeComplete(
val quest: Quest,
val challenge: Challenge,
val description: String?,
val imageData: ByteArray?,
override val player: Player?
) : Params()
data class ChallengeShared(
val challenge: Challenge,
val description: String?,
val imageData: ByteArray?,
override val player: Player?
) : Params()
data class HabitCompleted(
val habit: Habit,
val challenge: Challenge?,
val description: String?,
val imageData: ByteArray?,
override val player: Player?
) : Params()
data class ChallengeComplete(
val challenge: Challenge,
val description: String?,
val imageData: ByteArray?,
override val player: Player? = null
) : Params()
}
} | gpl-3.0 | 503bf25b891a6afbc0de925c6da58cc2 | 37.550781 | 145 | 0.509019 | 5.973366 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddOpenModifierIntention.kt | 4 | 2000 | // 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.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.core.implicitModality
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
class AddOpenModifierIntention : SelfTargetingIntention<KtCallableDeclaration>(
KtCallableDeclaration::class.java, KotlinBundle.lazyMessage("make.open")
), LowPriorityAction {
override fun isApplicableTo(element: KtCallableDeclaration, caretOffset: Int): Boolean {
if (element !is KtProperty && element !is KtNamedFunction) return false
if (element.hasModifier(KtTokens.OPEN_KEYWORD)
|| element.hasModifier(KtTokens.ABSTRACT_KEYWORD)
|| element.hasModifier(KtTokens.PRIVATE_KEYWORD)
) return false
val implicitModality = element.implicitModality()
if (implicitModality == KtTokens.OPEN_KEYWORD || implicitModality == KtTokens.ABSTRACT_KEYWORD) return false
val ktClassOrObject = element.containingClassOrObject ?: return false
return ktClassOrObject.hasModifier(KtTokens.ENUM_KEYWORD)
|| ktClassOrObject.hasModifier(KtTokens.OPEN_KEYWORD)
|| ktClassOrObject.hasModifier(KtTokens.ABSTRACT_KEYWORD)
|| ktClassOrObject.hasModifier(KtTokens.SEALED_KEYWORD)
}
override fun applyTo(element: KtCallableDeclaration, editor: Editor?) {
element.addModifier(KtTokens.OPEN_KEYWORD)
}
} | apache-2.0 | 8efffdb8f8c21209769c56c82bf004bf | 50.307692 | 158 | 0.7705 | 4.975124 | false | false | false | false |
jk1/intellij-community | platform/testFramework/extensions/src/com/intellij/testFramework/assertions/snapshot.kt | 3 | 1793 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testFramework.assertions
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.rt.execution.junit.FileComparisonFailure
import com.intellij.util.io.readText
import org.assertj.core.api.ListAssert
import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.nodes.Node
import org.yaml.snakeyaml.nodes.Tag
import org.yaml.snakeyaml.representer.Represent
import org.yaml.snakeyaml.representer.Representer
import java.nio.file.Path
import java.util.regex.Pattern
class ListAssertEx<ELEMENT>(actual: List<ELEMENT>) : ListAssert<ELEMENT>(actual) {
fun toMatchSnapshot(snapshotFile: Path) {
isNotNull
compareFileContent(actual, snapshotFile)
}
}
fun dumpData(data: Any): String {
val dumperOptions = DumperOptions()
dumperOptions.isAllowReadOnlyProperties = true
dumperOptions.lineBreak = DumperOptions.LineBreak.UNIX
val yaml = Yaml(DumpRepresenter(), dumperOptions)
return yaml.dump(data)
}
private class DumpRepresenter : Representer() {
init {
representers.put(Pattern::class.java, RepresentDump())
}
private inner class RepresentDump : Represent {
override fun representData(data: Any): Node = representScalar(Tag.STR, data.toString())
}
}
@Throws(FileComparisonFailure::class)
fun compareFileContent(actual: Any, snapshotFile: Path) {
val expectedContent = StringUtilRt.convertLineSeparators(snapshotFile.readText())
val actualContent = if (actual is String) actual else dumpData(actual)
if (actualContent != expectedContent) {
throw FileComparisonFailure(null, expectedContent, actualContent, snapshotFile.toString())
}
} | apache-2.0 | 1d5a10c2a0ed246d7047b24527d5ef43 | 34.88 | 140 | 0.78918 | 4.330918 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-darwin-legacy/darwin/test/DarwinLegacyEngineTest.kt | 1 | 4452 | import io.ktor.client.*
import io.ktor.client.engine.darwin.*
import io.ktor.client.engine.darwin.internal.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.client.tests.utils.*
import io.ktor.http.*
import kotlinx.coroutines.*
import platform.Foundation.*
import platform.Foundation.NSHTTPCookieStorage.Companion.sharedHTTPCookieStorage
import kotlin.test.*
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
class DarwinLegacyEngineTest {
@Test
fun testRequestInRunBlocking() = runBlocking {
val client = HttpClient(DarwinLegacy)
try {
withTimeout(1000) {
val response = client.get(TEST_SERVER)
assertEquals("Hello, world!", response.bodyAsText())
}
} finally {
client.close()
}
}
@Test
fun testQueryWithCyrillic() = runBlocking {
val client = HttpClient(DarwinLegacy)
try {
withTimeout(1000) {
val response = client.get("$TEST_SERVER/echo_query?привет")
assertEquals("привет=[]", response.bodyAsText())
}
} finally {
client.close()
}
}
@Test
fun testQueryWithMultipleParams() = runBlocking {
val client = HttpClient(DarwinLegacy)
try {
withTimeout(1000) {
val response = client.get("$TEST_SERVER/echo_query?asd=qwe&asd=123&qwe&zxc=vbn")
assertEquals("asd=[qwe, 123], qwe=[], zxc=[vbn]", response.bodyAsText())
}
} finally {
client.close()
}
}
@Test
fun testNSUrlSanitize() {
assertEquals(
"http://127.0.0.1/echo_query?%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82",
stringToNSUrlString("http://127.0.0.1/echo_query?привет")
)
assertEquals(
"http://%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82.%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82/",
stringToNSUrlString("http://привет.привет/")
)
}
@Test
fun testCookieIsNotPersistedByDefault() = runBlocking {
val client = HttpClient(DarwinLegacy)
try {
client.get("$TEST_SERVER/cookies")
val result = client.get("$TEST_SERVER/cookies/dump")
.bodyAsText()
assertEquals("Cookies: ", result)
} finally {
client.close()
}
}
@Test
fun testCookiePersistedWithSessionStore() = runBlocking {
val client = HttpClient(DarwinLegacy) {
engine {
configureSession {
setHTTPCookieStorage(sharedHTTPCookieStorage)
}
}
}
try {
client.get("$TEST_SERVER/cookies")
val result = client.get("$TEST_SERVER/cookies/dump")
.bodyAsText()
assertEquals("Cookies: hello-cookie=my%2Dawesome%2Dvalue", result)
} finally {
client.close()
}
}
@Test
fun testOverrideDefaultSession(): Unit = runBlocking {
val client = HttpClient(DarwinLegacy) {
val delegate = KtorLegacyNSURLSessionDelegate()
val session = NSURLSession.sessionWithConfiguration(
NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate,
delegateQueue = NSOperationQueue()
)
engine {
usePreconfiguredSession(session, delegate)
}
}
try {
val response = client.get(TEST_SERVER)
assertEquals("Hello, world!", response.bodyAsText())
} finally {
client.close()
}
}
@Test
fun testConfigureRequest(): Unit = runBlocking {
val client = HttpClient(DarwinLegacy) {
engine {
configureRequest {
setValue("my header value", forHTTPHeaderField = "XCustomHeader")
}
}
}
val response = client.get("$TEST_SERVER/headers/echo?headerName=XCustomHeader")
assertEquals(HttpStatusCode.OK, response.status)
assertEquals("my header value", response.bodyAsText())
}
private fun stringToNSUrlString(value: String): String {
return Url(value).toNSUrl().absoluteString!!
}
}
| apache-2.0 | bf029d54258efae294cc6c9c6c21d8f5 | 28.677852 | 119 | 0.569199 | 4.453172 | false | true | false | false |
abertschi/ad-free | app/src/main/java/ch/abertschi/adfree/model/YamlRemoteConfigFactory.kt | 1 | 2404 | /*
* Ad Free
* Copyright (c) 2017 by abertschi, www.abertschi.ch
* See the file "LICENSE" for the full license governing this code.
*/
package ch.abertschi.adfree.model
import com.github.kittinunf.fuel.httpGet
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Created by abertschi on 26.04.17.
*/
class YamlRemoteConfigFactory<MODEL>(val downloadUrl: String,
val modelType: Class<MODEL>,
val preferences: PreferencesFactory) {
private val SETTING_PERSISTENCE_LOCAL_KEY: String = "YAML_CONFIG_FACTORY_PERSISTENCE_"
init {
SETTING_PERSISTENCE_LOCAL_KEY + modelType.canonicalName
}
fun downloadObservable(): io.reactivex.Observable<Pair<MODEL, String>>
= Observable.create<Pair<MODEL, String>> { source ->
downloadUrl.httpGet().responseString { _, _, result ->
val (data, error) = result
if (error == null) {
try {
val yaml = createYamlInstance()
val model = yaml.loadAs(data, modelType)
source.onNext(Pair<MODEL, String>(model, data ?: ""))
} catch (exception: Exception) {
source.onError(exception)
}
} else {
source.onError(error)
}
source.onComplete()
}
}.observeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
fun loadFromLocalStore(defaultReturn: MODEL? = null): MODEL? {
val yaml = createYamlInstance()
val content = preferences.getPreferences().getString(SETTING_PERSISTENCE_LOCAL_KEY, null)
if (content == null) {
return defaultReturn
} else {
return yaml.loadAs(content, modelType)
}
}
fun storeToLocalStore(model: MODEL) {
val yaml = createYamlInstance()
preferences.getPreferences()
.edit().putString(SETTING_PERSISTENCE_LOCAL_KEY, yaml.dump(model)).commit()
}
private fun createYamlInstance(): org.yaml.snakeyaml.Yaml {
val representer = org.yaml.snakeyaml.representer.Representer()
representer.propertyUtils.setSkipMissingProperties(true)
return org.yaml.snakeyaml.Yaml(representer)
}
} | apache-2.0 | 04829b8bfd7b34dad582f903b11ce1d9 | 33.855072 | 97 | 0.610649 | 4.732283 | false | false | false | false |
santaevpavel/ClipboardTranslator | domain/src/main/java/com/example/santaev/domain/usecase/TranslateUseCase.kt | 1 | 1913 | package com.example.santaev.domain.usecase
import com.example.santaev.domain.api.IApiService
import com.example.santaev.domain.api.TranslateRequestDto
import com.example.santaev.domain.dto.LanguageDto
import com.example.santaev.domain.dto.TranslationDto
import com.example.santaev.domain.repository.ITranslationRepository
import io.reactivex.Single
class TranslateUseCase(
private val sourceLanguage: LanguageDto,
private val targetLanguage: LanguageDto,
private val text: String,
private var apiService: IApiService,
private var translationRepository: ITranslationRepository
) {
fun execute(): Single<out Response> {
return apiService.translate(
TranslateRequestDto(
text,
sourceLanguage,
targetLanguage
)
)
.map { response ->
val targetText = response.text.firstOrNull() ?: ""
translationRepository.insert(
TranslationDto(
id = 0,
sourceLangCode = sourceLanguage.code,
targetLangCode = targetLanguage.code,
sourceText = text,
targetText = targetText
)
).subscribe()
Response.Success(
sourceText = text,
targetText = targetText
) as Response
}
.onErrorResumeNext { Single.just(Response.Error()) }
}
sealed class Response {
class Error : Response()
data class Success(
val sourceText: String,
val targetText: String
) : Response()
}
} | apache-2.0 | adbc08040e35d765a1bd0ecee47e118b | 33.8 | 73 | 0.521694 | 6.170968 | false | false | false | false |
eyneill777/SpacePirates | core/src/rustyice/game/actors/TestActor.kt | 1 | 1652 | package rustyice.game.actors
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.physics.box2d.FixtureDef
import rustyengine.RustyEngine
import rustyice.game.Actor
import rustyice.game.physics.SBPhysicsComponent
import rustyice.graphics.Camera
import rustyice.graphics.RenderLayer
import rustyice.physics.LARGE
import rustyice.physics.WALL
/**
* @author gabek
*/
class TestActor() : Actor() {
@Transient private var testSprite: Sprite? = null
val sbPhysicsComponent: SBPhysicsComponent
override fun update(delta: Float) {
super.update(delta)
}
override fun render(batch: Batch, camera: Camera, layer: RenderLayer) {
val testSprite = testSprite
if(testSprite != null){
testSprite.x = x - width / 2
testSprite.y = y - height / 2
testSprite.rotation = rotation
testSprite.draw(batch)
}
}
override fun init() {
super.init()
val fixtureDef = FixtureDef()
fixtureDef.density = 1f
fixtureDef.filter.categoryBits = LARGE.toShort()
fixtureDef.filter.maskBits = (LARGE or
WALL).toShort()
sbPhysicsComponent.addRectangle(width, height, fixtureDef)
val testSprite = Sprite(RustyEngine.resorces.box)
this.testSprite = testSprite
testSprite.setSize(width, height)
testSprite.setOrigin(width/2, height/2)
}
init {
sbPhysicsComponent = SBPhysicsComponent()
physicsComponent = sbPhysicsComponent
width = 1.9f
height = 1.9f
}
}
| mit | 65a627d5b9505bc7a87ca45f13fe1b71 | 26.533333 | 75 | 0.658596 | 4.381963 | false | true | false | false |
Novatec-Consulting-GmbH/testit-testutils | logrecorder/logrecorder-log4j/src/main/kotlin/info/novatec/testit/logrecorder/log4j/junit5/Log4jRecorderExtension.kt | 1 | 3282 | /*
* Copyright 2017-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 info.novatec.testit.logrecorder.log4j.junit5
import info.novatec.testit.logrecorder.api.LogRecord
import info.novatec.testit.logrecorder.log4j.Log4jLogRecord
import info.novatec.testit.logrecorder.log4j.Log4jLogRecorder
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.junit.jupiter.api.extension.*
/**
* This extension will record the loggers specified by a [RecordLoggers] annotation and inject the [LogRecord]
* as a parameter into the test method.
*
* Recording a logger will set its log level to [org.apache.logging.log4j.Level.ALL] for the duration of the test. After the
* test was executed, the log level will be restored to whatever it was before.
*
* @see RecordLoggers
* @see LogRecord
* @since 1.1
*/
class Log4jRecorderExtension : BeforeTestExecutionCallback, AfterTestExecutionCallback,
ParameterResolver {
private val namespace = ExtensionContext.Namespace.create(javaClass)
override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean {
return LogRecord::class.java == parameterContext.parameter.type
}
override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any {
return extensionContext.logRecord
}
override fun beforeTestExecution(context: ExtensionContext) {
val annotation = context.requiredTestMethod.getAnnotation(RecordLoggers::class.java)
?: error("no @RecordLoggers annotation found on test method!")
val fromClasses = annotation.value.map { LogManager.getLogger(it.java) }
val fromNames = annotation.names.map { LogManager.getLogger(it) }
val logRecord = Log4jLogRecord()
context.logRecord = logRecord
val recorders = (fromClasses + fromNames)
.distinct()
.map { it as Logger }
.map { Log4jLogRecorder(it, logRecord) }
.onEach { it.start() }
context.recorders = recorders
}
override fun afterTestExecution(context: ExtensionContext) {
context.recorders.forEach { it.stop() }
}
@Suppress("UNCHECKED_CAST")
private var ExtensionContext.recorders: List<Log4jLogRecorder>
get() = store.get("log-recorders") as List<Log4jLogRecorder>
set(value) = store.put("log-recorders", value)
private var ExtensionContext.logRecord: Log4jLogRecord
get() = store.get("log-record", Log4jLogRecord::class.java)
set(value) = store.put("log-record", value)
private val ExtensionContext.store: ExtensionContext.Store
get() = getStore(namespace)
}
| apache-2.0 | ff5697b201dbba3dd669404adbfee82f | 39.02439 | 124 | 0.727605 | 4.370173 | false | true | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryAdapter.kt | 2 | 1130 | package eu.kanade.tachiyomi.ui.library
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.data.database.models.Manga
/**
* Adapter storing a list of manga in a certain category.
*
* @param view the fragment containing this adapter.
*/
class LibraryCategoryAdapter(view: LibraryCategoryView) :
FlexibleAdapter<LibraryItem>(null, view, true) {
/**
* The list of manga in this category.
*/
private var mangas: List<LibraryItem> = emptyList()
/**
* Sets a list of manga in the adapter.
*
* @param list the list to set.
*/
fun setItems(list: List<LibraryItem>) {
// A copy of manga always unfiltered.
mangas = list.toList()
performFilter()
}
/**
* Returns the position in the adapter for the given manga.
*
* @param manga the manga to find.
*/
fun indexOf(manga: Manga): Int {
return currentItems.indexOfFirst { it.manga.id == manga.id }
}
fun performFilter() {
val s = getFilter(String::class.java) ?: ""
updateDataSet(mangas.filter { it.filter(s) })
}
}
| apache-2.0 | aab5496fcadf143b43d05abf9fdfe553 | 24.681818 | 68 | 0.635398 | 4.169742 | false | false | false | false |
zhudyos/uia | server/src/main/kotlin/io/zhudy/uia/web/ResponseStatusException.kt | 1 | 494 | package io.zhudy.uia.web
/**
* @author Kevin Zou ([email protected])
*/
class ResponseStatusException : RuntimeException {
val status: Int
var reason: String = ""
/**
*
*/
constructor(status: Int) : super("http status [$status]") {
this.status = status
}
/**
*
*/
constructor(status: Int, reason: String) : super(reason) {
this.status = status
this.reason = reason
}
override fun fillInStackTrace() = this
} | apache-2.0 | ee1d1d24e81d0b1f64d1418760ca0c49 | 17.333333 | 63 | 0.572874 | 3.859375 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.