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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mvarnagiris/expensius | app/src/main/kotlin/com/mvcoding/expensius/feature/tag/TagItemView.kt | 1 | 2113 | /*
* Copyright (C) 2015 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature.tag
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.mvcoding.expensius.R
import com.mvcoding.expensius.extension.getColorFromTheme
import com.mvcoding.expensius.extension.makeOutlineProviderOval
import com.mvcoding.expensius.model.ModelState.ARCHIVED
import com.mvcoding.expensius.model.Tag
class TagItemView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
LinearLayout(context, attrs, defStyleAttr) {
private val colorImageView by lazy { findViewById(R.id.colorImageView) as ImageView }
private val titleTextView by lazy { findViewById(R.id.titleTextView) as TextView }
private val textColorPrimary by lazy { getColorFromTheme(context, android.R.attr.textColorPrimary) }
private val textColorSecondary by lazy { getColorFromTheme(context, android.R.attr.textColorSecondary) }
override fun onFinishInflate() {
super.onFinishInflate()
colorImageView.makeOutlineProviderOval()
}
fun setTag(tag: Tag) {
colorImageView.setColorFilter(getIconColor(tag))
titleTextView.setTextColor(getTextColor(tag))
titleTextView.text = tag.title.text
}
private fun getIconColor(tag: Tag) = if (tag.modelState == ARCHIVED) textColorSecondary else tag.color.rgb
private fun getTextColor(tag: Tag) = if (tag.modelState == ARCHIVED) textColorSecondary else textColorPrimary
} | gpl-3.0 | aa582b35061cef663bdbb5f4c181310a | 41.28 | 115 | 0.771415 | 4.514957 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/CafeteriaMenuInflater.kt | 1 | 7685 | package de.tum.`in`.tumcampusapp.component.ui.cafeteria
import android.content.Context
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ImageSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.CafeteriaMenu
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.CafeteriaPrices
import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.FavoriteDish
import de.tum.`in`.tumcampusapp.database.TcaDb
import de.tum.`in`.tumcampusapp.utils.Utils
import kotlinx.android.synthetic.main.card_list_header.view.*
import kotlinx.android.synthetic.main.card_price_line.view.*
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import java.util.regex.Pattern
class CafeteriaMenuInflater(
private val context: Context,
private val rootView: ViewGroup,
private val isBigLayout: Boolean
) {
private val inflater = LayoutInflater.from(context)
private val rolePrices: Map<String, String> by lazy {
CafeteriaPrices.getRolePrices(context)
}
private val dao: FavoriteDishDao by lazy {
TcaDb.getInstance(context).favoriteDishDao()
}
fun inflate(menu: CafeteriaMenu, isFirstInSection: Boolean): View? {
val typeShort = menu.typeShort
val shouldShow = Utils.getSettingBool(
context,
"card_cafeteria_$typeShort",
"tg" == typeShort || "ae" == typeShort
)
if (!isBigLayout && !shouldShow) {
return null
}
if (isFirstInSection) {
val header = inflater.inflate(R.layout.card_list_header, rootView, false)
header.list_header.text = menu.typeLong.replace("[0-9]", "").trim()
rootView.addView(header)
}
val menuView = inflater.inflate(R.layout.card_price_line, rootView, false)
if (!isBigLayout) {
menu.name = prepare(menu.name)
}
val menuSpan = menuToSpan(context, menu.name)
menuView.line_name.text = menuSpan
val isPriceAvailable = rolePrices.containsKey(menu.typeLong)
if (isPriceAvailable) {
inflateWithPrice(menuView, menu)
} else {
inflateWithoutPrice(menuView)
}
return menuView
}
private fun inflateWithPrice(view: View, menu: CafeteriaMenu) = with(view) {
val price = rolePrices[menu.typeLong]
price?.let {
line_price.text = String.format("%s €", it)
}
val tag = "${menu.name}__${menu.cafeteriaId}"
val isFavorite = dao.checkIfFavoriteDish(tag).isNotEmpty()
favoriteDish.isSelected = isFavorite
favoriteDish.setOnClickListener { view ->
if (!view.isSelected) {
val formatter = DateTimeFormat.forPattern("dd-MM-yyyy")
val date = formatter.print(DateTime.now())
dao.insertFavouriteDish(
FavoriteDish.create(menu.cafeteriaId, menu.name, date, tag)
)
view.isSelected = true
} else {
dao.deleteFavoriteDish(menu.cafeteriaId, menu.name)
view.isSelected = false
}
}
}
private fun inflateWithoutPrice(view: View) = with(view) {
line_price.visibility = View.GONE
favoriteDish.visibility = View.GONE
}
companion object {
private val SPLIT_ANNOTATIONS_PATTERN = Pattern.compile("\\(([A-Za-z0-9]+),")
private val NUMERICAL_ANNOTATIONS_PATTERN = Pattern.compile("\\(([1-9]|10|11)\\)")
/**
* Converts menu text to {@link SpannableString}.
* Replaces all (v), ... annotations with images
*
* @param context Context
* @param menu Text with annotations
* @return Spannable text with images
*/
@JvmStatic
fun menuToSpan(context: Context, menu: String): SpannableString {
val processedMenu = splitAnnotations(menu)
val text = SpannableString(processedMenu)
replaceWithImg(context, processedMenu, text, "(v)", R.drawable.meal_vegan)
replaceWithImg(context, processedMenu, text, "(f)", R.drawable.meal_veggie)
replaceWithImg(context, processedMenu, text, "(R)", R.drawable.meal_beef)
replaceWithImg(context, processedMenu, text, "(S)", R.drawable.meal_pork)
replaceWithImg(context, processedMenu, text, "(GQB)", R.drawable.ic_gqb)
replaceWithImg(context, processedMenu, text, "(99)", R.drawable.meal_alcohol)
return text
// TODO: Move to CafeteriaMenu
/* TODO Someday replace all of them:
'2':'mit Konservierungsstoff',
'3':'mit Antioxidationsmittel',
'4':'mit Geschmacksverstärker',
'5':'geschwefelt',
'6':'geschwärzt (Oliven)',
'7':'unbekannt',
'8':'mit Phosphat',
'9':'mit Süßungsmitteln',
'10':'enthält eine Phenylalaninquelle',
'11':'mit einer Zuckerart und Süßungsmitteln',
'99':'mit Alkohol',
'f':'fleischloses Gericht',
'v':'veganes Gericht',
'GQB':'Geprüfte Qualität - Bayern',
'S':'mit Schweinefleisch',
'R':'mit Rindfleisch',
'K':'mit Kalbfleisch',
'MSC':'Marine Stewardship Council',
'Kn':'Knoblauch',
'13':'kakaohaltige Fettglasur',
'14':'Gelatine',
'Ei':'Hühnerei',
'En':'Erdnuss',
'Fi':'Fisch',
'Gl':'Glutenhaltiges Getreide',
'GlW':'Weizen',
'GlR':'Roggen',
'GlG':'Gerste',
'GlH':'Hafer',
'GlD':'Dinkel',
'Kr':'Krebstiere',
'Lu':'Lupinen',
'Mi':'Milch und Laktose',
'Sc':'Schalenfrüchte',
'ScM':'Mandeln',
'ScH':'Haselnüsse',
'ScW':'Walnüsse',
'ScC':'Cashewnüssen',
'ScP':'Pistazien',
'Se':'Sesamsamen',
'Sf':'Senf',
'Sl':'Sellerie',
'So':'Soja',
'Sw':'Schwefeloxid und Sulfite',
'Wt':'Weichtiere'
*/
}
private fun replaceWithImg(context: Context, menu: String,
text: Spannable, sym: String, drawable: Int) {
var index = menu.indexOf(sym)
while (index >= 0) {
val imageSpan = ImageSpan(context, drawable)
text.setSpan(imageSpan, index, index + sym.length, 0)
index = menu.indexOf(sym, index + sym.length)
}
}
/**
* Replaces all annotations that cannot be replaces with images such as (1), ...
*
* @param menu Text to delete annotations from
* @return Text without un-replaceable annotations
*/
private fun prepare(menu: String): String {
val tmp = splitAnnotations(menu)
return NUMERICAL_ANNOTATIONS_PATTERN.matcher(tmp)
.replaceAll("")
}
private fun splitAnnotations(menu: String): String {
var len: Int
var tmp = menu
do {
len = tmp.length
tmp = SPLIT_ANNOTATIONS_PATTERN.matcher(tmp)
.replaceFirst("($1)(")
} while (tmp.length > len)
return tmp
}
}
}
| gpl-3.0 | 04acb33a2ea2fd5fd6e1e1c869daa871 | 34.341014 | 90 | 0.570479 | 4.066278 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/CervicalMucusRecord.kt | 3 | 5578 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:RestrictTo(RestrictTo.Scope.LIBRARY)
package androidx.health.connect.client.records
import androidx.annotation.IntDef
import androidx.annotation.RestrictTo
import androidx.health.connect.client.records.metadata.Metadata
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures the description of cervical mucus. Each record represents a self-assessed description of
* cervical mucus for a user. All fields are optional and can be used to describe the look and feel
* of cervical mucus.
*/
public class CervicalMucusRecord(
override val time: Instant,
override val zoneOffset: ZoneOffset?,
/** The consistency of the user's cervical mucus. */
@property:Appearances public val appearance: Int = APPEARANCE_UNKNOWN,
/** The feel of the user's cervical mucus. */
@property:Sensations public val sensation: Int = SENSATION_UNKNOWN,
override val metadata: Metadata = Metadata.EMPTY,
) : InstantaneousRecord {
companion object {
const val APPEARANCE_UNKNOWN = 0
const val APPEARANCE_DRY = 1
const val APPEARANCE_STICKY = 2
const val APPEARANCE_CREAMY = 3
const val APPEARANCE_WATERY = 4
/** A constant describing clear or egg white like looking cervical mucus. */
const val APPEARANCE_EGG_WHITE = 5
/** A constant describing an unusual (worth attention) kind of cervical mucus. */
const val APPEARANCE_UNUSUAL = 6
const val SENSATION_UNKNOWN = 0
const val SENSATION_LIGHT = 1
const val SENSATION_MEDIUM = 2
const val SENSATION_HEAVY = 3
/** Internal mappings useful for interoperability between integers and strings. */
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val APPEARANCE_STRING_TO_INT_MAP: Map<String, Int> =
mapOf(
Appearance.CLEAR to APPEARANCE_EGG_WHITE,
Appearance.CREAMY to APPEARANCE_CREAMY,
Appearance.DRY to APPEARANCE_DRY,
Appearance.STICKY to APPEARANCE_STICKY,
Appearance.WATERY to APPEARANCE_WATERY,
Appearance.UNUSUAL to APPEARANCE_UNUSUAL
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val APPEARANCE_INT_TO_STRING_MAP = APPEARANCE_STRING_TO_INT_MAP.reverse()
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val SENSATION_STRING_TO_INT_MAP: Map<String, Int> =
mapOf(
Sensation.LIGHT to SENSATION_LIGHT,
Sensation.MEDIUM to SENSATION_MEDIUM,
Sensation.HEAVY to SENSATION_HEAVY
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val SENSATION_INT_TO_STRING_MAP = SENSATION_STRING_TO_INT_MAP.reverse()
}
/** List of supported Cervical Mucus Sensation types on Health Platform. */
internal object Sensation {
const val LIGHT = "light"
const val MEDIUM = "medium"
const val HEAVY = "heavy"
}
/**
* List of supported Cervical Mucus Sensation types on Health Platform.
* @suppress
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(value = [SENSATION_UNKNOWN, SENSATION_LIGHT, SENSATION_MEDIUM, SENSATION_HEAVY])
@RestrictTo(RestrictTo.Scope.LIBRARY)
annotation class Sensations
/** The consistency or appearance of the user's cervical mucus. */
internal object Appearance {
const val DRY = "dry"
const val STICKY = "sticky"
const val CREAMY = "creamy"
const val WATERY = "watery"
const val CLEAR = "clear"
const val UNUSUAL = "unusual"
}
/**
* The consistency or appearance of the user's cervical mucus.
* @suppress
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(
value =
[
APPEARANCE_UNKNOWN,
APPEARANCE_DRY,
APPEARANCE_STICKY,
APPEARANCE_CREAMY,
APPEARANCE_WATERY,
APPEARANCE_EGG_WHITE,
APPEARANCE_UNUSUAL
]
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
annotation class Appearances
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CervicalMucusRecord
if (time != other.time) return false
if (zoneOffset != other.zoneOffset) return false
if (appearance != other.appearance) return false
if (sensation != other.sensation) return false
if (metadata != other.metadata) return false
return true
}
override fun hashCode(): Int {
var result = time.hashCode()
result = 31 * result + (zoneOffset?.hashCode() ?: 0)
result = 31 * result + appearance
result = 31 * result + sensation
result = 31 * result + metadata.hashCode()
return result
}
}
| apache-2.0 | 6f9f069c6b40cd8de461b770cceab15e | 34.081761 | 100 | 0.646648 | 4.068563 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/send/TextStoryPostSendRepository.kt | 1 | 5527 | package org.thoughtcrime.securesms.mediasend.v2.text.send
import android.graphics.Bitmap
import android.net.Uri
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import org.signal.core.util.ThreadUtil
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.ThreadDatabase
import org.thoughtcrime.securesms.database.model.StoryType
import org.thoughtcrime.securesms.database.model.databaseprotos.StoryTextPost
import org.thoughtcrime.securesms.fonts.TextFont
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.keyvalue.StorySend
import org.thoughtcrime.securesms.linkpreview.LinkPreview
import org.thoughtcrime.securesms.mediasend.v2.UntrustedRecords
import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryPostCreationState
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage
import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage
import org.thoughtcrime.securesms.providers.BlobProvider
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.stories.Stories
import org.thoughtcrime.securesms.util.Base64
import java.io.ByteArrayOutputStream
private val TAG = Log.tag(TextStoryPostSendRepository::class.java)
class TextStoryPostSendRepository {
fun compressToBlob(bitmap: Bitmap): Single<Uri> {
return Single.fromCallable {
val outputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
bitmap.recycle()
BlobProvider.getInstance().forData(outputStream.toByteArray()).createForSingleUseInMemory()
}.subscribeOn(Schedulers.computation())
}
fun send(contactSearchKey: Set<ContactSearchKey>, textStoryPostCreationState: TextStoryPostCreationState, linkPreview: LinkPreview?, identityChangesSince: Long): Single<TextStoryPostSendResult> {
return UntrustedRecords
.checkForBadIdentityRecords(contactSearchKey.filterIsInstance(ContactSearchKey.RecipientSearchKey::class.java).toSet(), identityChangesSince)
.toSingleDefault<TextStoryPostSendResult>(TextStoryPostSendResult.Success)
.onErrorReturn {
if (it is UntrustedRecords.UntrustedRecordsException) {
TextStoryPostSendResult.UntrustedRecordsError(it.untrustedRecords)
} else {
Log.w(TAG, "Unexpected error occurred", it)
TextStoryPostSendResult.Failure
}
}
.flatMap { result ->
if (result is TextStoryPostSendResult.Success) {
performSend(contactSearchKey, textStoryPostCreationState, linkPreview)
} else {
Single.just(result)
}
}
}
private fun performSend(contactSearchKey: Set<ContactSearchKey>, textStoryPostCreationState: TextStoryPostCreationState, linkPreview: LinkPreview?): Single<TextStoryPostSendResult> {
return Single.fromCallable {
val messages: MutableList<OutgoingSecureMediaMessage> = mutableListOf()
val distributionListSentTimestamp = System.currentTimeMillis()
for (contact in contactSearchKey) {
val recipient = Recipient.resolved(contact.requireShareContact().recipientId.get())
val isStory = contact is ContactSearchKey.RecipientSearchKey.Story || recipient.isDistributionList
if (isStory && !recipient.isMyStory) {
SignalStore.storyValues().setLatestStorySend(StorySend.newSend(recipient))
}
val storyType: StoryType = when {
recipient.isDistributionList -> SignalDatabase.distributionLists.getStoryType(recipient.requireDistributionListId())
isStory -> StoryType.STORY_WITH_REPLIES
else -> StoryType.NONE
}
val message = OutgoingMediaMessage(
recipient,
serializeTextStoryState(textStoryPostCreationState),
emptyList(),
if (recipient.isDistributionList) distributionListSentTimestamp else System.currentTimeMillis(),
-1,
0,
false,
ThreadDatabase.DistributionTypes.DEFAULT,
storyType.toTextStoryType(),
null,
false,
null,
emptyList(),
listOfNotNull(linkPreview),
emptyList(),
mutableSetOf(),
mutableSetOf(),
null
)
messages.add(OutgoingSecureMediaMessage(message))
ThreadUtil.sleep(5)
}
Stories.sendTextStories(messages)
}.flatMap { messages ->
messages.toSingleDefault<TextStoryPostSendResult>(TextStoryPostSendResult.Success)
}
}
private fun serializeTextStoryState(textStoryPostCreationState: TextStoryPostCreationState): String {
val builder = StoryTextPost.newBuilder()
builder.body = textStoryPostCreationState.body.toString()
builder.background = textStoryPostCreationState.backgroundColor.serialize()
builder.style = when (textStoryPostCreationState.textFont) {
TextFont.REGULAR -> StoryTextPost.Style.REGULAR
TextFont.BOLD -> StoryTextPost.Style.BOLD
TextFont.SERIF -> StoryTextPost.Style.SERIF
TextFont.SCRIPT -> StoryTextPost.Style.SCRIPT
TextFont.CONDENSED -> StoryTextPost.Style.CONDENSED
}
builder.textBackgroundColor = textStoryPostCreationState.textBackgroundColor
builder.textForegroundColor = textStoryPostCreationState.textForegroundColor
return Base64.encodeBytes(builder.build().toByteArray())
}
}
| gpl-3.0 | 0ccc156a3af5646f8401e12fde1cef62 | 41.844961 | 197 | 0.756287 | 4.908526 | false | false | false | false |
androidx/androidx | compose/ui/ui-inspection/src/androidTest/java/androidx/compose/ui/inspection/util/ProtoExtensions.kt | 3 | 5059 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.inspection.util
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.Command
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.ComposableNode
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetAllParametersCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetComposablesCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParametersCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.GetParameterDetailsCommand
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.ParameterReference
import layoutinspector.compose.inspection.LayoutInspectorComposeProtocol.UpdateSettingsCommand
fun List<LayoutInspectorComposeProtocol.StringEntry>.toMap() = associate { it.id to it.str }
fun GetParametersCommand(
rootViewId: Long,
node: ComposableNode,
useDelayedParameterExtraction: Boolean,
skipSystemComposables: Boolean = true
): Command = if (useDelayedParameterExtraction) {
GetParametersByAnchorIdCommand(rootViewId, node.anchorHash, node.id, skipSystemComposables)
} else {
GetParametersByIdCommand(rootViewId, node.id, skipSystemComposables)
}
fun GetParametersByIdCommand(
rootViewId: Long,
composableId: Long,
skipSystemComposables: Boolean = true
): Command = Command.newBuilder().apply {
getParametersCommand = GetParametersCommand.newBuilder().apply {
this.rootViewId = rootViewId
this.composableId = composableId
this.skipSystemComposables = skipSystemComposables
}.build()
}.build()
fun GetParametersByAnchorIdCommand(
rootViewId: Long,
anchorId: Int,
composableId: Long,
skipSystemComposables: Boolean = true
): Command = Command.newBuilder().apply {
getParametersCommand = GetParametersCommand.newBuilder().apply {
this.rootViewId = rootViewId
this.anchorHash = anchorId
this.composableId = composableId
this.skipSystemComposables = skipSystemComposables
}.build()
}.build()
fun GetAllParametersCommand(
rootViewId: Long,
skipSystemComposables: Boolean = true
): Command = Command.newBuilder().apply {
getAllParametersCommand = GetAllParametersCommand.newBuilder().apply {
this.rootViewId = rootViewId
this.skipSystemComposables = skipSystemComposables
}.build()
}.build()
fun GetParameterDetailsCommand(
rootViewId: Long,
reference: ParameterReference,
startIndex: Int,
maxElements: Int,
skipSystemComposables: Boolean = true
): Command = Command.newBuilder().apply {
getParameterDetailsCommand = GetParameterDetailsCommand.newBuilder().apply {
this.rootViewId = rootViewId
this.skipSystemComposables = skipSystemComposables
this.reference = reference
if (startIndex >= 0) {
this.startIndex = startIndex
}
if (maxElements >= 0) {
this.maxElements = maxElements
}
}.build()
}.build()
fun GetComposablesCommand(
rootViewId: Long,
skipSystemComposables: Boolean = true,
generation: Int = 1,
extractAllParameters: Boolean = false
): Command =
Command.newBuilder().apply {
getComposablesCommand = GetComposablesCommand.newBuilder().apply {
this.rootViewId = rootViewId
this.skipSystemComposables = skipSystemComposables
this.generation = generation
this.extractAllParameters = extractAllParameters
}
.setRootViewId(rootViewId)
.setSkipSystemComposables(skipSystemComposables)
.setGeneration(generation)
.build()
}.build()
fun GetUpdateSettingsCommand(
includeRecomposeCounts: Boolean = false,
keepRecomposeCounts: Boolean = false,
delayParameterExtractions: Boolean = false
): Command =
Command.newBuilder().apply {
updateSettingsCommand = UpdateSettingsCommand.newBuilder().apply {
this.includeRecomposeCounts = includeRecomposeCounts
this.keepRecomposeCounts = keepRecomposeCounts
this.delayParameterExtractions = delayParameterExtractions
}.build()
}.build()
fun ComposableNode.flatten(): List<ComposableNode> =
listOf(this).plus(this.childrenList.flatMap { it.flatten() })
| apache-2.0 | 97c2cad4dd782da9a738f4b5ff10511c | 37.618321 | 99 | 0.747381 | 5.364793 | false | false | false | false |
Popalay/Tutors | tutors-kotlin/src/main/kotlin/com/github/popalay/tutors/TutorsBuilder.kt | 1 | 1115 | package com.github.popalay.tutors
class TutorsBuilder(var textColorRes: Int = 0,
var shadowColorRes: Int = 0,
var textSizeRes: Int = 0,
var completeIconRes: Int = 0,
var spacingRes: Int = 0,
var lineWidthRes: Int = 0,
var cancelable: Boolean = false) {
constructor(init: TutorsBuilder.() -> Unit) : this() {
init()
}
fun textColorRes(init: TutorsBuilder.() -> Int) = apply { textColorRes = init() }
fun shadowColorRes(init: TutorsBuilder.() -> Int) = apply { shadowColorRes = init() }
fun textSizeRes(init: TutorsBuilder.() -> Int) = apply { textSizeRes = init() }
fun completeIconRes(init: TutorsBuilder.() -> Int) = apply { completeIconRes = init() }
fun spacingRes(init: TutorsBuilder.() -> Int) = apply { spacingRes = init() }
fun lineWidthRes(init: TutorsBuilder.() -> Int) = apply { lineWidthRes = init() }
fun cancelable(init: TutorsBuilder.() -> Boolean) = apply { cancelable = init() }
fun build() = Tutors.newInstance(this)
}
| apache-2.0 | f672440deedef55c4300ce087db95e83 | 34.967742 | 91 | 0.58565 | 4.069343 | false | false | false | false |
Soya93/Extract-Refactoring | plugins/settings-repository/src/settings/IcsSettings.kt | 4 | 3335 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
import com.fasterxml.jackson.databind.ObjectMapper
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.*
import java.nio.file.Path
private val DEFAULT_COMMIT_DELAY = 10 * Time.MINUTE
class MyPrettyPrinter : DefaultPrettyPrinter() {
init {
_arrayIndenter = DefaultPrettyPrinter.NopIndenter.instance
}
override fun createInstance() = MyPrettyPrinter()
override fun writeObjectFieldValueSeparator(jg: JsonGenerator) {
jg.writeRaw(": ")
}
override fun writeEndObject(jg: JsonGenerator, nrOfEntries: Int) {
if (!_objectIndenter.isInline) {
--_nesting
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(jg, _nesting)
}
jg.writeRaw('}')
}
override fun writeEndArray(jg: JsonGenerator, nrOfValues: Int) {
if (!_arrayIndenter.isInline) {
--_nesting
}
jg.writeRaw(']')
}
}
fun saveSettings(settings: IcsSettings, settingsFile: Path) {
val serialized = ObjectMapper().writer(MyPrettyPrinter()).writeValueAsBytes(settings)
if (serialized.size <= 2) {
settingsFile.delete()
}
else {
settingsFile.write(serialized)
}
}
fun loadSettings(settingsFile: Path): IcsSettings {
if (!settingsFile.exists()) {
return IcsSettings()
}
val settings = ObjectMapper().readValue(settingsFile.toFile(), IcsSettings::class.java)
if (settings.commitDelay <= 0) {
settings.commitDelay = DEFAULT_COMMIT_DELAY
}
return settings
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
class IcsSettings {
var shareProjectWorkspace = false
var commitDelay = DEFAULT_COMMIT_DELAY
var doNoAskMapProject = false
var readOnlySources: List<ReadonlySource> = SmartList()
var autoSync = true
}
@JsonInclude(value = JsonInclude.Include.NON_DEFAULT)
@JsonIgnoreProperties(ignoreUnknown = true)
class ReadonlySource(var url: String? = null, var active: Boolean = true) {
val path: String?
@JsonIgnore
get() {
if (url == null) {
return null
}
else {
var fileName = PathUtilRt.getFileName(url!!)
val suffix = ".git"
if (fileName.endsWith(suffix)) {
fileName = fileName.substring(0, fileName.length - suffix.length)
}
// the convention is that the .git extension should be used for bare repositories
return "${FileUtil.sanitizeFileName(fileName, false)}.${Integer.toHexString(url!!.hashCode())}.git"
}
}
} | apache-2.0 | 8b0d016a2d49f16a88328bb0ffeffff0 | 29.327273 | 107 | 0.717541 | 4.221519 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/info/industry/IndustryProjectFragment.kt | 2 | 2235 | package me.proxer.app.info.industry
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager.VERTICAL
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import me.proxer.app.GlideApp
import me.proxer.app.R
import me.proxer.app.base.PagedContentFragment
import me.proxer.app.media.MediaActivity
import me.proxer.app.util.DeviceUtils
import me.proxer.app.util.extension.toCategory
import me.proxer.app.util.extension.unsafeLazy
import me.proxer.library.entity.list.IndustryProject
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class IndustryProjectFragment : PagedContentFragment<IndustryProject>() {
companion object {
fun newInstance() = IndustryProjectFragment().apply {
arguments = bundleOf()
}
}
override val emptyDataMessage = R.string.error_no_data_projects
override val isSwipeToRefreshEnabled = false
override val viewModel by viewModel<IndustryProjectViewModel> { parametersOf(id) }
private val industryActivity
get() = activity as IndustryActivity
private val id: String
get() = industryActivity.id
override val layoutManager by unsafeLazy {
StaggeredGridLayoutManager(DeviceUtils.calculateSpanAmount(requireActivity()) + 1, VERTICAL)
}
override var innerAdapter by Delegates.notNull<IndustryProjectAdapter>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
innerAdapter = IndustryProjectAdapter()
innerAdapter.clickSubject
.autoDisposable(this.scope())
.subscribe { (view, project) ->
MediaActivity.navigateTo(requireActivity(), project.id, project.name, project.medium.toCategory(), view)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
innerAdapter.glide = GlideApp.with(this)
}
}
| gpl-3.0 | fdc4b8d47837541e4b2302b967aa5118 | 32.358209 | 120 | 0.750336 | 4.765458 | false | false | false | false |
qikh/kong-lang | src/main/kotlin/evaluator/Evaluator.kt | 1 | 8259 | package evaluator
import ast.*
import environment.Environment
import types.*
import types.Function
fun Eval(node: Node, env: Environment): types.Object {
when (node) {
is Program -> return evalProgram(node, env)
is ExpressionStatement -> return Eval(node.expression, env)
is IntegerLiteral -> return types.Integer(node.value)
is BooleanLiteral -> return nativeBoolToBoolean(node.value)
is StringLiteral -> return types.Str(node.value)
is PrefixExpression -> {
val rightVal = Eval(node.right, env)
if (isError(rightVal)) {
return rightVal
}
return evalPrefixExpression(node.operator, rightVal)
}
is InfixExpression -> {
val leftVal = Eval(node.left, env)
if (isError(leftVal)) {
return leftVal
}
val rightVal = Eval(node.right, env)
if (isError(rightVal)) {
return rightVal
}
return evalInfixExpression(node.operator, leftVal, rightVal)
}
is BlockStatement -> return evalBlockStatement(node, env)
is IfExpression -> return evalIfExpression(node, env)
is ReturnStatement -> {
val value = Eval(node.returnValue, env)
if (isError(value)) {
return value
}
return ReturnValue(value)
}
is LetStatement -> {
val value = Eval(node.value, env)
if (isError(value)) {
return value
}
return env.set(node.name.value, value)
}
is Identifier -> {
return evalIdentifier(node, env)
}
is FunctionLiteral -> {
val params = node.parameters
val body = node.body
return Function(params, body, env)
}
is CallExpression -> {
val function = Eval(node.function, env)
if (isError(function)) {
return function
}
val args = evalExpressions(node.arguments, env)
if (args.size == 1 && isError(args[0])) {
return args[0]
}
return applyFunction(function, args)
}
else -> return NULL
}
}
fun applyFunction(function: Object, args: List<Object>): Object {
when (function) {
is Function -> {
val extendedEnv = extendedFunctionEnv(function, args)
val evaluated = Eval(function.body, extendedEnv)
return unwrapReturnValue(evaluated)
}
is Builtin -> {
return function.builtinFn.invoke(args)
}
else -> return Error("not a function: ${function.type()}")
}
}
fun extendedFunctionEnv(function: Function, args: List<Object>): Environment {
val env = Environment(function.env)
for (i in 0..function.parameters.size - 1) {
env.set(function.parameters[i].value, args[i])
}
return env
}
fun unwrapReturnValue(obj: Object): Object {
if (obj is ReturnValue) {
return obj.value
}
return obj
}
fun evalExpressions(arguments: List<Expression>, env: Environment): List<types.Object> {
val result = mutableListOf<types.Object>()
arguments.forEach {
val evaluated = Eval(it, env)
if (isError(evaluated)) {
return listOf(evaluated)
}
result.add(evaluated)
}
return result.toList()
}
fun evalIdentifier(node: Identifier, env: Environment): Object {
val ident = env.get(node.value)
if (ident != null) {
return ident
}
val builtin = builtinFunctions.get(node.value)
if (builtin != null) {
return builtin
}
return Error("identifier not found: " + node.value)
}
fun isError(obj: types.Object): Boolean {
if (obj != NULL) {
return obj.type() == ERROR_OBJ
}
return false
}
fun evalBlockStatement(node: BlockStatement, env: Environment): Object {
var result: types.Object = NULL
for (statement in node.statements) {
result = Eval(statement, env)
if (result != NULL) {
if (result.type() == RETURN_VALUE_OBJ || result.type() == ERROR_OBJ) {
return result
}
}
}
return result
}
fun evalProgram(node: Program, env: Environment): Object {
var result: types.Object = NULL
for (statement in node.statements) {
result = Eval(statement, env)
when (result) {
is ReturnValue -> return result.value
is Error -> return result
}
}
return result
}
fun evalIfExpression(node: IfExpression, env: Environment): Object {
val condition = Eval(node.condition, env)
if (isError(condition)) {
return condition
}
if (isTruth(condition)) {
return Eval(node.consequence, env)
} else if (node.alternative != null) {
return Eval(node.alternative, env)
} else {
return NULL
}
}
fun isTruth(condition: Object): Boolean {
when (condition) {
NULL -> return false
TRUE -> return true
FALSE -> return false
else -> return true
}
}
fun evalInfixExpression(operator: String, left: Object, right: Object): Object {
if (left.type() == types.INTEGER_OBJ && right.type() == types.INTEGER_OBJ) {
return evalIntegerInfixExpression(operator, left, right)
} else if (left.type() != right.type()) {
return types.Error("type mismatch: ${left.type()} $operator ${right.type()}")
} else if (left.type() == types.STRING_OBJ && right.type() == types.STRING_OBJ) {
return evalStringInfixExpression(operator, left, right)
} else if (operator == "==") {
return nativeBoolToBoolean(left == right)
} else if (operator == "!=") {
return nativeBoolToBoolean(left != right)
} else {
return types.Error("unknown operator: ${left.type()} $operator ${right.type()}")
}
}
fun evalIntegerInfixExpression(operator: String, left: Object, right: Object): Object {
val leftVal = (left as Integer).value
val rightVal = (right as Integer).value
when (operator) {
"+" -> return Integer(leftVal + rightVal)
"-" -> return Integer(leftVal - rightVal)
"*" -> return Integer(leftVal * rightVal)
"/" -> return Integer(leftVal / rightVal)
"<" -> return nativeBoolToBoolean(leftVal < rightVal)
">" -> return nativeBoolToBoolean(leftVal > rightVal)
"==" -> return nativeBoolToBoolean(leftVal == rightVal)
"!=" -> return nativeBoolToBoolean(leftVal != rightVal)
else -> return types.Error("unknown operator: ${left.type()} $operator ${right.type()}")
}
}
fun evalStringInfixExpression(operator: String, left: Object, right: Object): Object {
val leftVal = (left as Str).value
val rightVal = (right as Str).value
when (operator) {
"+" -> return Str(leftVal + rightVal)
"<" -> return nativeBoolToBoolean(leftVal < rightVal)
">" -> return nativeBoolToBoolean(leftVal > rightVal)
"==" -> return nativeBoolToBoolean(leftVal == rightVal)
"!=" -> return nativeBoolToBoolean(leftVal != rightVal)
else -> return types.Error("unknown operator: ${left.type()} $operator ${right.type()}")
}
}
fun evalPrefixExpression(operator: String, right: Object): Object {
when (operator) {
"!" -> return evalBangOperatorExpression(right)
"-" -> return evalMinusPrefixOperatorExpression(right)
else -> return types.Error("unknown operator: $operator ${right.type()}")
}
}
fun evalMinusPrefixOperatorExpression(right: Object): Object {
if (right.type() != INTEGER_OBJ) {
return types.Error("unknown operator: -${right.type()}")
}
val value = (right as types.Integer).value
return types.Integer(-value)
}
fun evalBangOperatorExpression(right: Object): Object {
when (right) {
TRUE -> return FALSE
FALSE -> return TRUE
NULL -> return TRUE
else -> return FALSE
}
}
fun nativeBoolToBoolean(value: Boolean): types.Boolean {
if (value) {
return TRUE
} else {
return FALSE
}
}
| apache-2.0 | 41ab702438ce296f64c301fa0de09ce3 | 28.287234 | 96 | 0.589902 | 4.237558 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/origin/PersistentOriginList.kt | 1 | 3364 | /*
* Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.origin
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
import org.andstatus.app.ActivityRequestCode
import org.andstatus.app.IntentExtra
import org.andstatus.app.R
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.util.MyLog
class PersistentOriginList : OriginList(PersistentOriginList::class) {
override fun getOrigins(): Iterable<Origin> {
return MyContextHolder.myContextHolder.getNow().origins.collection()
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
var item = menu.findItem(R.id.addOriginButton)
if (item != null) {
item.isEnabled = addEnabled
item.isVisible = addEnabled
}
// TODO: Currently no corresponding services work
item = menu.findItem(R.id.discoverOpenInstances)
if (item != null) {
item.isEnabled = false
item.isVisible = false
}
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.addOriginButton -> onAddOriginSelected("")
R.id.discoverOpenInstances -> {
val intent = Intent(this, DiscoveredOriginList::class.java)
intent.action = Intent.ACTION_PICK
startActivityForResult(intent, ActivityRequestCode.SELECT_OPEN_INSTANCE.id)
}
else -> {
}
}
return super.onOptionsItemSelected(item)
}
private fun onAddOriginSelected(originName: String?) {
val intent = Intent(this, OriginEditor::class.java)
intent.action = Intent.ACTION_INSERT
intent.putExtra(IntentExtra.ORIGIN_NAME.key, originName)
intent.putExtra(IntentExtra.ORIGIN_TYPE.key, originType.getCode())
startActivityForResult(intent, ActivityRequestCode.EDIT_ORIGIN.id)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
MyLog.v(this) { "onActivityResult " + ActivityRequestCode.fromId(requestCode) }
when (ActivityRequestCode.fromId(requestCode)) {
ActivityRequestCode.EDIT_ORIGIN -> fillList()
ActivityRequestCode.SELECT_OPEN_INSTANCE -> if (resultCode == RESULT_OK) {
val originName = data?.getStringExtra(IntentExtra.ORIGIN_NAME.key)
if (!originName.isNullOrEmpty()) {
onAddOriginSelected(originName)
}
}
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
override fun getMenuResourceId(): Int {
return R.menu.persistent_origin_list
}
}
| apache-2.0 | d2ee25452379f36040e45c58c22e1c88 | 38.116279 | 91 | 0.668847 | 4.608219 | false | false | false | false |
qikh/kong-lang | src/test/kotlin/lexer/LexerTest.kt | 1 | 4185 | package lexer
import org.junit.Test
import kotlin.test.assertEquals
data class Expected(val expectedType: token.TokenType, val expectedLiteral: String)
class LexerTest {
@Test
fun lexerTest() {
val input = """let five = 5;
let ten = 10;
let add = fn(x, y) {
x + y;
};
let result = add(five, ten);
!-/*5;
5 < 10 > 5;
if (5 < 10) {
return true;
} else {
return false;
}
10 == 10;
10 != 9;
"foobar"
"foo bar"
"""
val tests = arrayOf(
Expected(token.LET, "let"),
Expected(token.IDENT, "five"),
Expected(token.ASSIGN, "="),
Expected(token.INT, "5"),
Expected(token.SEMICOLON, ";"),
Expected(token.LET, "let"),
Expected(token.IDENT, "ten"),
Expected(token.ASSIGN, "="),
Expected(token.INT, "10"),
Expected(token.SEMICOLON, ";"),
Expected(token.LET, "let"),
Expected(token.IDENT, "add"),
Expected(token.ASSIGN, "="),
Expected(token.FUNCTION, "fn"),
Expected(token.LPAREN, "("),
Expected(token.IDENT, "x"),
Expected(token.COMMA, ","),
Expected(token.IDENT, "y"),
Expected(token.RPAREN, ")"),
Expected(token.LBRACE, "{"),
Expected(token.IDENT, "x"),
Expected(token.PLUS, "+"),
Expected(token.IDENT, "y"),
Expected(token.SEMICOLON, ";"),
Expected(token.RBRACE, "}"),
Expected(token.SEMICOLON, ";"),
Expected(token.LET, "let"),
Expected(token.IDENT, "result"),
Expected(token.ASSIGN, "="),
Expected(token.IDENT, "add"),
Expected(token.LPAREN, "("),
Expected(token.IDENT, "five"),
Expected(token.COMMA, ","),
Expected(token.IDENT, "ten"),
Expected(token.RPAREN, ")"),
Expected(token.SEMICOLON, ";"),
Expected(token.BANG, "!"),
Expected(token.MINUS, "-"),
Expected(token.SLASH, "/"),
Expected(token.ASTERISK, "*"),
Expected(token.INT, "5"),
Expected(token.SEMICOLON, ";"),
Expected(token.INT, "5"),
Expected(token.LT, "<"),
Expected(token.INT, "10"),
Expected(token.GT, ">"),
Expected(token.INT, "5"),
Expected(token.SEMICOLON, ";"),
Expected(token.IF, "if"),
Expected(token.LPAREN, "("),
Expected(token.INT, "5"),
Expected(token.LT, "<"),
Expected(token.INT, "10"),
Expected(token.RPAREN, ")"),
Expected(token.LBRACE, "{"),
Expected(token.RETURN, "return"),
Expected(token.TRUE, "true"),
Expected(token.SEMICOLON, ";"),
Expected(token.RBRACE, "}"),
Expected(token.ELSE, "else"),
Expected(token.LBRACE, "{"),
Expected(token.RETURN, "return"),
Expected(token.FALSE, "false"),
Expected(token.SEMICOLON, ";"),
Expected(token.RBRACE, "}"),
Expected(token.INT, "10"),
Expected(token.EQ, "=="),
Expected(token.INT, "10"),
Expected(token.SEMICOLON, ";"),
Expected(token.INT, "10"),
Expected(token.NOT_EQ, "!="),
Expected(token.INT, "9"),
Expected(token.SEMICOLON, ";"),
Expected(token.STRING, "foobar"),
Expected(token.STRING, "foo bar"),
Expected(token.EOF, "")
)
val lexer = Lexer(input)
tests.forEach {
val token = lexer.nextToken()
assertEquals(token.type, it.expectedType)
assertEquals(token.literal, it.expectedLiteral)
}
}
}
| apache-2.0 | b4f5819646cd7603a186089aba1c2114 | 32.75 | 83 | 0.453047 | 4.485531 | false | true | false | false |
kirtan403/K4Kotlin | k4kotlin-retrofit/src/main/java/com/livinglifetechway/k4kotlin_retrofit/RetrofitCallback.kt | 1 | 23776 | package com.livinglifetechway.k4kotlin_retrofit
import android.view.View
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class RetrofitCallback<T>(function: RetrofitCallback<T>.() -> Unit) : Callback<T> {
/**
* A progress view will be shown when the view is set
* And will hide itself when onResponse/onFailure is received
* Note: If you do not want to show the view when callback function is initialized
* you should use lazyProgressView
*/
var progressView: View? = null
set(view) {
field = view
field?.visibility = View.VISIBLE
}
/**
* A lazy progress view will hide itself when onResponse/onFailure is received
* Showing view's visibility should be handled by the user
* Note: If you want to show the view when callback function is initialized
* you should use progressView
*/
var lazyProgressView: View? = null
private var onResponseCallback: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var onFailureCallback: (call: Call<T>?, throwable: Throwable?) -> Unit = { _, _ -> }
private var onCompleted: (call: Call<T>?, response: Response<T>?, throwable: Throwable?) -> Unit = { _, _, _ -> }
private var onCancelled: (call: Call<T>?, throwable: Throwable?) -> Unit = { _, _ -> }
private var onFailureNotCancelled: (call: Call<T>?, throwable: Throwable?) -> Unit = { _, _ -> }
private var on2xxSuccess: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on3xxRedirection: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on4xxClientError: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on5xxServerError: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var onUnsuccessfulResponse: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var onUnsuccessfulResponseOrFailure: (call: Call<T>?, response: Response<T>?, throwable: Throwable?) -> Unit = { _, _, _ -> }
private var onUnsuccessfulResponseOrFailureNotCancelled: (call: Call<T>?, response: Response<T>?, throwable: Throwable?) -> Unit = { _, _, _ -> }
private var on200Ok: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on201Created: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on202Accepted: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on203NonAuthoritativeInformation: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on204NoContent: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on205ResetContent: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on206PartialContent: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on207MultiStatus: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on208AlreadyReported: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on226ImUsed: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on300MultipleChoices: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on301MovedPermanently: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on302Found: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on303SeeOther: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on304NotModified: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on305UseProxy: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on306SwitchProxy: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on307TemporaryRedirect: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on308PermanentRedirect: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on400BadRequest: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on401Unauthorized: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on402PaymentFailed: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on403Forbidden: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on404NotFound: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on405MethodNotAllowed: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on406NotAcceptable: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on407ProxyAuthenticationRequired: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on408RequestTimeout: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on409Conflict: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on410Gone: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on411LengthRequired: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on412PreconditionFailed: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on413PayloadTooLarge: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on414UriTooLong: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on415UnsupportedMediaType: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on416RangeNotSatisfiable: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on417ExpectationFailed: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on418ImaTeapot: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on421MisdirectedRequest: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on422UnprocessableEntity: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on423Locked: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on424FailedDependency: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on426UpgradeRequired: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on428PreconditionRequired: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on429TooManyRequests: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on431RequestHeaderFieldsTooLarge: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on451UnavailableForLegalReasons: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on500InternalServerError: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on501NotImplemented: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on502BadGateway: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on503ServiceUnavailable: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on504GatewayTimeout: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on505HttpVersionNotSupported: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on506VariantAlsoNegotiates: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on507InsufficientStorage: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on508LoopDetected: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on510NotExtended: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private var on511NetworkAuthenticationRequired: (call: Call<T>?, response: Response<T>?) -> Unit = { _, _ -> }
private fun hideProgressView() {
progressView?.visibility = View.GONE
lazyProgressView?.visibility = View.GONE
}
override fun onFailure(call: Call<T>?, t: Throwable?) {
// hide progress view after call is finished
hideProgressView()
// call is completed
onCompleted(call, null, t)
// call failed
onFailureCallback(call, t)
// check if call is cancelled
if (call?.isCanceled == true) {
onCancelled(call, t)
} else {
onFailureNotCancelled(call, t)
}
// unsuccessful or failure? -> Failure
onUnsuccessfulResponseOrFailure(call, null, t)
// unsuccessful or failure(not cancelled)? -> Failure(not cancelled)
if (call?.isCanceled == false) {
onUnsuccessfulResponseOrFailureNotCancelled(call, null, t)
}
}
override fun onResponse(call: Call<T>?, response: Response<T>?) {
// hide progress view after call is finished
hideProgressView()
// call is completed
onCompleted(call, response, null)
// call failed
onResponseCallback(call, response)
// check for response code range callbacks
when (response?.code()) {
in 200..299 -> on2xxSuccess(call, response)
in 300..399 -> on3xxRedirection(call, response)
in 400..499 -> on4xxClientError(call, response)
in 500..599 -> on5xxServerError(call, response)
}
// check for unsuccessful callback (any response code other than 2xx)
if (response?.isSuccessful != true) {
onUnsuccessfulResponse(call, response)
// unsuccessful or failure? -> Unsuccessful
onUnsuccessfulResponseOrFailure(call, response, null)
// unsuccessful or failure (not cancelled)? -> Unsuccessful
onUnsuccessfulResponseOrFailureNotCancelled(call, response, null)
}
// check for individual response code
when (response?.code()) {
200 -> on200Ok(call, response)
201 -> on201Created(call, response)
202 -> on202Accepted(call, response)
203 -> on203NonAuthoritativeInformation(call, response)
204 -> on204NoContent(call, response)
205 -> on205ResetContent(call, response)
206 -> on206PartialContent(call, response)
207 -> on207MultiStatus(call, response)
208 -> on208AlreadyReported(call, response)
226 -> on226ImUsed(call, response)
300 -> on300MultipleChoices(call, response)
301 -> on301MovedPermanently(call, response)
302 -> on302Found(call, response)
303 -> on303SeeOther(call, response)
304 -> on304NotModified(call, response)
305 -> on305UseProxy(call, response)
306 -> on306SwitchProxy(call, response)
307 -> on307TemporaryRedirect(call, response)
308 -> on308PermanentRedirect(call, response)
400 -> on400BadRequest(call, response)
401 -> on401Unauthorized(call, response)
402 -> on402PaymentFailed(call, response)
403 -> on403Forbidden(call, response)
404 -> on404NotFound(call, response)
405 -> on405MethodNotAllowed(call, response)
406 -> on406NotAcceptable(call, response)
407 -> on407ProxyAuthenticationRequired(call, response)
408 -> on408RequestTimeout(call, response)
409 -> on409Conflict(call, response)
410 -> on410Gone(call, response)
411 -> on411LengthRequired(call, response)
412 -> on412PreconditionFailed(call, response)
413 -> on413PayloadTooLarge(call, response)
414 -> on414UriTooLong(call, response)
415 -> on415UnsupportedMediaType(call, response)
416 -> on416RangeNotSatisfiable(call, response)
417 -> on417ExpectationFailed(call, response)
418 -> on418ImaTeapot(call, response)
421 -> on421MisdirectedRequest(call, response)
422 -> on422UnprocessableEntity(call, response)
423 -> on423Locked(call, response)
424 -> on424FailedDependency(call, response)
426 -> on426UpgradeRequired(call, response)
428 -> on428PreconditionRequired(call, response)
429 -> on429TooManyRequests(call, response)
431 -> on431RequestHeaderFieldsTooLarge(call, response)
451 -> on451UnavailableForLegalReasons(call, response)
500 -> on500InternalServerError(call, response)
501 -> on501NotImplemented(call, response)
502 -> on502BadGateway(call, response)
503 -> on503ServiceUnavailable(call, response)
504 -> on504GatewayTimeout(call, response)
505 -> on505HttpVersionNotSupported(call, response)
506 -> on506VariantAlsoNegotiates(call, response)
507 -> on507InsufficientStorage(call, response)
508 -> on508LoopDetected(call, response)
510 -> on510NotExtended(call, response)
511 -> on511NetworkAuthenticationRequired(call, response)
}
}
// DSL
fun onResponseCallback(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.onResponseCallback = function
}
fun onFailureCallback(function: (call: Call<T>?, throwable: Throwable?) -> Unit) {
this.onFailureCallback = function
}
fun onCompleted(function: (call: Call<T>?, response: Response<T>?, throwable: Throwable?) -> Unit) {
this.onCompleted = function
}
fun onCancelled(function: (call: Call<T>?, throwable: Throwable?) -> Unit) {
this.onCancelled = function
}
fun onFailureNotCancelled(function: (call: Call<T>?, throwable: Throwable?) -> Unit) {
this.onFailureNotCancelled = function
}
fun on2xxSuccess(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on2xxSuccess = function
}
fun on3xxRedirection(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on3xxRedirection = function
}
fun on4xxClientError(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on4xxClientError = function
}
fun on5xxServerError(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on5xxServerError = function
}
fun onUnsuccessfulResponse(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.onUnsuccessfulResponse = function
}
fun onUnsuccessfulResponseOrFailure(function: (call: Call<T>?, response: Response<T>?, throwable: Throwable?) -> Unit) {
this.onUnsuccessfulResponseOrFailure = function
}
fun onUnsuccessfulResponseOrFailureNotCancelled(function: (call: Call<T>?, response: Response<T>?, throwable: Throwable?) -> Unit) {
this.onUnsuccessfulResponseOrFailureNotCancelled = function
}
fun on200Ok(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on200Ok = function
}
fun on201Created(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on201Created = function
}
fun on202Accepted(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on202Accepted = function
}
fun on203NonAuthoritativeInformation(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on203NonAuthoritativeInformation = function
}
fun on204NoContent(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on204NoContent = function
}
fun on205ResetContent(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on205ResetContent = function
}
fun on206PartialContent(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on206PartialContent = function
}
fun on207MultiStatus(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on207MultiStatus = function
}
fun on208AlreadyReported(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on208AlreadyReported = function
}
fun on226ImUsed(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on226ImUsed = function
}
fun on300MultipleChoices(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on300MultipleChoices = function
}
fun on301MovedPermanently(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on301MovedPermanently = function
}
fun on302Found(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on302Found = function
}
fun on303SeeOther(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on303SeeOther = function
}
fun on304NotModified(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on304NotModified = function
}
fun on305UseProxy(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on305UseProxy = function
}
fun on306SwitchProxy(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on306SwitchProxy = function
}
fun on307TemporaryRedirect(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on307TemporaryRedirect = function
}
fun on308PermanentRedirect(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on308PermanentRedirect = function
}
fun on400BadRequest(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on400BadRequest = function
}
fun on401Unauthorized(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on401Unauthorized = function
}
fun on402PaymentFailed(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on402PaymentFailed = function
}
fun on403Forbidden(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on403Forbidden = function
}
fun on404NotFound(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on404NotFound = function
}
fun on405MethodNotAllowed(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on405MethodNotAllowed = function
}
fun on406NotAcceptable(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on406NotAcceptable = function
}
fun on407ProxyAuthenticationRequired(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on407ProxyAuthenticationRequired = function
}
fun on408RequestTimeout(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on408RequestTimeout = function
}
fun on409Conflict(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on409Conflict = function
}
fun on410Gone(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on410Gone = function
}
fun on411LengthRequired(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on411LengthRequired = function
}
fun on412PreconditionFailed(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on412PreconditionFailed = function
}
fun on413PayloadTooLarge(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on413PayloadTooLarge = function
}
fun on414UriTooLong(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on414UriTooLong = function
}
fun on415UnsupportedMediaType(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on415UnsupportedMediaType = function
}
fun on416RangeNotSatisfiable(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on416RangeNotSatisfiable = function
}
fun on417ExpectationFailed(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on417ExpectationFailed = function
}
fun on418ImaTeapot(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on418ImaTeapot = function
}
fun on421MisdirectedRequest(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on421MisdirectedRequest = function
}
fun on422UnprocessableEntity(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on422UnprocessableEntity = function
}
fun on423Locked(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on423Locked = function
}
fun on424FailedDependency(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on424FailedDependency = function
}
fun on426UpgradeRequired(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on426UpgradeRequired = function
}
fun on428PreconditionRequired(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on428PreconditionRequired = function
}
fun on429TooManyRequests(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on429TooManyRequests = function
}
fun on431RequestHeaderFieldsTooLarge(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on431RequestHeaderFieldsTooLarge = function
}
fun on451UnavailableForLegalReasons(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on451UnavailableForLegalReasons = function
}
fun on500InternalServerError(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on500InternalServerError = function
}
fun on501NotImplemented(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on501NotImplemented = function
}
fun on502BadGateway(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on502BadGateway = function
}
fun on503ServiceUnavailable(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on503ServiceUnavailable = function
}
fun on504GatewayTimeout(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on504GatewayTimeout = function
}
fun on505HttpVersionNotSupported(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on505HttpVersionNotSupported = function
}
fun on506VariantAlsoNegotiates(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on506VariantAlsoNegotiates = function
}
fun on507InsufficientStorage(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on507InsufficientStorage = function
}
fun on508LoopDetected(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on508LoopDetected = function
}
fun on510NotExtended(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on510NotExtended = function
}
fun on511NetworkAuthenticationRequired(function: (call: Call<T>?, response: Response<T>?) -> Unit) {
this.on511NetworkAuthenticationRequired = function
}
// IMPORTANT: If init call is defined at the start of the file,
// It's value will be override by the property's default values
// As property initialization will be called after init
// It init is in the last, property initialization will be done first
// and then init will replace the actual functions
init {
// dsl method calls
function()
}
} | apache-2.0 | e0f61f0b8ce10a054f40c82521a8aacf | 45.168932 | 149 | 0.623612 | 3.92797 | false | false | false | false |
bjzhou/Coolapk | app/src/main/kotlin/bjzhou/coolapk/app/ui/activities/NavActivity.kt | 1 | 5322 | package bjzhou.coolapk.app.ui.activities
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.SearchView
import android.view.Menu
import android.view.MenuItem
import android.view.View
import bjzhou.coolapk.app.R
import bjzhou.coolapk.app.net.ApkDownloader
import bjzhou.coolapk.app.ui.base.BaseActivity
import bjzhou.coolapk.app.ui.fragments.HomepageFragment
import bjzhou.coolapk.app.ui.fragments.PicturesRootFragment
import bjzhou.coolapk.app.ui.fragments.SettingsFragment
import bjzhou.coolapk.app.ui.fragments.UpgradeFragment
import kotlinx.android.synthetic.main.activity_nav.*
import kotlinx.android.synthetic.main.app_bar_nav.*
class NavActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedListener {
private var mSearchMenuItem: MenuItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nav)
setSupportActionBar(toolbar)
setActionBarTitle(R.string.title_section1)
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
nav_view.setCheckedItem(R.id.nav_home)
setFragment(HomepageFragment.newInstance())
ApkDownloader.instance.checkPermission(this)
}
override fun onNewIntent(intent: Intent) {
if (Intent.ACTION_SEARCH == intent.action) {
val query = intent.getStringExtra(SearchManager.QUERY)
supportFragmentManager.beginTransaction()
.add(R.id.container, HomepageFragment.newInstance(query), "Search")
.addToBackStack("Search")
.commit()
mSearchMenuItem?.collapseActionView()
}
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else if (currentFragment !is HomepageFragment) {
tabs.visibility = View.GONE
val lp = toolbar.layoutParams as AppBarLayout.LayoutParams
lp.scrollFlags = 0
setActionBarTitle(R.string.title_section1)
setFragment(HomepageFragment.newInstance())
nav_view.setCheckedItem(R.id.nav_home)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.nav, menu)
mSearchMenuItem = menu.findItem(R.id.action_search)
// Associate searchable configuration with the SearchView
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = mSearchMenuItem?.actionView as SearchView
searchView.setSearchableInfo(
searchManager.getSearchableInfo(componentName))
return true
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
val fragment: Fragment
tabs.visibility = View.GONE
val lp = toolbar.layoutParams as AppBarLayout.LayoutParams
lp.scrollFlags = 0
when (item.itemId) {
R.id.nav_home -> {
fragment = HomepageFragment.newInstance()
setActionBarTitle(R.string.title_section1)
setFragment(fragment)
}
R.id.nav_start_page -> {
val intent = Intent(this, PhotoViewer::class.java)
intent.putExtra("startPage", true)
startActivity(intent)
drawer_layout.closeDrawer(GravityCompat.START)
return false
}
R.id.nav_pictures -> {
fragment = PicturesRootFragment.newInstance()
fragment.onSetupTabs = {
val layoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
layoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or
AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
tabs.visibility = View.VISIBLE
tabs.setupWithViewPager(it)
}
setActionBarTitle(R.string.title_pictures)
setFragment(fragment)
}
R.id.nav_upgrade -> {
fragment = UpgradeFragment.newInstance()
setActionBarTitle(R.string.title_section2)
setFragment(fragment)
}
R.id.nav_settings -> {
fragment = SettingsFragment.newInstance()
setActionBarTitle(R.string.title_section3)
setFragment(fragment)
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
}
| gpl-2.0 | 8eb6a6d51d594d2c2f4fcfa2d674db5a | 39.015038 | 112 | 0.658023 | 5.030246 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/stats/dto/StatsActivity.kt | 1 | 2151 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.stats.dto
import com.google.gson.annotations.SerializedName
import kotlin.Int
/**
* Activity stats
* @param comments - Comments number
* @param copies - Reposts number
* @param hidden - Hidden from news count
* @param likes - Likes number
* @param subscribed - New subscribers count
* @param unsubscribed - Unsubscribed count
*/
data class StatsActivity(
@SerializedName("comments")
val comments: Int? = null,
@SerializedName("copies")
val copies: Int? = null,
@SerializedName("hidden")
val hidden: Int? = null,
@SerializedName("likes")
val likes: Int? = null,
@SerializedName("subscribed")
val subscribed: Int? = null,
@SerializedName("unsubscribed")
val unsubscribed: Int? = null
)
| mit | 9c18824f29b8b3f611cf8e140d1c7757 | 38.109091 | 81 | 0.680149 | 4.518908 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/schlockmercenary/src/eu/kanade/tachiyomi/extension/en/schlockmercenary/Schlockmercenary.kt | 1 | 7418 | package eu.kanade.tachiyomi.extension.en.schlockmercenary
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
import java.lang.UnsupportedOperationException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.GregorianCalendar
import java.util.Locale
class Schlockmercenary : ParsedHttpSource() {
override val name = "Schlock Mercenary"
override val baseUrl = "https://www.schlockmercenary.com"
override val lang = "en"
override val supportsLatest = false
private var chapterCount = 1
// Books
override fun popularMangaRequest(page: Int): Request = GET("${baseUrl}$archiveUrl")
override fun popularMangaSelector(): String = "div.archive-book"
override fun popularMangaFromElement(element: Element): SManga {
val book = element.select("h4 > a").first()
val thumb = (
baseUrl + (
element.select("img").first()?.attr("src")
?: defaultThumbnailUrl
)
).substringBefore("?")
return SManga.create().apply {
url = book.attr("href")
title = book.text()
artist = "Howard Tayler"
author = "Howard Tayler"
// Schlock Mercenary finished as of July 2020
status = SManga.COMPLETED
description = element.select("p").first()?.text() ?: ""
thumbnail_url = thumb
}
}
// Chapters
override fun chapterListSelector() = "ul.chapters > li:not(ul > li > ul > li) > a"
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
val requestUrl = "${baseUrl}$archiveUrl"
return client.newCall(GET(requestUrl))
.asObservableSuccess()
.map { response ->
getChaptersForBook(response, manga)
}
}
private fun getChaptersForBook(response: Response, manga: SManga): List<SChapter> {
val document = response.asJsoup()
val sanitizedTitle = manga.title.replace("""([",'])""".toRegex(), "\\\\$1")
val book = document.select(popularMangaSelector() + ":contains($sanitizedTitle)")
val chapters = mutableListOf<SChapter>()
chapterCount = 1
book.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) }
return chapters
}
override fun chapterFromElement(element: Element): SChapter {
val chapter = SChapter.create()
chapter.url = element.attr("href")
chapter.name = element.text()
chapter.chapter_number = chapterCount++.toFloat()
chapter.date_upload = chapter.url.takeLast(10).let {
SimpleDateFormat(dateFormat, Locale.getDefault()).parse(it)!!.time
}
return chapter
}
// Pages
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
val requestUrl = "${baseUrl}$archiveUrl"
return client.newCall(GET(requestUrl))
.asObservableSuccess()
.map { response ->
getPagesForChapter(response, chapter)
}
}
private fun getPagesForChapter(response: Response, chapter: SChapter): List<Page> {
val document = response.asJsoup()
/**
* To find the end page, first, the next chapter start must be found,
* then subtract one day off of the next chapter start.
* If no chapter start is found, grab the next book start.
* If no next book exists, assume one page long.
*/
val currentChapter = document.select(chapterListSelector() + "[href=${chapter.url}]").first()!!
val start = chapterFromElement(currentChapter).date_upload
// Find next chapter start
var nextChapter = currentChapter.parent()?.nextElementSibling()?.select("a")?.first()
var end = start + 1
// Chapter is the last in the book
if (nextChapter == null) {
// Grab next book start.
nextChapter = currentChapter.parents()[2]?.nextElementSibling()?.select(chapterListSelector())?.first()
}
if (nextChapter != null) {
end = chapterFromElement(nextChapter).date_upload
}
return generatePageListBetweenDates(start, end)
}
private fun generatePageListBetweenDates(start: Long, end: Long): List<Page> {
val pages = mutableListOf<Page>()
val calendar = GregorianCalendar()
calendar.time = Date(start)
while (calendar.time.before(Date(end))) {
val result = calendar.time
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
val today = formatter.format(result)
getImageUrlsForDay(today).forEach { pages.add(Page(pages.size, "", it)) }
calendar.add(Calendar.DATE, 1)
}
return pages
}
private fun getImageUrlsForDay(day: String): List<String> {
val requestUrl = "$baseUrl/$day"
val document = client.newCall(GET(requestUrl)).execute().asJsoup()
val urls = document.select("div#strip-$day > img").map { it.attr("abs:src") }
return urls
}
override fun fetchMangaDetails(manga: SManga): Observable<SManga> = Observable.just(manga)
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> = Observable.just(MangasPage(emptyList(), false))
override fun searchMangaFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used")
override fun searchMangaNextPageSelector(): String? = throw UnsupportedOperationException("Not used")
override fun imageUrlParse(document: Document) = throw UnsupportedOperationException("Not used")
override fun popularMangaNextPageSelector(): String? = null
override fun searchMangaSelector(): String = throw UnsupportedOperationException("Not used")
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw UnsupportedOperationException("Not used")
override fun mangaDetailsParse(document: Document): SManga = throw UnsupportedOperationException("Not used")
override fun pageListParse(document: Document): List<Page> = throw UnsupportedOperationException("Not used")
override fun latestUpdatesNextPageSelector(): String? = throw UnsupportedOperationException("Not used")
override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException("Not used")
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used")
override fun latestUpdatesSelector(): String = throw UnsupportedOperationException("Not used")
companion object {
const val defaultThumbnailUrl = "/static/img/logo.b6dacbb8.jpg"
const val archiveUrl = "/archives/"
const val dateFormat = "yyyy-MM-dd"
}
}
| apache-2.0 | 4947a277e9a9d34a2d0542b440217436 | 37.837696 | 154 | 0.670666 | 4.867454 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/utils/CountUpdater.kt | 1 | 3142 | package xyz.gnarbot.gnar.utils
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.sharding.ShardManager
import okhttp3.*
import org.json.JSONObject
import xyz.gnarbot.gnar.Bot
import java.io.IOException
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
class CountUpdater(private val bot: Bot, shardManager: ShardManager) {
val client: OkHttpClient = OkHttpClient.Builder().build()
val executor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
var index = 0
init {
executor.scheduleAtFixedRate({
for (shard in shardManager.shards) {
update(shard); index++
}
}, 10L + index * 5, 30, TimeUnit.MINUTES)
}
private fun update(jda: JDA) {
if (jda.status != JDA.Status.CONNECTED)
return
Bot.getLogger().info("Sending shard updates for shard ${jda.shardInfo.shardId}")
updateCarbonitex(jda)
updateGuildCount(jda)
}
private fun createCallback(name: String, jda: JDA): Callback {
return object : Callback {
override fun onFailure(call: Call, e: IOException) {
Bot.getLogger().error("$name update failed for shard ${jda.shardInfo.shardId}: ${e.message}")
call.cancel()
}
override fun onResponse(call: Call, response: Response) {
response.close()
}
}
}
private fun updateGuildCount(jda: JDA) {
val auth = bot.credentials.discordBots ?: return
val json = JSONObject()
.put("shards", jda.guildCache.size())
.put("shard_id", jda.shardInfo.shardId)
.put("shard_count", bot.credentials.totalShards)
val request = Request.Builder()
.url("https://top.gg/api/bots/138481382794985472/stats")
.header("User-Agent", "Octave")
.header("Authorization", auth)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.post(RequestBody.create(HttpUtils.JSON, json.toString()))
.build()
client.newCall(request).enqueue(createCallback("top.gg", jda))
}
private fun updateCarbonitex(jda: JDA) {
val authCarbon = bot.credentials.carbonitex ?: return
val json = JSONObject()
.put("key", authCarbon)
.put("shardid", jda.shardInfo.shardId)
.put("shardcount", bot.credentials.totalShards)
.put("servercount", jda.guildCache.size())
val request = Request.Builder()
.url("https://www.carbonitex.net/discord/data/botdata.php")
.header("User-Agent", "Octave")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.post(RequestBody.create(HttpUtils.JSON, json.toString()))
.build()
client.newCall(request).enqueue(createCallback("carbonitex.net", jda))
}
} | mit | ec25e843f1c80d2dafb62939696e163c | 35.126437 | 109 | 0.601528 | 4.333793 | false | false | false | false |
geckour/Glyph | app/src/main/java/jp/org/example/geckour/glyph/ui/PrefFragment.kt | 1 | 10785 | package jp.org.example.geckour.glyph.ui
import android.app.PendingIntent
import android.content.*
import android.os.Bundle
import android.os.IBinder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.preference.PreferenceManager
import com.android.vending.billing.IInAppBillingService
import jp.org.example.geckour.glyph.App.Companion.moshi
import jp.org.example.geckour.glyph.R
import jp.org.example.geckour.glyph.databinding.FragmentPreferenceBinding
import jp.org.example.geckour.glyph.ui.model.SkuDetail
import jp.org.example.geckour.glyph.util.*
import timber.log.Timber
class PrefFragment : ScopedFragment() {
companion object {
val tag: String = PrefFragment::class.java.simpleName
fun newInstance(): PrefFragment = PrefFragment()
}
private lateinit var binding: FragmentPreferenceBinding
private lateinit var sharedPreferences: SharedPreferences
private val serviceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName) {
billingService = null
}
override fun onServiceConnected(name: ComponentName, service: IBinder) {
billingService = IInAppBillingService.Stub.asInterface(service)
}
}
private var billingService: IInAppBillingService? = null
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = FragmentPreferenceBinding.inflate(inflater, container, false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val serviceIntent =
Intent("com.android.vending.billing.InAppBillingService.BIND").apply {
`package` = "com.android.vending"
}
activity?.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
binding.elementMode.apply {
val type = sharedPreferences.getIntValue(Key.GAME_MODE)
value = type.toString()
root.setOnClickListener { showModePicker() }
summary = getString(R.string.summary_pref_game_mode, HintType.values()[type].displayName)
}
binding.elementVibration.apply {
elementWidget?.widgetSwitch?.apply {
visibility = View.VISIBLE
isChecked = sharedPreferences.getBooleanValue(Key.VIBRATE)
setOnCheckedChangeListener { _, bool ->
sharedPreferences.edit().putBoolean(Key.VIBRATE.name, bool).apply()
binding.elementHapticFeedback.elementWidget.widgetSwitch.isEnabled = bool
}
}
}
binding.elementHapticFeedback.apply {
elementWidget?.widgetSwitch?.apply {
visibility = View.VISIBLE
isChecked = sharedPreferences.getBooleanValue(Key.HAPTIC_FEEDBACK)
setOnCheckedChangeListener { _, bool ->
sharedPreferences.edit().putBoolean(Key.HAPTIC_FEEDBACK.name, bool).apply()
}
}
}
binding.elementCountHack.apply {
elementWidget?.widgetSwitch?.apply {
visibility = View.VISIBLE
isChecked = sharedPreferences.getBooleanValue(Key.SHOW_COUNT)
setOnCheckedChangeListener { _, bool ->
sharedPreferences.edit().putBoolean(Key.SHOW_COUNT.name, bool).apply()
}
}
}
binding.elementLevelMin.apply {
val min = sharedPreferences.getIntValue(Key.LEVEL_MIN)
value = min.toString()
summary = getString(R.string.summary_pref_minimum_level, min)
root.setOnClickListener { showLevelPicker(LevelPickDialogFragment.LevelType.MIN) }
}
binding.elementLevelMax.apply {
val max = sharedPreferences.getIntValue(Key.LEVEL_MAX)
value = max.toString()
summary = getString(R.string.summary_pref_minimum_level, max)
root.setOnClickListener { showLevelPicker(LevelPickDialogFragment.LevelType.MAX) }
}
binding.elementDonate.root.setOnClickListener { onClickDonate() }
}
override fun onDestroy() {
super.onDestroy()
if (billingService != null) {
activity?.unbindService(serviceConnection)
}
}
private fun showModePicker() {
ModePickDialogFragment.newInstance(
try {
binding.elementMode.value?.toInt() ?: 0
} catch (e: NumberFormatException) {
0
}
).apply {
onConfirm = { onModeChanged(it) }
}.show(activity?.supportFragmentManager ?: return, ModePickDialogFragment.tag)
}
private fun onModeChanged(type: Int) {
binding.elementMode.apply {
value = type.toString()
summary = getString(R.string.summary_pref_game_mode, HintType.values()[type].displayName)
}
sharedPreferences.edit().putInt(Key.GAME_MODE.name, type).apply()
}
private fun showLevelPicker(type: LevelPickDialogFragment.LevelType) {
LevelPickDialogFragment.newInstance(
type,
try {
binding.elementLevelMin.value?.toInt()
} catch (e: NumberFormatException) {
null
},
try {
binding.elementLevelMax.value?.toInt()
} catch (e: NumberFormatException) {
null
}
).apply {
onConfirm = {
when (type) {
LevelPickDialogFragment.LevelType.MIN -> onMinLevelChanged(it)
LevelPickDialogFragment.LevelType.MAX -> onMaxLevelChanged(it)
}
}
}.show(activity?.supportFragmentManager ?: return, LevelPickDialogFragment.tag)
}
private fun onMinLevelChanged(newValue: Int) {
val max = try {
binding.elementLevelMax.value?.toInt() ?: 8
} catch (e: NumberFormatException) {
8
}
when {
newValue < 0 -> 0
newValue > 8 -> 0
else -> newValue
}.let { value ->
if (value > max) {
binding.elementLevelMin.apply {
this.value = max.toString()
summary = getString(R.string.summary_pref_minimum_level, max)
}
binding.elementLevelMax.apply {
this.value = value.toString()
summary = getString(R.string.summary_pref_maximum_level, value)
}
sharedPreferences.edit()
.putInt(Key.LEVEL_MIN.name, max)
.putInt(Key.LEVEL_MAX.name, value)
.apply()
} else {
binding.elementLevelMin.apply {
this.value = value.toString()
summary = getString(R.string.summary_pref_minimum_level, value)
}
sharedPreferences.edit()
.putInt(Key.LEVEL_MIN.name, value)
.apply()
}
}
}
private fun onMaxLevelChanged(newValue: Int) {
val min = try {
binding.elementLevelMin.value?.toInt() ?: 0
} catch (e: NumberFormatException) {
0
}
when {
newValue < 0 -> 0
newValue > 8 -> 0
else -> newValue
}.let { value ->
if (value < min) {
binding.elementLevelMax.apply {
this.value = min.toString()
summary = getString(R.string.summary_pref_maximum_level, min)
}
binding.elementLevelMin.apply {
this.value = value.toString()
summary = getString(R.string.summary_pref_minimum_level, value)
}
sharedPreferences.edit()
.putInt(Key.LEVEL_MAX.name, min)
.putInt(Key.LEVEL_MIN.name, value)
.apply()
} else {
binding.elementLevelMax.apply {
this.value = value.toString()
summary = getString(R.string.summary_pref_maximum_level, value)
}
sharedPreferences.edit()
.putInt(Key.LEVEL_MAX.name, value)
.apply()
}
}
}
private fun onClickDonate() {
billingService?.let {
ui {
val type = "inapp"
val key = "donate"
val sku =
it.getSkuDetails(3, activity?.packageName, type, Bundle().apply {
putStringArrayList(
"ITEM_ID_LIST",
ArrayList(listOf(key)))
}).let {
if (it.getInt("RESPONSE_CODE") == 0) {
it.getStringArrayList("DETAILS_LIST").map {
Timber.d(it)
moshi.adapter(SkuDetail::class.java)
.fromJson(it)
}
} else listOf()
}.firstOrNull() ?: return@ui
val purchasedSkus =
it.getPurchases(3,
activity?.packageName, type, null
).getStringArrayList("INAPP_PURCHASE_ITEM_LIST")
if (purchasedSkus?.contains(sku.productId)?.not() != false) {
val pendingIntent: PendingIntent =
it.getBuyIntent(3,
activity?.packageName, key, type, null)?.let {
if (it.containsKey("RESPONSE_CODE")
&& it.getInt("RESPONSE_CODE") == 0)
it.getParcelable("BUY_INTENT") as PendingIntent
else null
} ?: return@ui
activity?.startIntentSender(pendingIntent.intentSender,
Intent(), 0, 0, 0)
}
}
}
}
} | gpl-2.0 | 1dc00bb886048edb2e240c4a6574ee66 | 35.439189 | 101 | 0.531386 | 5.363003 | false | false | false | false |
kamontat/CheckIDNumberA | app/src/main/java/com/kamontat/checkidnumber/model/IDNumber.kt | 1 | 6022 | package com.kamontat.checkidnumber.model
import com.kamontat.checkidnumber.api.constants.Status
import com.kamontat.checkidnumber.model.strategy.idnumber.IDNumberStrategy
import com.kamontat.checkidnumber.model.strategy.idnumber.ThailandIDNumberStrategy
import java.io.Serializable
import java.util.*
/**
* object that deal with `id-number` of this program
*
* keep id-number by String,s
* and status of this id-number by using id rule of **Thailand** and you also able to change it by [IDNumber Strategy][IDNumberStrategy]
*
* @author kamontat
* @version 2.2
* @since 19/8/59 - 20:41
*/
class IDNumber : Serializable {
private var splitID: CharArray? = null
private var id: String? = null
var status: Status = Status.NOT_CREATE
private set
val size: Int
get() {
return if (id != null) id!!.length else 0
}
/**
* **init** id-number with nothing
*/
constructor() {
this.id = null
splitID = null
status = Status.NOT_CREATE
}
/**
* **init** id-number by using parameter `id`
* @param id
* * some id-number
*/
constructor(id: String) {
setId(id)
}
fun getId(): String? {
return id
}
fun setId(id: String) {
this.id = id
splitID = id.toCharArray()
status = isIDCorrect
}
/**
* convert first digit in id-number to genre in form of String by using id rule of **Thailand**
* @return string of genre
*/
val idGenre: String
get() {
when {
splitID!![0] == '1' -> return "สัญชาติไทย และ แจ้งเกิดทันเวลา"
splitID!![0] == '2' -> return "สัญชาติไทย และ แจ้งเกิดไม่ทันเวลา"
splitID!![0] == '3' -> return "คนไทยหรือคนต่างด้าวถูกกฏหมาย\nที่มีชื่ออยู่ในทะเบียนบ้านก่อนวันที่ 31 พฤษภาคม พ.ศ. 2527"
splitID!![0] == '4' -> return "คนไทยหรือคนต่างด้าวถูกกฏหมายที่ไม่มีเลขประจำตัวประชาชน\nหรือไม่ทันได้เลขประจำตัวก็ขอย้ายบ้านก่อน"
splitID!![0] == '5' -> return "คนไทยที่ได้รับอนุมัติให้เพิ่มชื่อในกรณีตกสำรวจหรือคนที่ถือ 2 สัญชาติ"
splitID!![0] == '6' -> return "ผู้ที่เข้าเมืองโดยไม่ชอบด้วยกฎหมาย \nหรือ ผู้ที่เข้าเมืองโดยชอบด้วยกฎหมายแต่อยู่ในลักษณะชั่วคราว"
splitID!![0] == '7' -> return "บุตรของบุคคลประเภทที่ 6 ซึ่งเกิดในประเทศไทย"
splitID!![0] == '8' -> return "คนต่างด้าวถูกกฎหมาย ที่ได้รับการให้สัญชาติไทยตั้งแต่หลังวันที่ 31 พฤษภาคม พ.ศ. 2527"
splitID!![0] == '0' -> return "บุคคลที่ไม่มีสถานะทางทะเบียนราษฎร ไม่มีสัญชาติ"
else -> return "No Genre"
}
}
/**
* get address in id-number by using id rule of **Thailand**<br></br>
* **address** is mean province + district
* @return address in form of number
*/
val idAddress: String
get() = if (splitID != null && splitID!!.isNotEmpty()) String(splitID!!, 1, 4) else ""
/**
* get province in id-number by using id rule of **Thailand**
* @return province in form of number
*/
val idProvince: String
get() = if (splitID != null && splitID!!.isNotEmpty()) String(splitID!!, 1, 2) else ""
/**
* get district in id-number by using id rule of **Thailand**
* @return district in form of number
*/
val idDistrict: String
get() = if (splitID != null && splitID!!.isNotEmpty()) String(splitID!!, 3, 2) else ""
/**
* get ID of **Birth Certificate** in id-number by using id rule of **Thailand**
* @return Birth Certificate ID in form of number
*/
val idbc: String
get() = if (splitID != null && splitID!!.isNotEmpty()) String(splitID!!, 5, 5) else ""
/**
* get order in **Birth Certificate** by using id rule of **Thailand**
* @return order of that in form of number
*/
val idOrder: String
get() = if (splitID != null && splitID!!.isNotEmpty()) String(splitID!!, 10, 2) else ""
/**
* check id is passing id rule of **Thailand** or not
* @return status of current id
*/
val isIDCorrect: Status
get() = strategy.checking(id)
override fun toString(): String = if (id != null) id!! else ""
/**
* check only id is equal
* @param other
* * test object
* *
* @return true if same
*/
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (other.javaClass != this.javaClass) return false
val number = this.javaClass.cast(other)
return this.getId() == number.getId()
}
override fun hashCode(): Int {
var result = splitID?.let { Arrays.hashCode(it) } ?: 0
result = 31 * result + (id?.hashCode() ?: 0)
result = 31 * result + status.hashCode()
return result
}
companion object {
public var strategy: IDNumberStrategy = ThailandIDNumberStrategy()
}
} | mit | 6a0c7445b06055ec2d221efe9eeb8ebd | 32.653061 | 144 | 0.578649 | 2.448515 | false | false | false | false |
InsertKoinIO/koin | examples/androidx-samples/src/main/java/org/koin/sample/androidx/mvvm/MVVMFragment.kt | 1 | 2721 | package org.koin.sample.androidx.mvvm
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import org.koin.android.ext.android.get
import org.koin.android.ext.android.getKoin
import org.koin.android.scope.AndroidScopeComponent
import org.koin.androidx.scope.fragmentScope
import org.koin.androidx.scope.requireScopeActivity
import org.koin.androidx.viewmodel.ext.android.activityViewModel
import org.koin.androidx.viewmodel.ext.android.getActivityViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.androidx.viewmodel.ext.android.viewModelForClass
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.named
import org.koin.core.scope.Scope
import org.koin.sample.android.R
import org.koin.sample.androidx.components.ID
import org.koin.sample.androidx.components.mvvm.ExtSimpleViewModel
import org.koin.sample.androidx.components.mvvm.SavedStateViewModel
import org.koin.sample.androidx.components.mvvm.SimpleViewModel
import org.koin.sample.androidx.components.scope.Session
class MVVMFragment(private val session: Session) : Fragment(R.layout.mvvm_fragment), AndroidScopeComponent {
override val scope: Scope by fragmentScope()
val simpleViewModel: SimpleViewModel by viewModel { parametersOf(ID) }
// Generic KClass Access
val scopeVm: ExtSimpleViewModel by viewModelForClass(ExtSimpleViewModel::class)
val extScopeVm: ExtSimpleViewModel by viewModel(named("ext"))
val shared: SimpleViewModel by activityViewModel()// sharedViewModel { parametersOf(ID) }
val sharedSaved: SavedStateViewModel by activityViewModel { parametersOf(ID) }
val saved by viewModel<SavedStateViewModel> { parametersOf(ID) }
val saved2 by viewModel<SavedStateViewModel> { parametersOf(ID) }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val shared2 = getActivityViewModel<SimpleViewModel> { parametersOf(ID) }
checkNotNull(session)
assert(shared != simpleViewModel)
assert((requireActivity() as MVVMActivity).simpleViewModel == shared)
assert((requireActivity() as MVVMActivity).savedVm != saved)
assert((requireActivity() as MVVMActivity).savedVm != saved2)
assert(scopeVm.session.id == extScopeVm.session.id)
assert((requireActivity() as MVVMActivity).savedVm == sharedSaved)
assert(shared == shared2)
assert(saved == saved2)
assert(requireScopeActivity<MVVMActivity>().get<Session>().id == getKoin().getProperty("session_id"))
assert(scope.get<Session>().id == requireScopeActivity<MVVMActivity>().get<Session>().id)
}
}
| apache-2.0 | a77db1e669bfcd8fc120a3dc3c66758e | 42.190476 | 109 | 0.774715 | 4.225155 | false | false | false | false |
rebus007/PermissionUtils | sample/src/main/java/com/raphaelbussa/permissionutils/sample/SecondFragment.kt | 1 | 8582 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Raphaël Bussa
*
* 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.raphaelbussa.permissionutils.sample
import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.raphaelbussa.permissionutils.AskAgainCallback.UserResponse
import com.raphaelbussa.permissionutils.FullCallback
import com.raphaelbussa.permissionutils.PermissionManager
import com.raphaelbussa.permissionutils.PermissionManager.Companion.Builder
import com.raphaelbussa.permissionutils.PermissionUtils
import java.util.*
class SecondFragment : Fragment(), FullCallback {
private lateinit var askOnePermission: Button
private lateinit var askThreePermission: Button
private lateinit var checkPermission: Button
private lateinit var askOnePermissionSimple: Button
private lateinit var askThreePermissionSimple: Button
private lateinit var askOnePermissionSmart: Button
private lateinit var askThreePermissionSmart: Button
@SuppressLint("InflateParams")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_second, null)
askOnePermission = view.findViewById(R.id.ask_one_permission)
askThreePermission = view.findViewById(R.id.ask_three_permission)
checkPermission = view.findViewById(R.id.check_permission)
askOnePermissionSimple = view.findViewById(R.id.ask_one_permission_simple)
askThreePermissionSimple = view.findViewById(R.id.ask_three_permission_simple)
askOnePermissionSmart = view.findViewById(R.id.ask_one_permission_smart)
askThreePermissionSmart = view.findViewById(R.id.ask_three_permission_smart)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
askOnePermission.setOnClickListener {
Builder().key(9001)
.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.askAgain(true)
.askAgainCallback { response -> showDialog(response) }
.callback(this@SecondFragment)
.ask(this@SecondFragment)
}
askThreePermission.setOnClickListener {
Builder()
.key(801)
.permission(Manifest.permission.GET_ACCOUNTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_SMS)
.askAgain(true)
.askAgainCallback { response -> showDialog(response) }
.callback(this@SecondFragment)
.ask(this@SecondFragment)
}
askOnePermissionSimple.setOnClickListener {
Builder()
.key(701)
.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.askAgain(true)
.askAgainCallback { response -> showDialog(response) }
.callback { allPermissionsGranted -> Toast.makeText(requireContext(), "${Manifest.permission.WRITE_EXTERNAL_STORAGE} allPermissionsGranted [$allPermissionsGranted]", Toast.LENGTH_SHORT).show() }
.ask(this@SecondFragment)
}
askThreePermissionSimple.setOnClickListener {
Builder()
.key(601)
.permission(Manifest.permission.GET_ACCOUNTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_SMS)
.askAgain(true)
.askAgainCallback { response -> showDialog(response) }
.callback { allPermissionsGranted -> Toast.makeText(requireContext(), "${Manifest.permission.GET_ACCOUNTS}, ${Manifest.permission.ACCESS_FINE_LOCATION}, ${Manifest.permission.READ_SMS} allPermissionsGranted [$allPermissionsGranted]", Toast.LENGTH_SHORT).show() }
.ask(this@SecondFragment)
}
askOnePermissionSmart.setOnClickListener {
Builder()
.key(2001)
.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.askAgain(true)
.askAgainCallback { response -> showDialog(response) }
.callback { allPermissionsGranted, somePermissionsDeniedForever -> Toast.makeText(requireContext(), "${Manifest.permission.WRITE_EXTERNAL_STORAGE} allPermissionsGranted [$allPermissionsGranted] somePermissionsDeniedForever [$somePermissionsDeniedForever]", Toast.LENGTH_SHORT).show() }
.ask(this@SecondFragment)
}
askThreePermissionSmart.setOnClickListener {
Builder()
.key(2101)
.permission(Manifest.permission.GET_ACCOUNTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_SMS)
.askAgain(true)
.askAgainCallback { response -> showDialog(response) }
.callback { allPermissionsGranted, somePermissionsDeniedForever -> Toast.makeText(activity, "${Manifest.permission.GET_ACCOUNTS }, ${Manifest.permission.ACCESS_FINE_LOCATION}, ${Manifest.permission.READ_SMS } allPermissionsGranted [$allPermissionsGranted] somePermissionsDeniedForever [$somePermissionsDeniedForever]", Toast.LENGTH_SHORT).show() }
.ask(this@SecondFragment)
}
checkPermission.setOnClickListener {
val granted = PermissionUtils.isGranted(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
Toast.makeText(activity, "${Manifest.permission.WRITE_EXTERNAL_STORAGE} isGranted [$granted]", Toast.LENGTH_SHORT).show()
}
}
private fun showDialog(response: UserResponse) {
if (activity == null) return
AlertDialog.Builder(requireContext())
.setTitle("Permission needed")
.setMessage("This app really need to use this permission, you wont to authorize it?")
.setPositiveButton("OK") { _, _ -> response.result(true) }
.setNegativeButton("NOT NOW") { _, _ -> response.result(false) }
.setCancelable(false)
.show()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
PermissionManager.handleResult(this, requestCode, permissions, grantResults)
}
override fun result(permissionsGranted: List<String>, permissionsDenied: List<String>, permissionsDeniedForever: List<String>, permissionsAsked: List<String>) {
val msg = mutableListOf<String>()
for (permissionEnum in permissionsGranted) {
msg.add("$permissionEnum [Granted]")
}
for (permissionEnum in permissionsDenied) {
msg.add("$permissionEnum [Denied]")
}
for (permissionEnum in permissionsDeniedForever) {
msg.add("$permissionEnum [DeniedForever]")
}
for (permissionEnum in permissionsAsked) {
msg.add("$permissionEnum [Asked]")
}
AlertDialog.Builder(requireContext())
.setTitle("Permission result")
.setItems(msg.toTypedArray()) { _, _ -> }
.show()
}
} | mit | ae201021f80c3c3504eab42e3fd00f97 | 52.304348 | 367 | 0.67801 | 4.968732 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/user_reviews/reducer/UserReviewsReducer.kt | 1 | 5488 | package org.stepik.android.presentation.user_reviews.reducer
import org.stepik.android.presentation.user_reviews.UserReviewsFeature.State
import org.stepik.android.presentation.user_reviews.UserReviewsFeature.Message
import org.stepik.android.presentation.user_reviews.UserReviewsFeature.Action
import org.stepik.android.presentation.user_reviews.mapper.UserReviewsStateMapper
import ru.nobird.android.presentation.redux.reducer.StateReducer
import javax.inject.Inject
class UserReviewsReducer
@Inject
constructor(
private val userReviewsStateMapper: UserReviewsStateMapper
) : StateReducer<State, Message, Action> {
override fun reduce(state: State, message: Message): Pair<State, Set<Action>> =
when (message) {
is Message.InitMessage -> {
if (state is State.Idle || state is State.Error && message.forceUpdate) {
State.Loading to setOf(Action.FetchUserReviews)
} else {
null
}
}
is Message.FetchUserReviewsSuccess -> {
if (state !is State.Idle) {
val newState =
if (message.userCourseReviewsResult.userCourseReviewItems.isEmpty()) {
State.Empty
} else {
State.Content(message.userCourseReviewsResult)
}
newState to emptySet()
} else {
null
}
}
is Message.FetchUserReviewsError -> {
if (state is State.Loading) {
State.Error to emptySet()
} else {
null
}
}
is Message.ScreenOpenedMessage -> {
state to setOf(Action.LogScreenOpenedEvent)
}
is Message.NewReviewSubmission -> {
if (state is State.Content) {
userReviewsStateMapper.mergeStateWithNewReview(state, message.courseReview)?.let { newState ->
newState to emptySet()
}
} else {
null
}
}
is Message.EditReviewSubmission -> {
if (state is State.Content) {
userReviewsStateMapper.mergeStateWithEditedReview(state, message.courseReview)?.let { newState ->
newState to emptySet()
}
} else {
null
}
}
is Message.DeletedReviewSubmission -> {
if (state is State.Content) {
userReviewsStateMapper.mergeStateWithDeletedReview(state, message.courseReview)?.let { newState ->
newState to emptySet()
}
} else {
null
}
}
is Message.DeletedReviewUserReviews -> {
if (state is State.Content) {
userReviewsStateMapper.mergeStateWithDeletedReviewPlaceholder(state, message.courseReview)?.let { newState ->
newState to setOf(Action.DeleteReview(message.courseReview))
}
} else {
null
}
}
is Message.DeletedReviewUserReviewsSuccess -> {
if (state is State.Content) {
userReviewsStateMapper.mergeStateWithDeletedReviewToSuccess(state, message.courseReview)?.let { newState ->
newState to setOf(Action.ViewAction.ShowDeleteSuccessSnackbar)
}
} else {
null
}
}
is Message.DeletedReviewUserReviewsError -> {
if (state is State.Content) {
val newState = userReviewsStateMapper.mergeStateWithDeletedReviewToError(state)
newState to setOf(Action.ViewAction.ShowDeleteFailureSnackbar)
} else {
null
}
}
is Message.EnrolledCourseMessage -> {
if (state is State.Content) {
if (message.course.enrollment != 0L) {
state to setOf(Action.FetchEnrolledCourseInfo(message.course))
} else {
val newState = userReviewsStateMapper.mergeStateWithDroppedCourse(state, message.course.id)
newState to emptySet()
}
} else {
null
}
}
is Message.EnrolledReviewedCourseMessage -> {
if (state is State.Content) {
val newState = userReviewsStateMapper.mergeStateWithEnrolledReviewedItem(state, message.reviewedItem)
newState to emptySet()
} else {
null
}
}
is Message.EnrolledPotentialReviewMessage -> {
if (state is State.Content) {
val newState = userReviewsStateMapper.mergeStateWithEnrolledPotentialReviewItem(state, message.potentialReviewItem)
newState to emptySet()
} else {
null
}
}
} ?: state to emptySet()
} | apache-2.0 | 36b966141b1dc5655103eab118d5ebfc | 37.929078 | 135 | 0.510204 | 5.813559 | false | false | false | false |
savvasdalkitsis/gameframe | workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/layer/view/LayersView.kt | 1 | 3597 | /**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.workspace.element.layer.view
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.util.AttributeSet
import com.savvasdalkitsis.gameframe.feature.history.usecase.HistoryUseCase
import com.savvasdalkitsis.gameframe.feature.workspace.model.WorkspaceModel
import com.savvasdalkitsis.gameframe.kotlin.Action
class LayersView : RecyclerView {
private lateinit var layers: LayersAdapter
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)
override fun onFinishInflate() {
super.onFinishInflate()
layers = LayersAdapter()
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true)
setHasFixedSize(true)
val itemTouchHelper = ItemTouchHelper(MoveLayersItemHelper())
itemTouchHelper.attachToRecyclerView(this)
adapter = layers
}
fun addNewLayer() = layers.addNewLayer()
fun bind(modelHistory: HistoryUseCase<WorkspaceModel>, action: Action) = layers.bind(modelHistory, action)
private inner class MoveLayersItemHelper internal constructor() : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) {
private val ALLOW_DRAG = ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
ItemTouchHelper.DOWN or ItemTouchHelper.UP or ItemTouchHelper.START or ItemTouchHelper.END)
private var newMove = true
override fun onMoved(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, fromPos: Int, target: RecyclerView.ViewHolder, toPos: Int, x: Int, y: Int) {
super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y)
layers.swapLayers(viewHolder, target)
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
if (newMove) {
newMove = false
layers.swapStarted()
}
return target.adapterPosition > 0
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) =
if (viewHolder.adapterPosition > 0) ALLOW_DRAG else 0
override fun clearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
motionFinished()
}
private fun motionFinished() {
newMove = true
layers.swapLayersFinished()
}
}
} | apache-2.0 | 370f0c9b53967566236f08495db7f993 | 40.356322 | 170 | 0.723659 | 4.940934 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt | 1 | 15429 | package info.nightscout.androidaps.activities
import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.ArrayAdapter
import android.widget.TextView
import com.google.android.material.tabs.TabLayout
import com.google.common.collect.Lists
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.ProfileSealed
import info.nightscout.androidaps.data.PureProfile
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch
import info.nightscout.androidaps.databinding.ActivityProfilehelperBinding
import info.nightscout.androidaps.dialogs.ProfileViewerDialog
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.defaultProfile.DefaultProfile
import info.nightscout.androidaps.utils.defaultProfile.DefaultProfileDPV
import info.nightscout.androidaps.utils.stats.TddCalculator
import java.text.DecimalFormat
import javax.inject.Inject
class ProfileHelperActivity : NoSplashAppCompatActivity() {
@Inject lateinit var tddCalculator: TddCalculator
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var defaultProfile: DefaultProfile
@Inject lateinit var defaultProfileDPV: DefaultProfileDPV
@Inject lateinit var localProfilePlugin: LocalProfilePlugin
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var repository: AppRepository
enum class ProfileType {
MOTOL_DEFAULT,
DPV_DEFAULT,
CURRENT,
AVAILABLE_PROFILE,
PROFILE_SWITCH
}
private var tabSelected = 0
private val typeSelected = arrayOf(ProfileType.MOTOL_DEFAULT, ProfileType.CURRENT)
private val ageUsed = arrayOf(15.0, 15.0)
private val weightUsed = arrayOf(0.0, 0.0)
private val tddUsed = arrayOf(0.0, 0.0)
private val pctUsed = arrayOf(32.0, 32.0)
private lateinit var profileList: ArrayList<CharSequence>
private val profileUsed = arrayOf(0, 0)
private lateinit var profileSwitch: List<EffectiveProfileSwitch>
private val profileSwitchUsed = arrayOf(0, 0)
private lateinit var binding: ActivityProfilehelperBinding
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityProfilehelperBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
switchTab(tab.position, typeSelected[tab.position])
}
override fun onTabUnselected(tab: TabLayout.Tab) {}
override fun onTabReselected(tab: TabLayout.Tab) {}
})
val profileTypeList = Lists.newArrayList(
rh.gs(R.string.motoldefaultprofile),
rh.gs(R.string.dpvdefaultprofile),
rh.gs(R.string.currentprofile),
rh.gs(R.string.availableprofile),
rh.gs(R.string.careportal_profileswitch)
)
binding.profileType.setAdapter(ArrayAdapter(this, R.layout.spinner_centered, profileTypeList))
binding.profileType.setOnItemClickListener { _, _, _, _ ->
when (binding.profileType.text.toString()) {
rh.gs(R.string.motoldefaultprofile) -> switchTab(tabSelected, ProfileType.MOTOL_DEFAULT)
rh.gs(R.string.dpvdefaultprofile) -> switchTab(tabSelected, ProfileType.DPV_DEFAULT)
rh.gs(R.string.currentprofile) -> switchTab(tabSelected, ProfileType.CURRENT)
rh.gs(R.string.availableprofile) -> switchTab(tabSelected, ProfileType.AVAILABLE_PROFILE)
rh.gs(R.string.careportal_profileswitch) -> switchTab(tabSelected, ProfileType.PROFILE_SWITCH)
}
}
// Active profile
profileList = activePlugin.activeProfileSource.profile?.getProfileList() ?: ArrayList()
binding.availableProfileList.setAdapter(ArrayAdapter(this, R.layout.spinner_centered, profileList))
binding.availableProfileList.setOnItemClickListener { _, _, index, _ ->
profileUsed[tabSelected] = index
}
// Profile switch
profileSwitch = repository.getEffectiveProfileSwitchDataFromTime(dateUtil.now() - T.months(2).msecs(), true).blockingGet()
val profileswitchListNames = profileSwitch.map { it.originalCustomizedName }
binding.profileswitchList.setAdapter(ArrayAdapter(this, R.layout.spinner_centered, profileswitchListNames))
binding.profileswitchList.setOnItemClickListener { _, _, index, _ ->
profileSwitchUsed[tabSelected] = index
}
// Default profile
binding.copyToLocalProfile.setOnClickListener {
storeValues()
val age = ageUsed[tabSelected]
val weight = weightUsed[tabSelected]
val tdd = tddUsed[tabSelected]
val pct = pctUsed[tabSelected]
val profile = if (typeSelected[tabSelected] == ProfileType.MOTOL_DEFAULT) defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())
else defaultProfileDPV.profile(age, tdd, pct / 100.0, profileFunction.getUnits())
profile?.let {
OKDialog.showConfirmation(this, rh.gs(R.string.careportal_profileswitch), rh.gs(R.string.copytolocalprofile), Runnable {
localProfilePlugin.addProfile(
localProfilePlugin.copyFrom(
it, "DefaultProfile " +
dateUtil.dateAndTimeAndSecondsString(dateUtil.now())
.replace(".", "/")
)
)
rxBus.send(EventLocalProfileChanged())
})
}
}
binding.age.setParams(0.0, 1.0, 18.0, 1.0, DecimalFormat("0"), false, null)
binding.weight.setParams(0.0, 0.0, 150.0, 1.0, DecimalFormat("0"), false, null, object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
binding.tddRow.visibility = (binding.weight.value == 0.0).toVisibility()
}
})
binding.tdd.setParams(0.0, 0.0, 200.0, 1.0, DecimalFormat("0"), false, null, object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
binding.weightRow.visibility = (binding.tdd.value == 0.0).toVisibility()
}
})
binding.basalPctFromTdd.setParams(32.0, 32.0, 37.0, 1.0, DecimalFormat("0"), false, null)
binding.tdds.addView(TextView(this).apply { text = rh.gs(R.string.tdd) + ": " + rh.gs(R.string.calculation_in_progress) })
Thread {
val tdds = tddCalculator.stats(this)
runOnUiThread {
binding.tdds.removeAllViews()
binding.tdds.addView(tdds)
}
}.start()
// Current profile
binding.currentProfileText.text = profileFunction.getProfileName()
// General
binding.compareProfiles.setOnClickListener {
storeValues()
for (i in 0..1) {
if (typeSelected[i] == ProfileType.MOTOL_DEFAULT) {
if (ageUsed[i] < 1 || ageUsed[i] > 18) {
ToastUtils.showToastInUiThread(this, R.string.invalidage)
return@setOnClickListener
}
if ((weightUsed[i] < 5 || weightUsed[i] > 150) && tddUsed[i] == 0.0) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
if ((tddUsed[i] < 5 || tddUsed[i] > 150) && weightUsed[i] == 0.0) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
}
if (typeSelected[i] == ProfileType.DPV_DEFAULT) {
if (ageUsed[i] < 1 || ageUsed[i] > 18) {
ToastUtils.showToastInUiThread(this, R.string.invalidage)
return@setOnClickListener
}
if (tddUsed[i] < 5 || tddUsed[i] > 150) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
if ((pctUsed[i] < 32 || pctUsed[i] > 37)) {
ToastUtils.showToastInUiThread(this, R.string.invalidpct)
return@setOnClickListener
}
}
}
getProfile(ageUsed[0], tddUsed[0], weightUsed[0], pctUsed[0] / 100.0, 0)?.let { profile0 ->
getProfile(ageUsed[1], tddUsed[1], weightUsed[1], pctUsed[1] / 100.0, 1)?.let { profile1 ->
ProfileViewerDialog().also { pvd ->
pvd.arguments = Bundle().also {
it.putLong("time", dateUtil.now())
it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal)
it.putString("customProfile", profile0.jsonObject.toString())
it.putString("customProfile2", profile1.jsonObject.toString())
it.putString(
"customProfileName",
getProfileName(ageUsed[0], tddUsed[0], weightUsed[0], pctUsed[0] / 100.0, 0) + "\n" + getProfileName(
ageUsed[1],
tddUsed[1],
weightUsed[1],
pctUsed[1] / 100.0,
1
)
)
}
}.show(supportFragmentManager, "ProfileViewDialog")
return@setOnClickListener
}
}
ToastUtils.showToastInUiThread(this, R.string.invalidinput)
}
binding.ageLabel.labelFor = binding.age.editTextId
binding.tddLabel.labelFor = binding.tdd.editTextId
binding.weightLabel.labelFor = binding.weight.editTextId
binding.basalPctFromTddLabel.labelFor = binding.basalPctFromTdd.editTextId
switchTab(0, typeSelected[0], false)
}
private fun getProfile(age: Double, tdd: Double, weight: Double, basalPct: Double, tab: Int): PureProfile? =
try { // Profile must not exist
when (typeSelected[tab]) {
ProfileType.MOTOL_DEFAULT -> defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())
ProfileType.DPV_DEFAULT -> defaultProfileDPV.profile(age, tdd, basalPct, profileFunction.getUnits())
ProfileType.CURRENT -> profileFunction.getProfile()?.convertToNonCustomizedProfile(dateUtil)
ProfileType.AVAILABLE_PROFILE -> activePlugin.activeProfileSource.profile?.getSpecificProfile(profileList[profileUsed[tab]].toString())
ProfileType.PROFILE_SWITCH -> ProfileSealed.EPS(profileSwitch[profileSwitchUsed[tab]]).convertToNonCustomizedProfile(dateUtil)
}
} catch (e: Exception) {
null
}
private fun getProfileName(age: Double, tdd: Double, weight: Double, basalSumPct: Double, tab: Int): String =
when (typeSelected[tab]) {
ProfileType.MOTOL_DEFAULT -> if (tdd > 0) rh.gs(R.string.formatwithtdd, age, tdd) else rh.gs(R.string.formatwithweight, age, weight)
ProfileType.DPV_DEFAULT -> rh.gs(R.string.formatwittddandpct, age, tdd, (basalSumPct * 100).toInt())
ProfileType.CURRENT -> profileFunction.getProfileName()
ProfileType.AVAILABLE_PROFILE -> profileList[profileUsed[tab]].toString()
ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].originalCustomizedName
}
private fun storeValues() {
ageUsed[tabSelected] = binding.age.value
weightUsed[tabSelected] = binding.weight.value
tddUsed[tabSelected] = binding.tdd.value
pctUsed[tabSelected] = binding.basalPctFromTdd.value
}
private fun switchTab(tab: Int, newContent: ProfileType, storeOld: Boolean = true) {
// Store values for selected tab. listBox values are stored on selection change
if (storeOld) storeValues()
tabSelected = tab
typeSelected[tabSelected] = newContent
// Show new content
binding.profileType.setText(
when (typeSelected[tabSelected]) {
ProfileType.MOTOL_DEFAULT -> rh.gs(R.string.motoldefaultprofile)
ProfileType.DPV_DEFAULT -> rh.gs(R.string.dpvdefaultprofile)
ProfileType.CURRENT -> rh.gs(R.string.currentprofile)
ProfileType.AVAILABLE_PROFILE -> rh.gs(R.string.availableprofile)
ProfileType.PROFILE_SWITCH -> rh.gs(R.string.careportal_profileswitch)
},
false
)
binding.defaultProfile.visibility = (newContent == ProfileType.MOTOL_DEFAULT || newContent == ProfileType.DPV_DEFAULT).toVisibility()
binding.currentProfile.visibility = (newContent == ProfileType.CURRENT).toVisibility()
binding.availableProfile.visibility = (newContent == ProfileType.AVAILABLE_PROFILE).toVisibility()
binding.profileSwitch.visibility = (newContent == ProfileType.PROFILE_SWITCH).toVisibility()
// Restore selected values
binding.age.value = ageUsed[tabSelected]
binding.weight.value = weightUsed[tabSelected]
binding.tdd.value = tddUsed[tabSelected]
binding.basalPctFromTdd.value = pctUsed[tabSelected]
binding.basalPctFromTddRow.visibility = (newContent == ProfileType.DPV_DEFAULT).toVisibility()
if (profileList.isNotEmpty()) {
binding.availableProfileList.setText(profileList[profileUsed[tabSelected]].toString(), false)
}
if (profileSwitch.isNotEmpty()) {
binding.profileswitchList.setText(profileSwitch[profileSwitchUsed[tabSelected]].originalCustomizedName, false)
}
}
}
| agpl-3.0 | 8060cddef5c1e6d0fca4e0e07c21981e | 49.421569 | 154 | 0.63076 | 4.611178 | false | false | false | false |
notsyncing/lightfur | lightfur-entity/src/main/kotlin/io/github/notsyncing/lightfur/entity/EntityModel.kt | 1 | 14701 | package io.github.notsyncing.lightfur.entity
import com.alibaba.fastjson.annotation.JSONField
import io.github.notsyncing.lightfur.DataSession
import io.github.notsyncing.lightfur.entity.dsl.*
import io.github.notsyncing.lightfur.entity.events.CanFireEvents
import io.github.notsyncing.lightfur.entity.events.EntityEvent
import io.github.notsyncing.lightfur.entity.events.EntityEventDispatcher
import io.github.notsyncing.lightfur.sql.base.ExpressionBuilder
import io.github.notsyncing.lightfur.sql.models.TableModel
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.future.future
import java.io.InvalidObjectException
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty0
abstract class EntityModel(@field:JSONField(serialize = false, deserialize = false) val database: String? = null,
@field:JSONField(serialize = false, deserialize = false) val schema: String? = null,
@field:JSONField(serialize = false, deserialize = false) val table: String) :
CanFireEvents {
companion object {
@JSONField(serialize = false, deserialize = false)
val primaryKeyFieldCache = ConcurrentHashMap<Class<EntityModel>, MutableSet<KProperty<*>>>()
fun getPrimaryKeyFieldsFromCache(modelClass: Class<EntityModel>): MutableSet<KProperty<*>> {
var l = primaryKeyFieldCache[modelClass]
if (l == null) {
l = mutableSetOf()
primaryKeyFieldCache[modelClass] = l
}
return l
}
}
@JSONField(serialize = false, deserialize = false)
override val events = mutableListOf<EntityEvent>()
@JSONField(serialize = false, deserialize = false)
lateinit var primaryKeyFields: Set<KProperty<*>>
@JSONField(serialize = false, deserialize = false)
val fieldMap = ConcurrentHashMap<String, EntityField<*>>()
@JSONField(serialize = false, deserialize = false)
val referenceMap = ConcurrentHashMap<String, EntityReference<*>>()
@JSONField(serialize = false, deserialize = false)
val primaryKeyFieldInfos = ArrayList<EntityField<*>>()
@JSONField(serialize = false, deserialize = false)
var skipTableName = false
@JSONField(serialize = false, deserialize = false)
var skipTableAlias = false
@JSONField(serialize = false, deserialize = false)
var modelAliasBeforeColumnName = false
init {
if (!EntityGlobal.tableModels.containsKey(this::class.java)) {
val t = TableModel()
t.name = table
t.database = database
t.schema = schema
EntityGlobal.tableModels[this::class.java as Class<EntityModel>] = t
}
}
protected inline fun <reified T> field(column: String? = null, type: String? = null,
length: Int = 0, nullable: Boolean = false, defaultValue: T? = null,
defaultValueDefinedInDatabase: Boolean = false,
primaryKey: Boolean = false, autoGenerated: Boolean = false): EntityField<T> {
return EntityField(T::class.java, column, type, length, nullable,
defaultValue, defaultValueDefinedInDatabase, primaryKey, autoGenerated)
}
protected inline fun <reified T: EntityModel?> reference(refField: KProperty<*>,
keyField: KProperty0<*>? = null): EntityReference<T> {
return EntityReference(T::class.java, null, refField.name, keyField?.name)
}
protected inline fun <reified I: EntityModel, reified T: MutableCollection<I>> referenceMany(refField: KProperty<*>,
keyField: KProperty0<*>? = null): EntityReference<T> {
return EntityReference(T::class.java, I::class.java, refField.name, keyField?.name)
}
infix fun F(property: KProperty0<*>): EntityField<*> = fieldMap[property.name]!!
infix fun R(property: KProperty0<*>): EntityReference<*> = referenceMap[property.name]!!
fun assumeNoChange() {
fieldMap.forEach { it.value.changed = false }
}
fun assumeAllChanged() {
fieldMap.forEach { it.value.changed = true }
}
fun assumeChanged(property: KProperty<*>) {
fieldMap[property.name]!!.changed = true
}
fun assumeNoChange(property: KProperty<*>) {
fieldMap[property.name]!!.changed = false
}
fun hasChanged() = fieldMap.any { it.value.changed }
fun copyFieldsTo(obj: Any) {
if (obj is EntityModel) {
fieldMap.forEach {
obj.fieldMap[it.key]?.data = it.value.data
}
} else {
fieldMap.forEach {
obj.javaClass.getField(it.key)?.set(obj, it.value.data)
}
}
}
fun copyFieldsFrom(obj: Any) {
if (obj is EntityModel) {
fieldMap.forEach {
it.value.data = obj.fieldMap[it.key]?.data
}
} else {
fieldMap.forEach {
val field = obj.javaClass.getField(it.key)
if (field != null) {
it.value.data = field.get(obj)
}
}
}
}
private fun getReferenceKeyField(ref: EntityReference<*>): EntityField<*> {
val keyFieldName = if (ref.keyFieldName == null) {
if (primaryKeyFields.size != 1) {
throw InvalidObjectException("To use reference, the model $this must contain only one primary key " +
"field, or specify a key field explicitly, while this model has " +
"${primaryKeyFields.size} primary key column(s), neither specified a key field!")
}
primaryKeyFieldInfos[0].name
} else {
ref.keyFieldName
}
return fieldMap[keyFieldName]!!
}
private fun getReferenceKeyFieldValue(ref: EntityReference<*>): Any? {
return getReferenceKeyField(ref).data
}
class LoadResult(val _intermediateModel: EntityModel,
val data: Any?)
fun load(db: DataSession<*, *, *>, ref: EntityReference<*>) = future {
val key = getReferenceKeyFieldValue(ref)
val targetModel: EntityModel
try {
targetModel = (ref.componentClass ?: ref.targetClass).newInstance()
} catch (e: Exception) {
val ex = Exception("Target model ${ref.componentClass ?: ref.targetClass} cannot be " +
"instantiated, please make sure it contains a no-arg constructor!", e)
throw ex
}
val query = targetModel.select()
.where { targetModel.fieldMap[ref.refFieldName]!! eq key }
val data: Any? = if (ref.componentClass == null) {
query.executeFirst(db)
.await()
} else {
query.execute(db)
.thenApply { (l, _) -> l }
.await()
}
val refField = referenceMap[ref.name]!! as EntityReference<Any>
refField.data = data
refField.changed = false
LoadResult(targetModel, data)
}
fun load(db: DataSession<*, *, *>, refField: KProperty0<*>): CompletableFuture<LoadResult> {
return load(db, R(refField))
}
fun loadAll(db: DataSession<*, *, *>, recursive: Boolean = true): CompletableFuture<Unit> = future {
for ((_, refField) in referenceMap) {
load(db, refField).await()
}
if (recursive) {
for ((_, refField) in referenceMap) {
val data = refField.data
if (data is EntityModel) {
data.loadAll(db, recursive).await()
} else if (data is MutableCollection<*>) {
for (m in data) {
if (m !is EntityModel) {
continue
}
m.loadAll(db, recursive).await()
}
}
}
}
}
class SaveResult(val _intermediateModel: EntityModel?,
val list: List<EntityModel>,
val count: Int)
fun save(db: DataSession<*, *, *>): CompletableFuture<Pair<List<EntityModel>, Int>> = future {
val r = insert()
.updateWhenExists(primaryKeyFieldInfos) {
it.set(skipPrimaryKeys = true)
.where(null)
}
.execute(db)
.await()
dispatchEvents(db).await()
r
}
fun save(db: DataSession<*, *, *>, refField: EntityReference<*>): CompletableFuture<SaveResult> = future {
save(db).await()
val keyField = getReferenceKeyField(refField)
val field = referenceMap[refField.name]!!
if (refField.componentClass == null) {
var refModel = field.data as? EntityModel
val r = if (field.changed) {
if (refModel == null) {
refModel = refField.targetClass.newInstance()
refModel!!.fieldMap[refField.refFieldName]!!.data = keyField.data
refModel.delete()
.execute(db)
.await()
} else {
refModel.fieldMap[refField.refFieldName]!!.data = keyField.data
refModel.save(db)
.await()
}
} else {
Pair(emptyList(), 0)
}
refModel?.dispatchEvents(db)?.await()
SaveResult(refModel, r.first, r.second)
} else {
val refModelList = field.data as MutableCollection<EntityModel>
val refModelPrimaryKeyList = mutableListOf<MutableList<Any?>>()
for (m in refModelList) {
m.fieldMap[refField.refFieldName]!!.data = keyField.data
m.save(db).await()
val pkValues = mutableListOf<Any?>()
for (pkField in m.primaryKeyFieldInfos) {
pkValues.add(m.fieldMap[pkField.name]!!.data)
}
refModelPrimaryKeyList.add(pkValues)
}
val refModel = refField.componentClass!!.newInstance()
val notInCurrentKeys = if (refModelPrimaryKeyList.isNotEmpty()) {
ExpressionBuilder()
.beginGroup()
.apply {
for (pkField in refModel.primaryKeyFieldInfos) {
column(EntityBaseDSL.getColumnModelFromEntityField(pkField))
.separator()
}
}
.trimLastSeparator()
.endGroup()
.not()
.`in`()
.beginGroup()
.apply {
for (pkValues in refModelPrimaryKeyList) {
beginGroup()
for (v in pkValues) {
literal(v)
separator()
}
trimLastSeparator()
endGroup()
separator()
}
}
.trimLastSeparator()
.endGroup()
} else {
ExpressionBuilder()
.literal(true)
}
val r = refModel.delete()
.where {
(refModel.fieldMap[refField.refFieldName]!! eq keyField.data) and notInCurrentKeys
}
.execute(db)
.await()
refModel.dispatchEvents(db).await()
SaveResult(refModel, r.first, r.second)
}
}
fun save(db: DataSession<*, *, *>, refField: KProperty0<*>): CompletableFuture<SaveResult> {
return save(db, R(refField))
}
fun saveAll(db: DataSession<*, *, *>, recursive: Boolean = true): CompletableFuture<Unit> = future {
for ((_, refField) in referenceMap) {
save(db, refField).await()
}
if (recursive) {
for ((_, refField) in referenceMap) {
val data = refField.data
if (data is EntityModel) {
data.saveAll(db, recursive).await()
} else if (data is MutableCollection<*>) {
for (m in data) {
if (m !is EntityModel) {
continue
}
m.saveAll(db, recursive).await()
}
}
}
}
}
fun dispatchEvents(db: DataSession<*, *, *>, recursive: Boolean = false): CompletableFuture<Unit> = future {
try {
EntityEventDispatcher.dispatch(db, events).await()
} catch (e: Exception) {
throw Exception("Failed to dispatch events in $this", e)
} finally {
events.clear()
}
if (recursive) {
for ((_, refField) in referenceMap) {
val data = refField.data
if (data is EntityModel) {
data.dispatchEvents(db).await()
} else if (data is MutableCollection<*>) {
for (m in data) {
if (m !is EntityModel) {
continue
}
m.dispatchEvents(db).await()
}
}
}
}
}
}
fun <T: EntityModel> T.select(): EntitySelectDSL<T> {
return EntityDSL.select(this).from()
}
fun <T: EntityModel> T.insert(): EntityInsertDSL<T> {
this.assumeAllChanged()
for ((i, v) in primaryKeyFieldInfos.withIndex()) {
if (v.dbAutoGenerated == true) {
fieldMap[v.name]!!.changed = false
}
}
return EntityDSL.insert(this).values()
}
fun <T: EntityModel> T.update(): EntityUpdateDSL<T> {
return EntityDSL.update(this).set()
}
fun <T: EntityModel> T.delete(): EntityDeleteDSL<T> {
return EntityDSL.delete(this)
} | gpl-3.0 | 4c9ca80d4dfc05271ede29b8788a17c8 | 33.921615 | 151 | 0.526631 | 4.936535 | false | false | false | false |
MMorihiro/LifeGame | core/src/test/com.github.mmorihiro.core/TestMakeNewGeneration.kt | 1 | 2972 | package com.github.mmorihiro.core
import io.kotlintest.specs.WordSpec
class TestMakeNewGeneration : WordSpec() {
init {
val sut = MakeNewGeneration()
"MakeNewGeneration.get" should {
"return the same size array" {
val expect = 10
val array = Array(expect) { BooleanArray(expect) { false } }
sut.get(array).size shouldBe expect
}
("""
|make new generation
|when there are three living cell adjacent to one dead cell
""".trimMargin()) {
val array = arrayOf(
booleanArrayOf(true, true),
booleanArrayOf(true, false))
sut.get(array)[1][1] shouldBe true
}
("""
|continue to make them alive
|if there are two or three living cells
|adjacent to the living cell
""".trimMargin()) {
val array = arrayOf(
booleanArrayOf(false, false, false, false),
booleanArrayOf(false, true, true, false),
booleanArrayOf(false, true, true, false),
booleanArrayOf(false, false, false, false))
val actual = sut.get(array)
val expectAlive = table(
headers("x", "y"),
row(1, 1),
row(1, 2),
row(2, 1),
row(2, 2))
forAll(expectAlive) { x, y -> actual[x][y] shouldBe true }
}
"kill the living cell adjacent to less than one living cell" {
val array = arrayOf(
booleanArrayOf(false, false, false),
booleanArrayOf(false, true, true),
booleanArrayOf(false, false, false))
val actual = sut.get(array)
actual[1][1] shouldBe false
actual[1][2] shouldBe false
}
"kill the living cell adjacent to more than four living cells" {
val array = arrayOf(
booleanArrayOf(true, true, true),
booleanArrayOf(true, true, false),
booleanArrayOf(false, false, false))
val actual = sut.get(array)
actual[0][1] shouldBe false
actual[1][1] shouldBe false
}
}
"BooleanArray.copyOf" should {
"return shallow copy" {
val array = arrayOf(
booleanArrayOf(true, true, true),
booleanArrayOf(true, true, false),
booleanArrayOf(false, false, false))
val copy = array.copyOf()
copy[1][1] = false
array[1][1] shouldBe false
}
}
}
}
| apache-2.0 | 8a9be4eb74551abf5cb5dd30c7fa038e | 33.16092 | 76 | 0.456931 | 5.354955 | false | false | false | false |
treelzebub/zinepress | app/src/main/java/net/treelzebub/zinepress/db/zines/DbZines.kt | 1 | 957 | package net.treelzebub.zinepress.db.zines
import android.content.Context
import android.database.Cursor
import android.net.Uri
import net.treelzebub.zinepress.R
import net.treelzebub.zinepress.db.IDatabase
import net.treelzebub.zinepress.db.IQuery
import net.treelzebub.zinepress.util.BaseInjection
/**
* Created by Tre Murillo on 1/8/16
*/
object DbZines : IDatabase<IZine> {
override val context: Context get() = BaseInjection.context
override fun uri(): Uri {
return Uri.Builder()
.scheme("content")
.authority(context.getString(R.string.authority_zines))
.build()
}
override fun write(): ZineWriter = ZineWriter(this)
override fun all(): List<IZine> = query().list()
override fun query(): ZineQuery = ZineQuery(this)
override fun cursor(query: IQuery<IZine>): Cursor = query.cursor()
override fun list(query: IQuery<IZine>): List<IZine> = query.list()
}
| gpl-2.0 | 1824309cd8247b6c4c1ed10476cc6509 | 27.147059 | 71 | 0.693835 | 3.812749 | false | false | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/bot/commands/Quote.kt | 1 | 4415 | /*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.bot.commands
import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername
import be.duncanc.discordmodbot.data.services.UserBlockService
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import org.springframework.stereotype.Component
@Component
class Quote(
userBlockService: UserBlockService
) : CommandModule(
arrayOf("Quote"),
"[message id / message link to quote] [response text]",
"Will quote text and put a response under it, response text is optional",
ignoreWhitelist = true,
userBlockService = userBlockService
) {
companion object {
private const val JUMP_URL_PREFIX = "https://discord.com/channels/"
}
override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) {
if (arguments == null) {
throw IllegalArgumentException("This command requires at least a message id or link.")
}
val toQuoteSource = arguments.split(" ")[0]
// This assumes a standard format of
// https://discord.com/channels/<SERVER ID>/<CHANNEL ID>/<MESSAGE ID>
if (toQuoteSource.startsWith(JUMP_URL_PREFIX)) {
// idArray, as shown above, follows the pattern Server ID, TextChannel ID, Message ID.
val idArray = toQuoteSource
.removePrefix(JUMP_URL_PREFIX)
.split("/")
// make sure we are pulling from a valid place
val guild = event.jda.getGuildById(idArray[0])
guild?.getTextChannelById(idArray[1])?.retrieveMessageById(idArray[2])?.queue { messageToQuote ->
if (messageToQuote != null) {
if (messageToQuote.contentDisplay.isBlank()) {
throw IllegalArgumentException("The message you want to quote has no content to quote.")
}
quoteMessage(event, messageToQuote, arguments.substring(toQuoteSource.length))
} else {
throw IllegalArgumentException("This command requires a valid Message Link.")
}
}
}
// In case its a standard MessageID
else {
val messageId = arguments.split(" ")[0]
event.textChannel.retrieveMessageById(messageId).queue { messageToQuote ->
if (messageToQuote.contentDisplay.isBlank()) {
throw IllegalArgumentException("The message you want to quote has no content to quote.")
}
quoteMessage(event, messageToQuote, arguments.substring(messageId.length))
}
}
}
private fun quoteMessage(
event: MessageReceivedEvent,
quotedMessage: Message,
responseString: String
) {
val quoteEmbed = EmbedBuilder()
.setAuthor(
quotedMessage.member?.nicknameAndUsername,
quotedMessage.jumpUrl,
quotedMessage.author.effectiveAvatarUrl
)
.setDescription(quotedMessage.contentDisplay)
.setFooter("Posted by ${event.author}", event.author.effectiveAvatarUrl)
val responseEmbed = if (responseString.isBlank()) {
null
} else {
EmbedBuilder()
.setAuthor(event.member?.nicknameAndUsername, null, event.author.effectiveAvatarUrl)
.setDescription(responseString)
.setFooter("Posted by ${event.member}", event.author.effectiveAvatarUrl)
}
event.textChannel.sendMessageEmbeds(quoteEmbed.build()).queue()
if (responseEmbed != null) {
event.textChannel.sendMessageEmbeds(responseEmbed.build()).queue()
}
}
}
| apache-2.0 | f85cb962da328b8c72c019b3ad5bb4d9 | 40.650943 | 112 | 0.644394 | 4.889258 | false | false | false | false |
Hexworks/zircon | zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/data/DefaultBlockTest.kt | 1 | 1236 | package org.hexworks.zircon.internal.data
import org.assertj.core.api.Assertions.assertThat
import org.hexworks.zircon.api.builder.data.BlockBuilder
import org.hexworks.zircon.api.builder.graphics.StyleSetBuilder
import org.hexworks.zircon.api.data.BlockTileType
import org.hexworks.zircon.api.data.Tile
import org.junit.Test
class DefaultBlockTest {
@Test
fun shouldProperlyFetchSide() {
val top = Tile.createCharacterTile('x', StyleSetBuilder.newBuilder().build())
val target = BlockBuilder.newBuilder<Tile>()
.withEmptyTile(Tile.empty())
.withTop(top)
.build()
assertThat(target.top).isEqualTo(top)
}
@Test
fun nonEmptyBlockShouldNotBeEmpty() {
val top = Tile.createCharacterTile('x', StyleSetBuilder.newBuilder().build())
val target = BlockBuilder.newBuilder<Tile>()
.withEmptyTile(Tile.empty())
.withTop(top)
.build()
assertThat(target.isEmpty()).isFalse()
}
@Test
fun emptyBlockShouldNotBeEmpty() {
val target = BlockBuilder.newBuilder<Tile>()
.withEmptyTile(Tile.empty())
.build()
assertThat(target.isEmpty()).isTrue()
}
}
| apache-2.0 | 9b4ec632c55f85ec3dfdccf9fa722347 | 27.090909 | 85 | 0.659385 | 4.276817 | false | true | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/viewholders/ExpandableItemViewHolder.kt | 1 | 3826 | package org.wordpress.android.ui.stats.refresh.lists.sections.viewholders
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import org.wordpress.android.R
import org.wordpress.android.R.id
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ExpandableItem
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemWithIcon.TextStyle
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemWithIcon.TextStyle.LIGHT
import org.wordpress.android.util.extensions.getColorResIdFromAttribute
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.extensions.setVisible
class ExpandableItemViewHolder(parent: ViewGroup, val imageManager: ImageManager) : BlockListItemViewHolder(
parent,
R.layout.stats_block_list_item
) {
private val iconContainer = itemView.findViewById<LinearLayout>(id.icon_container)
private val text = itemView.findViewById<TextView>(id.text)
private val value = itemView.findViewById<TextView>(id.value)
private val divider = itemView.findViewById<View>(id.divider)
private val expandButton = itemView.findViewById<ImageView>(id.expand_button)
private var bar = itemView.findViewById<ProgressBar>(R.id.bar)
fun bind(
expandableItem: ExpandableItem,
expandChanged: Boolean
) {
val header = expandableItem.header
iconContainer.setIconOrAvatar(header, imageManager)
text.setTextOrHide(header.textResource, header.text)
val textColor = when (expandableItem.header.textStyle) {
TextStyle.NORMAL -> text.context.getColorResIdFromAttribute(R.attr.colorOnSurface)
LIGHT -> text.context.getColorResIdFromAttribute(R.attr.wpColorOnSurfaceMedium)
}
text.contentDescription = header.contentDescription
expandButton.visibility = View.VISIBLE
val expandButtonDescription = when (expandableItem.isExpanded) {
true -> R.string.stats_collapse_content_description
false -> R.string.stats_expand_content_description
}
expandButton.contentDescription = itemView.resources.getString(expandButtonDescription)
value.setTextOrHide(header.valueResource, header.value)
divider.setVisible(header.showDivider && !expandableItem.isExpanded)
text.setTextColor(AppCompatResources.getColorStateList(text.context, textColor))
if (header.barWidth != null) {
bar.visibility = View.VISIBLE
bar.progress = header.barWidth
} else {
bar.visibility = View.GONE
}
if (expandChanged) {
val rotationAngle = if (expandButton.rotation == 0F) 180 else 0
expandButton.animate().rotation(rotationAngle.toFloat()).setDuration(200).start()
} else {
expandButton.rotation = if (expandableItem.isExpanded) 180F else 0F
}
itemView.isClickable = true
itemView.setOnClickListener {
val announcement = if (expandableItem.isExpanded) {
itemView.resources.getString(R.string.stats_item_collapsed)
} else {
itemView.resources.getString(R.string.stats_item_expanded)
}
itemView.announceForAccessibility(announcement)
expandableItem.onExpandClicked(!expandableItem.isExpanded)
}
val longClickAction = expandableItem.header.longClickAction
if (longClickAction != null) {
itemView.setOnLongClickListener {
longClickAction.invoke(itemView)
}
}
}
}
| gpl-2.0 | c79534174f0b8d0c1a01793d44653ec3 | 45.658537 | 108 | 0.719812 | 4.700246 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/widgets/AppRatingDialog.kt | 1 | 8611 | @file:Suppress("DEPRECATION")
package org.wordpress.android.widgets
import android.app.Dialog
import android.app.DialogFragment
import android.app.FragmentManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import java.util.Date
import java.util.concurrent.TimeUnit
object AppRatingDialog {
private const val PREF_NAME = "rate_wpandroid"
private const val KEY_INSTALL_DATE = "rate_install_date"
private const val KEY_LAUNCH_TIMES = "rate_launch_times"
private const val KEY_OPT_OUT = "rate_opt_out"
private const val KEY_ASK_LATER_DATE = "rate_ask_later_date"
private const val KEY_INTERACTIONS = "rate_interactions"
// app must have been installed this long before the rating dialog will appear
private const val CRITERIA_INSTALL_DAYS: Int = 7
// app must have been launched this many times before the rating dialog will appear
private const val CRITERIA_LAUNCH_TIMES: Int = 10
// user must have performed this many interactions before the rating dialog will appear
private const val CRITERIA_INTERACTIONS: Int = 10
private var installDate = Date()
private var askLaterDate = Date()
private var launchTimes = 0
private var interactions = 0
private var optOut = false
private lateinit var preferences: SharedPreferences
/**
* Call this when the launcher activity is launched.
*/
fun init(context: Context) {
preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val editor = preferences.edit()
// If it is the first launch, save the date in shared preference.
if (preferences.getLong(KEY_INSTALL_DATE, 0) == 0L) {
storeInstallDate(context)
}
// Increment launch times
launchTimes = preferences.getInt(KEY_LAUNCH_TIMES, 0)
launchTimes++
editor.putInt(KEY_LAUNCH_TIMES, launchTimes)
editor.apply()
interactions = preferences.getInt(KEY_INTERACTIONS, 0)
optOut = preferences.getBoolean(KEY_OPT_OUT, false)
installDate = Date(preferences.getLong(KEY_INSTALL_DATE, 0))
askLaterDate = Date(preferences.getLong(KEY_ASK_LATER_DATE, 0))
}
/**
* Show the rate dialog if the criteria is satisfied.
* @return true if shown, false otherwise.
*/
@Suppress("DEPRECATION")
fun showRateDialogIfNeeded(fragmentManger: FragmentManager): Boolean {
return if (shouldShowRateDialog()) {
showRateDialog(fragmentManger)
true
} else {
false
}
}
/**
* Called from various places in the app where the user has performed a non-trivial action, such as publishing post
* or page. We use this to avoid showing the rating dialog to uninvolved users
*/
fun incrementInteractions(incrementInteractionTracker: AnalyticsTracker.Stat) {
if (!optOut) {
interactions++
preferences.edit().putInt(KEY_INTERACTIONS, interactions)?.apply()
AnalyticsTracker.track(incrementInteractionTracker)
}
}
/**
* Check whether the rate dialog should be shown or not.
* @return true if the dialog should be shown
*/
private fun shouldShowRateDialog(): Boolean {
return if (optOut or (launchTimes < CRITERIA_LAUNCH_TIMES) or (interactions < CRITERIA_INTERACTIONS)) {
false
} else {
val thresholdMs = TimeUnit.DAYS.toMillis(CRITERIA_INSTALL_DAYS.toLong())
Date().time - installDate.time >= thresholdMs && Date().time - askLaterDate.time >= thresholdMs
}
}
@Suppress("DEPRECATION")
private fun showRateDialog(fragmentManger: FragmentManager) {
var dialog = fragmentManger.findFragmentByTag(AppRatingDialog.TAG_APP_RATING_PROMPT_DIALOG)
if (dialog == null) {
dialog = AppRatingDialog()
dialog.show(fragmentManger, AppRatingDialog.TAG_APP_RATING_PROMPT_DIALOG)
AnalyticsTracker.track(AnalyticsTracker.Stat.APP_REVIEWS_SAW_PROMPT)
}
}
@Suppress("DEPRECATION")
class AppRatingDialog : DialogFragment() {
companion object {
internal const val TAG_APP_RATING_PROMPT_DIALOG = "TAG_APP_RATING_PROMPT_DIALOG"
}
@Suppress("SwallowedException")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = MaterialAlertDialogBuilder(activity)
val appName = getString(R.string.app_name)
val title = getString(R.string.app_rating_title, appName)
builder.setTitle(title)
.setMessage(R.string.app_rating_message)
.setCancelable(true)
.setPositiveButton(R.string.app_rating_rate_now) { _, _ ->
val appPackage = activity.packageName
val url = "market://details?id=$appPackage"
try {
activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
} catch (e: ActivityNotFoundException) {
// play store app isn't on this device so open app's page in browser instead
activity.startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse(
"http://play.google.com/store/apps/details?id=" +
activity.packageName
)
)
)
}
setOptOut(true)
AnalyticsTracker.track(AnalyticsTracker.Stat.APP_REVIEWS_RATED_APP)
}
.setNeutralButton(R.string.app_rating_rate_later) { _, _ ->
clearSharedPreferences()
storeAskLaterDate()
AnalyticsTracker.track(AnalyticsTracker.Stat.APP_REVIEWS_DECIDED_TO_RATE_LATER)
}
.setNegativeButton(R.string.app_rating_rate_never) { _, _ ->
setOptOut(true)
AnalyticsTracker.track(AnalyticsTracker.Stat.APP_REVIEWS_DECLINED_TO_RATE_APP)
}
return builder.create()
}
override fun onCancel(dialog: DialogInterface?) {
super.onCancel(dialog)
clearSharedPreferences()
storeAskLaterDate()
AnalyticsTracker.track(AnalyticsTracker.Stat.APP_REVIEWS_CANCELLED_PROMPT)
}
}
/**
* Clear data other than opt-out in shared preferences - called when the "Later" is pressed or dialog is canceled.
*/
private fun clearSharedPreferences() {
preferences.edit().remove(KEY_INSTALL_DATE)?.remove(KEY_LAUNCH_TIMES)?.remove(KEY_INTERACTIONS)?.apply()
}
/**
* Set opt out flag - when true, the rate dialog will never be shown unless app data is cleared.
*/
private fun setOptOut(optOut: Boolean) {
preferences.edit().putBoolean(KEY_OPT_OUT, optOut)?.apply()
this.optOut = optOut
}
/**
* Store install date - retrieved from package manager if possible.
*/
private fun storeInstallDate(context: Context) {
var installDate = Date()
val packMan = context.packageManager
try {
val pkgInfo = packMan.getPackageInfo(context.packageName, 0)
installDate = Date(pkgInfo.firstInstallTime)
} catch (e: PackageManager.NameNotFoundException) {
AppLog.e(T.UTILS, e)
}
preferences.edit().putLong(KEY_INSTALL_DATE, installDate.time)?.apply()
}
/**
* Store the date the user asked for being asked again later.
*/
private fun storeAskLaterDate() {
val nextAskDate = System.currentTimeMillis()
preferences.edit().putLong(KEY_ASK_LATER_DATE, nextAskDate)?.apply()
}
}
| gpl-2.0 | fcaf596687964ab8a959915159c6aec2 | 39.617925 | 119 | 0.618511 | 4.82409 | false | false | false | false |
eneim/android-UniversalMusicPlayer | media/src/main/java/com/example/android/uamp/media/PackageValidator.kt | 1 | 15051 | /*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media
import android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE
import android.Manifest.permission.MEDIA_CONTENT_CONTROL
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED
import android.content.pm.PackageManager
import android.content.res.XmlResourceParser
import android.os.Build
import android.os.Process
import androidx.annotation.XmlRes
import androidx.media.MediaBrowserServiceCompat
import android.support.v4.media.session.MediaSessionCompat
import android.util.Base64
import android.util.Log
import org.xmlpull.v1.XmlPullParserException
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
/**
* Validates that the calling package is authorized to browse a [MediaBrowserServiceCompat].
*
* The list of allowed signing certificates and their corresponding package names is defined in
* res/xml/allowed_media_browser_callers.xml.
*
* If you want to add a new caller to allowed_media_browser_callers.xml and you don't know
* its signature, this class will print to logcat (INFO level) a message with the proper
* xml tags to add to allow the caller.
*
* For more information, see res/xml/allowed_media_browser_callers.xml.
*/
class PackageValidator(context: Context, @XmlRes xmlResId: Int) {
private val context: Context
private val packageManager: PackageManager
private val certificateWhitelist: Map<String, KnownCallerInfo>
private val platformSignature: String
private val callerChecked = mutableMapOf<String, Pair<Int, Boolean>>()
init {
val parser = context.resources.getXml(xmlResId)
this.context = context.applicationContext
this.packageManager = this.context.packageManager
certificateWhitelist = buildCertificateWhitelist(parser)
platformSignature = getSystemSignature()
}
/**
* Checks whether the caller attempting to connect to a [MediaBrowserServiceCompat] is known.
* See [MusicService.onGetRoot] for where this is utilized.
*
* @param callingPackage The package name of the caller.
* @param callingUid The user id of the caller.
* @return `true` if the caller is known, `false` otherwise.
*/
fun isKnownCaller(callingPackage: String, callingUid: Int): Boolean {
// If the caller has already been checked, return the previous result here.
val (checkedUid, checkResult) = callerChecked[callingPackage] ?: Pair(0, false)
if (checkedUid == callingUid) {
return checkResult
}
/**
* Because some of these checks can be slow, we save the results in [callerChecked] after
* this code is run.
*
* In particular, there's little reason to recompute the calling package's certificate
* signature (SHA-256) each call.
*
* This is safe to do as we know the UID matches the package's UID (from the check above),
* and app UIDs are set at install time. Additionally, a package name + UID is guaranteed to
* be constant until a reboot. (After a reboot then a previously assigned UID could be
* reassigned.)
*/
// Build the caller info for the rest of the checks here.
val callerPackageInfo = buildCallerInfo(callingPackage)
?: throw IllegalStateException("Caller wasn't found in the system?")
// Verify that things aren't ... broken. (This test should always pass.)
if (callerPackageInfo.uid != callingUid) {
throw IllegalStateException("Caller's package UID doesn't match caller's actual UID?")
}
val callerSignature = callerPackageInfo.signature
val isPackageInWhitelist = certificateWhitelist[callingPackage]?.signatures?.first {
it.signature == callerSignature
} != null
val isCallerKnown = when {
// If it's our own app making the call, allow it.
callingUid == Process.myUid() -> true
// If it's one of the apps on the whitelist, allow it.
isPackageInWhitelist -> true
// If the system is making the call, allow it.
callingUid == Process.SYSTEM_UID -> true
// If the app was signed by the same certificate as the platform itself, also allow it.
callerSignature == platformSignature -> true
/**
* [MEDIA_CONTENT_CONTROL] permission is only available to system applications, and
* while it isn't required to allow these apps to connect to a
* [MediaBrowserServiceCompat], allowing this ensures optimal compatability with apps
* such as Android TV and the Google Assistant.
*/
callerPackageInfo.permissions.contains(MEDIA_CONTENT_CONTROL) -> true
/**
* This last permission can be specifically granted to apps, and, in addition to
* allowing them to retrieve notifications, it also allows them to connect to an
* active [MediaSessionCompat].
* As with the above, it's not required to allow apps holding this permission to
* connect to your [MediaBrowserServiceCompat], but it does allow easy comparability
* with apps such as Wear OS.
*/
callerPackageInfo.permissions.contains(BIND_NOTIFICATION_LISTENER_SERVICE) -> true
// If none of the pervious checks succeeded, then the caller is unrecognized.
else -> false
}
if (!isCallerKnown) {
logUnknownCaller(callerPackageInfo)
}
// Save our work for next time.
callerChecked[callingPackage] = Pair(callingUid, isCallerKnown)
return isCallerKnown
}
/**
* Logs an info level message with details of how to add a caller to the allowed callers list
* when the app is debuggable.
*/
private fun logUnknownCaller(callerPackageInfo: CallerPackageInfo) {
if (BuildConfig.DEBUG && callerPackageInfo.signature != null) {
val formattedLog =
context.getString(
R.string.allowed_caller_log,
callerPackageInfo.name,
callerPackageInfo.packageName,
callerPackageInfo.signature)
Log.i(TAG, formattedLog)
}
}
/**
* Builds a [CallerPackageInfo] for a given package that can be used for all the
* various checks that are performed before allowing an app to connect to a
* [MediaBrowserServiceCompat].
*/
private fun buildCallerInfo(callingPackage: String): CallerPackageInfo? {
val packageInfo = getPackageInfo(callingPackage) ?: return null
val appName = packageInfo.applicationInfo.loadLabel(packageManager).toString()
val uid = packageInfo.applicationInfo.uid
val signature = getSignature(packageInfo)
val requestedPermissions = packageInfo.requestedPermissions
val permissionFlags = packageInfo.requestedPermissionsFlags
val activePermissions = mutableSetOf<String>()
requestedPermissions?.forEachIndexed { index, permission ->
if (permissionFlags[index] and REQUESTED_PERMISSION_GRANTED != 0) {
activePermissions += permission
}
}
return CallerPackageInfo(appName, callingPackage, uid, signature, activePermissions.toSet())
}
/**
* Looks up the [PackageInfo] for a package name.
* This requests both the signatures (for checking if an app is on the whitelist) and
* the app's permissions, which allow for more flexibility in the whitelist.
*
* @return [PackageInfo] for the package name or null if it's not found.
*/
@SuppressLint("PackageManagerGetSignatures")
private fun getPackageInfo(callingPackage: String): PackageInfo? =
packageManager.getPackageInfo(callingPackage,
PackageManager.GET_SIGNATURES or PackageManager.GET_PERMISSIONS)
/**
* Gets the signature of a given package's [PackageInfo].
*
* The "signature" is a SHA-256 hash of the public key of the signing certificate used by
* the app.
*
* If the app is not found, or if the app does not have exactly one signature, this method
* returns `null` as the signature.
*/
private fun getSignature(packageInfo: PackageInfo): String? {
// Security best practices dictate that an app should be signed with exactly one (1)
// signature. Because of this, if there are multiple signatures, reject it.
if (packageInfo.signatures == null || packageInfo.signatures.size != 1) {
return null
} else {
val certificate = packageInfo.signatures[0].toByteArray()
return getSignatureSha256(certificate)
}
}
private fun buildCertificateWhitelist(parser: XmlResourceParser): Map<String, KnownCallerInfo> {
val certificateWhitelist = LinkedHashMap<String, KnownCallerInfo>()
try {
var eventType = parser.next()
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
val callerInfo = when (parser.name) {
"signing_certificate" -> parseV1Tag(parser)
"signature" -> parseV2Tag(parser)
else -> null
}
callerInfo?.let { info ->
val packageName = info.packageName
val existingCallerInfo = certificateWhitelist[packageName]
if (existingCallerInfo != null) {
existingCallerInfo.signatures += callerInfo.signatures
} else {
certificateWhitelist[packageName] = callerInfo
}
}
}
eventType = parser.next()
}
} catch (xmlException: XmlPullParserException) {
Log.e(TAG, "Could not read allowed callers from XML.", xmlException)
} catch (ioException: IOException) {
Log.e(TAG, "Could not read allowed callers from XML.", ioException)
}
return certificateWhitelist
}
/**
* Parses a v1 format tag. See allowed_media_browser_callers.xml for more details.
*/
private fun parseV1Tag(parser: XmlResourceParser): KnownCallerInfo {
val name = parser.getAttributeValue(null, "name")
val packageName = parser.getAttributeValue(null, "package")
val isRelease = parser.getAttributeBooleanValue(null, "release", false)
val certificate = parser.nextText().replace(WHITESPACE_REGEX, "")
val signature = getSignatureSha256(certificate)
val callerSignature = KnownSignature(signature, isRelease)
return KnownCallerInfo(name, packageName, mutableSetOf(callerSignature))
}
/**
* Parses a v2 format tag. See allowed_media_browser_callers.xml for more details.
*/
private fun parseV2Tag(parser: XmlResourceParser): KnownCallerInfo {
val name = parser.getAttributeValue(null, "name")
val packageName = parser.getAttributeValue(null, "package")
val callerSignatures = mutableSetOf<KnownSignature>()
var eventType = parser.next()
while (eventType != XmlResourceParser.END_TAG) {
val isRelease = parser.getAttributeBooleanValue(null, "release", false)
val signature = parser.nextText().replace(WHITESPACE_REGEX, "").toLowerCase()
callerSignatures += KnownSignature(signature, isRelease)
eventType = parser.next()
}
return KnownCallerInfo(name, packageName, callerSignatures)
}
/**
* Finds the Android platform signing key signature. This key is never null.
*/
private fun getSystemSignature(): String =
getPackageInfo(ANDROID_PLATFORM)?.let { platformInfo ->
getSignature(platformInfo)
} ?: throw IllegalStateException("Platform signature not found")
/**
* Creates a SHA-256 signature given a Base64 encoded certificate.
*/
private fun getSignatureSha256(certificate: String): String {
return getSignatureSha256(Base64.decode(certificate, Base64.DEFAULT))
}
/**
* Creates a SHA-256 signature given a certificate byte array.
*/
private fun getSignatureSha256(certificate: ByteArray): String {
val md: MessageDigest
try {
md = MessageDigest.getInstance("SHA256")
} catch (noSuchAlgorithmException: NoSuchAlgorithmException) {
Log.e(TAG, "No such algorithm: $noSuchAlgorithmException")
throw RuntimeException("Could not find SHA256 hash algorithm", noSuchAlgorithmException)
}
md.update(certificate)
// This code takes the byte array generated by `md.digest()` and joins each of the bytes
// to a string, applying the string format `%02x` on each digit before it's appended, with
// a colon (':') between each of the items.
// For example: input=[0,2,4,6,8,10,12], output="00:02:04:06:08:0a:0c"
return md.digest().joinToString(":") { String.format("%02x", it) }
}
private data class KnownCallerInfo(
internal val name: String,
internal val packageName: String,
internal val signatures: MutableSet<KnownSignature>
)
private data class KnownSignature(
internal val signature: String,
internal val release: Boolean
)
/**
* Convenience class to hold all of the information about an app that's being checked
* to see if it's a known caller.
*/
private data class CallerPackageInfo(
internal val name: String,
internal val packageName: String,
internal val uid: Int,
internal val signature: String?,
internal val permissions: Set<String>
)
}
private const val TAG = "PackageValidator"
private const val ANDROID_PLATFORM = "android"
private val WHITESPACE_REGEX = "\\s|\\n".toRegex()
| apache-2.0 | a96b527ea87552822200f94457f03a49 | 41.880342 | 100 | 0.65597 | 4.978829 | false | false | false | false |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/commandframework/commands/development/JsInteropCommands.kt | 1 | 2242 | package me.aberrantfox.hotbot.commandframework.commands.development
import me.aberrantfox.hotbot.commandframework.parsing.ArgumentType
import me.aberrantfox.hotbot.dsls.command.CommandSet
import me.aberrantfox.hotbot.dsls.command.CommandsContainer
import me.aberrantfox.hotbot.dsls.command.commands
import me.aberrantfox.hotbot.services.Configuration
import me.aberrantfox.hotbot.services.configPath
import net.dv8tion.jda.core.JDA
import java.io.File
import javax.script.Invocable
import javax.script.ScriptEngine
import jdk.nashorn.api.scripting.NashornScriptEngineFactory
import me.aberrantfox.hotbot.services.HelpConf
object EngineContainer {
var engine: ScriptEngine? = null
fun setupScriptEngine(jda: JDA, container: CommandsContainer, config: Configuration): ScriptEngine {
val engine = NashornScriptEngineFactory().getScriptEngine("--language=es6", "-scripting")
engine.put("jda", jda)
engine.put("container", container)
engine.put("config", config)
engine.put("help", HelpConf)
val setupScripts = File(configPath("scripts${File.separator}jsapi"))
val custom = File(configPath("scripts${File.separator}custom"))
walkDirectory(setupScripts, engine)
walkDirectory(custom, engine)
return engine
}
private fun walkDirectory(dir: File, engine: ScriptEngine) = dir.walk()
.filter { !it.isDirectory }
.map { it.readText() }
.forEach { engine.eval(it) }
}
private const val functionName = "functionScope"
@CommandSet
fun jsCommands() = commands {
command("eval") {
expect(ArgumentType.Sentence)
execute {
val script = it.args.component1() as String
val functionContext = createFunctionContext(script)
try {
EngineContainer.engine?.eval(functionContext)
(EngineContainer.engine as Invocable).invokeFunction(functionName, it)
} catch (e: Exception) {
it.respond("${e.message} - **cause** - ${e.cause}")
}
}
}
}
private fun createFunctionContext(scriptBody: String) =
"""
function ${functionName}(event) {
$scriptBody
};
""".trimIndent() | mit | 4ccf41291600c169f91e48e32654f0bc | 32.984848 | 104 | 0.685103 | 4.404715 | false | true | false | false |
sanstorik/jworkflow_tracker | src/database/json_connection.kt | 1 | 9010 | package database
import activities.Activity
import activities.FocusContextAnalyzer
import activities.KeyContextAnalyzer
import activities.days.Day
import activities.days.hour.HourActivity
import activities.projects.Project
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import java.io.*
import java.util.*
import kotlin.collections.HashSet
/**
* Class that represents connection between model of projects
* and JSON file, that holds data for this model.
*/
public class ProjectConnectionJson : DatabaseConnection<Project> {
override fun save(obj: Set<Project>, holderName: String) {
val file = File(holderName)
if (!file.exists() || file.isDirectory) file.createNewFile()
BufferedWriter(OutputStreamWriter(FileOutputStream(file))).use {
it.write(getProjectSetJson(obj))
}
}
override fun read(holderName: String): Set<Project> {
val file = File(holderName)
if (!file.exists() || file.isDirectory) {
throw NoSuchFileException(file)
}
var content = ""
FileReader(file).use { content = it.readText() }
//file may be created but not filled with data yer
//so we return empty set in that case
if (content.isEmpty() || content.isBlank()) {
return setOf()
}
return readProjectsSet(JsonParser().parse(FileReader(file)))
}
@Suppress("UNCHECKED_CAST")
private fun readProjectsSet(json: JsonElement): Set<Project> {
val set = HashSet<Project>()
val rootObject = json.asJsonObject
rootObject.entrySet().forEach {
val project : JsonObject = it.value.asJsonObject
set.add(Project(_projectName = it.key,
_mouseClickedCount = project.get("mouseClickedCount").asInt,
_timeSpentAfkInSec = project.get("timeSpentAfkInSec").asInt,
_timeSpentInSec = project.get("timeSpentInSec").asInt,
_timerStartsCount = project.get("timerStartsCount").asInt,
_focusContextMap = getFocusContextMap(project.get("focusContext")),
_keysContextMap = getKeyContextMap(project.get("keyContext")),
_keysClickedCount = getKeyContextClicked(project.get("keyContext")),
_dateOfCreation = getDateOfProjectCreation(project.get("dateOfCreation")))
)
}
return set
}
private fun getProjectSetJson(projects: Set<Project>): String {
val rootObj = JsonObject()
for (obj in projects) {
rootObj.add(obj.projectName, getProjectJson(obj))
}
return Gson().toJson(rootObj)
}
private fun getProjectJson(project: Project): JsonObject {
val projectValues = JsonObject()
addActivityJsonProperties(projectValues, project)
val calendarDate = Gson().toJson(project.dateOfCreation)
projectValues.addProperty("dateOfCreation", calendarDate)
return projectValues
}
private fun getDateOfProjectCreation(element: JsonElement) =
Gson().fromJson(element.asString, Calendar::class.java)
}
internal class DaysConnectionJson: DatabaseConnection<Day> {
override fun save(obj: Set<Day>, holderName: String) {
val file = File(holderName)
if (!file.exists() || file.isDirectory) file.createNewFile()
BufferedWriter(OutputStreamWriter(FileOutputStream(file))).use {
it.write(getDaysSetJson(obj))
}
}
override fun read(holderName: String): Set<Day> {
val file = File(holderName)
if (!file.exists() || file.isDirectory) {
throw NoSuchFileException(file)
}
var content = ""
FileReader(file).use { content = it.readText() }
//file may be created but not filled with data yet
//so we return empty set in that case
if (content.isEmpty() || content.isBlank()) {
return setOf()
}
return readDaySet(JsonParser().parse(FileReader(file)))
}
private fun getDaysSetJson(days: Set<Day>): String {
val rootObj = JsonObject()
for (obj in days) {
rootObj.add(obj.date.toString(), getDayJson(obj))
}
return Gson().toJson(rootObj)
}
private fun getDayJson(day: Day): JsonElement {
val dayValues = JsonObject()
addActivityJsonProperties(dayValues, day)
val date = Gson().toJson(day.date)
dayValues.addProperty("date", date)
dayValues.add("hourActivities", getHourActivitiesJson(day))
return dayValues
}
/**
* Save to days set of Hours, 1-24 which
* are actually activities as well.
*/
private fun getHourActivitiesJson(day: Day): JsonElement {
val rootObj = JsonObject()
day.getHourActivities().forEach {
rootObj.add(it.hour.toString(), getHourActivityJson(it))
}
return rootObj
}
private fun getHourActivityJson(hourActivity: HourActivity): JsonElement {
val hourValues = JsonObject()
addActivityJsonProperties(hourValues, hourActivity)
return hourValues
}
@Suppress("UNCHECKED_CAST")
private fun readDaySet(json: JsonElement): Set<Day> {
val set = HashSet<Day>()
val rootObject = json.asJsonObject
rootObject.entrySet().forEach {
val day : JsonObject = it.value.asJsonObject
set.add(Day(_date = getDayDate(day.get("date")),
_hourActivities = readHourSet(day.get("hourActivities")),
_mouseClickedCount = day.get("mouseClickedCount").asInt,
_timeSpentAfkInSec = day.get("timeSpentAfkInSec").asInt,
_timeSpentInSec = day.get("timeSpentInSec").asInt,
_timerStartsCount = day.get("timerStartsCount").asInt,
_focusContextMap = getFocusContextMap(day.get("focusContext")),
_keysContextMap = getKeyContextMap(day.get("keyContext")),
_keysClickedCount = getKeyContextClicked(day.get("keyContext")))
)
}
return set
}
private fun getDayDate(element: JsonElement) =
Gson().fromJson(element.asString, activities.days.Date::class.java)
private fun readHourSet(json: JsonElement): Set<HourActivity> {
val set = HashSet<HourActivity>(24)
val rootObject = json.asJsonObject
rootObject.entrySet().forEach {
val hour : JsonObject = it.value.asJsonObject
set.add(HourActivity(hour = Integer.parseInt(it.key),
_mouseClickedCount = hour.get("mouseClickedCount").asInt,
_timeSpentAfkInSec = hour.get("timeSpentAfkInSec").asInt,
_timeSpentInSec = hour.get("timeSpentInSec").asInt,
_timerStartsCount = hour.get("timerStartsCount").asInt,
_focusContextMap = getFocusContextMap(hour.get("focusContext")),
_keysContextMap = getKeyContextMap(hour.get("keyContext")),
_keysClickedCount = getKeyContextClicked(hour.get("keyContext")))
)
}
return set
}
}
private fun addActivityJsonProperties(jsonObject: JsonObject, activity: Activity) {
jsonObject.addProperty("mouseClickedCount", activity.mouseClickedCount)
jsonObject.addProperty("timeSpentAfkInSec", activity.timeSpentAfkInSec)
jsonObject.addProperty("timeSpentInSec", activity.timeSpentInSec)
jsonObject.addProperty("timerStartsCount", activity.timerStartsCount)
jsonObject.add("focusContext", focusAnalyzerJsonObject(activity.focusContextAnalyzer))
jsonObject.add("keyContext", keyAnalyzerJsonObject(activity.keysContextAnalyser))
}
private fun focusAnalyzerJsonObject(focus: FocusContextAnalyzer): JsonObject {
val gson = Gson()
val focusContextObject = JsonObject()
focusContextObject.addProperty("visitedContextMap", gson.toJson(focus.getVisitedContexts()))
return focusContextObject
}
private fun keyAnalyzerJsonObject(keyContext: KeyContextAnalyzer): JsonObject {
val gson = Gson()
val keyContextObject = JsonObject()
keyContextObject.addProperty("keyContextMap", gson.toJson(keyContext.getClickedButtons()))
keyContextObject.addProperty("clickedTotalCount", keyContext.keysClicked)
return keyContextObject
}
@Suppress("UNCHECKED_CAST")
private fun getKeyContextMap(obj: JsonElement) =
Gson().fromJson(obj.asJsonObject.get("keyContextMap").asString, Map::class.java) as Map<String,Int>
private fun getKeyContextClicked(obj: JsonElement) = obj.asJsonObject.get("clickedTotalCount").asInt
@Suppress("UNCHECKED_CAST")
private fun getFocusContextMap(obj: JsonElement) =
Gson().fromJson(obj.asJsonObject.get("visitedContextMap").asString, Map::class.java) as Map<String,Long>
| gpl-3.0 | 2e0513d978b0515354a5cb340385acbb | 34.472441 | 109 | 0.656271 | 4.599285 | false | false | false | false |
howard-e/just-quotes-kt | app/src/main/java/com/heed/justquotes/fragments/QuoteCategoryFragment.kt | 1 | 4148 | package com.heed.justquotes.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.heed.justquotes.R
import com.heed.justquotes.activities.BaseActivity
import com.heed.justquotes.adapters.QuoteRecyclerAdapter
import com.heed.justquotes.data.remote.ApiRequest
import com.heed.justquotes.models.Quote
import com.heed.justquotes.models.RandomFamousQuote
import kotlinx.android.synthetic.main.fragment_quote_category.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* @author Howard.
*/
class QuoteCategoryFragment : Fragment() {
private var quotes: ArrayList<Any>? = ArrayList()
private var category: String? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
category = arguments?.getString("category", null)
return inflater.inflate(R.layout.fragment_quote_category, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val quoteRecyclerAdapter = QuoteRecyclerAdapter(this.context!!, quotes as ArrayList<Any>)
[email protected]_view.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
[email protected]_view.adapter = quoteRecyclerAdapter
loadQuotesData(quoteRecyclerAdapter)
[email protected]_refresh_layout.setOnRefreshListener {
loadQuotesData(quoteRecyclerAdapter)
}
}
private fun loadQuotesData(quoteRecyclerAdapter: QuoteRecyclerAdapter) {
val progressDialog = (activity as BaseActivity).showIndeterminateProgressDialog("Getting Quotes ...", true).build()
progressDialog.show()
ApiRequest.hitRandomFamousQuotesApi(category, 5).enqueue(object : Callback<List<RandomFamousQuote>> {
override fun onResponse(call: Call<List<RandomFamousQuote>>, response: Response<List<RandomFamousQuote>>) {
Log.d(TAG, "response status: " + response.isSuccessful)
if (response.isSuccessful) {
val randomFamousQuotes = response.body()
Log.d(TAG, "randomFamousQuotes: $randomFamousQuotes")
if (randomFamousQuotes != null && randomFamousQuotes.isNotEmpty()) {
quotes!!.clear()
quoteRecyclerAdapter.notifyDataSetChanged()
for (quote: RandomFamousQuote in randomFamousQuotes) {
val quoteToAdd = Quote(quotes!!.size.toString(), quote.quote!!, quote.author, null)
if (!quotes!!.contains(quoteToAdd)) {
quotes!!.add(quoteToAdd)
quoteRecyclerAdapter.notifyItemInserted(quoteRecyclerAdapter.itemCount)
}
}
progressDialog.dismiss()
[email protected]_refresh_layout.isRefreshing = false
} else {
progressDialog.dismiss()
[email protected]_refresh_layout.isRefreshing = false
// TODO: Show error on-screen
}
} else {
progressDialog.dismiss()
[email protected]_refresh_layout.isRefreshing = false
// TODO: Show error on-screen
}
}
override fun onFailure(call: Call<List<RandomFamousQuote>>, t: Throwable) {
Log.e(TAG, t.message, t)
progressDialog.dismiss()
[email protected]_refresh_layout.isRefreshing = false
// TODO: Show error on-screen
}
})
}
companion object {
private val TAG = QuoteCategoryFragment::class.java.simpleName
}
} | apache-2.0 | 6dd054ac6f53bdd477f06b5de3685ce8 | 43.612903 | 130 | 0.644648 | 4.961722 | false | false | false | false |
googlemaps/android-maps-utils | lint-checks/src/main/java/com/google/maps/android/lint/checks/GoogleMapDetector.kt | 1 | 3941 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.maps.android.lint.checks
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.TextFormat
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
@Suppress("UnstableApiUsage")
class GoogleMapDetector : Detector(), SourceCodeScanner {
override fun getApplicableMethodNames(): List<String>? =
listOf(
"setInfoWindowAdapter",
"setOnInfoWindowClickListener",
"setOnInfoWindowLongClickListener",
"setOnMarkerClickListener",
"setOnMarkerDragListener",
)
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
val evaluator = context.evaluator
if (!evaluator.isMemberInClass(method, "com.google.android.gms.maps.GoogleMap")) {
return
}
context.report(
issue = POTENTIAL_BEHAVIOR_OVERRIDE,
scope = node,
location = context.getLocation(node),
message = POTENTIAL_BEHAVIOR_OVERRIDE.getBriefDescription(TextFormat.TEXT)
)
}
companion object {
private val migrationGuideUrl = "https://bit.ly/3kTpQmY"
val POTENTIAL_BEHAVIOR_OVERRIDE = Issue.create(
id = "PotentialBehaviorOverride",
briefDescription = "Using this method may override behaviors set by the Maps SDK for " +
"Android Utility Library. If you are not using clustering, GeoJson, or KML, you " +
"can safely suppress this warning, otherwise, refer to the utility " +
"library's migration guide: $migrationGuideUrl",
explanation = """
This lint warns for potential behavior override while using clustering, GeoJson, or
KML since these features use this method in their internal implementations. As such,
to achieve the desired behavior requires using an alternative API.
For example, if you are using the clustering feature and want to set a custom info
window, rather than invoking `GoogleMap#setInfoWindowAdapter(...)`, you would need
to set the custom info window on the MarkerManager.Collection object instead.
e.g.
```
ClusterManager clusterManager = // ...
MarkerManager.Collection collection = clusterManager.getMarkerCollection();
collection.setInfoWindowAdapter(...);
```
Refer to the migration guide for more info: $migrationGuideUrl
""",
category = Category.CORRECTNESS,
priority = 6,
severity = Severity.WARNING,
implementation = Implementation(
GoogleMapDetector::class.java,
Scope.JAVA_FILE_SCOPE
)
)
}
}
| apache-2.0 | 72669c3272ac4020a3893afdc49513f7 | 42.788889 | 100 | 0.655671 | 4.963476 | false | false | false | false |
google/flexbox-layout | demo-playground/src/main/java/com/google/android/flexbox/FlexItemViewHolder.kt | 1 | 1369 | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.flexbox
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.apps.flexbox.R
/**
* ViewHolder implementation for a flex item.
*/
class FlexItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textView: TextView = itemView.findViewById(R.id.textview)
fun bindTo(params: RecyclerView.LayoutParams) {
val adapterPosition = adapterPosition
textView.apply {
text = (adapterPosition + 1).toString()
setBackgroundResource(R.drawable.flex_item_background)
gravity = Gravity.CENTER
layoutParams = params
}
}
}
| apache-2.0 | b06507203ad8a58a12311f96a7b47c37 | 32.390244 | 78 | 0.724617 | 4.444805 | false | false | false | false |
google/accompanist | sample/src/main/java/com/google/accompanist/sample/ImageLoadingSampleUtils.kt | 1 | 1237 | /*
* 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.google.accompanist.sample
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
private val rangeForRandom = (0..100000)
fun randomSampleImageUrl(
seed: Int = rangeForRandom.random(),
width: Int = 300,
height: Int = width,
): String {
return "https://picsum.photos/seed/$seed/$width/$height"
}
/**
* Remember a URL generate by [randomSampleImageUrl].
*/
@Composable
fun rememberRandomSampleImageUrl(
seed: Int = rangeForRandom.random(),
width: Int = 300,
height: Int = width,
): String = remember { randomSampleImageUrl(seed, width, height) }
| apache-2.0 | 4ee118c97ad0703490083833b614b047 | 29.925 | 75 | 0.729184 | 3.977492 | false | false | false | false |
ktorio/ktor | ktor-network/nix/src/io/ktor/network/sockets/NativeSocketOptions.kt | 1 | 953 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.sockets
import io.ktor.network.util.*
import kotlinx.cinterop.*
import platform.posix.*
internal fun nonBlocking(descriptor: Int) {
fcntl(descriptor, F_SETFL, O_NONBLOCK).check { it == 0 }
}
internal fun assignOptions(descriptor: Int, options: SocketOptions) {
setSocketFlag(descriptor, SO_REUSEADDR, options.reuseAddress)
setSocketFlag(descriptor, SO_REUSEPORT, options.reusePort)
if (options is SocketOptions.UDPSocketOptions) {
setSocketFlag(descriptor, SO_BROADCAST, options.broadcast)
}
}
private fun setSocketFlag(
descriptor: Int,
optionName: Int,
optionValue: Boolean
) = memScoped {
val flag = alloc<IntVar>()
flag.value = if (optionValue) 1 else 0
setsockopt(descriptor, SOL_SOCKET, optionName, flag.ptr, sizeOf<IntVar>().convert())
}
| apache-2.0 | 1aaa8d01f92c60cdf7b1cac7b2197d29 | 29.741935 | 119 | 0.727177 | 3.751969 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/utilities/FileProcessUtilities.kt | 1 | 7108 | package org.roylance.yaclib.core.utilities
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream
import org.apache.commons.io.IOUtils
import org.roylance.yaclib.YaclibModel
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.StringWriter
import java.util.ArrayList
import java.util.HashMap
import java.util.HashSet
import java.util.UUID
object FileProcessUtilities {
private const val Space = " "
private const val TempDirectory = "java.io.tmpdir"
private val knownApplicationLocations = HashMap<String, String>()
private val whitespaceRegex = Regex("\\s+")
fun buildCommand(application: String, allArguments: String): List<String> {
val returnList = ArrayList<String>()
val actualApplicationLocation = getActualLocation(application)
print(actualApplicationLocation)
if (actualApplicationLocation.isEmpty()) {
returnList.add(application)
} else {
returnList.add(actualApplicationLocation)
}
val splitArguments = allArguments.split(whitespaceRegex)
returnList.addAll(splitArguments)
return returnList
}
fun readFile(path: String): String {
val foundFile = File(path)
return foundFile.readText()
}
fun writeFile(file: String, path: String) {
val newFile = File(path)
newFile.writeText(file)
}
fun handleProcess(process: ProcessBuilder, name: String) {
try {
process.redirectError(ProcessBuilder.Redirect.INHERIT)
process.redirectOutput(ProcessBuilder.Redirect.INHERIT)
process.start().waitFor()
println("finished $name")
} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
fun buildReport(process: Process): YaclibModel.ProcessReport {
val returnReport = YaclibModel.ProcessReport.newBuilder()
val inputWriter = StringWriter()
val errorWriter = StringWriter()
IOUtils.copy(process.inputStream, inputWriter)
IOUtils.copy(process.errorStream, errorWriter)
return returnReport.setErrorOutput(errorWriter.toString()).setNormalOutput(
inputWriter.toString()).build()
}
fun executeProcess(location: String, application: String,
allArguments: String): YaclibModel.ProcessReport {
val tempFile = File(getTempDirectory(), UUID.randomUUID().toString())
val actualCommand = buildCommand(application, allArguments).joinToString(Space)
val tempScript = buildTempScript(location, actualCommand)
tempFile.writeText(tempScript)
try {
Runtime.getRuntime().exec(
"${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}")
val process = Runtime.getRuntime().exec(tempFile.absolutePath)
process.waitFor()
val report = buildReport(process).toBuilder()
report.normalOutput = report.normalOutput + "\n" + tempScript
return report.build()
} finally {
tempFile.delete()
}
}
fun executeScript(location: String, application: String,
script: String): YaclibModel.ProcessReport {
val tempScript = File(getTempDirectory(), UUID.randomUUID().toString())
tempScript.writeText(script)
val tempFile = File(getTempDirectory(), UUID.randomUUID().toString())
val actualCommand = buildCommand(application, tempScript.absolutePath).joinToString(Space)
val tempExecuteScript = buildTempScript(location, actualCommand)
tempFile.writeText(tempExecuteScript)
try {
Runtime.getRuntime().exec(
"${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}")
Runtime.getRuntime().exec(
"${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempScript.absolutePath}")
val process = Runtime.getRuntime().exec(tempFile.absolutePath)
process.waitFor()
val report = buildReport(process).toBuilder()
report.normalOutput = report.normalOutput + "\n" + tempScript
return report.build()
} finally {
tempScript.delete()
tempFile.delete()
}
}
fun createTarFromDirectory(inputDirectory: String, outputFile: String,
directoriesToExclude: HashSet<String>): Boolean {
val directory = File(inputDirectory)
if (!directory.exists()) {
return false
}
val outputStream = FileOutputStream(File(outputFile))
val bufferedOutputStream = BufferedOutputStream(outputStream)
val gzipOutputStream = GzipCompressorOutputStream(bufferedOutputStream)
val tarOutputStream = TarArchiveOutputStream(gzipOutputStream)
try {
addFileToTarGz(tarOutputStream, inputDirectory, "", directoriesToExclude)
} finally {
tarOutputStream.finish()
tarOutputStream.close()
gzipOutputStream.close()
bufferedOutputStream.close()
outputStream.close()
}
return true
}
fun getActualLocation(application: String): String {
if (knownApplicationLocations.containsKey(application)) {
return knownApplicationLocations[application]!!
}
val tempFile = File(getTempDirectory(), UUID.randomUUID().toString())
tempFile.writeText("""#!/usr/bin/env bash
. ~/.bash_profile
. ~/.bashrc
which $application""")
print(tempFile.readText())
val inputWriter = StringWriter()
try {
Runtime.getRuntime().exec(
"${InitUtilities.Chmod} ${InitUtilities.ChmodExecutable} ${tempFile.absolutePath}")
val process = Runtime.getRuntime().exec(tempFile.absolutePath)
process.waitFor()
IOUtils.copy(process.inputStream, inputWriter)
return inputWriter.toString().trim()
} finally {
inputWriter.close()
tempFile.delete()
}
}
private fun addFileToTarGz(tarOutputStream: TarArchiveOutputStream, path: String, base: String,
directoriesToExclude: HashSet<String>) {
val fileOrDirectory = File(path)
if (directoriesToExclude.contains(fileOrDirectory.name)) {
return
}
val entryName: String
if (base.isEmpty()) {
entryName = "."
} else {
entryName = base + fileOrDirectory.name
}
val tarEntry = TarArchiveEntry(fileOrDirectory, entryName)
tarOutputStream.putArchiveEntry(tarEntry)
if (fileOrDirectory.isDirectory) {
fileOrDirectory.listFiles()?.forEach { file ->
addFileToTarGz(tarOutputStream, file.absolutePath, "$entryName/", directoriesToExclude)
}
} else {
val inputStream = FileInputStream(fileOrDirectory)
try {
IOUtils.copy(inputStream, tarOutputStream)
} finally {
inputStream.close()
tarOutputStream.closeArchiveEntry()
}
}
}
private fun getTempDirectory(): String {
return System.getProperty(TempDirectory)
}
private fun buildTempScript(location: String, actualCommand: String): String {
return """#!/usr/bin/env bash
. ~/.bash_profile
. ~/.bashrc
pushd $location
$actualCommand
"""
}
} | mit | 9e00693740f5d6c44979f92bd1fc1209 | 30.595556 | 97 | 0.714406 | 4.670171 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/source/online/HttpSource.kt | 1 | 12396 | package eu.kanade.tachiyomi.source.online
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.network.newCallWithProgress
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.net.URI
import java.net.URISyntaxException
import java.security.MessageDigest
/**
* A simple implementation for sources from a website.
*/
abstract class HttpSource : CatalogueSource {
/**
* Network service.
*/
protected val network: NetworkHelper by injectLazy()
/**
* Base url of the website without the trailing slash, like: http://mysite.com
*/
abstract val baseUrl: String
/**
* Version id used to generate the source id. If the site completely changes and urls are
* incompatible, you may increase this value and it'll be considered as a new source.
*/
open val versionId = 1
/**
* Id of the source. By default it uses a generated id using the first 16 characters (64 bits)
* of the MD5 of the string: sourcename/language/versionId
* Note the generated id sets the sign bit to 0.
*/
override val id by lazy {
val key = "${name.lowercase()}/$lang/$versionId"
val bytes = MessageDigest.getInstance("MD5").digest(key.toByteArray())
(0..7).map { bytes[it].toLong() and 0xff shl 8 * (7 - it) }.reduce(Long::or) and Long.MAX_VALUE
}
/**
* Headers used for requests.
*/
val headers: Headers by lazy { headersBuilder().build() }
/**
* Default network client for doing requests.
*/
open val client: OkHttpClient
get() = network.client
/**
* Headers builder for requests. Implementations can override this method for custom headers.
*/
protected open fun headersBuilder() = Headers.Builder().apply {
add("User-Agent", DEFAULT_USER_AGENT)
}
/**
* Visible name of the source.
*/
override fun toString() = "$name (${lang.uppercase()})"
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
*/
override fun fetchPopularManga(page: Int): Observable<MangasPage> {
return client.newCall(popularMangaRequest(page))
.asObservableSuccess()
.map { response ->
popularMangaParse(response)
}
}
/**
* Returns the request for the popular manga given the page.
*
* @param page the page number to retrieve.
*/
protected abstract fun popularMangaRequest(page: Int): Request
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
protected abstract fun popularMangaParse(response: Response): MangasPage
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return client.newCall(searchMangaRequest(page, query, filters))
.asObservableSuccess()
.map { response ->
searchMangaParse(response)
}
}
/**
* Returns the request for the search manga given the page.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
protected abstract fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
protected abstract fun searchMangaParse(response: Response): MangasPage
/**
* Returns an observable containing a page with a list of latest manga updates.
*
* @param page the page number to retrieve.
*/
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> {
return client.newCall(latestUpdatesRequest(page))
.asObservableSuccess()
.map { response ->
latestUpdatesParse(response)
}
}
/**
* Returns the request for latest manga given the page.
*
* @param page the page number to retrieve.
*/
protected abstract fun latestUpdatesRequest(page: Int): Request
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
protected abstract fun latestUpdatesParse(response: Response): MangasPage
/**
* Returns an observable with the updated details for a manga. Normally it's not needed to
* override this method.
*
* @param manga the manga to be updated.
*/
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return client.newCall(mangaDetailsRequest(manga))
.asObservableSuccess()
.map { response ->
mangaDetailsParse(response).apply { initialized = true }
}
}
/**
* Returns the request for the details of a manga. Override only if it's needed to change the
* url, send different headers or request method like POST.
*
* @param manga the manga to be updated.
*/
open fun mangaDetailsRequest(manga: SManga): Request {
return GET(baseUrl + manga.url, headers)
}
/**
* Parses the response from the site and returns the details of a manga.
*
* @param response the response from the site.
*/
protected abstract fun mangaDetailsParse(response: Response): SManga
/**
* Returns an observable with the updated chapter list for a manga. Normally it's not needed to
* override this method. If a manga is licensed an empty chapter list observable is returned
*
* @param manga the manga to look for chapters.
*/
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
return if (manga.status != SManga.LICENSED) {
client.newCall(chapterListRequest(manga))
.asObservableSuccess()
.map { response ->
chapterListParse(response)
}
} else {
Observable.error(Exception("Licensed - No chapters to show"))
}
}
/**
* Returns the request for updating the chapter list. Override only if it's needed to override
* the url, send different headers or request method like POST.
*
* @param manga the manga to look for chapters.
*/
protected open fun chapterListRequest(manga: SManga): Request {
return GET(baseUrl + manga.url, headers)
}
/**
* Parses the response from the site and returns a list of chapters.
*
* @param response the response from the site.
*/
protected abstract fun chapterListParse(response: Response): List<SChapter>
/**
* Returns an observable with the page list for a chapter.
*
* @param chapter the chapter whose page list has to be fetched.
*/
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
return client.newCall(pageListRequest(chapter))
.asObservableSuccess()
.map { response ->
pageListParse(response)
}
}
/**
* Returns the request for getting the page list. Override only if it's needed to override the
* url, send different headers or request method like POST.
*
* @param chapter the chapter whose page list has to be fetched.
*/
protected open fun pageListRequest(chapter: SChapter): Request {
return GET(baseUrl + chapter.url, headers)
}
/**
* Parses the response from the site and returns a list of pages.
*
* @param response the response from the site.
*/
protected abstract fun pageListParse(response: Response): List<Page>
/**
* Returns an observable with the page containing the source url of the image. If there's any
* error, it will return null instead of throwing an exception.
*
* @param page the page whose source image has to be fetched.
*/
open fun fetchImageUrl(page: Page): Observable<String> {
return client.newCall(imageUrlRequest(page))
.asObservableSuccess()
.map { imageUrlParse(it) }
}
/**
* Returns the request for getting the url to the source image. Override only if it's needed to
* override the url, send different headers or request method like POST.
*
* @param page the chapter whose page list has to be fetched
*/
protected open fun imageUrlRequest(page: Page): Request {
return GET(page.url, headers)
}
/**
* Parses the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
protected abstract fun imageUrlParse(response: Response): String
/**
* Returns an observable with the response of the source image.
*
* @param page the page whose source image has to be downloaded.
*/
fun fetchImage(page: Page): Observable<Response> {
return client.newCallWithProgress(imageRequest(page), page)
.asObservableSuccess()
}
/**
* Returns the request for getting the source image. Override only if it's needed to override
* the url, send different headers or request method like POST.
*
* @param page the chapter whose page list has to be fetched
*/
protected open fun imageRequest(page: Page): Request {
return GET(page.imageUrl!!, headers)
}
/**
* Assigns the url of the chapter without the scheme and domain. It saves some redundancy from
* database and the urls could still work after a domain change.
*
* @param url the full url to the chapter.
*/
fun SChapter.setUrlWithoutDomain(url: String) {
this.url = getUrlWithoutDomain(url)
}
/**
* Assigns the url of the manga without the scheme and domain. It saves some redundancy from
* database and the urls could still work after a domain change.
*
* @param url the full url to the manga.
*/
fun SManga.setUrlWithoutDomain(url: String) {
this.url = getUrlWithoutDomain(url)
}
/**
* Returns the url of the given string without the scheme and domain.
*
* @param orig the full url.
*/
private fun getUrlWithoutDomain(orig: String): String {
return try {
val uri = URI(orig.replace(" ", "%20"))
var out = uri.path
if (uri.query != null) {
out += "?" + uri.query
}
if (uri.fragment != null) {
out += "#" + uri.fragment
}
out
} catch (e: URISyntaxException) {
orig
}
}
/**
* Called before inserting a new chapter into database. Use it if you need to override chapter
* fields, like the title or the chapter number. Do not change anything to [manga].
*
* @param chapter the chapter to be added.
* @param manga the manga of the chapter.
*/
open fun prepareNewChapter(chapter: SChapter, manga: SManga) {
}
/**
* Returns the list of filters for the source.
*/
override fun getFilterList() = FilterList()
companion object {
const val DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.63"
}
}
| apache-2.0 | 644d74a42697484ec501576801c5815b | 32.593496 | 172 | 0.641255 | 4.695455 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryItem.kt | 2 | 2026 | package eu.kanade.tachiyomi.ui.category
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractFlexibleItem
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Category
/**
* Category item for a recycler view.
*/
class CategoryItem(val category: Category) : AbstractFlexibleItem<CategoryHolder>() {
/**
* Whether this item is currently selected.
*/
var isSelected = false
/**
* Returns the layout resource for this item.
*/
override fun getLayoutRes(): Int {
return R.layout.categories_item
}
/**
* Returns a new view holder for this item.
*
* @param view The view of this item.
* @param adapter The adapter of this item.
*/
override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): CategoryHolder {
return CategoryHolder(view, adapter as CategoryAdapter)
}
/**
* Binds the given view holder with this item.
*
* @param adapter The adapter of this item.
* @param holder The holder to bind.
* @param position The position of this item in the adapter.
* @param payloads List of partial changes.
*/
override fun bindViewHolder(
adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>,
holder: CategoryHolder,
position: Int,
payloads: List<Any?>?
) {
holder.bind(category)
}
/**
* Returns true if this item is draggable.
*/
override fun isDraggable(): Boolean {
return true
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other is CategoryItem) {
return category.id == other.category.id
}
return false
}
override fun hashCode(): Int {
return category.id!!
}
}
| apache-2.0 | 1458cf3620089dd679dc64920ccfa406 | 26.753425 | 125 | 0.657947 | 4.678984 | false | false | false | false |
kyeongwan/GDG_QR_Staff | Android/app/src/main/java/com/firebaseapp/gdg_korea_campus/staff/adapter/RSVPListAdapter.kt | 1 | 1385 | package com.firebaseapp.gdg_korea_campus.staff.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.firebaseapp.gdg_korea_campus.staff.R
import com.firebaseapp.gdg_korea_campus.staff.data.MeetUpRSVP
/**
* Created by lk on 2017. 6. 15..
*/
class RSVPListAdapter : RSVPAdapterContract.View, BaseAdapter(), RSVPAdapterContract.Model{
override fun getView(p: Int, convertView: View?, parent: ViewGroup): View {
var view = convertView
if(view == null){
view = LayoutInflater.from(parent.context).inflate(R.layout.item_event, parent, false)
}
val tv = view!!.findViewById(R.id.tv_event_title) as TextView
tv.text = getItem(p).member.name
view.setOnClickListener { onClickFunc?.invoke(p) }
return view
}
override fun getItemId(p: Int) = p.toLong()
private var rsvpList: MutableList<MeetUpRSVP> = ArrayList()
override var onClickFunc: ((Int) -> Unit)? = null
override fun getItem(p: Int) = rsvpList[p]
override fun addItems(items: List<MeetUpRSVP>) {
rsvpList.clear()
rsvpList.addAll(items)
}
override fun clearItem() = rsvpList.clear()
override fun notifyAdapter() = notifyDataSetChanged()
override fun getCount() = rsvpList.size
} | mit | ba224a5af339de500a50d104acc10c49 | 30.5 | 98 | 0.698195 | 3.753388 | false | false | false | false |
cfieber/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/RescheduleExecutionHandlerTest.kt | 1 | 3273 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.Task
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.fixture.task
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.RescheduleExecution
import com.netflix.spinnaker.orca.q.RunTask
import com.netflix.spinnaker.q.Queue
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode
import org.jetbrains.spek.subject.SubjectSpek
object RescheduleExecutionHandlerTest : SubjectSpek<RescheduleExecutionHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
subject(CachingMode.GROUP) {
RescheduleExecutionHandler(queue, repository)
}
fun resetMocks() = reset(queue, repository)
describe("reschedule an execution") {
val pipeline = pipeline {
application = "spinnaker"
status = ExecutionStatus.RUNNING
stage {
refId = "1"
status = ExecutionStatus.SUCCEEDED
}
stage {
refId = "2a"
requisiteStageRefIds = listOf("1")
status = ExecutionStatus.RUNNING
task {
id = "4"
status = ExecutionStatus.RUNNING
}
}
stage {
refId = "2b"
requisiteStageRefIds = listOf("1")
status = ExecutionStatus.RUNNING
task {
id = "5"
status = ExecutionStatus.RUNNING
}
}
stage {
refId = "3"
requisiteStageRefIds = listOf("2a", "2b")
status = ExecutionStatus.NOT_STARTED
}
}
val message = RescheduleExecution(pipeline.type, pipeline.id, pipeline.application)
beforeGroup {
whenever(repository.retrieve(pipeline.type, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
@Suppress("UNCHECKED_CAST")
it("it updates the time for each running task") {
val stage2a = pipeline.stageByRef("2a")
val stage2b = pipeline.stageByRef("2b")
val task4 = stage2a.taskById("4")
val task5 = stage2b.taskById("5")
verify(queue).reschedule(RunTask(message, stage2a.id, task4.id, Class.forName(task4.implementingClass) as Class<out Task>))
verify(queue).reschedule(RunTask(message, stage2b.id, task5.id, Class.forName(task5.implementingClass) as Class<out Task>))
verifyNoMoreInteractions(queue)
}
}
})
| apache-2.0 | 7dc50d8c28271b14c57f48a878c1e58c | 31.405941 | 129 | 0.699358 | 4.212355 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mixin/action/GenerateSoftImplementsAction.kt | 1 | 3305 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.demonwav.mcdev.platform.mixin.util.findSoftImplements
import com.demonwav.mcdev.util.findContainingClass
import com.demonwav.mcdev.util.findMatchingMethod
import com.demonwav.mcdev.util.ifEmpty
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.generation.PsiMethodMember
import com.intellij.codeInsight.hint.HintManager
import com.intellij.ide.util.MemberChooser
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiModifier
import java.util.IdentityHashMap
class GenerateSoftImplementsAction : MixinCodeInsightAction() {
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val psiClass = file.findElementAt(offset)?.findContainingClass() ?: return
val implements = psiClass.findSoftImplements() ?: return
if (implements.isEmpty()) {
return
}
val methods = IdentityHashMap<PsiMethodMember, String>()
for ((prefix, iface) in implements) {
for (signature in iface.visibleSignatures) {
val method = signature.method
if (method.isConstructor || method.hasModifierProperty(PsiModifier.STATIC)) {
continue
}
// Include only methods from interfaces
val containingClass = method.containingClass
if (containingClass == null || !containingClass.isInterface) {
continue
}
// Check if not already implemented
if (psiClass.findMatchingMethod(method, false, prefix + method.name) == null) {
methods[PsiMethodMember(method)] = prefix
}
}
}
if (methods.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No methods to soft-implement have been found")
return
}
val chooser = MemberChooser<PsiMethodMember>(methods.keys.toTypedArray(), false, true, project)
chooser.title = "Select Methods to Soft-implement"
chooser.show()
val elements = (chooser.selectedElements ?: return).ifEmpty { return }
runWriteAction {
GenerateMembersUtil.insertMembersAtOffset(
file,
offset,
elements.flatMap {
val method = it.element
val prefix = methods[it]
OverrideImplementUtil.overrideOrImplementMethod(psiClass, method, it.substitutor, chooser.isCopyJavadoc, false)
.map { m ->
// Apply prefix
m.name = prefix + m.name
OverrideImplementUtil.createGenerationInfo(m)
}
}
).firstOrNull()?.positionCaret(editor, true)
}
}
}
| mit | 796481647fc5019c2c4e080c4d25c837 | 35.318681 | 131 | 0.629047 | 5.188383 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/api/cursorLayout.kt | 1 | 13272 | package imgui.api
import glm_.f
import glm_.glm
import glm_.max
import glm_.vec2.Vec2
import imgui.ImGui.currentWindow
import imgui.ImGui.currentWindowRead
import imgui.ImGui.itemAdd
import imgui.ImGui.itemSize
import imgui.ImGui.separatorEx
import imgui.ImGui.style
import imgui.internal.classes.GroupData
import imgui.internal.classes.Rect
import imgui.internal.sections.ItemStatusFlag
import imgui.internal.sections.SeparatorFlag
import imgui.internal.sections.or
import imgui.internal.sections.LayoutType as Lt
/** Cursor / Layout
* - By "cursor" we mean the current output position.
* - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.
* - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget.
* - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API:
* Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos()
* Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. */
interface cursorLayout {
/** Vertical separator, for menu bars (use current line height). not exposed because it is misleading
* what it doesn't have an effect on regular layout. */
fun separator() {
val window = g.currentWindow!!
if (window.skipItems)
return
// Those flags should eventually be overridable by the user
val flags = if (window.dc.layoutType == Lt.Horizontal) SeparatorFlag.Vertical else SeparatorFlag.Horizontal
separatorEx(flags or SeparatorFlag.SpanAllColumns)
}
fun sameLine(offsetFromStartX: Int, spacing: Int = -1) = sameLine(offsetFromStartX.f, spacing.f)
/** Call between widgets or groups to layout them horizontally. X position given in window coordinates.
* Gets back to previous line and continue with horizontal layout
* offset_from_start_x == 0 : follow right after previous item
* offset_from_start_x != 0 : align to specified x position (relative to window/group left)
* spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
* spacing_w >= 0 : enforce spacing amount */
fun sameLine(offsetFromStartX: Float = 0f, spacing: Float = -1f) {
val window = currentWindow
if (window.skipItems) return
with(window) {
dc.cursorPos.put(
if (offsetFromStartX != 0f)
pos.x - scroll.x + offsetFromStartX + glm.max(0f, spacing) + dc.groupOffset + dc.columnsOffset
else
dc.cursorPosPrevLine.x + if (spacing < 0f) style.itemSpacing.x else spacing, dc.cursorPosPrevLine.y)
dc.currLineSize.y = dc.prevLineSize.y
dc.currLineTextBaseOffset = dc.prevLineTextBaseOffset
}
}
/** undo a sameLine() or force a new line when in an horizontal-layout context. */
fun newLine() {
val window = currentWindow
if (window.skipItems) return
val backupLayoutType = window.dc.layoutType
window.dc.layoutType = Lt.Vertical
// In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
itemSize(Vec2(0f, if (window.dc.currLineSize.y > 0f) 0f else g.fontSize))
window.dc.layoutType = backupLayoutType
}
/** add vertical spacing. */
fun spacing() {
if (currentWindow.skipItems) return
itemSize(Vec2())
}
/** add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. */
fun dummy(size: Vec2) {
val window = currentWindow
if (window.skipItems) return
val bb = Rect(window.dc.cursorPos, window.dc.cursorPos + size)
itemSize(size)
itemAdd(bb, 0)
}
/** move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0 */
fun indent(indentW: Float = 0f) = with(currentWindow) {
dc.indent += if (indentW != 0f) indentW else style.indentSpacing
dc.cursorPos.x = pos.x + dc.indent + dc.columnsOffset
}
/** move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0 */
fun unindent(indentW: Float = 0f) = with(currentWindow) {
dc.indent -= if (indentW != 0f) indentW else style.indentSpacing
dc.cursorPos.x = pos.x + dc.indent + dc.columnsOffset
}
/** Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered()
* or layout primitives such as SameLine() on whole group, etc.) */
fun beginGroup() {
with(g.currentWindow!!) {
g.groupStack += GroupData().apply {
windowID = id
backupCursorPos put dc.cursorPos
backupCursorMaxPos put dc.cursorMaxPos
backupIndent = dc.indent
backupGroupOffset = dc.groupOffset
backupCurrLineSize put dc.currLineSize
backupCurrLineTextBaseOffset = dc.currLineTextBaseOffset
backupActiveIdIsAlive = g.activeIdIsAlive
backupActiveIdPreviousFrameIsAlive = g.activeIdPreviousFrameIsAlive
emitItem = true
}
dc.groupOffset = dc.cursorPos.x - pos.x - dc.columnsOffset
dc.indent = dc.groupOffset
dc.cursorMaxPos put dc.cursorPos
dc.currLineSize.y = 0f
if (g.logEnabled)
g.logLinePosY = -Float.MAX_VALUE// To enforce Log carriage return
}
}
/** unlock horizontal starting position + capture the whole group bounding box into one "item"
* (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) */
fun endGroup() {
val window = g.currentWindow!!
assert(g.groupStack.isNotEmpty()) { "Mismatched BeginGroup()/EndGroup() calls" }
val groupData = g.groupStack.last()
assert(groupData.windowID == window.id) { "EndGroup() in wrong window?" }
val groupBb = Rect(groupData.backupCursorPos, window.dc.cursorMaxPos max groupData.backupCursorPos)
with(window.dc) {
cursorPos put groupData.backupCursorPos
cursorMaxPos put glm.max(groupData.backupCursorMaxPos, cursorMaxPos)
indent = groupData.backupIndent
groupOffset = groupData.backupGroupOffset
currLineSize put groupData.backupCurrLineSize
currLineTextBaseOffset = groupData.backupCurrLineTextBaseOffset
if (g.logEnabled)
g.logLinePosY = -Float.MAX_VALUE // To enforce Log carriage return
}
if (!groupData.emitItem) {
g.groupStack.pop()
return
}
window.dc.currLineTextBaseOffset = window.dc.prevLineTextBaseOffset max groupData.backupCurrLineTextBaseOffset // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
itemSize(groupBb.size)
itemAdd(groupBb, 0)
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// Also if you grep for LastItemId you'll notice it is only used in that context.
// (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
// (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
val groupContainsCurrActiveId = groupData.backupActiveIdIsAlive != g.activeId && g.activeIdIsAlive == g.activeId && g.activeId != 0
val groupContainsPrevActiveId = !groupData.backupActiveIdPreviousFrameIsAlive && g.activeIdPreviousFrameIsAlive
if (groupContainsCurrActiveId)
window.dc.lastItemId = g.activeId
else if (groupContainsPrevActiveId)
window.dc.lastItemId = g.activeIdPreviousFrame
window.dc.lastItemRect put groupBb
// Forward Edited flag
if (groupContainsCurrActiveId && g.activeIdHasBeenEditedThisFrame)
window.dc.lastItemStatusFlags = window.dc.lastItemStatusFlags or ItemStatusFlag.Edited
// Forward Deactivated flag
window.dc.lastItemStatusFlags = window.dc.lastItemStatusFlags or ItemStatusFlag.HasDeactivated
if (groupContainsPrevActiveId && g.activeId != g.activeIdPreviousFrame)
window.dc.lastItemStatusFlags = window.dc.lastItemStatusFlags or ItemStatusFlag.Deactivated
g.groupStack.pop()
//window->DrawList->AddRect(groupBb.Min, groupBb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
var cursorPos: Vec2
/** cursor position in window coordinates (relative to window position)
*
* Cursor position is relative to window position
* User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates
* because it is more convenient.
* Conversion happens as we pass the value to user, but it makes our naming convention confusing because
* cursorPos == dc.cursorPos - window.pos. May want to rename 'dc.cursorPos'.
* ~GetCursorPos */
get() = with(currentWindowRead!!) { dc.cursorPos - pos + scroll }
/** are using the main, absolute coordinate system.
* ~SetCursorPos */
set(value) = with(currentWindowRead!!) {
dc.cursorPos put (pos - scroll + value)
dc.cursorMaxPos = glm.max(dc.cursorMaxPos, dc.cursorPos)
}
var cursorPosX: Float
/** cursor position is relative to window position
* (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc.
* ~GetCursorPosX */
get() = with(currentWindowRead!!) { dc.cursorPos.x - pos.x + scroll.x }
/** GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)
* ~SetCursorPosX */
set(value) = with(currentWindowRead!!) {
dc.cursorPos.x = pos.x - scroll.x + value
dc.cursorMaxPos.x = glm.max(dc.cursorMaxPos.x, dc.cursorPos.x)
}
var cursorPosY: Float
/** cursor position is relative to window position
* other functions such as GetCursorScreenPos or everything in ImDrawList::
* ~GetCursorPosY */
get() = with(currentWindowRead!!) { dc.cursorPos.y - pos.y + scroll.y }
/** ~SetCursorPosY */
set(value) = with(currentWindowRead!!) {
dc.cursorPos.y = pos.y - scroll.y + value
dc.cursorMaxPos.y = glm.max(dc.cursorMaxPos.y, dc.cursorPos.y)
}
/** initial cursor position in window coordinates
* ~GetCursorStartPos */
val cursorStartPos: Vec2
get() = with(currentWindowRead!!) { dc.cursorStartPos - pos }
/** cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) */
var cursorScreenPos: Vec2
/** ~GetCursorScreenPos */
get() = currentWindowRead!!.dc.cursorPos
/** ~SetCursorScreenPos */
set(value) = with(currentWindow.dc) {
cursorPos put value
cursorMaxPos maxAssign cursorPos
}
/** Vertically align/lower upcoming text to framePadding.y so that it will aligns to upcoming widgets
* (call if you have text on a line before regular widgets) */
fun alignTextToFramePadding() {
val window = currentWindow
if (window.skipItems) return
window.dc.currLineSize.y = glm.max(window.dc.currLineSize.y, g.fontSize + style.framePadding.y * 2)
window.dc.currLineTextBaseOffset = glm.max(window.dc.currLineTextBaseOffset, style.framePadding.y)
}
/** ~ FontSize
* ~GetTextLineHeight */
val textLineHeight: Float
get() = g.fontSize
/** ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
* ~GetTextLineHeightWithSpacing */
val textLineHeightWithSpacing: Float
get() = g.fontSize + style.itemSpacing.y
/** ~ FontSize + style.FramePadding.y * 2
* ~GetFrameHeight */
val frameHeight: Float
get() = g.fontSize + style.framePadding.y * 2f
/** distance (in pixels) between 2 consecutive lines of standard height widgets ==
* GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y
* ~GetFrameHeightWithSpacing */
val frameHeightWithSpacing: Float
get() = g.fontSize + style.framePadding.y * 2f + style.itemSpacing.y
} | mit | 78c638e80898ee519b6738cb583c4308 | 47.09058 | 240 | 0.663427 | 4.320313 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/eightQueen/EightQueen12.kt | 1 | 1809 | package katas.kotlin.eightQueen
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.Test
import java.lang.Math.abs
class EightQueen12 {
@Test fun `find positions of queens so that they don't attack each other`() {
assertThat(queenPositions(boardSize = 0), equalTo(setOf(emptySet())))
assertThat(queenPositions(boardSize = 1), equalTo(setOf(setOf(Queen(0, 0)))))
assertThat(queenPositions(boardSize = 2), equalTo(emptySet()))
assertThat(queenPositions(boardSize = 3), equalTo(emptySet()))
assertThat(queenPositions(boardSize = 4), equalTo(setOf(
setOf(Queen(3, 1), Queen(2, 3), Queen(1, 0), Queen(0, 2)),
setOf(Queen(3, 2), Queen(2, 0), Queen(1, 3), Queen(0, 1))
)))
assertThat(queenPositions(boardSize = 5).size, equalTo(10))
assertThat(queenPositions(boardSize = 8).size, equalTo(92))
}
private data class Queen(val column: Int, val row: Int) {
override fun toString() = "($column,$row)"
}
private fun queenPositions(boardSize: Int, column: Int = 0): Set<Set<Queen>> {
if (column == boardSize) return setOf(emptySet())
val rows = 0 until boardSize
val positions = queenPositions(boardSize, column + 1)
return positions.flatMap { queens ->
rows.mapNotNull { row ->
val newQueen = Queen(column, row)
if (isValidMove(newQueen, queens)) queens + newQueen else null
}
}.toSet()
}
private fun isValidMove(queen: Queen, queens: Set<Queen>): Boolean {
return queens.none { it.column == queen.column || it.row == queen.row } &&
queens.none { abs(it.column - queen.column) == abs(it.row - queen.row) }
}
} | unlicense | 6562ebd89b51a854132e17cd4543388f | 41.093023 | 87 | 0.62576 | 3.691837 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/git4idea/src/git4idea/config/MacExecutableProblemHandler.kt | 8 | 7242 | // 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 git4idea.config
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import git4idea.i18n.GitBundle
import org.jetbrains.annotations.NonNls
import java.io.File
class MacExecutableProblemHandler(val project: Project) : GitExecutableProblemHandler {
companion object {
val LOG = logger<MacExecutableProblemHandler>()
private const val XCODE_LICENSE_ERROR: @NonNls String = "Agreeing to the Xcode/iOS license"
private const val XCODE_DEVELOPER_PART_ERROR: @NonNls String = "invalid active developer path"
private const val XCODE_XCRUN: @NonNls String = "xcrun"
}
private val tempPath = FileUtil.createTempDirectory("git-install", null)
private val mountPoint = File(tempPath, "mount")
override fun showError(exception: Throwable, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) {
when {
isXcodeLicenseError(exception) -> showXCodeLicenseError(errorNotifier)
isInvalidActiveDeveloperPath(exception) -> showInvalidActiveDeveloperPathError(errorNotifier)
else -> showGenericError(exception, errorNotifier, onErrorResolved)
}
}
private fun showGenericError(exception: Throwable, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) {
errorNotifier.showError(GitBundle.message("executable.error.git.not.installed"),
getHumanReadableErrorFor(exception),
ErrorNotifier.FixOption.Standard(GitBundle.message("install.download.and.install.action")) {
this.downloadAndInstall(errorNotifier, onErrorResolved)
})
}
internal fun downloadAndInstall(errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) {
errorNotifier.executeTask(GitBundle.message("install.downloading.progress"), false) {
try {
val installer = fetchInstaller(errorNotifier) { it.os == "macOS" && it.pkgFileName != null }
if (installer != null) {
val fileName = installer.fileName
val dmgFile = File(tempPath, fileName)
val pkgFileName = installer.pkgFileName!!
if (downloadGit(installer, dmgFile, project, errorNotifier)) {
errorNotifier.changeProgressTitle(GitBundle.message("install.installing.progress"))
installGit(dmgFile, pkgFileName, errorNotifier, onErrorResolved)
}
}
}
finally {
FileUtil.delete(tempPath)
}
}
}
private fun installGit(dmgFile: File, pkgFileName: String, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) {
if (attachVolume(dmgFile, errorNotifier)) {
try {
if (installPackageOrShowError(pkgFileName, errorNotifier)) {
errorNotifier.showMessage(GitBundle.message("install.success.message"))
onErrorResolved()
errorNotifier.resetGitExecutable()
}
}
finally {
detachVolume()
}
}
}
private fun attachVolume(file: File, errorNotifier: ErrorNotifier): Boolean {
val cmd = GeneralCommandLine("hdiutil", "attach", "-readonly", "-noautoopen", "-noautofsck", "-nobrowse",
"-mountpoint", mountPoint.path, file.path)
return runOrShowError(cmd, errorNotifier, sudo = false)
}
private fun installPackageOrShowError(pkgFileName: String, errorNotifier: ErrorNotifier) =
runOrShowError(GeneralCommandLine("installer", "-package", "${mountPoint}/$pkgFileName", "-target", "/"),
errorNotifier, sudo = true)
private fun detachVolume() {
runCommand(GeneralCommandLine("hdiutil", "detach", mountPoint.path), sudo = false, onError = {})
}
private fun runOrShowError(commandLine: GeneralCommandLine, errorNotifier: ErrorNotifier, sudo: Boolean): Boolean {
return runCommand(commandLine, sudo) {
showCouldntInstallError(errorNotifier)
}
}
private fun runCommand(commandLine: GeneralCommandLine, sudo: Boolean, onError: () -> Unit): Boolean {
try {
val cmd = if (sudo) ExecUtil.sudoCommand(commandLine, GitBundle.message("title.sudo.command.install.git")) else commandLine
val output = ExecUtil.execAndGetOutput(cmd)
if (output.checkSuccess(LOG)) {
return true
}
LOG.warn(output.stderr)
onError()
return false
}
catch (e: Exception) {
LOG.warn(e)
onError()
return false
}
}
private fun showCouldntInstallError(errorNotifier: ErrorNotifier) {
errorNotifier.showError(GitBundle.message("install.general.error"), getLinkToConfigure(project))
}
private fun showCouldntStartInstallerError(errorNotifier: ErrorNotifier) {
errorNotifier.showError(GitBundle.message("install.mac.error.couldnt.start.command.line.tools"), getLinkToConfigure(project))
}
private fun showXCodeLicenseError(errorNotifier: ErrorNotifier) {
errorNotifier.showError(GitBundle.message("git.executable.validation.error.xcode.title"),
GitBundle.message("git.executable.validation.error.xcode.message"),
getLinkToConfigure(project))
}
private fun showInvalidActiveDeveloperPathError(errorNotifier: ErrorNotifier) {
val fixPathOption = ErrorNotifier.FixOption.Standard(GitBundle.message("executable.mac.fix.path.action")) {
errorNotifier.executeTask(GitBundle.message("install.mac.requesting.command.line.tools") + StringUtil.ELLIPSIS, false) {
execXCodeSelectInstall(errorNotifier)
}
}
errorNotifier.showError(GitBundle.message("executable.mac.error.invalid.path.to.command.line.tools"), fixPathOption)
}
/**
* Check if validation failed because the XCode license was not accepted yet
*/
private fun isXcodeLicenseError(exception: Throwable): Boolean =
isXcodeError(exception) { it.contains(XCODE_LICENSE_ERROR) }
/**
* Check if validation failed because the XCode command line tools were not found
*/
private fun isInvalidActiveDeveloperPath(exception: Throwable): Boolean =
isXcodeError(exception) { it.contains(XCODE_DEVELOPER_PART_ERROR) && it.contains(XCODE_XCRUN) }
private fun isXcodeError(exception: Throwable, messageIndicator: (String) -> Boolean): Boolean {
val message = if (exception is GitVersionIdentificationException) {
exception.cause?.message
}
else {
exception.message
}
return (message != null && messageIndicator(message))
}
private fun execXCodeSelectInstall(errorNotifier: ErrorNotifier) {
try {
val cmd = GeneralCommandLine("xcode-select", "--install")
val output = ExecUtil.execAndGetOutput(cmd)
errorNotifier.hideProgress()
if (!output.checkSuccess(LOG)) {
LOG.warn(output.stderr)
showCouldntStartInstallerError(errorNotifier)
}
else {
errorNotifier.resetGitExecutable()
}
}
catch (e: Exception) {
LOG.warn(e)
showCouldntStartInstallerError(errorNotifier)
}
}
}
| apache-2.0 | 386ddae41008350e92d0d05de70ea0f4 | 39.685393 | 158 | 0.711544 | 4.642308 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/sequentialparsers/impl/LinkParserUtil.kt | 2 | 5559 | package org.intellij.markdown.parser.sequentialparsers.impl
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil
import org.intellij.markdown.parser.sequentialparsers.TokensCache
import java.util.ArrayList
public class LinkParserUtil {
companion object {
fun parseLinkDestination(result: MutableCollection<SequentialParser.Node>, iterator: TokensCache.Iterator): TokensCache.Iterator? {
var it = iterator
if (it.type == MarkdownTokenTypes.EOL || it.type == MarkdownTokenTypes.RPAREN) {
return null
}
val startIndex = it.index
val withBraces = it.type == MarkdownTokenTypes.LT
if (withBraces) {
it = it.advance()
}
var hasOpenedParentheses = false
while (it.type != null) {
if (withBraces && it.type == MarkdownTokenTypes.GT) {
break
} else if (!withBraces) {
if (it.type == MarkdownTokenTypes.LPAREN) {
if (hasOpenedParentheses) {
break
}
hasOpenedParentheses = true
}
val next = it.rawLookup(1)
if (SequentialParserUtil.isWhitespace(it, 1) || next == null) {
break
} else if (next == MarkdownTokenTypes.RPAREN) {
if (!hasOpenedParentheses) {
break
}
hasOpenedParentheses = false
}
}
it = it.advance()
}
if (it.type != null && !hasOpenedParentheses) {
result.add(SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.LINK_DESTINATION))
return it
}
return null
}
fun parseLinkLabel(result: MutableCollection<SequentialParser.Node>, delegateIndices: MutableList<Int>, iterator: TokensCache.Iterator): TokensCache.Iterator? {
var it = iterator
if (it.type != MarkdownTokenTypes.LBRACKET) {
return null
}
val startIndex = it.index
val indicesToDelegate = ArrayList<Int>()
it = it.advance()
while (it.type != MarkdownTokenTypes.RBRACKET && it.type != null) {
indicesToDelegate.add(it.index)
if (it.type == MarkdownTokenTypes.LBRACKET) {
break
}
it = it.advance()
}
if (it.type == MarkdownTokenTypes.RBRACKET) {
val endIndex = it.index
if (endIndex == startIndex + 1) {
return null
}
result.add(SequentialParser.Node(startIndex..endIndex + 1, MarkdownElementTypes.LINK_LABEL))
delegateIndices.addAll(indicesToDelegate)
return it
}
return null
}
fun parseLinkText(result: MutableCollection<SequentialParser.Node>, delegateIndices: MutableList<Int>, iterator: TokensCache.Iterator): TokensCache.Iterator? {
var it = iterator
if (it.type != MarkdownTokenTypes.LBRACKET) {
return null
}
val startIndex = it.index
val indicesToDelegate = ArrayList<Int>()
var bracketDepth = 1
it = it.advance()
while (it.type != null) {
if (it.type == MarkdownTokenTypes.RBRACKET) {
if (--bracketDepth == 0) {
break
}
}
indicesToDelegate.add(it.index)
if (it.type == MarkdownTokenTypes.LBRACKET) {
bracketDepth++
}
it = it.advance()
}
if (it.type == MarkdownTokenTypes.RBRACKET) {
result.add(SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.LINK_TEXT))
delegateIndices.addAll(indicesToDelegate)
return it
}
return null
}
fun parseLinkTitle(result: MutableCollection<SequentialParser.Node>, iterator: TokensCache.Iterator): TokensCache.Iterator? {
var it = iterator
if (it.type == MarkdownTokenTypes.EOL) {
return null
}
val startIndex = it.index
val closingType: IElementType?
if (it.type == MarkdownTokenTypes.SINGLE_QUOTE || it.type == MarkdownTokenTypes.DOUBLE_QUOTE) {
closingType = it.type
} else if (it.type == MarkdownTokenTypes.LPAREN) {
closingType = MarkdownTokenTypes.RPAREN
} else {
return null
}
it = it.advance()
while (it.type != null && it.type != closingType) {
it = it.advance()
}
if (it.type != null) {
result.add(SequentialParser.Node(startIndex..it.index + 1, MarkdownElementTypes.LINK_TITLE))
return it
}
return null
}
}
}
| apache-2.0 | fa51a9a593a2d427f6b7e70e7abb7e02 | 34.864516 | 168 | 0.523835 | 5.586935 | false | false | false | false |
JiaweiWu/GiphyApp | app/src/main/java/com/jwu5/giphyapp/dataSingleton/SavedFavorites.kt | 1 | 952 | package com.jwu5.giphyapp.dataSingleton
import com.jwu5.giphyapp.network.model.GiphyModel
import java.util.LinkedHashMap
/**
* Created by Jiawei on 8/29/2017.
*/
class SavedFavorites {
var favorites: LinkedHashMap<String, GiphyModel>? = null
init {
favorites = LinkedHashMap<String, GiphyModel>()
}
fun addFavorite(item: GiphyModel) {
favorites!!.put(item.id!!, item)
}
fun removeFavorites(item: GiphyModel) {
favorites!!.remove(item.id)
}
fun isItInFavorites(item: GiphyModel): Boolean {
return favorites!!.containsKey(item.id)
}
companion object {
private val FILENAME = "file.sav"
private var mInstance: SavedFavorites? = null
val instance: SavedFavorites
get() {
if (mInstance == null) {
mInstance = SavedFavorites()
}
return mInstance!!
}
}
}
| mit | ec58c0a51a470f3c41c808421f7a22e2 | 21.666667 | 60 | 0.595588 | 4.347032 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/settings/buildsystem/Repository.kt | 4 | 2094 | // 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.tools.projectWizard.settings.buildsystem
interface Repository {
val url: String
val idForMaven: String
}
data class DefaultRepository(val type: Type) : Repository {
override val url: String
get() = type.url
override val idForMaven: String
get() = type.gradleName
enum class Type(val gradleName: String, val url: String) {
JCENTER("jcenter", "https://jcenter.bintray.com/"),
MAVEN_CENTRAL("mavenCentral", "https://repo1.maven.org/maven2/"),
GOOGLE("google", "https://dl.google.com/dl/android/maven2/"),
GRADLE_PLUGIN_PORTAL("gradlePluginPortal", "https://plugins.gradle.org/m2/")
}
companion object {
val JCENTER = DefaultRepository(Type.JCENTER)
val MAVEN_CENTRAL = DefaultRepository(Type.MAVEN_CENTRAL)
val GOOGLE = DefaultRepository(Type.GOOGLE)
val GRADLE_PLUGIN_PORTAL = DefaultRepository(Type.GRADLE_PLUGIN_PORTAL)
}
}
interface CustomMavenRepository : Repository
data class CustomMavenRepositoryImpl(val repository: String, val base: String) : CustomMavenRepository {
override val url: String = "$base/$repository"
override val idForMaven: String
get() = "bintray." + repository.replace('/', '.')
}
data class JetBrainsSpace(val repository: String) : CustomMavenRepository {
override val url: String = "https://maven.pkg.jetbrains.space/$repository"
override val idForMaven: String
get() = "jetbrains." + repository.replace('/', '.')
}
object Repositories {
val KTOR = DefaultRepository.MAVEN_CENTRAL
val KOTLINX_HTML = JetBrainsSpace("public/p/kotlinx-html/maven")
val KOTLIN_JS_WRAPPERS = DefaultRepository.MAVEN_CENTRAL
val KOTLIN_EAP_MAVEN_CENTRAL = DefaultRepository.MAVEN_CENTRAL
val JETBRAINS_COMPOSE_DEV = JetBrainsSpace("public/p/compose/dev")
val JETBRAINS_KOTLIN_DEV = JetBrainsSpace("kotlin/p/kotlin/dev")
}
| apache-2.0 | 0cbd2a6cd8f56b0509eb122adbba5b65 | 37.072727 | 158 | 0.708691 | 4.07393 | false | false | false | false |
DreierF/MyTargets | app/src/androidTest/java/de/dreier/mytargets/features/training/standardround/EditStandardRoundActivityTest.kt | 1 | 4872 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.features.training.standardround
import android.content.Intent
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItem
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.recyclerview.widget.RecyclerView
import de.dreier.mytargets.R
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.features.training.edit.EditTrainingActivity
import de.dreier.mytargets.features.training.edit.EditTrainingFragment.Companion.CREATE_TRAINING_WITH_STANDARD_ROUND_ACTION
import de.dreier.mytargets.shared.models.Dimension
import de.dreier.mytargets.shared.models.Dimension.Unit.CENTIMETER
import de.dreier.mytargets.shared.models.Dimension.Unit.METER
import de.dreier.mytargets.shared.models.Target
import de.dreier.mytargets.shared.targets.models.WAFull
import de.dreier.mytargets.test.base.UITestBase
import de.dreier.mytargets.test.utils.matchers.ParentViewMatcher.isNestedChildOfView
import de.dreier.mytargets.test.utils.matchers.RecyclerViewMatcher.Companion.withRecyclerView
import org.hamcrest.Matchers.*
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@Ignore
@RunWith(AndroidJUnit4::class)
class EditStandardRoundActivityTest : UITestBase() {
@get:Rule
var activityTestRule = IntentsTestRule(
EditTrainingActivity::class.java, true, false)
@Before
fun setUp() {
SettingsManager.target = Target(WAFull.ID, 0, Dimension(122f, CENTIMETER))
SettingsManager.distance = Dimension(50f, METER)
SettingsManager.timerEnabled = false
SettingsManager.shotsPerEnd = 3
SettingsManager.endCount = 10
SettingsManager.distance = Dimension(10f, METER)
}
@Test
fun editStandardRoundActivity() {
val intent = Intent()
intent.action = CREATE_TRAINING_WITH_STANDARD_ROUND_ACTION
activityTestRule.launchActivity(intent)
//allowPermissionsIfNeeded(activityTestRule.getActivity(), ACCESS_FINE_LOCATION);
onView(withId(R.id.standardRound)).perform(scrollTo(), click())
onView(withId(R.id.fab)).perform(click())
onView(withId(R.id.distance)).perform(nestedScrollTo(), click())
onView(allOf(withId(R.id.recyclerView), isDisplayed()))
.perform(actionOnItem<RecyclerView.ViewHolder>(hasDescendant(withText("20m")), click()))
onView(withId(R.id.target)).perform(nestedScrollTo(), click())
onView(withId(R.id.recyclerView))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(9, click()))
navigateUp()
onView(withId(R.id.addButton)).perform(nestedScrollTo(), click())
onView(withRecyclerView(R.id.rounds).atPositionOnView(1, R.id.distance))
.perform(nestedScrollTo(), click())
onView(allOf(withId(R.id.recyclerView), isDisplayed()))
.perform(actionOnItem<RecyclerView.ViewHolder>(hasDescendant(withText("15m")), click()))
onView(allOf(withId(R.id.number_increment), isNestedChildOfView(withId(R.id.shotCount)),
isNestedChildOfView(withRecyclerView(R.id.rounds).atPosition(1))))
.perform(nestedScrollTo(), click(), click(), click())
onView(allOf(withId(R.id.number_decrement), isNestedChildOfView(withId(R.id.endCount)),
isNestedChildOfView(withRecyclerView(R.id.rounds).atPosition(1))))
.perform(nestedScrollTo(), click(), click(), click(), click(), click())
save()
onView(withId(R.id.standardRound))
.check(matches(hasDescendant(withText(R.string.custom_round))))
onView(withId(R.id.standardRound))
.check(matches(hasDescendant(withText(
allOf(startsWith("20m: 10 × 3"), containsString("15m: 5 × 6"))))))
activityTestRule.activity.finish()
}
}
| gpl-2.0 | 56b2abcdc9b4b89b51ad7083e6ebe5c0 | 40.271186 | 123 | 0.734086 | 4.391344 | false | true | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/util/BucketList.kt | 1 | 6151 | package jp.juggler.subwaytooter.util
import java.util.AbstractList
import java.util.ArrayList
import java.util.NoSuchElementException
import java.util.RandomAccess
class BucketList<E> constructor(
val bucketCapacity: Int = 1024
) : AbstractList<E>(), MutableIterable<E>, RandomAccess {
companion object {
private val pos_internal = object : ThreadLocal<BucketPos>() {
override fun initialValue(): BucketPos {
return BucketPos()
}
}
}
override var size: Int = 0
override fun isEmpty(): Boolean {
return 0 == size
}
private class Bucket<E>(
capacity: Int,
var totalStart: Int = 0,
var totalEnd: Int = 0
) : ArrayList<E>(capacity)
private val groups = ArrayList<Bucket<E>>()
override fun clear() {
groups.clear()
size = 0
}
private fun updateIndex() {
var n = 0
for (bucket in groups) {
bucket.totalStart = n
n += bucket.size
bucket.totalEnd = n
}
size = n
}
internal class BucketPos(
var groupIndex: Int = 0,
var bucketIndex: Int = 0
) {
internal fun set(groupIndex: Int, bucketIndex: Int): BucketPos {
this.groupIndex = groupIndex
this.bucketIndex = bucketIndex
return this
}
}
// allocated を指定しない場合は BucketPosを生成します
private fun findPos(
totalIndex: Int,
result: BucketPos = pos_internal.get()!!
): BucketPos {
if (totalIndex < 0 || totalIndex >= size) {
throw IndexOutOfBoundsException("findPos: bad index=$totalIndex, size=$size")
}
// binary search
var gs = 0
var ge = groups.size
while (true) {
val gi = (gs + ge) shr 1
val group = groups[gi]
when {
totalIndex < group.totalStart -> ge = gi
totalIndex >= group.totalEnd -> gs = gi + 1
else -> {
return result.set(gi, totalIndex - group.totalStart)
}
}
}
}
override fun get(index: Int): E {
val pos = findPos(index)
return groups[pos.groupIndex][pos.bucketIndex]
}
override fun set(index: Int, element: E): E {
val pos = findPos(index)
return groups[pos.groupIndex].set(pos.bucketIndex, element)
}
// 末尾への追加
override fun addAll(elements: Collection<E>): Boolean {
val cSize = elements.size
if (cSize == 0) return false
// 最後のバケツに収まるなら、最後のバケツの中に追加する
if (groups.isNotEmpty()) {
val bucket = groups[groups.size - 1]
if (bucket.size + cSize <= bucketCapacity) {
bucket.addAll(elements)
bucket.totalEnd += cSize
size += cSize
return true
}
}
// 新しいバケツを作って、そこに追加する
val bucket = Bucket<E>(bucketCapacity)
bucket.addAll(elements)
bucket.totalStart = size
bucket.totalEnd = size + cSize
size += cSize
groups.add(bucket)
return true
}
// 位置を指定して挿入
override fun addAll(index: Int, elements: Collection<E>): Boolean {
// indexが終端なら、終端に追加する
// バケツがカラの場合もここ
if (index >= size) {
return addAll(elements)
}
val cSize = elements.size
if (cSize == 0) return false
val pos = findPos(index)
var bucket = groups[pos.groupIndex]
// 挿入位置がバケツの先頭ではないか、バケツのサイズに問題がないなら
if (pos.bucketIndex > 0 || bucket.size + cSize <= bucketCapacity) {
// バケツの中に挿入する
bucket.addAll(pos.bucketIndex, elements)
} else {
// 新しいバケツを作って、そこに追加する
bucket = Bucket(bucketCapacity)
bucket.addAll(elements)
groups.add(pos.groupIndex, bucket)
}
updateIndex()
return true
}
override fun removeAt(index: Int): E {
val pos = findPos(index)
val bucket = groups[pos.groupIndex]
val data = bucket.removeAt(pos.bucketIndex)
if (bucket.isEmpty()) {
groups.removeAt(pos.groupIndex)
}
updateIndex()
return data
}
inner class MyIterator internal constructor() : MutableIterator<E> {
private val pos: BucketPos // indicates next read point
init {
pos = BucketPos(0, 0)
}
override fun hasNext(): Boolean {
while (true) {
if (pos.groupIndex >= groups.size) {
return false
}
val bucket = groups[pos.groupIndex]
if (pos.bucketIndex >= bucket.size) {
pos.bucketIndex = 0
++pos.groupIndex
continue
}
return true
}
}
override fun next(): E {
while (true) {
if (pos.groupIndex >= groups.size) {
throw NoSuchElementException()
}
val bucket = groups[pos.groupIndex]
if (pos.bucketIndex >= bucket.size) {
pos.bucketIndex = 0
++pos.groupIndex
continue
}
return bucket[pos.bucketIndex++]
}
}
override fun remove() {
throw NotImplementedError()
}
}
override fun iterator(): MutableIterator<E> {
return MyIterator()
}
}
| apache-2.0 | 6a5f025d5a8d516d90f5234260a61494 | 26.043269 | 89 | 0.501286 | 4.469732 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/notification/PollingWorker2.kt | 1 | 5700 | package jp.juggler.subwaytooter.notification
import android.app.ActivityManager
import android.content.Context
import androidx.work.*
import jp.juggler.subwaytooter.App1
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.pref.PrefDevice
import jp.juggler.subwaytooter.pref.PrefS
import jp.juggler.util.LogCategory
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.coroutineScope
import java.util.concurrent.TimeUnit
import kotlin.math.max
/*
- WorkManagerのWorker。
- アカウント別にuniqueWorkNameを持つ。
- アプリが背面にいる間は進捗表示を通知で行う。
*/
class PollingWorker2(
context: Context,
workerParameters: WorkerParameters,
) : CoroutineWorker(context, workerParameters) {
companion object {
private val log = LogCategory("PollingWorker")
private const val KEY_ACCOUNT_DB_ID = "accountDbId"
private const val NOTIFICATION_ID_POLLING_WORKER = 2
private const val WORK_NAME = "PollingWorker2"
suspend fun cancelPolling(context: Context) {
val isOk = WorkManager.getInstance(context)
.cancelUniqueWork(WORK_NAME).await()
log.i("cancelPolling isOk=$isOk")
}
suspend fun enqueuePolling(
context: Context,
) {
val workManager = WorkManager.getInstance(context)
val prefDevice = PrefDevice.from(context)
val newInterval = max(
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
(PrefS.spPullNotificationCheckInterval().toLongOrNull() ?: 0L) * 60000L,
)
// すでに同じインターバルのが存在するなら何もしない
if (workManager.getWorkInfosForUniqueWork(WORK_NAME).await().any {
val oldInterval =
prefDevice.getLong(PrefDevice.KEY_POLLING_WORKER2_INTERVAL, 0L)
oldInterval == newInterval && !it.state.isFinished
}) {
return
}
// 登録し直す
val data = Data.Builder().build()
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
val workRequest = PeriodicWorkRequestBuilder<PollingWorker2>(
newInterval,
TimeUnit.MILLISECONDS,
// flexTimeInterval
// 決まった周期の間の末尾からflexTimeIntervalを引いた時刻の間の何処かで処理が実行される
// (周期より短い範囲で)大きい値の方が「より早いタイミングで」実行されてテストに良い
// (また、setInitialDelayはその何処かの範囲にないと効果がない)
newInterval - 1000L,
TimeUnit.MILLISECONDS,
)
.setInitialDelay(1000L, TimeUnit.MILLISECONDS)
.setConstraints(constraints)
.setInputData(data)
.build()
workManager.enqueueUniquePeriodicWork(
WORK_NAME,
ExistingPeriodicWorkPolicy.REPLACE,
workRequest
).await()
prefDevice.edit().putLong(PrefDevice.KEY_POLLING_WORKER2_INTERVAL, newInterval).apply()
}
}
private fun isAppForehround(): Boolean {
val processInfo = ActivityManager.RunningAppProcessInfo()
ActivityManager.getMyMemoryState(processInfo)
return processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
private suspend fun showMessage(text: String) =
CheckerNotification.showMessage(applicationContext, text) {
try {
if(!isAppForehround()) error("app is not foreground.")
setForegroundAsync(ForegroundInfo(NOTIFICATION_ID_POLLING_WORKER,it))
.await()
} catch (ex: Throwable) {
log.e(ex, "showMessage failed.")
}
}
private fun stateMapToString(map: Map<PollingState, List<String>>) =
StringBuilder().apply {
for (state in PollingState.valuesCache) {
val list = map[state] ?: continue
if (isNotEmpty()) append(" |")
append(state.desc)
append(": ")
if (list.size <= 2) {
append(list.sorted().joinToString(", "))
} else {
append("${list.size}")
}
}
}.toString()
private suspend fun workImpl() {
val context = applicationContext
coroutineScope {
if (importProtector.get()) {
log.w("abort by importProtector.")
return@coroutineScope
}
App1.prepare(context, "doWork")
showMessage(context.getString(R.string.loading_notification_title))
checkNoticifationAll(context, "") { map ->
showMessage(stateMapToString(map))
}
}
}
override suspend fun doWork(): Result {
try {
workImpl()
} catch (ex: Throwable) {
if (ex is CancellationException) {
log.e("doWork cancelled.")
} else {
log.trace(ex, "doWork failed.")
}
}
return Result.success()
}
}
| apache-2.0 | 7c6b52bff7216516592bfb7b6c5d4bcb | 32.512821 | 100 | 0.565936 | 4.735268 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/mfm/NodeParserMap.kt | 1 | 18950 | package jp.juggler.subwaytooter.mfm
import android.util.SparseArray
import android.util.SparseBooleanArray
import jp.juggler.subwaytooter.api.entity.TootAccount
import jp.juggler.util.LogCategory
import jp.juggler.util.asciiPattern
import jp.juggler.util.ellipsizeDot3
import jp.juggler.util.groupEx
import java.util.*
import java.util.regex.Pattern
private val log = LogCategory("NodeParserMap")
// ブロック要素は始端と終端の空行を除去したい
val reStartEmptyLines = """\A(?:[ ]*?[\x0d\x0a]+)+""".toRegex()
val reEndEmptyLines = """[\s\x0d\x0a]+\z""".toRegex()
fun trimBlock(s: String) =
s.replace(reStartEmptyLines, "")
.replace(reEndEmptyLines, "")
// ノードのパースを行う関数をキャプチャパラメータつきで生成する
fun simpleParser(
pattern: Pattern,
type: NodeType,
): NodeParseEnv.() -> NodeDetected? = {
val matcher = remainMatcher(pattern)
when {
!matcher.find() -> null
else -> {
val textInside = matcher.groupEx(1)!!
makeDetected(
type,
arrayOf(textInside),
matcher.start(), matcher.end(),
this.text, matcher.start(1), textInside.length
)
}
}
}
private val brackets = arrayOf(
"()",
"()",
"[]",
"{}",
"“”",
"‘’",
"‹›",
"«»",
"()",
"[]",
"{}",
"⦅⦆",
"⦅⦆",
"〚〛",
"⦃⦄",
"「」",
"〈〉",
"《》",
"【】",
"〔〕",
"⦗⦘",
"『』",
"〖〗",
"〘〙",
"[]",
"「」",
"⟦⟧",
"⟨⟩",
"⟪⟫",
"⟮⟯",
"⟬⟭",
"⌈⌉",
"⌊⌋",
"⦇⦈",
"⦉⦊",
"❛❜",
"❝❞",
"❨❩",
"❪❫",
"❴❵",
"❬❭",
"❮❯",
"❰❱",
"❲❳",
"()",
"﴾﴿",
"〈〉",
"⦑⦒",
"⧼⧽",
"﹙﹚",
"﹛﹜",
"﹝﹞",
"⁽⁾",
"₍₎",
"⦋⦌",
"⦍⦎",
"⦏⦐",
"⁅⁆",
"⸢⸣",
"⸤⸥",
"⟅⟆",
"⦓⦔",
"⦕⦖",
"⸦⸧",
"⸨⸩",
"⧘⧙",
"⧚⧛",
"⸜⸝",
"⸌⸍",
"⸂⸃",
"⸄⸅",
"⸉⸊",
"᚛᚜",
"༺༻",
"༼༽",
"⏜⏝",
"⎴⎵",
"⏞⏟",
"⏠⏡",
"﹁﹂",
"﹃﹄",
"︹︺",
"︻︼",
"︗︘",
"︿﹀",
"︽︾",
"﹇﹈",
"︷︸"
)
val bracketsMap = HashMap<Char, Int>().apply {
brackets.forEach {
put(it[0], 1)
put(it[1], -1)
}
}
val bracketsMapUrlSafe = HashMap<Char, Int>().apply {
brackets.forEach {
if ("([".contains(it[0])) return@forEach
put(it[0], 1)
put(it[1], -1)
}
}
// 末尾の余計な」や(を取り除く。
// 例えば「#タグ」 とか (#タグ)
fun String.removeOrphanedBrackets(urlSafe: Boolean = false): String {
var last = 0
val nests = when (urlSafe) {
true -> this.map {
last += bracketsMapUrlSafe[it] ?: 0
last
}
else -> this.map {
last += bracketsMap[it] ?: 0
last
}
}
// first position of unmatched close
var pos = nests.indexOfFirst { it < 0 }
if (pos != -1) return substring(0, pos)
// last position of unmatched open
pos = nests.indexOfLast { it == 0 }
return substring(0, pos + 1)
}
// [title] 【title】
// 直後に改行が必要だったが文末でも良いことになった https://github.com/syuilo/misskey/commit/79ffbf95db9d0cc019d06ab93b1bfa6ba0d4f9ae
// val titleParser = simpleParser(
// """\A[【\[](.+?)[】\]](\n|\z)""".asciiPattern()
// , NodeType.TITLE
// )
private val reTitle = """\A[【\[](.+?)[】\]](\n|\z)""".asciiPattern()
private val reFunction = """\A\$?\[([^\s\n\[\]]+) \s*([^\n\[\]]+)\]""".asciiPattern()
private fun NodeParseEnv.titleParserImpl(): NodeDetected? {
if (useFunction) {
val type = NodeType.FUNCTION
val matcher = remainMatcher(reFunction)
if (matcher.find()) {
val name = matcher.groupEx(1)?.ellipsizeDot3(3) ?: "???"
val textInside = matcher.groupEx(2)!!
return makeDetected(
type,
arrayOf(name),
matcher.start(), matcher.end(),
this.text, matcher.start(2), textInside.length
)
}
}
val type = NodeType.TITLE
val matcher = remainMatcher(reTitle)
if (matcher.find()) {
val textInside = matcher.groupEx(1)!!
return makeDetected(
type,
arrayOf(textInside),
matcher.start(), matcher.end(),
this.text, matcher.start(1), textInside.length
)
}
return null
}
@Suppress("SpellCheckingInspection")
private val latexEscape = listOf(
"\\#" to "#",
"\\$" to "$",
"\\%" to "%",
"\\&" to "&",
"\\_" to "_",
"\\{" to "{",
"\\}" to "}",
"\\;" to "",
"\\!" to "",
"\\textbackslash" to "\\",
"\\backslash" to "\\",
"\\textasciitilde" to "~",
"\\textasciicircum" to "^",
"\\textbar" to "|",
"\\textless" to "<",
"\\textgreater" to ">",
).sortedByDescending { it.first.length }
private fun partialEquals(src: String, start: Int, needle: String): Boolean {
for (i in needle.indices) {
if (src.elementAtOrNull(start + i) != needle[i]) return false
}
return true
}
private fun String.unescapeLatex(): String {
val sb = StringBuilder(length)
val end = length
var i = 0
while (i < end) {
val c = this[i]
if (c == '\\') {
val pair = latexEscape.find { partialEquals(this, i, it.first) }
if (pair != null) {
sb.append(pair.second)
i += pair.first.length
continue
}
}
sb.append(c)
++i
}
return sb.toString()
}
// \} \]はムダなエスケープに見えるが、androidでは必要なので削ってはいけない
@Suppress("RegExpRedundantEscape")
private val reLatexRemove =
"""\\(?:quad|Huge|atop|sf|scriptsize|bf|small|tiny|underline|large|(?:color)\{[^}]*\})""".toRegex()
@Suppress("RegExpRedundantEscape")
private val reLatex1 =
"""\\(?:(?:url)|(?:textcolor|colorbox)\{[^}]*\}|(?:fcolorbox|raisebox)\{[^}]*\}\{[^}]*\}|includegraphics\[[^]]*\])\{([^}]*)\}""".toRegex()
@Suppress("RegExpRedundantEscape")
private val reLatex2reversed = """\\(?:overset|href)\{([^}]+)\}\{([^}]+)\}""".toRegex()
private fun String.removeLatex(): String {
return this
.replace(reLatexRemove, "")
.replace(reLatex1, "$1")
.replace(reLatex2reversed, "$2 $1")
.unescapeLatex()
}
private val reLatexBlock =
"""^\\\[(.+?)\\\]""".asciiPattern(Pattern.MULTILINE or Pattern.DOTALL)
private val reLatexInline = """\A\\\((.+?)\\\)""".asciiPattern()
private fun NodeParseEnv.latexParserImpl(): NodeDetected? {
val type = NodeType.LATEX
var matcher = remainMatcher(reLatexBlock)
if (matcher.find()) {
val textInside = matcher.groupEx(1)!!.removeLatex().trim()
return makeDetected(
type,
arrayOf(textInside),
matcher.start(), matcher.end(),
textInside, 0, textInside.length
)
}
matcher = remainMatcher(reLatexInline)
if (matcher.find()) {
val textInside = matcher.groupEx(1)!!.removeLatex()
return makeDetected(
type,
arrayOf(textInside),
matcher.start(), matcher.end(),
textInside, 0, textInside.length
)
}
return null
}
// (マークダウン要素の特徴的な文字)と(パーサ関数の配列)のマップ
val nodeParserMap = SparseArray<Array<out NodeParseEnv.() -> NodeDetected?>>().apply {
fun addParser(
firstChars: String,
vararg nodeParsers: NodeParseEnv.() -> NodeDetected?,
) {
for (s in firstChars) {
put(s.code, nodeParsers)
}
}
// Strike ~~...~~
addParser(
"~", simpleParser(
"""\A~~(.+?)~~""".asciiPattern(), NodeType.STRIKE
)
)
// Quote "..."
addParser(
"\"", simpleParser(
"""\A"([^\x0d\x0a]+?)\n"[\x0d\x0a]*""".asciiPattern(), NodeType.QUOTE_INLINE
)
)
// Quote (行頭)>...(改行)
// この正規表現の場合は \A ではなく ^ で各行の始端にマッチさせる
val reQuoteBlock = """^>(?:[ ]?)([^\x0d\x0a]*)(\x0a|\x0d\x0a?)?"""
.asciiPattern(Pattern.MULTILINE)
addParser(">", {
if (pos > 0) {
val c = text[pos - 1]
if (c != '\r' && c != '\n') {
//直前が改行文字ではない
if (MisskeyMarkdownDecoder.DEBUG) log.d("QUOTE: previous char is not line end. $c pos=$pos text=$text")
return@addParser null
}
}
var p = pos
val content = StringBuilder()
val matcher = remainMatcher(reQuoteBlock)
while (true) {
if (!matcher.find(p)) break
p = matcher.end()
if (content.isNotEmpty()) content.append('\n')
content.append(matcher.groupEx(1))
// 改行の直後なので次回マッチの ^ は大丈夫なはず…
}
if (content.isNotEmpty()) content.append('\n')
if (p <= pos) {
// > のあとに全く何もない
if (MisskeyMarkdownDecoder.DEBUG) log.d("QUOTE: not a quote")
return@addParser null
}
val textInside = content.toString()
makeDetected(
NodeType.QUOTE_BLOCK,
emptyArray(),
pos, p,
textInside, 0, textInside.length
)
})
// 絵文字 :emoji:
addParser(
":",
simpleParser(
"""\A:([a-zA-Z0-9+-_@]+):""".asciiPattern(), NodeType.EMOJI
)
)
// モーション
addParser(
"(", simpleParser(
"""\A\Q(((\E(.+?)\Q)))\E""".asciiPattern(Pattern.DOTALL), NodeType.MOTION
)
)
val reHtmlTag = """\A<([a-z]+)>(.+?)</\1>""".asciiPattern(Pattern.DOTALL)
addParser("<", {
val matcher = remainMatcher(reHtmlTag)
when {
!matcher.find() -> null
else -> {
val tagName = matcher.groupEx(1)!!
val textInside = matcher.groupEx(2)!!
fun a(type: NodeType) = makeDetected(
type,
arrayOf(textInside),
matcher.start(), matcher.end(),
this.text, matcher.start(2), textInside.length
)
when (tagName) {
"motion" -> a(NodeType.MOTION)
"center" -> a(NodeType.CENTER)
"small" -> a(NodeType.SMALL)
"i" -> a(NodeType.ITALIC)
else -> null
}
}
}
})
// ***big*** **bold**
addParser(
"*",
// 処理順序に意味があるので入れ替えないこと
// 記号列が長い順にパースを試す
simpleParser(
"""^\Q***\E(.+?)\Q***\E""".asciiPattern(),
NodeType.BIG
),
simpleParser(
"""^\Q**\E(.+?)\Q**\E""".asciiPattern(),
NodeType.BOLD
),
)
val reAlnum = """[A-Za-z0-9]""".asciiPattern()
// http(s)://....
val reUrl = """\A(https?://[\w/:%#@${'$'}&?!()\[\]~.=+\-]+)"""
.asciiPattern()
addParser("h", {
// 直前の文字が英数字ならURLの開始とはみなさない
if (pos > 0 && MatcherCache.matcher(reAlnum, text, pos - 1, pos).find()) {
return@addParser null
}
val matcher = remainMatcher(reUrl)
if (!matcher.find()) {
return@addParser null
}
val url = matcher.groupEx(1)!!.removeOrphanedBrackets(urlSafe = true)
makeDetected(
NodeType.URL,
arrayOf(url),
matcher.start(), matcher.start() + url.length,
"", 0, 0
)
})
// 検索
val reSearchButton = """\A(検索|\[検索]|Search|\[Search])(\n|\z)"""
.asciiPattern(Pattern.CASE_INSENSITIVE)
fun NodeParseEnv.parseSearchPrev(): String? {
val prev = text.substring(lastEnd, pos)
val delm = prev.lastIndexOf('\n')
val end = prev.length
return when {
end <= 1 -> null // キーワードを含まないくらい短い
delm + 1 >= end - 1 -> null // 改行より後の部分が短すぎる
!" ".contains(prev.last()) -> null // 末尾が空白ではない
else -> prev.substring(delm + 1, end - 1) // キーワード部分を返す
}
}
val searchParser: NodeParseEnv.() -> NodeDetected? = {
val matcher = remainMatcher(reSearchButton)
when {
!matcher.find() -> null
else -> {
val keyword = parseSearchPrev()
when {
keyword?.isEmpty() != false -> null
else -> makeDetected(
NodeType.SEARCH,
arrayOf(keyword),
pos - (keyword.length + 1), matcher.end(),
this.text, pos - (keyword.length + 1), keyword.length
)
}
}
}
}
val titleParser: NodeParseEnv.() -> NodeDetected? = { titleParserImpl() }
// Link
val reLink = """\A\??\[([^\n\[\]]+?)]\((https?://[\w/:%#@${'$'}&?!()\[\]~.=+\-]+?)\)"""
.asciiPattern()
val linkParser: NodeParseEnv.() -> NodeDetected? = {
val matcher = remainMatcher(reLink)
when {
!matcher.find() -> null
else -> {
val title = matcher.groupEx(1)!!
makeDetected(
NodeType.LINK,
arrayOf(
title,
matcher.groupEx(2)!!, // url
text[pos].toString() // silent なら "?" になる
),
matcher.start(), matcher.end(),
this.text, matcher.start(1), title.length
)
}
}
}
// [ はいろんな要素で使われる
// searchの判定をtitleより前に行うこと。 「abc [検索] 」でtitleが優先されるとマズい
// v10でもv12でもlinkの優先度はtitleやfunctionより高い
addParser("[", searchParser, linkParser, titleParser)
addParser("$", titleParser)
// その他の文字でも判定する
addParser("【", titleParser)
addParser("検Ss", searchParser)
addParser("?", linkParser)
// \(…\) \{…\}
addParser("\\", { latexParserImpl() })
// メールアドレスの@の手前に使える文字なら真
val mailChars = SparseBooleanArray().apply {
for (it in '0'..'9') {
put(it.code, true)
}
for (it in 'A'..'Z') {
put(it.code, true)
}
for (it in 'a'..'z') {
put(it.code, true)
}
"""${'$'}!#%&'`"*+-/=?^_{|}~""".forEach { put(it.code, true) }
}
addParser("@", {
val matcher = remainMatcher(TootAccount.reMisskeyMentionMFM)
when {
!matcher.find() -> null
else -> when {
// 直前の文字がメールアドレスの@の手前に使える文字ならメンションではない
pos > 0 && mailChars.get(text.codePointBefore(pos)) -> null
else -> {
// log.d(
// "mention detected: ${matcher.group(1)},${matcher.group(2)},${
// matcher.group(
// 0
// )
// }"
// )
makeDetected(
NodeType.MENTION,
arrayOf(
matcher.groupEx(1)!!,
matcher.groupEx(2) ?: "" // username, host
),
matcher.start(), matcher.end(),
"", 0, 0
)
}
}
}
})
// Hashtag
val reHashtag = """\A#([^\s.,!?#:]+)""".asciiPattern()
val reDigitsOnly = """\A\d*\z""".asciiPattern()
addParser("#", {
if (pos > 0 && MatcherCache.matcher(reAlnum, text, pos - 1, pos).find()) {
// 直前に英数字があるならタグにしない
return@addParser null
}
val matcher = remainMatcher(reHashtag)
if (!matcher.find()) {
// タグにマッチしない
return@addParser null
}
// 先頭の#を含まないタグテキスト
val tag = matcher.groupEx(1)!!.removeOrphanedBrackets()
if (tag.isEmpty() || tag.length > 50 || reDigitsOnly.matcher(tag).find()) {
// 空文字列、50文字超過、数字だけのタグは不許可
return@addParser null
}
makeDetected(
NodeType.HASHTAG,
arrayOf(tag),
matcher.start(), matcher.start() + 1 + tag.length,
"", 0, 0
)
})
// code (ブロック、インライン)
addParser(
"`", simpleParser(
"""\A```(?:.*)\n([\s\S]+?)\n```(?:\n|$)""".asciiPattern(), NodeType.CODE_BLOCK
/*
(A)
```code``` は 閉じる部分の前後に改行がないのでダメ
(B)
```lang
code
code
code
```
はlang部分は表示されない
(C)
STの表示上の都合で閉じる部分の後の改行が複数あっても全て除去する
*/
), simpleParser(
// インラインコードは内部にとある文字を含むと認識されない。理由は顔文字と衝突するからだとか
"""\A`([^`´\x0d\x0a]+)`""".asciiPattern(), NodeType.CODE_INLINE
)
)
}
| apache-2.0 | f5c3678fc59cb58a03d7674524a1e083 | 24.981279 | 142 | 0.447759 | 3.435638 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/s3/src/main/kotlin/com/kotlin/s3/CreateBucket.kt | 1 | 1616 | // snippet-sourcedescription:[CreateBucket.kt demonstrates how to create an Amazon Simple Storage Service (Amazon S3) bucket.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon S3]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.s3
// snippet-start:[s3.kotlin.create_bucket.import]
import aws.sdk.kotlin.services.s3.S3Client
import aws.sdk.kotlin.services.s3.model.CreateBucketRequest
import kotlin.system.exitProcess
// snippet-end:[s3.kotlin.create_bucket.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<bucketName>
Where:
bucketName - The name of the Amazon S3 bucket to create. The Amazon S3 bucket name must be unique, or an error occurs.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val bucketName = args[0]
createNewBucket(bucketName)
}
// snippet-start:[s3.kotlin.create_bucket.main]
suspend fun createNewBucket(bucketName: String) {
val request = CreateBucketRequest {
bucket = bucketName
}
S3Client { region = "us-east-1" }.use { s3 ->
s3.createBucket(request)
println("$bucketName is ready")
}
}
// snippet-end:[s3.kotlin.create_bucket.main]
| apache-2.0 | 40be6dc480fbcba0b8145a333e11c0a2 | 27.381818 | 126 | 0.681312 | 3.697941 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/web/bean/data/schoolroom/SchoolroomBean.kt | 1 | 345 | package top.zbeboy.isy.web.bean.data.schoolroom
import top.zbeboy.isy.domain.tables.pojos.Schoolroom
/**
* Created by zbeboy 2017-12-08 .
**/
class SchoolroomBean: Schoolroom() {
var schoolName: String? = null
var collegeName: String? = null
var buildingName: String? = null
var schoolId: Int = 0
var collegeId: Int = 0
} | mit | 9a0bb7144578ed74aff39265ad56a28a | 23.714286 | 52 | 0.695652 | 3.415842 | false | false | false | false |
paplorinc/intellij-community | platform/lang-api/src/com/intellij/execution/filters/FileHyperlinkInfoBase.kt | 2 | 3198 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.filters
import com.intellij.ide.util.PsiNavigationSupport
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import java.io.File
abstract class FileHyperlinkInfoBase(private val myProject: Project,
private val myDocumentLine: Int,
private val myDocumentColumn: Int) : FileHyperlinkInfo {
protected abstract val virtualFile: VirtualFile?
override fun getDescriptor(): OpenFileDescriptor? {
val file = virtualFile
if (file == null || !file.isValid) return null
val document = FileDocumentManager.getInstance().getDocument(file) // need to load decompiler text
val line = file.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY)?.let { mapping ->
val mappingLine = mapping.bytecodeToSource(myDocumentLine + 1) - 1
if (mappingLine < 0) null else mappingLine
} ?: myDocumentLine
val offset = calculateOffset(document, line, myDocumentColumn)
if (offset == null) {
// although document position != logical position, it seems better than returning 'null'
return OpenFileDescriptor(myProject, file, line, myDocumentColumn)
}
else {
return OpenFileDescriptor(myProject, file, offset)
}
}
override fun navigate(project: Project?) {
project ?: return
descriptor?.let {
if (it.file.isDirectory) {
val psiManager = PsiManager.getInstance(project)
val psiDirectory = psiManager.findDirectory(it.file)
if (psiDirectory != null && psiManager.isInProject(psiDirectory)) {
psiDirectory.navigate(true)
}
else {
PsiNavigationSupport.getInstance().openDirectoryInSystemFileManager(File(it.file.path))
}
}
else {
if (null == FileEditorManager.getInstance(project).openTextEditor(it, true)) {
BrowserHyperlinkInfo(it.file.url).navigate(project)
}
}
}
}
/**
* Calculates an offset, that matches given line and column of the document.
*
* @param document [Document] instance
* @param documentLine zero-based line of the document
* @param documentColumn zero-based column of the document
* @return calculated offset or `null` if it's impossible to calculate
*/
protected open fun calculateOffset(document: Document?, documentLine: Int, documentColumn: Int): Int? {
document ?: return null
if (documentLine < 0 || document.lineCount <= documentLine) return null
val lineStartOffset = document.getLineStartOffset(documentLine)
val lineEndOffset = document.getLineEndOffset(documentLine)
val fixedColumn = Math.min(Math.max(documentColumn, 0), lineEndOffset - lineStartOffset)
return lineStartOffset + fixedColumn
}
} | apache-2.0 | 355fa2ddd89c33092492c03b6086f5e3 | 40.545455 | 140 | 0.713571 | 4.716814 | false | false | false | false |
CAD97/AndensMountain | TextAdventureCreationTool/src/cad97/anden/tact/model/PlayerProperty.kt | 1 | 1747 | package cad97.anden.tact.model
import cad97.anden.data.*
import cad97.fx.observable
import javafx.collections.ObservableMap
import tornadofx.getProperty
import tornadofx.property
class PlayerProperty {
val inventory: ObservableMap<String, Int> = mutableMapOf<String, Int>().observable()
val stats: StatsProperty = StatsProperty()
val flags: ObservableMap<String, Boolean> = mutableMapOf<String, Boolean>().observable()
fun asPlayer() = Player(
inventory = Inventory(inventory),
stats = stats.asStats(),
flags = Flags(flags)
)
}
class StatsProperty {
var health: Int by property<Int>()
var dodge: Int by property<Int>()
val attack: StatTripleProperty = StatTripleProperty()
val defense: StatTripleProperty = StatTripleProperty()
fun healthProperty() = getProperty(StatsProperty::health)
fun dodgeProperty() = getProperty(StatsProperty::dodge)
init {
health = 0
dodge = 0
}
fun asStats() = Stats(
health = health,
dodge = dodge,
attack = attack.asStatTriple(),
defense = defense.asStatTriple()
)
}
class StatTripleProperty {
var bashing: Int by property<Int>()
var piercing: Int by property<Int>()
var slashing: Int by property<Int>()
fun bashingProperty() = getProperty(StatTripleProperty::bashing)
fun piercingProperty() = getProperty(StatTripleProperty::piercing)
fun slashingProperty() = getProperty(StatTripleProperty::slashing)
init {
bashing = 0
piercing = 0
slashing = 0
}
fun asStatTriple() = StatTriple(
bashing = bashing,
piercing = piercing,
slashing = slashing
)
}
| gpl-3.0 | b8255e3e50263ccc77e247e8a277cec5 | 26.730159 | 92 | 0.65312 | 4.081776 | false | false | false | false |
HelmMobile/KotlinCleanArchitecture | data/src/main/java/cat/helm/basearchitecture/data/repository/Repository.kt | 1 | 8080 | package cat.helm.basearchitecture.data.repository
import cat.helm.basearchitecture.Result
import cat.helm.basearchitecture.data.repository.datasource.CacheDataSource
import cat.helm.basearchitecture.data.repository.datasource.ReadableDataSource
import cat.helm.basearchitecture.data.repository.datasource.WritableDataSource
import cat.helm.basearchitecture.data.repository.policy.ReadPolicy
import cat.helm.basearchitecture.data.repository.policy.WritePolicy
/**
* Created by Borja on 27/2/17.
*/
open class Repository<Key, Value> {
val writableDataSources = ArrayList<WritableDataSource<Key, Value>>()
val readableDataSources = ArrayList<ReadableDataSource<Key, Value>>()
val cacheDataSources = ArrayList<CacheDataSource<Key, Value>>()
fun getByKey(key: Key, policy: ReadPolicy = ReadPolicy.READ_ALL): Result<Value, Exception> {
var result: Result<Value, Exception> = Result.Failure()
if (policy.useCache()) {
result = getValueFromCacheDataSources(key)
}
result.failure {
if (policy.useReadable()) {
result = getValueFromReadableDataSources(key)
}
}
result.success {
result ->
populateCaches(result)
}
return result
}
fun getAll(policy: ReadPolicy = ReadPolicy.READ_ALL): Result<Collection<Value>, *> {
var result: Result<Collection<Value>, *> = Result.Failure()
if (policy.useCache()) {
result = getValuesFromCacheDataSources()
}
result.failure {
if (policy.useReadable()) {
result = getValuesFromReadableDataSources()
}
}
result.success {
value ->
populateCaches(value)
}
return result
}
fun addOrUpdate(value: Value, policy: WritePolicy = WritePolicy.WRITE_ALL): Result<Value, *> {
var result: Result<Value, Exception> = Result.Failure()
writableDataSources.forEach {
writableDataSource ->
result = writableDataSource.addOrUpdate(value)
}
result.success {
value ->
populateCaches(value)
}
if (policy.writeCache()) {
populateCaches(value)
}
return result
}
fun addOrUpdateAll(values: Collection<Value>): Result<Collection<Value>, *> {
var result: Result<Collection<Value>, *> = Result.Failure()
writableDataSources.forEach {
writableDataSource ->
result = writableDataSource.addOrUpdateAll(values)
}
result.success {
value ->
populateCaches(value)
}
return result
}
fun deleteByKey(key: Key): Result<Unit, *> {
var result: Result<Unit, Exception> = Result.Failure()
writableDataSources.forEach {
writableDataSource ->
result = writableDataSource.deleteByKey(key)
}
cacheDataSources.forEach {
cacheDataSource ->
result = cacheDataSource.deleteByKey(key)
}
return result
}
fun deleteAll(): Result<Unit, *> {
var result: Result<Unit, *> = Result.Failure()
writableDataSources.forEach {
writableDataSource ->
result = writableDataSource.deleteAll()
}
cacheDataSources.forEach {
cacheDataSource ->
result = cacheDataSource.deleteAll()
}
return result
}
fun query(query: Class<*>, parameters: HashMap<String, *>? = null, policy: ReadPolicy = ReadPolicy.READ_ALL)
: Result<Value, *> {
var result: Result<Value, *> = Result.Failure()
if (policy.useCache()) {
for (cacheDataSource in cacheDataSources) {
result = cacheDataSource.query(query, parameters)
if (result.isSuccess()) {
break
}
}
}
result.failure {
if (policy.useReadable()) {
for (readableDataSource in readableDataSources) {
result = readableDataSource.query(query, parameters)
if (result.isSuccess()) {
break
}
}
}
}
result.success {
value ->
populateCaches(value)
}
return result
}
fun queryAll(query: Class<*>, parameters: HashMap<String, *>? = null, policy: ReadPolicy = ReadPolicy.READ_ALL)
: Result<Collection<Value>, *> {
var result: Result<Collection<Value>, *> = Result.Failure()
if (policy.useCache()) {
for (cacheDataSource in cacheDataSources) {
result = cacheDataSource.queryAll(query, parameters)
if (result.isSuccess()) {
break
}
}
}
result.failure {
if (policy.useReadable()) {
for (readableDataSource in readableDataSources) {
result = readableDataSource.queryAll(query, parameters)
if (result.isSuccess()) {
break
}
}
}
}
result.success {
value ->
populateCaches(value)
}
return result
}
private fun populateCaches(value: Value) {
cacheDataSources.forEach {
cacheDataSource ->
cacheDataSource.addOrUpdate(value)
}
}
private fun populateCaches(values: Collection<Value>) {
cacheDataSources.forEach {
cacheDataSource ->
cacheDataSource.addOrUpdateAll(values)
}
}
private fun getValuesFromCacheDataSources(): Result<Collection<Value>, *> {
var result: Result<Collection<Value>, *> = Result.Failure()
cacheDataSources.forEach {
cacheDataSource ->
result = cacheDataSource.getAll()
result.success {
value ->
if (areValidValues(value, cacheDataSource)) {
return result
} else {
cacheDataSource.deleteAll()
result = Result.Failure()
}
}
}
return result
}
private fun getValueFromReadableDataSources(key: Key): Result<Value, *> {
var result: Result<Value, *> = Result.Failure()
readableDataSources.forEach {
readableDataSource ->
result = readableDataSource.getByKey(key)
result.success {
return result
}
}
return result
}
private fun getValueFromCacheDataSources(key: Key): Result<Value, *> {
var result: Result<Value, *> = Result.Failure()
cacheDataSources.forEach {
cacheDataSource ->
result = cacheDataSource.getByKey(key)
result.success {
value ->
if (cacheDataSource.isValid(value)) {
return result
} else {
cacheDataSource.deleteByKey(key)
result = Result.Failure()
}
}
}
return result
}
private fun getValuesFromReadableDataSources(): Result<Collection<Value>, *> {
var result: Result<Collection<Value>, *> = Result.Failure()
readableDataSources.forEach {
readableDataSource ->
result = readableDataSource.getAll()
result.success {
return result
}
}
return result
}
private fun areValidValues(values: Collection<Value>?, cacheDataSource: CacheDataSource<Key, Value>): Boolean {
var areValidValues = false
values?.forEach {
value ->
areValidValues = areValidValues or cacheDataSource.isValid(value)
}
return areValidValues
}
}
| apache-2.0 | 9d6a9522ab728c94c825af409747cb1d | 27.652482 | 115 | 0.552351 | 5.182809 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt | 1 | 28231 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.core
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.extensions.DeclarationAttributeAltererExtension
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.addRemoveModifier.MODIFIERS_ORDER
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentsInParentheses
import org.jetbrains.kotlin.resolve.calls.util.isFakeElement
import org.jetbrains.kotlin.resolve.checkers.ExplicitApiDeclarationChecker
import org.jetbrains.kotlin.resolve.checkers.explicitApiEnabled
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.SamConversionOracle
import org.jetbrains.kotlin.resolve.sam.SamConversionResolver
import org.jetbrains.kotlin.resolve.sam.getFunctionTypeForPossibleSamType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun KtLambdaArgument.moveInsideParentheses(bindingContext: BindingContext): KtCallExpression {
val ktExpression = this.getArgumentExpression()
?: throw KotlinExceptionWithAttachments("no argument expression for $this")
.withPsiAttachment("lambdaExpression", this)
return moveInsideParenthesesAndReplaceWith(ktExpression, bindingContext)
}
fun KtLambdaArgument.moveInsideParenthesesAndReplaceWith(
replacement: KtExpression,
bindingContext: BindingContext
): KtCallExpression = moveInsideParenthesesAndReplaceWith(replacement, getLambdaArgumentName(bindingContext))
fun KtLambdaArgument.getLambdaArgumentName(bindingContext: BindingContext): Name? {
val callExpression = parent as KtCallExpression
val resolvedCall = callExpression.getResolvedCall(bindingContext)
return (resolvedCall?.getArgumentMapping(this) as? ArgumentMatch)?.valueParameter?.name
}
fun KtLambdaArgument.moveInsideParenthesesAndReplaceWith(
replacement: KtExpression,
functionLiteralArgumentName: Name?,
withNameCheck: Boolean = true,
): KtCallExpression {
val oldCallExpression = parent as KtCallExpression
val newCallExpression = oldCallExpression.copy() as KtCallExpression
val psiFactory = KtPsiFactory(project)
val argument =
if (withNameCheck && shouldLambdaParameterBeNamed(newCallExpression.getValueArgumentsInParentheses(), oldCallExpression)) {
psiFactory.createArgument(replacement, functionLiteralArgumentName)
} else {
psiFactory.createArgument(replacement)
}
val functionLiteralArgument = newCallExpression.lambdaArguments.firstOrNull()!!
val valueArgumentList = newCallExpression.valueArgumentList ?: psiFactory.createCallArguments("()")
valueArgumentList.addArgument(argument)
(functionLiteralArgument.prevSibling as? PsiWhiteSpace)?.delete()
if (newCallExpression.valueArgumentList != null) {
functionLiteralArgument.delete()
} else {
functionLiteralArgument.replace(valueArgumentList)
}
return oldCallExpression.replace(newCallExpression) as KtCallExpression
}
fun KtLambdaExpression.moveFunctionLiteralOutsideParenthesesIfPossible() {
val valueArgument = parentOfType<KtValueArgument>()?.takeIf {
KtPsiUtil.deparenthesize(it.getArgumentExpression()) == this
} ?: return
val valueArgumentList = valueArgument.parent as? KtValueArgumentList ?: return
val call = valueArgumentList.parent as? KtCallExpression ?: return
if (call.canMoveLambdaOutsideParentheses()) {
call.moveFunctionLiteralOutsideParentheses()
}
}
private fun shouldLambdaParameterBeNamed(args: List<ValueArgument>, callExpr: KtCallExpression): Boolean {
if (args.any { it.isNamed() }) return true
val callee = (callExpr.calleeExpression?.mainReference?.resolve() as? KtFunction) ?: return false
return if (callee.valueParameters.any { it.isVarArg }) true else callee.valueParameters.size - 1 > args.size
}
fun KtCallExpression.getLastLambdaExpression(): KtLambdaExpression? {
if (lambdaArguments.isNotEmpty()) return null
return valueArguments.lastOrNull()?.getArgumentExpression()?.unpackFunctionLiteral()
}
@OptIn(FrontendInternals::class)
fun KtCallExpression.canMoveLambdaOutsideParentheses(): Boolean {
if (getStrictParentOfType<KtDelegatedSuperTypeEntry>() != null) return false
val lastLambdaExpression = getLastLambdaExpression() ?: return false
if (lastLambdaExpression.parentLabeledExpression()?.parentLabeledExpression() != null) return false
val callee = calleeExpression
if (callee is KtNameReferenceExpression) {
val resolutionFacade = getResolutionFacade()
val samConversionTransformer = resolutionFacade.frontendService<SamConversionResolver>()
val samConversionOracle = resolutionFacade.frontendService<SamConversionOracle>()
val languageVersionSettings = resolutionFacade.languageVersionSettings
val newInferenceEnabled = languageVersionSettings.supportsFeature(LanguageFeature.NewInference)
val bindingContext = safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
if (bindingContext.diagnostics.forElement(lastLambdaExpression).none { it.severity == Severity.ERROR }) {
val resolvedCall = getResolvedCall(bindingContext)
if (resolvedCall != null) {
val parameter = resolvedCall.getParameterForArgument(valueArguments.last()) ?: return false
val functionDescriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false
if (parameter != functionDescriptor.valueParameters.lastOrNull()) return false
return parameter.type.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)
}
}
val targets = bindingContext[BindingContext.REFERENCE_TARGET, callee]?.let { listOf(it) }
?: bindingContext[BindingContext.AMBIGUOUS_REFERENCE_TARGET, callee]
?: listOf()
val candidates = targets.filterIsInstance<FunctionDescriptor>()
val lambdaArgumentCount = valueArguments.count { it.getArgumentExpression()?.unpackFunctionLiteral() != null }
val referenceArgumentCount = valueArguments.count { it.getArgumentExpression() is KtCallableReferenceExpression }
// if there are functions among candidates but none of them have last function parameter then not show the intention
val areAllCandidatesWithoutLastFunctionParameter = candidates.none {
it.allowsMoveOfLastParameterOutsideParentheses(
lambdaArgumentCount + referenceArgumentCount,
samConversionTransformer,
samConversionOracle,
newInferenceEnabled
)
}
if (candidates.isNotEmpty() && areAllCandidatesWithoutLastFunctionParameter) return false
}
return true
}
private fun KtExpression.parentLabeledExpression(): KtLabeledExpression? {
return getStrictParentOfType<KtLabeledExpression>()?.takeIf { it.baseExpression == this }
}
private fun KotlinType.allowsMoveOutsideParentheses(
samConversionTransformer: SamConversionResolver,
samConversionOracle: SamConversionOracle,
newInferenceEnabled: Boolean
): Boolean {
// Fast-path
if (isFunctionOrSuspendFunctionType || isTypeParameter()) return true
// Also check if it can be SAM-converted
// Note that it is not necessary in OI, where we provide synthetic candidate descriptors with already
// converted types, but in NI it is performed by conversions, so we check it explicitly
// Also note that 'newInferenceEnabled' is essentially a micro-optimization, as there are no
// harm in just calling 'samConversionTransformer' on all candidates.
return newInferenceEnabled && samConversionTransformer.getFunctionTypeForPossibleSamType(this.unwrap(), samConversionOracle) != null
}
private fun FunctionDescriptor.allowsMoveOfLastParameterOutsideParentheses(
lambdaAndCallableReferencesInOriginalCallCount: Int,
samConversionTransformer: SamConversionResolver,
samConversionOracle: SamConversionOracle,
newInferenceEnabled: Boolean
): Boolean {
val params = valueParameters
val lastParamType = params.lastOrNull()?.type ?: return false
if (!lastParamType.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)) return false
val movableParametersOfCandidateCount = params.count {
it.type.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)
}
return movableParametersOfCandidateCount == lambdaAndCallableReferencesInOriginalCallCount
}
fun KtCallExpression.moveFunctionLiteralOutsideParentheses() {
assert(lambdaArguments.isEmpty())
val argumentList = valueArgumentList!!
val argument = argumentList.arguments.last()
val expression = argument.getArgumentExpression()!!
assert(expression.unpackFunctionLiteral() != null)
fun isWhiteSpaceOrComment(e: PsiElement) = e is PsiWhiteSpace || e is PsiComment
val prevComma = argument.siblings(forward = false, withItself = false).firstOrNull { it.elementType == KtTokens.COMMA }
val prevComments = (prevComma ?: argumentList.leftParenthesis)
?.siblings(forward = true, withItself = false)
?.takeWhile(::isWhiteSpaceOrComment)?.toList().orEmpty()
val nextComments = argumentList.rightParenthesis
?.siblings(forward = false, withItself = false)
?.takeWhile(::isWhiteSpaceOrComment)?.toList()?.reversed().orEmpty()
val psiFactory = KtPsiFactory(project)
val dummyCall = psiFactory.createExpression("foo() {}") as KtCallExpression
val functionLiteralArgument = dummyCall.lambdaArguments.single()
functionLiteralArgument.getArgumentExpression()?.replace(expression)
if (prevComments.any { it is PsiComment }) {
if (prevComments.firstOrNull() !is PsiWhiteSpace) this.add(psiFactory.createWhiteSpace())
prevComments.forEach { this.add(it) }
prevComments.forEach { if (it is PsiComment) it.delete() }
}
this.add(functionLiteralArgument)
if (nextComments.any { it is PsiComment }) {
nextComments.forEach { this.add(it) }
nextComments.forEach { if (it is PsiComment) it.delete() }
}
/* we should not remove empty parenthesis when callee is a call too - it won't parse */
if (argumentList.arguments.size == 1 && calleeExpression !is KtCallExpression) {
argumentList.delete()
} else {
argumentList.removeArgument(argument)
}
}
fun KtBlockExpression.appendElement(element: KtElement, addNewLine: Boolean = false): KtElement {
val rBrace = rBrace
val newLine = KtPsiFactory(project).createNewLine()
val anchor = if (rBrace == null) {
val lastChild = lastChild
lastChild as? PsiWhiteSpace ?: addAfter(newLine, lastChild)!!
} else {
rBrace.prevSibling!!
}
val addedElement = addAfter(element, anchor)!! as KtElement
if (addNewLine) {
addAfter(newLine, addedElement)
}
return addedElement
}
//TODO: git rid of this method
fun PsiElement.deleteElementAndCleanParent() {
val parent = parent
deleteElementWithDelimiters(this)
deleteChildlessElement(parent, this::class.java)
}
// Delete element if it doesn't contain children of a given type
private fun <T : PsiElement> deleteChildlessElement(element: PsiElement, childClass: Class<T>) {
if (PsiTreeUtil.getChildrenOfType(element, childClass) == null) {
element.delete()
}
}
// Delete given element and all the elements separating it from the neighboring elements of the same class
private fun deleteElementWithDelimiters(element: PsiElement) {
val paramBefore = PsiTreeUtil.getPrevSiblingOfType(element, element.javaClass)
val from: PsiElement
val to: PsiElement
if (paramBefore != null) {
from = paramBefore.nextSibling
to = element
} else {
val paramAfter = PsiTreeUtil.getNextSiblingOfType(element, element.javaClass)
from = element
to = if (paramAfter != null) paramAfter.prevSibling else element
}
val parent = element.parent
parent.deleteChildRange(from, to)
}
fun PsiElement.deleteSingle() {
CodeEditUtil.removeChild(parent?.node ?: return, node ?: return)
}
fun KtClass.getOrCreateCompanionObject(): KtObjectDeclaration {
companionObjects.firstOrNull()?.let { return it }
return appendDeclaration(KtPsiFactory(project).createCompanionObject())
}
inline fun <reified T : KtDeclaration> KtClass.appendDeclaration(declaration: T): T {
val body = getOrCreateBody()
val anchor = PsiTreeUtil.skipSiblingsBackward(body.rBrace ?: body.lastChild!!, PsiWhiteSpace::class.java)
val newDeclaration =
if (anchor?.nextSibling is PsiErrorElement)
body.addBefore(declaration, anchor)
else
body.addAfter(declaration, anchor)
return newDeclaration as T
}
fun KtDeclaration.toDescriptor(): DeclarationDescriptor? {
if (this is KtScriptInitializer) {
return null
}
return resolveToDescriptorIfAny()
}
fun KtModifierListOwner.setVisibility(visibilityModifier: KtModifierKeywordToken, addImplicitVisibilityModifier: Boolean = false) {
if (this is KtDeclaration && !addImplicitVisibilityModifier) {
val defaultVisibilityKeyword = implicitVisibility()
if (visibilityModifier == defaultVisibilityKeyword) {
// Fake elements do not have ModuleInfo and languageVersionSettings because they can't be analysed
// Effectively, this leads to J2K not respecting explicit api mode, but this case seems to be rare anyway.
val explicitVisibilityRequired = !this.isFakeElement &&
this.languageVersionSettings.explicitApiEnabled &&
this.resolveToDescriptorIfAny()?.let { !ExplicitApiDeclarationChecker.explicitVisibilityIsNotRequired(it) } == true
if (!explicitVisibilityRequired) {
this.visibilityModifierType()?.let { removeModifier(it) }
return
}
}
}
addModifier(visibilityModifier)
}
fun KtDeclaration.implicitVisibility(): KtModifierKeywordToken? {
return when {
this is KtPropertyAccessor && isSetter && property.hasModifier(KtTokens.OVERRIDE_KEYWORD) -> {
property.resolveToDescriptorIfAny()
?.safeAs<PropertyDescriptor>()
?.overriddenDescriptors?.forEach {
val visibility = it.setter?.visibility?.toKeywordToken()
if (visibility != null) return visibility
}
KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
this is KtConstructor<*> -> {
// constructors cannot be declared in objects
val klass = getContainingClassOrObject() as? KtClass ?: return KtTokens.DEFAULT_VISIBILITY_KEYWORD
when {
klass.isEnum() -> KtTokens.PRIVATE_KEYWORD
klass.isSealed() ->
if (klass.languageVersionSettings.supportsFeature(LanguageFeature.SealedInterfaces)) KtTokens.PROTECTED_KEYWORD
else KtTokens.PRIVATE_KEYWORD
else -> KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
}
hasModifier(KtTokens.OVERRIDE_KEYWORD) -> {
resolveToDescriptorIfAny()?.safeAs<CallableMemberDescriptor>()
?.overriddenDescriptors
?.let { OverridingUtil.findMaxVisibility(it) }
?.toKeywordToken()
}
else -> KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
}
fun KtModifierListOwner.canBePrivate(): Boolean {
if (modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true) return false
if (this.isAnnotationClassPrimaryConstructor()) return false
if (this is KtProperty && this.hasJvmFieldAnnotation()) return false
if (this is KtDeclaration) {
if (hasActualModifier() || isExpectDeclaration()) return false
val containingClassOrObject = containingClassOrObject as? KtClass ?: return true
if (containingClassOrObject.isAnnotation()) return false
if (containingClassOrObject.isInterface() && !hasBody()) return false
}
return true
}
fun KtModifierListOwner.canBePublic(): Boolean = !isSealedClassConstructor()
fun KtModifierListOwner.canBeProtected(): Boolean {
return when (val parent = if (this is KtPropertyAccessor) this.property.parent else this.parent) {
is KtClassBody -> {
val parentClass = parent.parent as? KtClass
parentClass != null && !parentClass.isInterface() && !this.isFinalClassConstructor()
}
is KtParameterList -> parent.parent is KtPrimaryConstructor
is KtClass -> !this.isAnnotationClassPrimaryConstructor() && !this.isFinalClassConstructor()
else -> false
}
}
fun KtModifierListOwner.canBeInternal(): Boolean {
if (containingClass()?.isInterface() == true) {
val objectDeclaration = getStrictParentOfType<KtObjectDeclaration>() ?: return false
if (objectDeclaration.isCompanion() && hasJvmFieldAnnotation()) return false
}
return !isAnnotationClassPrimaryConstructor() && !isSealedClassConstructor()
}
private fun KtModifierListOwner.isAnnotationClassPrimaryConstructor(): Boolean =
this is KtPrimaryConstructor && (this.parent as? KtClass)?.hasModifier(KtTokens.ANNOTATION_KEYWORD) ?: false
private fun KtModifierListOwner.isFinalClassConstructor(): Boolean {
if (this !is KtConstructor<*>) return false
val ktClass = getContainingClassOrObject().safeAs<KtClass>() ?: return false
return ktClass.toDescriptor().safeAs<ClassDescriptor>()?.isFinalOrEnum ?: return false
}
private fun KtModifierListOwner.isSealedClassConstructor(): Boolean {
if (this !is KtConstructor<*>) return false
val ktClass = getContainingClassOrObject().safeAs<KtClass>() ?: return false
return ktClass.isSealed()
}
fun KtClass.isInheritable(): Boolean {
return when (getModalityFromDescriptor()) {
KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD, KtTokens.SEALED_KEYWORD -> true
else -> false
}
}
val KtParameter.isOverridable: Boolean
get() = hasValOrVar() && !isEffectivelyFinal
val KtProperty.isOverridable: Boolean
get() = !isTopLevel && !isEffectivelyFinal
private val KtDeclaration.isEffectivelyFinal: Boolean
get() = hasModifier(KtTokens.FINAL_KEYWORD) ||
!(hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD) || hasModifier(KtTokens.OVERRIDE_KEYWORD) ||
(containingClassOrObject as? KtClass)?.isInterface() == true) ||
containingClassOrObject?.isEffectivelyFinal == true
private val KtClassOrObject.isEffectivelyFinal: Boolean
get() = this is KtObjectDeclaration ||
this is KtClass && isEffectivelyFinal
private val KtClass.isEffectivelyFinal: Boolean
get() = hasModifier(KtTokens.FINAL_KEYWORD) ||
isData() ||
!(isSealed() || hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD) || isInterface())
fun KtDeclaration.isOverridable(): Boolean {
val parent = parent
if (!(parent is KtClassBody || parent is KtParameterList)) return false
val klass = if (parent.parent is KtPrimaryConstructor)
parent.parent.parent as? KtClass
else
parent.parent as? KtClass
if (klass == null || (!klass.isInheritable() && !klass.isEnum())) return false
if (this.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
// 'private' is incompatible with 'open'
return false
}
return when (getModalityFromDescriptor()) {
KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD -> true
else -> false
}
}
fun KtDeclaration.getModalityFromDescriptor(descriptor: DeclarationDescriptor? = resolveToDescriptorIfAny()): KtModifierKeywordToken? {
if (descriptor is MemberDescriptor) {
return mapModality(descriptor.modality)
}
return null
}
fun KtDeclaration.implicitModality(): KtModifierKeywordToken {
var predictedModality = predictImplicitModality()
val bindingContext = safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] ?: return predictedModality
val containingDescriptor = descriptor.containingDeclaration ?: return predictedModality
val extensions = DeclarationAttributeAltererExtension.getInstances(this.project)
for (extension in extensions) {
val newModality = extension.refineDeclarationModality(
this,
descriptor as? ClassDescriptor,
containingDescriptor,
mapModalityToken(predictedModality),
isImplicitModality = true
)
if (newModality != null) {
predictedModality = mapModality(newModality)
}
}
return predictedModality
}
fun mapModality(accurateModality: Modality): KtModifierKeywordToken = when (accurateModality) {
Modality.FINAL -> KtTokens.FINAL_KEYWORD
Modality.SEALED -> KtTokens.SEALED_KEYWORD
Modality.OPEN -> KtTokens.OPEN_KEYWORD
Modality.ABSTRACT -> KtTokens.ABSTRACT_KEYWORD
}
private fun mapModalityToken(modalityToken: IElementType): Modality = when (modalityToken) {
KtTokens.FINAL_KEYWORD -> Modality.FINAL
KtTokens.SEALED_KEYWORD -> Modality.SEALED
KtTokens.OPEN_KEYWORD -> Modality.OPEN
KtTokens.ABSTRACT_KEYWORD -> Modality.ABSTRACT
else -> error("Unexpected modality keyword $modalityToken")
}
private fun KtDeclaration.predictImplicitModality(): KtModifierKeywordToken {
if (this is KtClassOrObject) {
if (this is KtClass && this.isInterface()) return KtTokens.ABSTRACT_KEYWORD
return KtTokens.FINAL_KEYWORD
}
val klass = containingClassOrObject ?: return KtTokens.FINAL_KEYWORD
if (hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
if (klass.hasModifier(KtTokens.ABSTRACT_KEYWORD) ||
klass.hasModifier(KtTokens.OPEN_KEYWORD) ||
klass.hasModifier(KtTokens.SEALED_KEYWORD)
) {
return KtTokens.OPEN_KEYWORD
}
}
if (klass is KtClass && klass.isInterface() && !hasModifier(KtTokens.PRIVATE_KEYWORD)) {
return if (hasBody()) KtTokens.OPEN_KEYWORD else KtTokens.ABSTRACT_KEYWORD
}
return KtTokens.FINAL_KEYWORD
}
fun KtSecondaryConstructor.getOrCreateBody(): KtBlockExpression {
bodyExpression?.let { return it }
val delegationCall = getDelegationCall()
val anchor = if (delegationCall.isImplicit) valueParameterList else delegationCall
val newBody = KtPsiFactory(project).createEmptyBody()
return addAfter(newBody, anchor) as KtBlockExpression
}
fun KtParameter.dropDefaultValue() {
val from = equalsToken ?: return
val to = defaultValue ?: from
deleteChildRange(from, to)
}
fun KtTypeParameterListOwner.addTypeParameter(typeParameter: KtTypeParameter): KtTypeParameter? {
typeParameterList?.let { return it.addParameter(typeParameter) }
val list = KtPsiFactory(project).createTypeParameterList("<X>")
list.parameters[0].replace(typeParameter)
val leftAnchor = when (this) {
is KtClass -> nameIdentifier
is KtNamedFunction -> funKeyword
is KtProperty -> valOrVarKeyword
is KtTypeAlias -> nameIdentifier
else -> null
} ?: return null
return (addAfter(list, leftAnchor) as KtTypeParameterList).parameters.first()
}
fun KtNamedFunction.getOrCreateValueParameterList(): KtParameterList {
valueParameterList?.let { return it }
val parameterList = KtPsiFactory(project).createParameterList("()")
val anchor = nameIdentifier ?: funKeyword!!
return addAfter(parameterList, anchor) as KtParameterList
}
fun KtCallableDeclaration.setType(type: KotlinType, shortenReferences: Boolean = true) {
if (type.isError) return
setType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type), shortenReferences)
}
fun KtCallableDeclaration.setType(typeString: String, shortenReferences: Boolean = true) {
val typeReference = KtPsiFactory(project).createType(typeString)
setTypeReference(typeReference)
if (shortenReferences) {
ShortenReferences.DEFAULT.process(getTypeReference()!!)
}
}
fun KtCallableDeclaration.setReceiverType(type: KotlinType) {
if (type.isError) return
val typeReference = KtPsiFactory(project).createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type))
setReceiverTypeReference(typeReference)
ShortenReferences.DEFAULT.process(receiverTypeReference!!)
}
fun KtParameter.setDefaultValue(newDefaultValue: KtExpression): PsiElement {
defaultValue?.let { return it.replaced(newDefaultValue) }
val psiFactory = KtPsiFactory(project)
val eq = equalsToken ?: add(psiFactory.createEQ())
return addAfter(newDefaultValue, eq) as KtExpression
}
fun KtModifierList.appendModifier(modifier: KtModifierKeywordToken) {
add(KtPsiFactory(project).createModifier(modifier))
}
fun KtModifierList.normalize(): KtModifierList {
val psiFactory = KtPsiFactory(project)
return psiFactory.createEmptyModifierList().also { newList ->
val modifiers = SmartList<PsiElement>()
allChildren.forEach {
val elementType = it.node.elementType
when {
it is KtAnnotation || it is KtAnnotationEntry -> newList.add(it)
elementType is KtModifierKeywordToken -> {
if (elementType == KtTokens.DEFAULT_VISIBILITY_KEYWORD) return@forEach
if (elementType == KtTokens.FINALLY_KEYWORD && !hasModifier(KtTokens.OVERRIDE_KEYWORD)) return@forEach
modifiers.add(it)
}
}
}
modifiers.sortBy { MODIFIERS_ORDER.indexOf(it.node.elementType) }
modifiers.forEach { newList.add(it) }
}
} | apache-2.0 | 0678677f121c1c1f1f3c461fbb9575cc | 42.10229 | 136 | 0.738018 | 5.307577 | false | false | false | false |
java-graphics/assimp | src/main/kotlin/assimp/format/X/helpers.kt | 2 | 3390 | package assimp.format.X
import assimp.ai_real
import assimp.AiColor4D
import assimp.AiVector2D
class Pointer<T>(var datas: Array<T>, var pointer: Int = 0) {
//constructor(dat : T, pointer: Int = 0) : this(Array<T>(1, {i -> dat}), pointer)
var value: T
get() = datas[pointer]
set(value) {
datas[pointer] = value
}
val lastIndex: Int get() = datas.lastIndex-pointer
operator fun inc(): Pointer<T> {
return Pointer<T>(datas, pointer + 1)
}
operator fun dec(): Pointer<T> {
return Pointer<T>(datas, pointer - 1)
}
operator fun plus(b: Int): Pointer<T> {
return Pointer<T>(datas, pointer + b)
}
operator fun minus(b: Int): Pointer<T> {
return Pointer<T>(datas, pointer - b)
}
operator fun compareTo(b: Pointer<T>): Int {
return pointer - b.pointer
}
operator fun get(index: Int): T {
return datas[pointer+index]
}
operator fun set(index: Int, value: T) {
datas[pointer+index] = value
}
fun subset(range: IntRange): MutableList<T> {
var result: MutableList<T> = mutableListOf()
for (i in range) {
result.add(datas[pointer + i])
}
return result
}
}
operator fun Pointer<Char>.get(range: IntRange): String = subset(range).joinToString(separator = "")
fun <T> MutableList<T>.resize(newsize: Int, init: () -> T) {
if (newsize - size < 0) throw RuntimeException("Downsizing unsupported")
for (a in size until newsize)
add(init())
}
fun <T> MutableList<T>.reserve(newsize: Int, init: () -> T) {
if (newsize - size > 0) {
for (a in size until newsize)
add(init())
}
}
/**
* Creates a new mutable list with the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns a list element given its index.
*/
@Suppress("FunctionName")
inline fun <reified T> ArrayList(size: Int, init: (index: Int) -> T): ArrayList<T> {
val result = ArrayList<T>(size)
repeat(size) { index -> result.add(init(index)) }
return result
}
fun String.size(): Int = length
fun StringBuilder.length(): Int = length
fun <T> MutableList<T>.pushBack(t: T): Boolean = add(t)
fun <T> MutableList<T>.size(): Int = size
fun <T> MutableList<T>.front(): T = first()
fun <T> MutableList<T>.back(): T = last()
fun <T> ArrayList<T>.reserve(newsize : Int): Unit = ensureCapacity(newsize)
fun <T> ArrayList<T>.reserve(newsize: Int, init: () -> T) : ArrayList<T> {
if (newsize - size > 0) {
for (a in size until newsize)
add(init())
}
return this
}
fun isspace(char: Char): Boolean {
return char.isWhitespace()
}
fun strncmp(P: Pointer<Char>, s: String, l: Int): Int { //Highly simplified from C++ function definition
if (P[0 until l] == s) return 0
return -1
}
fun ASSIMP_strincmp(_s1: Pointer<Char>, _s2: String, n: Int): Int {
return ASSIMP_strincmp(_s1, Pointer<Char>(Array<Char>(_s2.length, { i -> _s2.get(i) })), n)
}
fun ASSIMP_strincmp(_s1: Pointer<Char>, _s2: Pointer<Char>, n: Int): Int {
var c1: Char;
var c2: Char;
var s1 = _s1;
var s2 = _s2;
var p: Int = 0;
do {
if (p++ >= n) return 0;
c1 = tolower(s1.value); s1++;
c2 = tolower(s2.value); s2++;
} while (c1.toInt() != 0 && (c1 == c2));
return c1 - c2;
}
fun tolower(c: Char): Char {
return c.toLowerCase()
}
fun isdigit(c: Char): Boolean {
return c.isDigit()
}
fun String.length() = length
fun warn(s: String) {
println(s)
}
fun debug(s : String) {
println(s)
}
| bsd-3-clause | 01989739847ec249faf426c09017ecdf | 21.905405 | 114 | 0.642773 | 2.817955 | false | false | false | false |
avram/zandy | src/main/java/com/gimranov/zandy/app/FakeDataUtil.kt | 1 | 466 | package com.gimranov.zandy.app
import com.gimranov.zandy.app.data.Item
import io.bloco.faker.Faker
import java.util.*
internal object FakeDataUtil {
private val faker = Faker()
fun book(): Item {
val item = Item()
item.title = faker.book.title()
item.type = "book"
item.creatorSummary = faker.name.name() + ", " + faker.name.name()
item.year = (1900 + Random().nextInt(117)).toString()
return item
}
}
| agpl-3.0 | bec9330f797ed12523b8cb598ac99f02 | 23.526316 | 74 | 0.620172 | 3.426471 | false | false | false | false |
android/wear-os-samples | WearTilesKotlin/app/src/debug/java/com/example/wear/tiles/golden/GoldenTilesPreviewsRow1.kt | 1 | 3620 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.wear.tiles.golden
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import com.example.wear.tiles.R
import com.example.wear.tiles.tools.WearLargeRoundDevicePreview
import com.example.wear.tiles.tools.WearSmallRoundDevicePreview
import com.example.wear.tiles.tools.emptyClickable
import com.google.android.horologist.compose.tools.LayoutRootPreview
import com.google.android.horologist.compose.tools.buildDeviceParameters
import com.google.android.horologist.tiles.images.drawableResToImageResource
@WearSmallRoundDevicePreview
@WearLargeRoundDevicePreview
@Composable
fun Goal() {
val context = LocalContext.current
LayoutRootPreview(
Goal.layout(context, context.deviceParams(), steps = 5168, goal = 8000)
)
}
@WearSmallRoundDevicePreview
@WearLargeRoundDevicePreview
@Composable
fun WorkoutButtons() {
val context = LocalContext.current
LayoutRootPreview(
Workout.buttonsLayout(
context,
context.deviceParams(),
weekSummary = "1 run this week",
button1Clickable = emptyClickable,
button2Clickable = emptyClickable,
button3Clickable = emptyClickable,
chipClickable = emptyClickable
)
) {
addIdToImageMapping(
Workout.BUTTON_1_ICON_ID,
drawableResToImageResource(R.drawable.ic_run_24)
)
addIdToImageMapping(
Workout.BUTTON_2_ICON_ID,
drawableResToImageResource(R.drawable.ic_yoga_24)
)
addIdToImageMapping(
Workout.BUTTON_3_ICON_ID,
drawableResToImageResource(R.drawable.ic_cycling_24)
)
}
}
@WearSmallRoundDevicePreview
@WearLargeRoundDevicePreview
@Composable
fun WorkoutLargeChip() {
val context = LocalContext.current
LayoutRootPreview(
Workout.largeChipLayout(
context,
context.deviceParams(),
clickable = emptyClickable,
lastWorkoutSummary = "Last session 45m"
)
)
}
@WearSmallRoundDevicePreview
@WearLargeRoundDevicePreview
@Composable
fun Run() {
val context = LocalContext.current
LayoutRootPreview(
Run.layout(
context,
context.deviceParams(),
lastRunText = "2 days ago",
startRunClickable = emptyClickable,
moreChipClickable = emptyClickable
)
)
}
@WearSmallRoundDevicePreview
@WearLargeRoundDevicePreview
@Composable
fun Ski() {
val context = LocalContext.current
LayoutRootPreview(
Ski.layout(
context,
stat1 = Ski.Stat("Max Spd", "46.5", "mph"),
stat2 = Ski.Stat("Distance", "21.8", "mile")
)
)
}
@WearSmallRoundDevicePreview
@WearLargeRoundDevicePreview
@Composable
fun SleepTracker() {
// TODO: yuri has an example of this one
}
private fun Context.deviceParams() = buildDeviceParameters(resources)
| apache-2.0 | de84d84b57c195b9cd90634e7721ba86 | 28.672131 | 79 | 0.696409 | 4.409257 | false | false | false | false |
ursjoss/sipamato | core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/keyword/JooqKeywordRepoTest.kt | 2 | 5369 | @file:Suppress("SpellCheckingInspection")
package ch.difty.scipamato.core.persistence.keyword
import ch.difty.scipamato.common.DateTimeService
import ch.difty.scipamato.core.db.tables.KeywordTr.KEYWORD_TR
import ch.difty.scipamato.core.db.tables.records.KeywordTrRecord
import ch.difty.scipamato.core.entity.keyword.KeywordDefinition
import ch.difty.scipamato.core.entity.keyword.KeywordTranslation
import ch.difty.scipamato.core.persistence.OptimisticLockingException
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.amshove.kluent.invoking
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeNull
import org.amshove.kluent.shouldHaveSize
import org.amshove.kluent.shouldThrow
import org.amshove.kluent.withMessage
import org.jooq.DSLContext
import org.jooq.Result
import org.junit.jupiter.api.Test
internal class JooqKeywordRepoTest {
private val dslContextMock = mockk<DSLContext>()
private val dateTimeServiceMock = mockk<DateTimeService>()
private var repo = JooqKeywordRepo(dslContextMock, dateTimeServiceMock)
@Test
fun insertingKeywordDefinition_withEntityWithNonNullId_throws() {
val ntd = KeywordDefinition(1, "de", 1)
invoking { repo.insert(ntd) } shouldThrow IllegalArgumentException::class withMessage "id must be null."
}
@Test
fun removingObsoletePersistedRecords() {
val kt = KeywordTranslation(1, "de", "kw1", 1)
val ktr1 = mockk<KeywordTrRecord>(relaxed = true) {
every { get(KEYWORD_TR.ID) } returns 1
}
val ktr2 = mockk<KeywordTrRecord>(relaxed = true) {
every { get(KEYWORD_TR.ID) } returns 2
}
val resultMock: Result<KeywordTrRecord> = mockk {
every { iterator() } returns mockk {
every { hasNext() } returnsMany listOf(true, true, false)
every { next() } returnsMany listOf(ktr1, ktr2)
}
}
repo.removeObsoletePersistedRecordsFor(resultMock, listOf(kt))
verify { resultMock.iterator() }
verify { ktr1.get(KEYWORD_TR.ID) }
verify { ktr2.get(KEYWORD_TR.ID) }
verify { ktr2.delete() }
confirmVerified(resultMock, ktr1, ktr2)
}
@Test
fun removingObsoletePersistedRecords_whenCheckingIfTranslationIsPresentInEntity_doesntConsiderIdLessEntityTransl() {
val ct = KeywordTranslation(null, "de", "1ade", 1)
val ctr1 = mockk<KeywordTrRecord>(relaxed = true)
val ctr2 = mockk<KeywordTrRecord>(relaxed = true)
val resultMock: Result<KeywordTrRecord> = mockk {
every { iterator() } returns mockk {
every { hasNext() } returnsMany listOf(true, true, false)
every { next() } returnsMany listOf(ctr1, ctr2)
}
}
repo.removeObsoletePersistedRecordsFor(resultMock, listOf(ct))
verify { resultMock.iterator() }
verify { ctr1.delete() }
verify { ctr2.delete() }
confirmVerified(resultMock, ctr1, ctr2)
}
@Test
fun managingTranslations() {
val entity = KeywordDefinition(1, "de", 10)
invoking { repo.manageTranslations(null, entity, emptyList()) } shouldThrow OptimisticLockingException::class withMessage
"Record in table 'keyword' has been modified prior to the update attempt. Aborting...." +
" [KeywordDefinition(id=1, searchOverride=null)]"
}
@Test
fun addingOrUpdatingTranslation() {
val ktrMock = mockk<KeywordTrRecord> {
every { get(KEYWORD_TR.ID) } returns 1000
every { get(KEYWORD_TR.LANG_CODE) } returns "de"
every { get(KEYWORD_TR.NAME) } returns "someName"
every { get(KEYWORD_TR.VERSION) } returns 500
}
repo = object : JooqKeywordRepo(dslContextMock, dateTimeServiceMock) {
override fun insertAndGetKeywordTr(keywordId: Int, userId: Int, kt: KeywordTranslation) = ktrMock
}
val entity = KeywordDefinition(1, "de", 1)
val userId = 5
val translations = ArrayList<KeywordTranslation>()
val kt = KeywordTranslation(null, "de", "trs1", 1)
kt.id.shouldBeNull()
repo.addOrUpdateTranslation(kt, entity, userId, translations)
translations shouldHaveSize 1
val translation = translations[0]
translation.id shouldBeEqualTo 1000
translation.langCode shouldBeEqualTo "de"
translation.name shouldBeEqualTo "someName"
translation.version shouldBeEqualTo 500
}
@Test
fun addOrThrow_withNullRecord_throwsOptimisticLockingException() {
invoking {
repo.addOrThrow(null, "trslString", ArrayList())
} shouldThrow OptimisticLockingException::class withMessage
"Record in table 'keyword_tr' has been modified prior to the update attempt." +
" Aborting.... [trslString]"
}
@Test
fun loggingOrThrowing_withDeleteCountZero_throws() {
invoking {
repo.logOrThrow(0, 1, KeywordDefinition(10, "de", 100))
} shouldThrow OptimisticLockingException::class withMessage
"Record in table 'keyword' has been modified prior to the delete attempt." +
" Aborting.... [KeywordDefinition(id=10, searchOverride=null)]"
}
}
| gpl-3.0 | cbccc2be73a1553c398d66b2d056f69a | 36.809859 | 129 | 0.673123 | 4.298639 | false | true | false | false |
leafclick/intellij-community | platform/indexing-impl/src/com/intellij/psi/impl/search/helper.kt | 1 | 12895 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.search
import com.intellij.model.search.SearchParameters
import com.intellij.model.search.Searcher
import com.intellij.model.search.impl.*
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ClassExtension
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.cache.impl.id.IdIndexEntry
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.util.ObjectUtils
import com.intellij.util.Processor
import com.intellij.util.Query
import com.intellij.util.SmartList
import com.intellij.util.text.StringSearcher
import gnu.trove.THashMap
import org.jetbrains.annotations.ApiStatus.Internal
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.LinkedHashMap
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
private val searchersExtension = ClassExtension<Searcher<*, *>>("com.intellij.searcher")
internal val indicatorOrEmpty: ProgressIndicator
get() = EmptyProgressIndicator.notNullize(ProgressIndicatorProvider.getGlobalProgressIndicator())
@Internal
fun <R> runSearch(project: Project, query: Query<out R>, processor: Processor<in R>): Boolean {
val progress = indicatorOrEmpty
var currentQueries: Collection<Query<out R>> = listOf(query)
while (currentQueries.isNotEmpty()) {
progress.checkCanceled()
val layer = buildLayer(progress, project, currentQueries)
when (val layerResult = layer.runLayer(processor)) {
is LayerResult.Ok -> currentQueries = layerResult.subqueries
is LayerResult.Stop -> return false
}
}
return true
}
private fun <R> buildLayer(progress: ProgressIndicator, project: Project, queries: Collection<Query<out R>>): Layer<out R> {
val queue: Queue<Query<out R>> = ArrayDeque()
queue.addAll(queries)
val queryRequests = SmartList<QueryRequest<*, R>>()
val subQueryQueryRequests = SmartList<QueryRequest<*, Query<out R>>>()
val wordRequests = SmartList<WordRequest<R>>()
val subQueryWordRequests = SmartList<WordRequest<Query<out R>>>()
while (queue.isNotEmpty()) {
progress.checkCanceled()
val query: Query<out R> = queue.remove()
val primitives: PrimitiveRequests<R> = decompose(query)
val resultRequests: Requests<R> = primitives.resultRequests
queryRequests.addAll(resultRequests.queryRequests)
wordRequests.addAll(resultRequests.wordRequests)
for (parametersRequest: ParametersRequest<*, R> in resultRequests.parametersRequests) {
progress.checkCanceled()
handleParamRequest(progress, parametersRequest) {
queue.offer(it)
}
}
val subQueryRequests: Requests<Query<out R>> = primitives.subQueryRequests
subQueryQueryRequests.addAll(subQueryRequests.queryRequests)
subQueryWordRequests.addAll(subQueryRequests.wordRequests)
for (parametersRequest: ParametersRequest<*, Query<out R>> in subQueryRequests.parametersRequests) {
progress.checkCanceled()
handleSubQueryParamRequest(progress, parametersRequest) {
queue.offer(it)
}
}
}
return Layer(project, progress, queryRequests, wordRequests, subQueryQueryRequests, subQueryWordRequests)
}
private fun <B, R> handleParamRequest(progress: ProgressIndicator,
request: ParametersRequest<B, R>,
queue: (Query<out R>) -> Unit) {
val searchRequests: Collection<Query<out B>> = collectSearchRequests(request.params)
for (query: Query<out B> in searchRequests) {
progress.checkCanceled()
queue(transformingQuery(query, request.transformation))
}
}
private fun <B, R> handleSubQueryParamRequest(progress: ProgressIndicator,
request: ParametersRequest<B, Query<out R>>,
queue: (Query<out R>) -> Unit) {
val searchRequests: Collection<Query<out B>> = collectSearchRequests(request.params)
for (query: Query<out B> in searchRequests) {
progress.checkCanceled()
queue(LayeredQuery(query, request.transformation))
}
}
private fun <R> collectSearchRequests(parameters: SearchParameters<R>): Collection<Query<out R>> {
return DumbService.getInstance(parameters.project).runReadActionInSmartMode(Computable {
if (parameters.areValid()) {
doCollectSearchRequests(parameters)
}
else {
emptyList()
}
})
}
private fun <R> doCollectSearchRequests(parameters: SearchParameters<R>): Collection<Query<out R>> {
val queries = ArrayList<Query<out R>>()
@Suppress("UNCHECKED_CAST")
val searchers = searchersExtension.forKey(parameters.javaClass) as List<Searcher<SearchParameters<R>, R>>
for (searcher: Searcher<SearchParameters<R>, R> in searchers) {
ProgressManager.checkCanceled()
queries += searcher.collectSearchRequests(parameters)
}
return queries
}
private sealed class LayerResult<out T> {
object Stop : LayerResult<Nothing>()
class Ok<T>(val subqueries: Collection<Query<out T>>) : LayerResult<T>()
}
private class Layer<T>(
private val project: Project,
private val progress: ProgressIndicator,
private val queryRequests: Collection<QueryRequest<*, T>>,
private val wordRequests: Collection<WordRequest<T>>,
private val subQueryQueryRequests: Collection<QueryRequest<*, Query<out T>>>,
private val subQueryWordRequests: Collection<WordRequest<Query<out T>>>
) {
private val myHelper = PsiSearchHelper.getInstance(project) as PsiSearchHelperImpl
fun runLayer(processor: Processor<in T>): LayerResult<T> {
if (!processQueryRequests(progress, queryRequests, processor)) {
return LayerResult.Stop
}
val subQueries = ArrayList<Query<out T>>()
val subQueryProcessor: Processor<Query<out T>> = synchronizedCollectProcessor(subQueries)
if (!processWordRequests(processor, subQueryProcessor)) {
return LayerResult.Stop
}
processQueryRequests(progress, subQueryQueryRequests, subQueryProcessor)
return LayerResult.Ok(subQueries)
}
private fun processWordRequests(processor: Processor<in T>, subQueryProcessor: Processor<in Query<out T>>): Boolean {
if (wordRequests.isEmpty() && subQueryWordRequests.isEmpty()) {
return true
}
val allRequests: Collection<RequestAndProcessors> = distributeWordRequests(processor, subQueryProcessor)
val globals = SmartList<RequestAndProcessors>()
val locals = SmartList<RequestAndProcessors>()
for (requestAndProcessor: RequestAndProcessors in allRequests) {
if (requestAndProcessor.request.searchScope is LocalSearchScope) {
locals += requestAndProcessor
}
else {
globals += requestAndProcessor
}
}
return processGlobalRequests(globals)
&& processLocalRequests(locals)
}
private fun distributeWordRequests(processor: Processor<in T>,
subQueryProcessor: Processor<in Query<out T>>): Collection<RequestAndProcessors> {
val theMap = LinkedHashMap<
WordRequestInfo,
Pair<
MutableCollection<OccurrenceProcessor>,
MutableMap<LanguageInfo, MutableCollection<OccurrenceProcessor>>
>
>()
fun <X> distribute(requests: Collection<WordRequest<X>>, processor: Processor<in X>) {
for (wordRequest: WordRequest<X> in requests) {
progress.checkCanceled()
val byRequest = theMap.getOrPut(wordRequest.searchWordRequest) {
Pair(SmartList(), LinkedHashMap())
}
val occurrenceProcessors: MutableCollection<OccurrenceProcessor> = when (val injectionInfo = wordRequest.injectionInfo) {
InjectionInfo.NoInjection -> byRequest.first
is InjectionInfo.InInjection -> byRequest.second.getOrPut(injectionInfo.languageInfo) {
SmartList()
}
}
occurrenceProcessors += wordRequest.occurrenceProcessor(processor)
}
}
distribute(wordRequests, processor)
distribute(subQueryWordRequests, subQueryProcessor)
return theMap.map { (wordRequest: WordRequestInfo, byRequest) ->
progress.checkCanceled()
val (hostProcessors, injectionProcessors) = byRequest
RequestAndProcessors(wordRequest, RequestProcessors(hostProcessors, injectionProcessors))
}
}
private fun processGlobalRequests(globals: Collection<RequestAndProcessors>): Boolean {
if (globals.isEmpty()) {
return true
}
else if (globals.size == 1) {
return processSingleRequest(globals.first())
}
val globalsIds: Map<Set<IdIndexEntry>, List<WordRequestInfo>> = globals.groupBy(
{ (request: WordRequestInfo, _) -> PsiSearchHelperImpl.getWordEntries(request.word, request.isCaseSensitive).toSet() },
{ (request: WordRequestInfo, _) -> progress.checkCanceled(); request }
)
return myHelper.processGlobalRequests(globalsIds, progress, scopeProcessors(globals))
}
private fun scopeProcessors(globals: Collection<RequestAndProcessors>): Map<WordRequestInfo, Processor<in PsiElement>> {
val result = THashMap<WordRequestInfo, Processor<in PsiElement>>()
for (requestAndProcessors: RequestAndProcessors in globals) {
progress.checkCanceled()
result[requestAndProcessors.request] = scopeProcessor(requestAndProcessors)
}
return result
}
private fun scopeProcessor(requestAndProcessors: RequestAndProcessors): Processor<in PsiElement> {
val (request: WordRequestInfo, processors: RequestProcessors) = requestAndProcessors
val searcher = StringSearcher(request.word, request.isCaseSensitive, true, false)
val adapted = MyBulkOccurrenceProcessor(project, processors)
return PsiSearchHelperImpl.localProcessor(searcher, adapted)
}
private fun processLocalRequests(locals: Collection<RequestAndProcessors>): Boolean {
if (locals.isEmpty()) {
return true
}
for (requestAndProcessors: RequestAndProcessors in locals) {
progress.checkCanceled()
if (!processSingleRequest(requestAndProcessors)) return false
}
return true
}
private fun processSingleRequest(requestAndProcessors: RequestAndProcessors): Boolean {
val (request: WordRequestInfo, processors: RequestProcessors) = requestAndProcessors
val options = EnumSet.of(PsiSearchHelperImpl.Options.PROCESS_ONLY_JAVA_IDENTIFIERS_IF_POSSIBLE)
if (request.isCaseSensitive) options.add(PsiSearchHelperImpl.Options.CASE_SENSITIVE_SEARCH)
return myHelper.bulkProcessElementsWithWord(
request.searchScope,
request.word,
request.searchContext,
options,
request.containerName,
MyBulkOccurrenceProcessor(project, processors)
)
}
}
private fun <R> processQueryRequests(progress: ProgressIndicator,
requests: Collection<QueryRequest<*, R>>,
processor: Processor<in R>): Boolean {
if (requests.isEmpty()) {
return true
}
val map: Map<Query<*>, List<Transformation<*, R>>> = requests.groupBy({ it.query }, { it.transformation })
for ((query: Query<*>, transforms: List<Transformation<*, R>>) in map.iterator()) {
progress.checkCanceled()
@Suppress("UNCHECKED_CAST")
if (!runQueryRequest(query as Query<Any>, transforms as Collection<Transformation<Any, R>>, processor)) {
return false
}
}
return true
}
private fun <B, R> runQueryRequest(query: Query<out B>,
transformations: Collection<Transformation<B, R>>,
processor: Processor<in R>): Boolean {
return query.forEach(fun(baseValue: B): Boolean {
for (transformation: Transformation<B, R> in transformations) {
for (resultValue: R in transformation(baseValue)) {
if (!processor.process(resultValue)) {
return false
}
}
}
return true
})
}
private fun <T> synchronizedCollectProcessor(subQueries: MutableCollection<in T>): Processor<T> {
val lock = ObjectUtils.sentinel("synchronizedCollectProcessor")
return Processor {
synchronized(lock) {
subQueries += it
}
true
}
}
private data class RequestAndProcessors(
val request: WordRequestInfo,
val processors: RequestProcessors
)
internal class RequestProcessors(
val hostProcessors: Collection<OccurrenceProcessor>,
val injectionProcessors: Map<LanguageInfo, Collection<OccurrenceProcessor>>
)
| apache-2.0 | 5c86d9eed83576cf94b768eb0d45a5de | 38.676923 | 140 | 0.72501 | 4.804396 | false | false | false | false |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/PackageManagementPanel.kt | 1 | 7661 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.ui.JBSplitter
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.actions.ShowSettingsAction
import com.jetbrains.packagesearch.intellij.plugin.actions.TogglePackageDetailsAction
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.LifetimeProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.RootDataModelProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SearchClient
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SelectedPackageSetter
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModuleSetter
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.modules.ModulesTree
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails.PackageDetailsPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesListPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.rd.util.reactive.map
import java.awt.Dimension
import javax.swing.BorderFactory
import javax.swing.JScrollPane
@Suppress("MagicNumber") // Thanks Swing
internal class PackageManagementPanel(
private val rootDataModelProvider: RootDataModelProvider,
selectedPackageSetter: SelectedPackageSetter,
targetModuleSetter: TargetModuleSetter,
searchClient: SearchClient,
operationExecutor: OperationExecutor,
lifetimeProvider: LifetimeProvider
) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.title")), Disposable {
private val operationFactory = PackageSearchOperationFactory()
private val modulesTree = ModulesTree(targetModuleSetter)
private val modulesScrollPanel = JBScrollPane(
modulesTree,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
)
private val packagesListPanel = PackagesListPanel(
project = rootDataModelProvider.project,
searchClient = searchClient,
lifetimeProvider = lifetimeProvider,
operationExecutor = operationExecutor,
operationFactory = operationFactory
)
private val packageDetailsPanel = PackageDetailsPanel(operationFactory, operationExecutor)
private val packagesSplitter = JBSplitter(
"PackageSearch.PackageManagementPanel.DetailsSplitter",
PackageSearchGeneralConfiguration.DefaultPackageDetailsSplitterProportion
).apply {
firstComponent = packagesListPanel.content
secondComponent = packageDetailsPanel.content
orientation = false // Horizontal split
dividerWidth = 2.scaled()
}
private val mainSplitter = JBSplitter("PackageSearch.PackageManagementPanel.Splitter", 0.1f).apply {
firstComponent = modulesScrollPanel
secondComponent = packagesSplitter
orientation = false // Horizontal split
dividerWidth = 2.scaled()
}
init {
updatePackageDetailsVisible(PackageSearchGeneralConfiguration.getInstance(rootDataModelProvider.project).packageDetailsVisible)
modulesScrollPanel.apply {
border = BorderFactory.createEmptyBorder()
minimumSize = Dimension(250.scaled(), 0)
UIUtil.putClientProperty(verticalScrollBar, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true)
}
packagesListPanel.content.minimumSize = Dimension(250.scaled(), 0)
packagesListPanel.selectedPackage.advise(lifetimeProvider.lifetime) { selectedPackage ->
selectedPackageSetter.setSelectedPackage(selectedPackage)
packageDetailsPanel.display(
selectedPackageModel = selectedPackage,
knownRepositories = rootDataModelProvider.dataModelProperty.value.knownRepositoryModels,
targetModules = rootDataModelProvider.dataModelProperty.value.targetModules,
onlyStable = rootDataModelProvider.dataModelProperty.value.filterOptions.onlyStable
)
}
rootDataModelProvider.statusProperty.advise(lifetimeProvider.lifetime) { status ->
packagesListPanel.setIsBusy(status.isBusy)
}
rootDataModelProvider.statusProperty.map { it.isExecutingOperations }.advise(lifetimeProvider.lifetime) { isExecutingOperations ->
content.isEnabled = !isExecutingOperations
content.updateAndRepaint()
}
rootDataModelProvider.dataModelProperty.advise(lifetimeProvider.lifetime) { data ->
modulesTree.display(
projectModules = data.projectModules,
targetModules = data.targetModules,
traceInfo = data.traceInfo
)
packagesListPanel.display(
headerData = data.headerData,
packageModels = data.packageModels,
targetModules = data.targetModules,
installedKnownRepositories = data.knownRepositoryModels,
filterOptions = data.filterOptions,
traceInfo = data.traceInfo
)
packageDetailsPanel.display(
selectedPackageModel = data.selectedPackage,
knownRepositories = data.knownRepositoryModels,
targetModules = data.targetModules,
onlyStable = data.filterOptions.onlyStable
)
}
}
private fun updatePackageDetailsVisible(becomeVisible: Boolean) {
val wasVisible = packagesSplitter.secondComponent.isVisible
packagesSplitter.secondComponent.isVisible = becomeVisible
if (!wasVisible && becomeVisible) {
packagesSplitter.proportion = PackageSearchGeneralConfiguration.getInstance(rootDataModelProvider.project).packageDetailsSplitterProportion
}
if (!becomeVisible) {
PackageSearchGeneralConfiguration.getInstance(rootDataModelProvider.project).packageDetailsSplitterProportion = packagesSplitter.proportion
packagesSplitter.proportion = 1.0f
}
}
private val togglePackageDetailsAction = TogglePackageDetailsAction(rootDataModelProvider.project, ::updatePackageDetailsVisible)
override fun build() = mainSplitter
override fun buildGearActions() = DefaultActionGroup(
ShowSettingsAction(rootDataModelProvider.project),
togglePackageDetailsAction
)
override fun buildTitleActions(): Array<AnAction> = arrayOf(togglePackageDetailsAction)
override fun dispose() {
logDebug("PackageManagementPanel#dispose()") { "Disposing PackageManagementPanel..." }
modulesTree.dispose()
packagesListPanel.dispose()
}
}
| apache-2.0 | db429752aa32a17835aef1820f3ddcb6 | 46.290123 | 151 | 0.757603 | 5.543415 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/JarOrderStarter.kt | 1 | 3341 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.plugins
import com.intellij.openapi.application.ApplicationStarter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.text.StringUtil
import java.io.File
import kotlin.reflect.full.memberFunctions
import kotlin.reflect.jvm.isAccessible
import kotlin.streams.toList
import kotlin.system.exitProcess
/**
* This class is used in build scripts for providing classes and modules loading orders.
*
* Performance tests show 200ms startup performance improvement after adding jar files order
* Performance tests (mostly Windows) show 600ms startup performance improvement after reordering classes in jar files
*/
@Suppress("UNCHECKED_CAST")
class JarOrderStarter : ApplicationStarter {
override fun getCommandName(): String = "jarOrder"
override fun main(args: Array<String>) {
try {
generateJarAccessLog(JarOrderStarter::class.java.classLoader, args[1])
generateClassesAccessLog(JarOrderStarter::class.java.classLoader, args[2])
}
catch (e: Throwable) {
Logger.getInstance(JarOrderStarter::class.java).error(e)
}
finally {
exitProcess(0)
}
}
/**
* Generates module loading order file.
*
* We cannot start this code on the final jar-s so the output contains mostly module paths (jar only for libraries):
* path/to/intellij.platform.bootstrap
* path/to/intellij.platform.impl
* path/to/log4j-1.4.5.jar
* path/to/trove-4.4.4.jar
* path/to/intellij.platform.api
* ...
* Afterward the build scripts convert the output file to the final list of jar files (classpath-order.txt)
*/
fun generateJarAccessLog(loader: ClassLoader, path: String?) {
// Must use reflection because the classloader class is loaded with a different classloader
val accessor = loader::class.memberFunctions.find { it.name == "getJarAccessLog" }
?: throw Exception("Can't find getJarAccessLog() method")
val log = accessor.call(loader) as? Collection<String> ?: throw Exception("Unexpected return type of getJarAccessLog()")
val result = log
.stream()
.map { it.removePrefix("jar:").removePrefix("file:").removeSuffix("!/").removeSuffix("/") }
.toList()
.joinToString("\n")
if (result.isNotEmpty()) {
File(path).writeText(result)
}
}
/**
* Generates class loading order file.
*
* Format:
* com/package/ClassName.class:path/to/intellij.platform.impl
* com/package2/ClassName2.class:path/to/module
* com/package3/ClassName3.class:path/to/some.jar
*/
private fun generateClassesAccessLog(loader: ClassLoader, path: String?) {
val classPathMember = loader::class.memberFunctions.find { it.name == "getClassPath" }
classPathMember?.isAccessible = true
val result = classPathMember?.call(loader) ?: return
val javaClass = result.javaClass
val field = javaClass.getDeclaredField("ourLoadedClasses")
field.isAccessible = true
val log = field.get(null) as? Collection<String> ?: throw Exception("Unexpected type of ourLoadedClasses")
if (log.isNotEmpty()) {
synchronized(log) {
File(path).writeText(StringUtil.join(log, "\n"))
}
}
}
}
| apache-2.0 | 81a944c2c3cf83cb5f874b20a4c49a6b | 37.402299 | 140 | 0.714157 | 4.134901 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/ui/advanced/apps/AppsFilterFragment.kt | 1 | 2164 | /*
* This file is part of Blokada.
*
* 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 https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui.advanced.apps
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import org.blokada.R
import ui.BottomSheetFragment
class AppsFilterFragment : BottomSheetFragment() {
companion object {
fun newInstance() = AppsFilterFragment()
}
private lateinit var viewModel: AppsViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
activity?.run {
viewModel = ViewModelProvider(this).get(AppsViewModel::class.java)
}
val root = inflater.inflate(R.layout.fragment_apps_filter, container, false)
val back: View = root.findViewById(R.id.back)
back.setOnClickListener {
dismiss()
}
val cancel: View = root.findViewById(R.id.cancel)
cancel.setOnClickListener {
dismiss()
}
val all: View = root.findViewById(R.id.app_filterall)
all.setOnClickListener {
viewModel.filter(AppsViewModel.Filter.ALL)
dismiss()
}
val blocked: View = root.findViewById(R.id.app_filterbypassed)
blocked.setOnClickListener {
viewModel.filter(AppsViewModel.Filter.BYPASSED)
dismiss()
}
val allowed: View = root.findViewById(R.id.app_filternotbypassed)
allowed.setOnClickListener {
viewModel.filter(AppsViewModel.Filter.NOT_BYPASSED)
dismiss()
}
val toggle: View = root.findViewById(R.id.app_togglesystem)
toggle.setOnClickListener {
viewModel.switchBypassForAllSystemApps()
dismiss()
}
return root
}
} | mpl-2.0 | a4bb8af33d58dcceb4c2631c18a87e3e | 26.74359 | 84 | 0.649561 | 4.432377 | false | false | false | false |
jguerinet/Suitcase | settings/src/main/java/com/guerinet/suitcase/settings/NullStringSetting.kt | 2 | 1536 | /*
* Copyright 2016-2021 Julien Guerinet
*
* 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.guerinet.suitcase.settings
import com.russhwolf.settings.ExperimentalSettingsApi
import com.russhwolf.settings.Settings
import com.russhwolf.settings.coroutines.getStringOrNullFlow
import com.russhwolf.settings.set
import kotlinx.coroutines.flow.Flow
/**
* Helper class for nullable String settings
* @author Julien Guerinet
* @since 7.0.0
*/
open class NullStringSetting(settings: Settings, key: String, defaultValue: String? = null) :
BaseSetting<String?>(settings, key, defaultValue) {
override var value: String?
get() = settings.getStringOrNull(key) ?: defaultValue
set(value) = set(value)
override fun set(value: String?) {
if (!value.isNullOrEmpty()) {
settings[key] = value
} else {
settings.clear()
}
}
@ExperimentalSettingsApi
override fun asFlow(): Flow<String?> = observableSettings.getStringOrNullFlow(key)
}
| apache-2.0 | 7b765d22d4692edfc9c52ca70535cfab | 31.680851 | 93 | 0.718099 | 4.162602 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/whenToAssignment/cascadeWhen.kt | 9 | 385 | // WITH_STDLIB
fun test(x: Any) {
var res: String
<caret>when (x) {
is String ->
if (x.length > 3) res = "long string"
else res = "short string"
is Int ->
if (x > 999 || x < -99) res = "long int"
else res = "short int"
is Long ->
TODO()
else ->
res = "I don't know"
}
} | apache-2.0 | 0ab403750f834fb4306191893dd6285b | 23.125 | 52 | 0.407792 | 3.598131 | false | true | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/project/ProjectRootManagerBridge.kt | 3 | 14018 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.project
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.RootProvider
import com.intellij.openapi.roots.RootProvider.RootSetChangedListener
import com.intellij.openapi.roots.impl.OrderRootsCache
import com.intellij.openapi.roots.impl.ProjectRootManagerComponent
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar.APPLICATION_LEVEL
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.util.containers.BidirectionalMultiMap
import com.intellij.util.containers.MultiMap
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.OrderRootsCacheBridge
import com.intellij.workspaceModel.storage.EntityChange
import com.intellij.workspaceModel.storage.VersionedStorageChange
import com.intellij.workspaceModel.storage.bridgeEntities.*
class ProjectRootManagerBridge(project: Project) : ProjectRootManagerComponent(project) {
companion object {
private const val LIBRARY_NAME_DELIMITER = ":"
@JvmStatic
private val LOG = logger<ProjectRootManagerBridge>()
}
private val globalLibraryTableListener = GlobalLibraryTableListener()
private val jdkChangeListener = JdkChangeListener()
init {
if (!project.isDefault) {
val bus = project.messageBus.connect(this)
WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(bus, object : WorkspaceModelChangeListener {
override fun changed(event: VersionedStorageChange) {
if (myProject.isDisposed) return
// Roots changed event should be fired for the global libraries linked with module
val moduleChanges = event.getChanges(ModuleEntity::class.java)
for (change in moduleChanges) {
when (change) {
is EntityChange.Added -> addTrackedLibraryAndJdkFromEntity(change.entity)
is EntityChange.Removed -> removeTrackedLibrariesAndJdkFromEntity(change.entity)
is EntityChange.Replaced -> {
removeTrackedLibrariesAndJdkFromEntity(change.oldEntity)
addTrackedLibraryAndJdkFromEntity(change.newEntity)
}
}
}
}
})
bus.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, jdkChangeListener)
}
}
override fun getActionToRunWhenProjectJdkChanges(): Runnable {
return Runnable {
super.getActionToRunWhenProjectJdkChanges().run()
if (jdkChangeListener.hasProjectSdkDependency()) fireRootsChanged()
}
}
override fun projectClosed() {
super.projectClosed()
unsubscribeListeners()
}
override fun dispose() {
super.dispose()
unsubscribeListeners()
}
override fun getOrderRootsCache(project: Project): OrderRootsCache {
return OrderRootsCacheBridge(project, project)
}
fun isFiringEvent(): Boolean = isFiringEvent
private fun unsubscribeListeners() {
if (project.isDefault) return
val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance()
val globalLibraryTable = libraryTablesRegistrar.libraryTable
globalLibraryTableListener.getLibraryLevels().forEach { libraryLevel ->
val libraryTable = when (libraryLevel) {
APPLICATION_LEVEL -> globalLibraryTable
else -> libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project)
}
libraryTable?.libraryIterator?.forEach { (it as? RootProvider)?.removeRootSetChangedListener(globalLibraryTableListener) }
libraryTable?.removeListener(globalLibraryTableListener)
}
globalLibraryTableListener.clear()
jdkChangeListener.unsubscribeListeners()
}
fun setupTrackedLibrariesAndJdks() {
val currentStorage = WorkspaceModel.getInstance(project).entityStorage.current
for (moduleEntity in currentStorage.entities(ModuleEntity::class.java)) {
addTrackedLibraryAndJdkFromEntity(moduleEntity)
}
}
private fun addTrackedLibraryAndJdkFromEntity(moduleEntity: ModuleEntity) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
LOG.debug { "Add tracked global libraries and JDK from ${moduleEntity.name}" }
val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance()
moduleEntity.dependencies.forEach {
when {
it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId is LibraryTableId.GlobalLibraryTableId -> {
val libraryName = it.library.name
val libraryLevel = it.library.tableId.level
val libraryTable = libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project) ?: return@forEach
if (globalLibraryTableListener.isEmpty(libraryLevel)) libraryTable.addListener(globalLibraryTableListener)
globalLibraryTableListener.addTrackedLibrary(moduleEntity, libraryTable, libraryName)
}
it is ModuleDependencyItem.SdkDependency || it is ModuleDependencyItem.InheritedSdkDependency -> {
jdkChangeListener.addTrackedJdk(it, moduleEntity)
}
}
}
}
private fun removeTrackedLibrariesAndJdkFromEntity(moduleEntity: ModuleEntity) {
LOG.debug { "Removed tracked global libraries and JDK from ${moduleEntity.name}" }
val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance()
moduleEntity.dependencies.forEach {
when {
it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId is LibraryTableId.GlobalLibraryTableId -> {
val libraryName = it.library.name
val libraryLevel = it.library.tableId.level
val libraryTable = libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project) ?: return@forEach
globalLibraryTableListener.unTrackLibrary(moduleEntity, libraryTable, libraryName)
if (globalLibraryTableListener.isEmpty(libraryLevel)) libraryTable.removeListener(globalLibraryTableListener)
}
it is ModuleDependencyItem.SdkDependency || it is ModuleDependencyItem.InheritedSdkDependency -> {
jdkChangeListener.removeTrackedJdk(it, moduleEntity)
}
}
}
}
private fun fireRootsChanged() {
if (myProject.isOpen) {
makeRootsChange(EmptyRunnable.INSTANCE, false, true)
}
}
// Listener for global libraries linked to module
private inner class GlobalLibraryTableListener : LibraryTable.Listener, RootSetChangedListener {
private val librariesPerModuleMap = BidirectionalMultiMap<ModuleId, String>()
private var insideRootsChange = false
fun addTrackedLibrary(moduleEntity: ModuleEntity, libraryTable: LibraryTable, libraryName: String) {
val library = libraryTable.getLibraryByName(libraryName)
val libraryIdentifier = getLibraryIdentifier(libraryTable, libraryName)
if (!librariesPerModuleMap.containsValue(libraryIdentifier)) {
(library as? RootProvider)?.addRootSetChangedListener(this)
}
librariesPerModuleMap.put(moduleEntity.persistentId(), libraryIdentifier)
}
fun unTrackLibrary(moduleEntity: ModuleEntity, libraryTable: LibraryTable, libraryName: String) {
val library = libraryTable.getLibraryByName(libraryName)
val libraryIdentifier = getLibraryIdentifier(libraryTable, libraryName)
librariesPerModuleMap.remove(moduleEntity.persistentId(), libraryIdentifier)
if (!librariesPerModuleMap.containsValue(libraryIdentifier)) {
(library as? RootProvider)?.removeRootSetChangedListener(this)
}
}
fun isEmpty(libraryLevel: String) = librariesPerModuleMap.values.none { it.startsWith("$libraryLevel$LIBRARY_NAME_DELIMITER") }
fun getLibraryLevels() = librariesPerModuleMap.values.mapTo(HashSet()) { it.substringBefore(LIBRARY_NAME_DELIMITER) }
override fun afterLibraryAdded(newLibrary: Library) {
if (librariesPerModuleMap.containsValue(getLibraryIdentifier(newLibrary))) fireRootsChanged()
}
override fun afterLibraryRemoved(library: Library) {
if (librariesPerModuleMap.containsValue(getLibraryIdentifier(library))) fireRootsChanged()
}
override fun afterLibraryRenamed(library: Library, oldName: String?) {
val libraryTable = library.table
val newName = library.name
if (libraryTable != null && oldName != null && newName != null) {
val affectedModules = librariesPerModuleMap.getKeys(getLibraryIdentifier(libraryTable, oldName))
if (affectedModules.isNotEmpty()) {
val libraryTableId = LibraryNameGenerator.getLibraryTableId(libraryTable.tableLevel)
WorkspaceModel.getInstance(myProject).updateProjectModel { builder ->
//maybe it makes sense to simplify this code by reusing code from PEntityStorageBuilder.updateSoftReferences
affectedModules.mapNotNull { builder.resolve(it) }.forEach { module ->
val updated = module.dependencies.map {
when {
it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId == libraryTableId && it.library.name == oldName ->
it.copy(library = LibraryId(newName, libraryTableId))
else -> it
}
}
builder.modifyEntity(ModifiableModuleEntity::class.java, module) {
dependencies = updated
}
}
}
}
}
}
override fun rootSetChanged(wrapper: RootProvider) {
if (insideRootsChange) return
insideRootsChange = true
try {
fireRootsChanged()
}
finally {
insideRootsChange = false
}
}
private fun getLibraryIdentifier(library: Library) = "${library.table.tableLevel}$LIBRARY_NAME_DELIMITER${library.name}"
private fun getLibraryIdentifier(libraryTable: LibraryTable,
libraryName: String) = "${libraryTable.tableLevel}$LIBRARY_NAME_DELIMITER$libraryName"
fun clear() = librariesPerModuleMap.clear()
}
private inner class JdkChangeListener : ProjectJdkTable.Listener, RootSetChangedListener {
private val sdkDependencies = MultiMap.createSet<ModuleDependencyItem, ModuleId>()
private val watchedSdks = HashSet<RootProvider>()
override fun jdkAdded(jdk: Sdk) {
if (hasDependencies(jdk)) {
if (watchedSdks.add(jdk.rootProvider)) {
jdk.rootProvider.addRootSetChangedListener(this)
}
fireRootsChanged()
}
}
override fun jdkNameChanged(jdk: Sdk, previousName: String) {
val sdkDependency = ModuleDependencyItem.SdkDependency(previousName, jdk.sdkType.name)
val affectedModules = sdkDependencies.get(sdkDependency)
if (affectedModules.isNotEmpty()) {
WorkspaceModel.getInstance(myProject).updateProjectModel { builder ->
for (moduleId in affectedModules) {
val module = moduleId.resolve(builder) ?: continue
val updated = module.dependencies.map {
when (it) {
is ModuleDependencyItem.SdkDependency -> ModuleDependencyItem.SdkDependency(jdk.name, jdk.sdkType.name)
else -> it
}
}
builder.modifyEntity(ModifiableModuleEntity::class.java, module) {
dependencies = updated
}
}
}
}
}
override fun jdkRemoved(jdk: Sdk) {
if (watchedSdks.remove(jdk.rootProvider)) {
jdk.rootProvider.removeRootSetChangedListener(this)
}
if (hasDependencies(jdk)) {
fireRootsChanged()
}
}
override fun rootSetChanged(wrapper: RootProvider) {
fireRootsChanged()
}
fun addTrackedJdk(sdkDependency: ModuleDependencyItem, moduleEntity: ModuleEntity) {
val sdk = findSdk(sdkDependency)
if (sdk != null && watchedSdks.add(sdk.rootProvider)) {
sdk.rootProvider.addRootSetChangedListener(this)
}
sdkDependencies.putValue(sdkDependency, moduleEntity.persistentId())
}
fun removeTrackedJdk(sdkDependency: ModuleDependencyItem, moduleEntity: ModuleEntity) {
sdkDependencies.remove(sdkDependency, moduleEntity.persistentId())
val sdk = findSdk(sdkDependency)
if (sdk != null && !hasDependencies(sdk) && watchedSdks.remove(sdk.rootProvider)) {
sdk.rootProvider.removeRootSetChangedListener(this)
}
}
fun hasProjectSdkDependency(): Boolean {
return sdkDependencies.get(ModuleDependencyItem.InheritedSdkDependency).isNotEmpty()
}
private fun findSdk(sdkDependency: ModuleDependencyItem): Sdk? = when (sdkDependency) {
is ModuleDependencyItem.InheritedSdkDependency -> projectSdk
is ModuleDependencyItem.SdkDependency -> ProjectJdkTable.getInstance().findJdk(sdkDependency.sdkName, sdkDependency.sdkType)
else -> null
}
private fun hasDependencies(jdk: Sdk): Boolean {
return sdkDependencies.get(ModuleDependencyItem.SdkDependency(jdk.name, jdk.sdkType.name)).isNotEmpty()
|| jdk.name == projectSdkName && jdk.sdkType.name == projectSdkTypeName && hasProjectSdkDependency()
}
fun unsubscribeListeners() {
watchedSdks.forEach {
it.removeRootSetChangedListener(this)
}
watchedSdks.clear()
}
}
} | apache-2.0 | eaae3b56634c9b3e43f50491b28ba3d2 | 42.135385 | 146 | 0.726994 | 5.309848 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/multiplatform/multiplatformLibrary/common/common.kt | 3 | 374 | package sample
expect class <!LINE_MARKER("descr='Has actuals in JVM, JS'")!>Sample<!>() {
fun <!LINE_MARKER("descr='Has actuals in JVM, JS'")!>checkMe<!>(): Int
}
expect object <!LINE_MARKER("descr='Has actuals in JVM, JS'")!>Platform<!> {
val <!LINE_MARKER("descr='Has actuals in JVM, JS'")!>name<!>: String
}
fun hello(): String = "Hello from ${Platform.name}" | apache-2.0 | 51189fab529d7c9475f70925945b1f26 | 33.090909 | 76 | 0.639037 | 3.666667 | false | false | false | false |
smmribeiro/intellij-community | plugins/ide-features-trainer/src/training/statistic/SupportedLanguageRuleValidator.kt | 1 | 1161 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.statistic
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor
import training.lang.LangManager
import training.statistic.FeatureUsageStatisticConsts.LANGUAGE
private class SupportedLanguageRuleValidator : CustomValidationRule() {
override fun acceptRuleId(ruleId: String?): Boolean = (LANGUAGE == ruleId)
override fun doValidate(data: String, context: EventContext): ValidationResultType {
val langSupport = LangManager.getInstance().supportedLanguagesExtensions.find {
getPluginInfoByDescriptor(it.pluginDescriptor).isDevelopedByJetBrains() && it.language.equals(data, ignoreCase = true)
}
if (langSupport != null) {
return ValidationResultType.ACCEPTED
}
return ValidationResultType.REJECTED
}
} | apache-2.0 | 550284264c515437817014f4ee586e08 | 49.521739 | 140 | 0.81137 | 5.047826 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/fragments/CheckoutRiskMessageFragment.kt | 1 | 5220 | package com.kickstarter.ui.fragments
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.kickstarter.R
import com.kickstarter.databinding.FragmentCheckoutRiskMessageBinding
import com.kickstarter.libs.BaseBottomSheetDialogFragment
import com.kickstarter.libs.qualifiers.RequiresFragmentViewModel
import com.kickstarter.libs.utils.ApplicationUtils
import com.kickstarter.libs.utils.extensions.parseHtmlTag
import com.kickstarter.ui.extensions.makeLinks
import com.kickstarter.ui.extensions.parseHtmlTag
import com.kickstarter.viewmodels.CheckoutRiskMessageFragmentViewModel
import rx.android.schedulers.AndroidSchedulers
@RequiresFragmentViewModel(CheckoutRiskMessageFragmentViewModel.ViewModel::class)
class CheckoutRiskMessageFragment : BaseBottomSheetDialogFragment <CheckoutRiskMessageFragmentViewModel.ViewModel>() {
interface Delegate {
fun onDialogConfirmButtonClicked()
}
companion object {
fun newInstance(delegate: Delegate):
CheckoutRiskMessageFragment {
val fragment = CheckoutRiskMessageFragment().apply {
this.delegate = delegate
}
return fragment
}
}
private var binding: FragmentCheckoutRiskMessageBinding? = null
private var delegate: Delegate? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.BottomSheetDialogStyle)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
binding = FragmentCheckoutRiskMessageBinding.inflate(inflater, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val resources = resources
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
val parent = view.parent as View
parent.setPadding(
resources.getDimensionPixelSize(R.dimen.grid_15_half), // LEFT 16dp
0,
resources.getDimensionPixelSize(R.dimen.grid_15_half), // RIGHT 16dp
0
)
val layoutParams = parent.layoutParams as CoordinatorLayout.LayoutParams
layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
parent.layoutParams = layoutParams
}
binding?.confirm?.setOnClickListener {
delegate?.onDialogConfirmButtonClicked()
dismissDialog()
}
viewModel.outputs.openLearnMoreAboutAccountabilityLink()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
context?.let { context ->
ApplicationUtils.openUrlExternally(context, it)
}
}
(dialog as? BottomSheetDialog)?.let {
it.findViewById<FrameLayout>(
com.google.android.material.R.id
.design_bottom_sheet
)?.let { bottomSheet ->
val bottomSheetBehavior: BottomSheetBehavior<*> = BottomSheetBehavior.from(bottomSheet)
bottomSheetBehavior.addBottomSheetCallback(object :
BottomSheetBehavior.BottomSheetCallback() {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
}
override fun onStateChanged(bottomSheet: View, newState: Int) {
if (newState == BottomSheetBehavior.STATE_COLLAPSED || newState ==
BottomSheetBehavior.STATE_HIDDEN
) {
dismissDialog()
}
}
})
}
}
binding?.learnMoreAboutAccountabilityTv?.parseHtmlTag()
context?.resources?.getString(R.string.Learn_more_about_accountability)?.let {
val args = Pair(
it,
View.OnClickListener {
this.viewModel.inputs.onLearnMoreAboutAccountabilityLinkClicked()
},
)
binding?.learnMoreAboutAccountabilityTv?.makeLinks(
args,
linkColor = R.color.text_primary,
isUnderlineText = true
)
}
}
fun dismissDialog() {
dismiss()
}
override fun onStart() {
super.onStart()
// this forces the sheet to appear at max height even on landscape
val behavior = BottomSheetBehavior.from(requireView().parent as View)
behavior.state = BottomSheetBehavior.STATE_EXPANDED
}
}
| apache-2.0 | de2010fefe098a63c44fd554b63dffa7 | 38.847328 | 118 | 0.64751 | 5.931818 | false | false | false | false |
korotyx/VirtualEntity | src/main/kotlin/com/korotyx/virtualentity/base/VirtualEntityCollector.kt | 1 | 1035 | @file:JvmName("VirtualEntityCollector")
package com.korotyx.virtualentity.base
import com.korotyx.virtualentity.system.GenericIdentity
import java.util.*
abstract class VirtualEntityCollector<E : VirtualEntity<E>>: GenericIdentity<E>()
{
companion object
{
private val REGISTER_DATA : HashMap<Class<*>, VirtualEntityCollector<*>> = HashMap()
fun getVirtualCollector(c : Class<*>) = REGISTER_DATA[c]
}
private val entityCollector : ArrayList<E> = ArrayList()
@Suppress("UNCHECKED_CAST")
fun register(e : Any) : Boolean = entityCollector.add(e as E)
fun getEntity(obj : Any) : E?
{
val id : String = obj as String
return entityCollector.firstOrNull {
it.getUniqueId() == id
}
}
init
{
if(! isProvenCollector(this))
{
REGISTER_DATA.put(this.getGenericBaseType(), this)
}
}
private fun isProvenCollector(vec: VirtualEntityCollector<*>) = REGISTER_DATA.containsKey(vec.getGenericBaseType())
} | mit | 83411fb34a368869bf02553c12fa5720 | 26.263158 | 119 | 0.654106 | 4.14 | false | false | false | false |
Flank/flank | common/src/main/kotlin/flank/common/Archive.kt | 1 | 1708 | package flank.common
import org.rauschig.jarchivelib.ArchiveFormat
import org.rauschig.jarchivelib.ArchiverFactory
import org.rauschig.jarchivelib.CompressionType
import java.io.File
fun File.extract(
destination: File,
archiveFormat: ArchiveFormat = ArchiveFormat.AR,
compressFormat: CompressionType? = null
) {
println("Unpacking...$name")
val archiver = if (compressFormat != null) {
ArchiverFactory.createArchiver(archiveFormat, compressFormat)
} else {
ArchiverFactory.createArchiver(archiveFormat)
}
runCatching {
archiver.extract(this, destination)
}.onFailure {
println("There was an error when unpacking $name - $it")
}
}
fun File.extract(
destination: File,
archiveFormat: String,
compressFormat: String? = null
) {
println("Unpacking...$name")
val archiver = if (compressFormat != null) {
ArchiverFactory.createArchiver(archiveFormat, compressFormat)
} else {
ArchiverFactory.createArchiver(archiveFormat)
}
runCatching {
archiver.extract(this, destination)
}.onFailure {
println("There was an error when unpacking $name - $it")
}
}
fun List<File>.archive(
destinationFileName: String,
destinationDirectory: File,
archiveFormat: ArchiveFormat = ArchiveFormat.ZIP
) {
println("Packing...$destinationFileName")
val archiver = ArchiverFactory.createArchiver(archiveFormat)
runCatching {
archiver.create(destinationFileName, destinationDirectory, *toTypedArray())
}.onFailure {
println("There was an error when packing ${destinationDirectory.absolutePath}${File.separator}$destinationFileName - $it")
}
}
| apache-2.0 | 54d88264e5957563ceb4de2cd4f6222f | 29.5 | 130 | 0.704333 | 4.313131 | false | false | false | false |
ingokegel/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/archetype/CatalogUiUtil.kt | 8 | 2853 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.wizards.archetype
import com.intellij.openapi.ui.validation.validationErrorFor
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import org.jetbrains.idea.maven.indices.archetype.MavenCatalog
import org.jetbrains.idea.maven.indices.archetype.MavenCatalogManager
import org.jetbrains.idea.maven.wizards.MavenWizardBundle
import java.net.URL
import kotlin.io.path.Path
import kotlin.io.path.name
internal fun createCatalog(name: String, location: String): MavenCatalog? {
if (MavenCatalogManager.isLocal(location)) {
val path = getPathOrNull(location) ?: return null
return MavenCatalog.Local(name, path)
}
else {
val url = getUrlOrNull(location) ?: return null
return MavenCatalog.Remote(name, url)
}
}
internal fun createCatalog(location: String): MavenCatalog? {
if (location.isNotEmpty()) {
val name = suggestCatalogNameByLocation(location)
return createCatalog(name, location)
}
return null
}
internal fun getPathOrError(location: String) = runCatching { Path(FileUtil.expandUserHome(location)) }
internal fun getUrlOrError(location: String) = runCatching { URL(location) }
internal fun getPathOrNull(location: String) = getPathOrError(location).getOrNull()
internal fun getUrlOrNull(location: String) = getUrlOrError(location).getOrNull()
internal fun suggestCatalogNameByLocation(location: String): String {
if (MavenCatalogManager.isLocal(location)) {
return getPathOrNull(location)?.name?.nullize() ?: location
}
else {
return getUrlOrNull(location)?.host?.nullize() ?: location
}
}
val CHECK_MAVEN_CATALOG = validationErrorFor<String> { location ->
if (MavenCatalogManager.isLocal(location)) {
validateLocalLocation(location)
}
else {
validateRemoteLocation(location)
}
}
private fun validateLocalLocation(location: String): String? {
val pathOrError = getPathOrError(location)
val exception = pathOrError.exceptionOrNull()
if (exception != null) {
val message = exception.message
return MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.dialog.location.error.invalid", message)
}
val path = pathOrError.getOrThrow()
if (!path.exists()) {
return MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.dialog.location.error.not.exists")
}
return null
}
private fun validateRemoteLocation(location: String): String? {
val exception = getUrlOrError(location).exceptionOrNull()
if (exception != null) {
val message = exception.message
return MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.dialog.location.error.invalid", message)
}
return null
} | apache-2.0 | c681a45329e60d450a3075cd28f45aed | 34.675 | 121 | 0.767964 | 4.099138 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToStringTemplateIntention.kt | 1 | 6902 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.util.PsiUtilCore
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ConvertToStringTemplateInspection : IntentionBasedInspection<KtBinaryExpression>(
ConvertToStringTemplateIntention::class,
{ it -> ConvertToStringTemplateIntention.shouldSuggestToConvert(it) },
problemText = KotlinBundle.message("convert.concatenation.to.template.before.text")
)
open class ConvertToStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("convert.concatenation.to.template")
) {
override fun isApplicableTo(element: KtBinaryExpression): Boolean {
if (!isApplicableToNoParentCheck(element)) return false
val parent = element.parent
if (parent is KtBinaryExpression && isApplicableToNoParentCheck(parent)) return false
return true
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val replacement = buildReplacement(element)
runWriteAction {
element.replaced(replacement)
}
}
companion object {
fun shouldSuggestToConvert(expression: KtBinaryExpression): Boolean {
val entries = buildReplacement(expression).entries
return entries.none { it is KtBlockStringTemplateEntry }
&& !entries.all { it is KtLiteralStringTemplateEntry || it is KtEscapeStringTemplateEntry }
&& entries.count { it is KtLiteralStringTemplateEntry } >= 1
&& !expression.textContains('\n')
}
@JvmStatic
fun buildReplacement(expression: KtBinaryExpression): KtStringTemplateExpression {
val rightText = buildText(expression.right, false)
return fold(expression.left, rightText, KtPsiFactory(expression))
}
private fun fold(left: KtExpression?, right: String, factory: KtPsiFactory): KtStringTemplateExpression {
val forceBraces = right.isNotEmpty() && right.first() != '$' && right.first().isJavaIdentifierPart()
return if (left is KtBinaryExpression && isApplicableToNoParentCheck(left)) {
val leftRight = buildText(left.right, forceBraces)
fold(left.left, leftRight + right, factory)
} else {
val leftText = buildText(left, forceBraces)
factory.createExpression("\"$leftText$right\"") as KtStringTemplateExpression
}
}
fun buildText(expr: KtExpression?, forceBraces: Boolean): String {
if (expr == null) return ""
val expression = KtPsiUtil.safeDeparenthesize(expr).let {
when {
(it as? KtDotQualifiedExpression)?.isToString() == true -> it.receiverExpression
it is KtLambdaExpression && it.parent is KtLabeledExpression -> expr
else -> it
}
}
val expressionText = expression.text
when (expression) {
is KtConstantExpression -> {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val type = bindingContext.getType(expression)!!
val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext)
if (constant != null) {
val stringValue = constant.getValue(type).toString()
if (KotlinBuiltIns.isChar(type) || stringValue == expressionText) {
return buildString {
StringUtil.escapeStringCharacters(stringValue.length, stringValue, if (forceBraces) "\"$" else "\"", this)
}
}
}
}
is KtStringTemplateExpression -> {
val base = if (expressionText.startsWith("\"\"\"") && expressionText.endsWith("\"\"\"")) {
val unquoted = expressionText.substring(3, expressionText.length - 3)
StringUtil.escapeStringCharacters(unquoted)
} else {
StringUtil.unquoteString(expressionText)
}
if (forceBraces) {
if (base.endsWith('$')) {
return base.dropLast(1) + "\\$"
} else {
val lastPart = expression.children.lastOrNull()
if (lastPart is KtSimpleNameStringTemplateEntry) {
return base.dropLast(lastPart.textLength) + "\${" + lastPart.text.drop(1) + "}"
}
}
}
return base
}
is KtNameReferenceExpression ->
return "$" + (if (forceBraces) "{$expressionText}" else expressionText)
is KtThisExpression ->
return "$" + (if (forceBraces || expression.labelQualifier != null) "{$expressionText}" else expressionText)
}
return "\${$expressionText}"
}
private fun isApplicableToNoParentCheck(expression: KtBinaryExpression): Boolean {
if (expression.operationToken != KtTokens.PLUS) return false
val expressionType = expression.analyze(BodyResolveMode.PARTIAL).getType(expression)
if (!KotlinBuiltIns.isString(expressionType)) return false
return isSuitable(expression)
}
private fun isSuitable(expression: KtExpression): Boolean {
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.PLUS) {
return isSuitable(expression.left ?: return false) && isSuitable(expression.right ?: return false)
}
if (PsiUtilCore.hasErrorElementChild(expression)) return false
if (expression.textContains('\n')) return false
return true
}
}
}
| apache-2.0 | 1244eba8113e02ef9946e58682dd2589 | 45.952381 | 158 | 0.616343 | 5.980936 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinMethodFilter.kt | 1 | 5609 | // 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.debugger.stepping.smartStepInto
import com.intellij.debugger.PositionManager
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.NamedMethodFilter
import com.intellij.openapi.application.ReadAction
import com.intellij.util.Range
import com.sun.jdi.LocalVariable
import com.sun.jdi.Location
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.trimIfMangledInBytecode
import org.jetbrains.kotlin.idea.debugger.getInlineFunctionAndArgumentVariablesToBordersMap
import org.jetbrains.kotlin.idea.debugger.safeMethod
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate
import org.jetbrains.kotlin.resolve.DescriptorUtils
open class KotlinMethodFilter(
declaration: KtDeclaration?,
private val lines: Range<Int>?,
private val methodInfo: CallableMemberInfo
) : NamedMethodFilter {
private val declarationPtr = declaration?.createSmartPointer()
override fun locationMatches(process: DebugProcessImpl, location: Location): Boolean {
if (!nameMatches(location)) {
return false
}
return ReadAction.nonBlocking<Boolean> {
declarationMatches(process, location)
}.executeSynchronously()
}
private fun declarationMatches(process: DebugProcessImpl, location: Location): Boolean {
val (currentDescriptor, currentDeclaration) = getMethodDescriptorAndDeclaration(process.positionManager, location)
if (currentDescriptor == null || currentDeclaration == null) {
return false
}
@Suppress("FoldInitializerAndIfToElvis")
if (currentDescriptor !is CallableMemberDescriptor) return false
if (currentDescriptor.kind != CallableMemberDescriptor.Kind.DECLARATION) return false
if (methodInfo.isInvoke) {
// There can be only one 'invoke' target at the moment so consider position as expected.
// Descriptors can be not-equal, say when parameter has type `(T) -> T` and lambda is `Int.() -> Int`.
return true
}
// Element is lost. But we know that name matches, so stop.
val declaration = declarationPtr?.element ?: return true
val psiManager = currentDeclaration.manager
if (psiManager.areElementsEquivalent(currentDeclaration, declaration)) {
return true
}
return DescriptorUtils.getAllOverriddenDescriptors(currentDescriptor).any { baseOfCurrent ->
val currentBaseDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(currentDeclaration.project, baseOfCurrent)
psiManager.areElementsEquivalent(declaration, currentBaseDeclaration)
}
}
override fun getCallingExpressionLines(): Range<Int>? =
lines
override fun getMethodName(): String =
methodInfo.name
private fun nameMatches(location: Location): Boolean {
val method = location.safeMethod() ?: return false
val targetMethodName = methodName
val isNameMangledInBytecode = methodInfo.isNameMangledInBytecode
val actualMethodName = method.name().trimIfMangledInBytecode(isNameMangledInBytecode)
return actualMethodName == targetMethodName ||
actualMethodName == "$targetMethodName${JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX}" ||
// A correct way here is to memorize the original location (where smart step into was started)
// and filter out ranges that contain that original location.
// Otherwise, nested inline with the same method name will not work correctly.
method.getInlineFunctionAndArgumentVariablesToBordersMap()
.filter { location in it.value }
.any { it.key.isInlinedFromFunction(targetMethodName, isNameMangledInBytecode) }
}
}
private fun getMethodDescriptorAndDeclaration(
positionManager: PositionManager,
location: Location
): Pair<DeclarationDescriptor?, KtDeclaration?> {
val actualMethodName = location.safeMethod()?.name() ?: return null to null
val elementAt = positionManager.getSourcePosition(location)?.elementAt
val declaration = elementAt?.getParentOfTypesAndPredicate(false, KtDeclaration::class.java) {
it !is KtProperty || !it.isLocal
}
return if (declaration is KtClass && actualMethodName == "<init>") {
declaration.resolveToDescriptorIfAny()?.unsubstitutedPrimaryConstructor to declaration
} else {
declaration?.resolveToDescriptorIfAny() to declaration
}
}
private fun LocalVariable.isInlinedFromFunction(methodName: String, isNameMangledInBytecode: Boolean): Boolean {
val variableName = name().trimIfMangledInBytecode(isNameMangledInBytecode)
return variableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) &&
variableName.substringAfter(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) == methodName
}
| apache-2.0 | 51382facefa530d265c1448576372f13 | 46.533898 | 158 | 0.745409 | 5.435078 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/lambda/lambda9.kt | 4 | 731 | /*
* 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 codegen.lambda.lambda9
import kotlin.test.*
@Test fun runTest() {
val lambdas = ArrayList<() -> Unit>()
for (i in 0..1) {
var x = Integer(0)
val istr = i.toString()
lambdas.add {
println(istr)
println(x.toString())
x = x + 1
}
}
val lambda1 = lambdas[0]
val lambda2 = lambdas[1]
lambda1()
lambda2()
lambda1()
lambda2()
}
class Integer(val value: Int) {
override fun toString() = value.toString()
operator fun plus(other: Int) = Integer(value + other)
} | apache-2.0 | c0d64732326d0e6b79e2673f01e2aaeb | 19.333333 | 101 | 0.578659 | 3.600985 | false | true | false | false |
DevPicon/kotlin-marvel-hero-finder | app/src/main/kotlin/pe/devpicon/android/marvelheroes/data/local/DatabaseMapper.kt | 1 | 1326 | package pe.devpicon.android.marvelheroes.data.local
import pe.devpicon.android.marvelheroes.data.remote.ComicCharacterResponse
import pe.devpicon.android.marvelheroes.data.remote.ComicResponse
class DatabaseMapper {
fun mapCharacterResponseToEntity(characterResponse: ComicCharacterResponse): CharacterEntity {
return CharacterEntity(
id = characterResponse.id,
name = characterResponse.name,
description = characterResponse.description,
thumbnailUrl = with(characterResponse.thumbnailResponse) {
"${path}.${extension}"
}
)
}
fun mapComicResponseListToEntity(characterId: Long, comicResponseList: List<ComicResponse>): List<ComicEntity> {
return comicResponseList.map { mapComicResponseToEntity(characterId, it) }
}
private fun mapComicResponseToEntity(characterId: Long, comicResponse: ComicResponse): ComicEntity {
return ComicEntity(
id = comicResponse.id,
title = comicResponse.title,
description = comicResponse.description,
thumbnailUrl = with(comicResponse.thumbnailResponse) {
"${path}.${extension}"
},
characterId = characterId
)
}
} | mit | 688b1ea84e2928f0054390a59cf99541 | 39.212121 | 116 | 0.648567 | 5.241107 | false | false | false | false |
androidx/androidx | appcompat/appcompat-lint/src/test/kotlin/androidx/appcompat/lint/integ/UseCompatDetectorTest.kt | 3 | 2754 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.appcompat.lint.integ
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class UseCompatDetectorTest {
@Test
fun checkCompatSubstitutionsOnActivity() {
val input = arrayOf(
javaSample("com.example.android.appcompat.AppCompatLintDemo"),
javaSample("com.example.android.appcompat.AppCompatLintDemoExt"),
javaSample("com.example.android.appcompat.CoreActivityExt")
)
/* ktlint-disable max-line-length */
val expected = """
src/com/example/android/appcompat/AppCompatLintDemo.java:68: Warning: Use SwitchCompat from AppCompat or SwitchMaterial from Material library [UseSwitchCompatOrMaterialCode]
Switch mySwitch = new Switch(this);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/com/example/android/appcompat/AppCompatLintDemo.java:63: Warning: Use TextViewCompat.setCompoundDrawableTintList() [UseCompatTextViewDrawableApis]
noop.setCompoundDrawableTintList(csl);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/com/example/android/appcompat/AppCompatLintDemo.java:64: Warning: Use TextViewCompat.setCompoundDrawableTintMode() [UseCompatTextViewDrawableApis]
noop.setCompoundDrawableTintMode(PorterDuff.Mode.DST);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0 errors, 3 warnings
""".trimIndent()
/* ktlint-enable max-line-length */
check(*input).expect(expected)
}
@Test
fun checkCompatSubstitutionsOnWidget() {
val input = arrayOf(
javaSample("com.example.android.appcompat.CustomSwitch")
)
/* ktlint-disable max-line-length */
val expected = """
src/com/example/android/appcompat/CustomSwitch.java:27: Warning: Use SwitchCompat from AppCompat or SwitchMaterial from Material library [UseSwitchCompatOrMaterialCode]
public class CustomSwitch extends Switch {
~~~~~~
0 errors, 1 warnings
""".trimIndent()
/* ktlint-enable max-line-length */
check(*input).expect(expected)
}
}
| apache-2.0 | 3f15118a6b214d3e7dcf6262eaf8acbc | 38.913043 | 173 | 0.67284 | 4.636364 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceMapGetOrDefaultIntention.kt | 3 | 3113 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullable
class ReplaceMapGetOrDefaultIntention : SelfTargetingRangeIntention<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java, KotlinBundle.lazyMessage("replace.with.indexing.and.elvis.operator")
) {
companion object {
private val getOrDefaultFqName = FqName("kotlin.collections.Map.getOrDefault")
}
override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? {
val callExpression = element.callExpression ?: return null
val calleeExpression = callExpression.calleeExpression ?: return null
if (calleeExpression.text != getOrDefaultFqName.shortName().asString()) return null
val (firstArg, secondArg) = callExpression.arguments() ?: return null
val context = element.analyze(BodyResolveMode.PARTIAL)
if (callExpression.getResolvedCall(context)?.isCalling(getOrDefaultFqName) != true) return null
if (element.receiverExpression.getType(context)?.arguments?.lastOrNull()?.type?.isNullable() == true) return null
setTextGetter(KotlinBundle.lazyMessage("replace.with.0.1.2", element.receiverExpression.text, firstArg.text, secondArg.text))
return calleeExpression.textRange
}
override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) {
val callExpression = element.callExpression ?: return
val (firstArg, secondArg) = callExpression.arguments() ?: return
val replaced = element.replaced(
KtPsiFactory(element).createExpressionByPattern("$0[$1] ?: $2", element.receiverExpression, firstArg, secondArg)
)
replaced.findDescendantOfType<KtArrayAccessExpression>()?.leftBracket?.startOffset?.let {
editor?.caretModel?.moveToOffset(it)
}
}
private fun KtCallExpression.arguments(): Pair<KtExpression, KtExpression>? {
val args = valueArguments
if (args.size != 2) return null
val first = args[0].getArgumentExpression() ?: return null
val second = args[1].getArgumentExpression() ?: return null
return first to second
}
} | apache-2.0 | 11eb90e4d9f0744447dd56c60c1a24ea | 51.779661 | 158 | 0.760039 | 4.925633 | false | false | false | false |
GunoH/intellij-community | plugins/git-features-trainer/src/training/git/lesson/GitAnnotateLesson.kt | 1 | 18506 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.git.lesson
import com.intellij.diff.impl.DiffWindowBase
import com.intellij.diff.tools.util.DiffSplitter
import com.intellij.ide.IdeBundle
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorBundle
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.vcs.actions.ActiveAnnotationGutter
import com.intellij.openapi.vcs.actions.AnnotateToggleAction
import com.intellij.openapi.vcs.changes.VcsEditorTabFilesManager
import com.intellij.openapi.vcs.changes.ui.ChangeListViewerDialog
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.util.ui.HtmlPanel
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.ui.details.CommitDetailsListPanel
import org.assertj.swing.core.MouseButton
import org.assertj.swing.timing.Timeout
import training.dsl.*
import training.dsl.LessonUtil.adjustPopupPosition
import training.dsl.LessonUtil.restorePopupPosition
import training.git.GitLessonsBundle
import training.ui.IftTestContainerFixture
import training.ui.LearningUiUtil.findComponentWithTimeout
import training.util.LessonEndInfo
import java.awt.Component
import java.awt.Point
import java.awt.Rectangle
class GitAnnotateLesson : GitLesson("Git.Annotate", GitLessonsBundle.message("git.annotate.lesson.name")) {
override val sampleFilePath = "git/martian_cat.yml"
override val branchName = "main"
private val propertyName = "ears_number"
private val editedPropertyName = "ear_number"
private val firstStateText = "ears_number: 4"
private val secondStateText = "ear_number: 4"
private val thirdStateText = "ear_number: 2"
private val partOfTargetCommitMessage = "Edit ear number of martian cat"
private var backupDiffLocation: Point? = null
private var backupRevisionsLocation: Point? = null
override val testScriptProperties = TaskTestContext.TestScriptProperties(duration = 60)
override val lessonContent: LessonContext.() -> Unit = {
val annotateActionName = ActionsBundle.message("action.Annotate.text").dropMnemonic()
task {
text(GitLessonsBundle.message("git.annotate.introduction", strong(annotateActionName)))
triggerAndBorderHighlight().componentPart l@{ ui: EditorComponentImpl ->
val startOffset = ui.editor.document.charsSequence.indexOf(firstStateText)
if (startOffset == -1) return@l null
val endOffset = startOffset + firstStateText.length
val startPoint = ui.editor.offsetToXY(startOffset)
val endPoint = ui.editor.offsetToXY(endOffset)
Rectangle(startPoint.x - 3, startPoint.y, endPoint.x - startPoint.x + 6, ui.editor.lineHeight)
}
proceedLink()
}
val annotateMenuItemText = ActionsBundle.message("action.Annotate.with.Blame.text").dropMnemonic()
if (isAnnotateShortcutSet()) {
task("Annotate") {
text(GitLessonsBundle.message("git.annotate.invoke.shortcut.1", action(it)))
trigger(it)
test { actions(it) }
}
}
else {
task {
highlightGutterComponent(null, firstStateText, highlightRight = true)
}
task {
text(GitLessonsBundle.message("git.annotate.open.context.menu"))
text(GitLessonsBundle.message("git.annotate.click.gutter.balloon"), LearningBalloonConfig(Balloon.Position.atRight, 0))
highlightAnnotateMenuItem(clearPreviousHighlights = true)
test { clickGutter(null, firstStateText, MouseButton.RIGHT_BUTTON) }
}
task("Annotate") {
val addShortcutText = IdeBundle.message("shortcut.balloon.add.shortcut")
text(GitLessonsBundle.message("git.annotate.choose.annotate", strong(annotateMenuItemText)))
text(GitLessonsBundle.message("git.annotate.add.shortcut.tip", strong(annotateActionName), action(it), strong(addShortcutText)))
trigger(it)
restoreByUi()
test { clickAnnotateAction() }
}
}
lateinit var openFirstDiffTaskId: TaskContext.TaskId
task {
openFirstDiffTaskId = taskId
highlightAnnotation(null, firstStateText, highlightRight = true)
}
val showDiffText = ActionsBundle.message("action.Diff.ShowDiff.text")
task {
text(GitLessonsBundle.message("git.annotate.feature.explanation", strong(annotateActionName), strong("Johnny Catsville")))
text(GitLessonsBundle.message("git.annotate.click.annotation.tooltip"), LearningBalloonConfig(Balloon.Position.above, 0))
highlightShowDiffMenuItem()
test {
clickAnnotation(null, firstStateText, rightOriented = true, MouseButton.RIGHT_BUTTON)
}
}
var firstDiffSplitter: DiffSplitter? = null
task {
text(GitLessonsBundle.message("git.annotate.choose.show.diff", strong(showDiffText)))
trigger("com.intellij.openapi.vcs.actions.ShowDiffFromAnnotation")
restoreByUi(openFirstDiffTaskId, delayMillis = defaultRestoreDelay)
test { clickShowDiffAction() }
}
task {
triggerUI().component { ui: EditorComponentImpl ->
if (ui.editor.document.charsSequence.contains(secondStateText)) {
firstDiffSplitter = UIUtil.getParentOfType(DiffSplitter::class.java, ui)
true
}
else false
}
}
prepareRuntimeTask l@{
if (backupDiffLocation == null) {
backupDiffLocation = adjustPopupPosition(DiffWindowBase.DEFAULT_DIALOG_GROUP_KEY)
}
}
if (isAnnotateShortcutSet()) {
task("Annotate") {
text(GitLessonsBundle.message("git.annotate.go.deeper", code(propertyName)) + " "
+ GitLessonsBundle.message("git.annotate.invoke.shortcut.2", action(it)))
triggerOnAnnotationsShown(firstDiffSplitter, secondStateText)
restoreIfDiffClosed(openFirstDiffTaskId, firstDiffSplitter)
test(waitEditorToBeReady = false) {
clickGutter(firstDiffSplitter, secondStateText, MouseButton.LEFT_BUTTON)
actions(it)
}
}
} else {
task {
highlightGutterComponent(firstDiffSplitter, secondStateText, highlightRight = false)
}
task {
text(GitLessonsBundle.message("git.annotate.go.deeper", code(propertyName)) + " "
+ GitLessonsBundle.message("git.annotate.invoke.manually", strong(annotateMenuItemText)))
text(GitLessonsBundle.message("git.annotate.click.gutter.balloon"), LearningBalloonConfig(Balloon.Position.atLeft, 0))
highlightAnnotateMenuItem()
triggerOnAnnotationsShown(firstDiffSplitter, secondStateText)
restoreIfDiffClosed(openFirstDiffTaskId, firstDiffSplitter)
test(waitEditorToBeReady = false) {
clickGutter(firstDiffSplitter, secondStateText, MouseButton.RIGHT_BUTTON)
clickAnnotateAction()
}
}
}
var secondDiffSplitter: DiffSplitter? = null
lateinit var openSecondDiffTaskId: TaskContext.TaskId
task {
openSecondDiffTaskId = taskId
text(GitLessonsBundle.message("git.annotate.show.diff", strong(showDiffText)))
highlightAnnotation(firstDiffSplitter, secondStateText, highlightRight = false)
highlightShowDiffMenuItem()
triggerUI().component { ui: EditorComponentImpl ->
if (ui.editor.document.charsSequence.contains(thirdStateText)) {
secondDiffSplitter = UIUtil.getParentOfType(DiffSplitter::class.java, ui)
true
}
else false
}
restoreIfDiffClosed(openFirstDiffTaskId, firstDiffSplitter)
test(waitEditorToBeReady = false) {
clickAnnotation(firstDiffSplitter, secondStateText, rightOriented = false, MouseButton.RIGHT_BUTTON)
clickShowDiffAction()
}
}
if (isAnnotateShortcutSet()) {
task("Annotate") {
text(GitLessonsBundle.message("git.annotate.found.needed.commit", code(editedPropertyName)) + " "
+ GitLessonsBundle.message("git.annotate.invoke.shortcut.3", action(it)))
triggerOnAnnotationsShown(secondDiffSplitter, secondStateText)
restoreIfDiffClosed(openSecondDiffTaskId, secondDiffSplitter)
test(waitEditorToBeReady = false) {
clickGutter(secondDiffSplitter, secondStateText, MouseButton.LEFT_BUTTON)
actions(it)
}
}
} else {
task {
text(GitLessonsBundle.message("git.annotate.found.needed.commit", code(editedPropertyName)) + " "
+ GitLessonsBundle.message("git.annotate.invoke.manually", strong(annotateMenuItemText)))
highlightGutterComponent(secondDiffSplitter, secondStateText, highlightRight = true)
highlightAnnotateMenuItem()
triggerOnAnnotationsShown(secondDiffSplitter, secondStateText)
restoreIfDiffClosed(openSecondDiffTaskId, secondDiffSplitter)
test(waitEditorToBeReady = false) {
clickGutter(secondDiffSplitter, secondStateText, MouseButton.RIGHT_BUTTON)
clickAnnotateAction()
}
}
}
task {
text(GitLessonsBundle.message("git.annotate.click.annotation"))
highlightAnnotation(secondDiffSplitter, secondStateText, highlightRight = true)
triggerAndBorderHighlight { usePulsation = true }.component { ui: CommitDetailsListPanel ->
val textPanel = UIUtil.findComponentOfType(ui, HtmlPanel::class.java)
textPanel?.text?.contains(partOfTargetCommitMessage) == true
}
restoreIfDiffClosed(openSecondDiffTaskId, secondDiffSplitter)
test(waitEditorToBeReady = false) {
clickAnnotation(secondDiffSplitter, secondStateText, rightOriented = true, MouseButton.LEFT_BUTTON)
}
}
task("HideActiveWindow") {
before {
if (backupRevisionsLocation == null) {
backupRevisionsLocation = adjustPopupPosition(ChangeListViewerDialog.DIMENSION_SERVICE_KEY)
}
}
text(GitLessonsBundle.message("git.annotate.close.changes", code(editedPropertyName), action(it)))
stateCheck {
previous.ui?.isShowing != true
}
test(waitEditorToBeReady = false) {
Thread.sleep(500)
actions(it)
}
}
task("EditorEscape") {
text(GitLessonsBundle.message("git.annotate.close.all.windows",
if (VcsEditorTabFilesManager.getInstance().shouldOpenInNewWindow) 0 else 1, action(it)))
stateCheck {
firstDiffSplitter?.isShowing != true && secondDiffSplitter?.isShowing != true
}
test(waitEditorToBeReady = false) {
repeat(2) {
Thread.sleep(300)
invokeActionViaShortcut("ESCAPE")
}
}
}
if (isAnnotateShortcutSet()) {
task("Annotate") {
text(GitLessonsBundle.message("git.annotate.close.annotations") + " "
+ GitLessonsBundle.message("git.annotate.close.by.shortcut", action(it)))
stateCheck { !isAnnotationsShown(editor) }
test { actions(it) }
}
}
else {
task("Annotate") {
val closeAnnotationsText = EditorBundle.message("close.editor.annotations.action.name")
text(GitLessonsBundle.message("git.annotate.close.annotations") + " "
+ GitLessonsBundle.message("git.annotate.invoke.manually.2", strong(closeAnnotationsText)))
triggerAndBorderHighlight().componentPart { ui: EditorGutterComponentEx ->
if (CommonDataKeys.EDITOR.getData(ui as DataProvider) == editor) {
Rectangle(ui.x + ui.annotationsAreaOffset, ui.y, ui.annotationsAreaWidth, ui.height)
}
else null
}
highlightMenuItem(clearPreviousHighlights = false) { item -> item.text?.contains(closeAnnotationsText) == true }
stateCheck { !isAnnotationsShown(editor) }
test {
clickGutter(null, firstStateText, MouseButton.RIGHT_BUTTON)
ideFrame {
val fixture = jMenuItem { item: ActionMenuItem -> item.text?.contains(closeAnnotationsText) == true }
fixture.click()
}
}
}
}
}
override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) {
restorePopupPosition(project, DiffWindowBase.DEFAULT_DIALOG_GROUP_KEY, backupDiffLocation)
backupDiffLocation = null
restorePopupPosition(project, ChangeListViewerDialog.DIMENSION_SERVICE_KEY, backupRevisionsLocation)
backupRevisionsLocation = null
}
private fun TaskContext.highlightGutterComponent(splitter: DiffSplitter?, partOfEditorText: String, highlightRight: Boolean) {
triggerAndBorderHighlight().componentPart l@{ ui: EditorGutterComponentEx ->
if (ui.checkInsideSplitterAndRightEditor(splitter, partOfEditorText)) {
if (highlightRight) {
Rectangle(ui.x, ui.y, ui.width - 5, ui.height)
}
else Rectangle(ui.x + 5, ui.y, ui.width, ui.height)
}
else null
}
}
private fun EditorGutterComponentEx.checkInsideSplitterAndRightEditor(splitter: DiffSplitter?, partOfEditorText: String): Boolean {
if (splitter != null && !isInsideSplitter(splitter, this)) return false
val editor = CommonDataKeys.EDITOR.getData(this as DataProvider) ?: return false
return editor.document.charsSequence.contains(partOfEditorText)
}
private fun TaskContext.highlightAnnotation(splitter: DiffSplitter?, partOfLineText: String, highlightRight: Boolean) {
triggerAndBorderHighlight().componentPart l@{ ui: EditorGutterComponentEx ->
if (splitter != null && !isInsideSplitter(splitter, ui)) return@l null
ui.getAnnotationRect(partOfLineText, highlightRight)
}
}
private fun EditorGutterComponentEx.getAnnotationRect(partOfLineText: String, rightOriented: Boolean): Rectangle? {
val editor = CommonDataKeys.EDITOR.getData(this as DataProvider) ?: return null
val offset = editor.document.charsSequence.indexOf(partOfLineText)
if (offset == -1) return null
return invokeAndWaitIfNeeded {
val lineY = editor.offsetToXY(offset).y
if (rightOriented) {
Rectangle(x + annotationsAreaOffset, lineY, annotationsAreaWidth, editor.lineHeight)
}
else Rectangle(x + width - annotationsAreaOffset - annotationsAreaWidth, lineY, annotationsAreaWidth, editor.lineHeight)
}
}
private fun TaskContext.highlightAnnotateMenuItem(clearPreviousHighlights: Boolean = false) {
highlightMenuItem(clearPreviousHighlights) { it.anAction is AnnotateToggleAction }
}
private fun TaskContext.highlightShowDiffMenuItem(clearPreviousHighlights: Boolean = false) {
val showDiffText = ActionsBundle.message("action.Diff.ShowDiff.text")
return highlightMenuItem(clearPreviousHighlights) { it.text?.contains(showDiffText) == true }
}
private fun TaskContext.highlightMenuItem(clearPreviousHighlights: Boolean, predicate: (ActionMenuItem) -> Boolean) {
triggerAndBorderHighlight { this.clearPreviousHighlights = clearPreviousHighlights }.component { ui: ActionMenuItem -> predicate(ui) }
}
private fun TaskContext.triggerOnAnnotationsShown(splitter: DiffSplitter?, partOfEditorText: String) {
triggerUI().component { ui: EditorComponentImpl ->
ui.editor.document.charsSequence.contains(partOfEditorText)
&& UIUtil.getParentOfType(DiffSplitter::class.java, ui) == splitter
&& isAnnotationsShown(ui.editor)
}
}
private fun TaskContext.restoreIfDiffClosed(restoreId: TaskContext.TaskId, diff: DiffSplitter?) {
restoreState(restoreId, delayMillis = defaultRestoreDelay) { diff?.isShowing != true }
}
private fun isInsideSplitter(splitter: DiffSplitter, component: Component): Boolean {
return UIUtil.getParentOfType(DiffSplitter::class.java, component) == splitter
}
private fun isAnnotationsShown(editor: Editor): Boolean {
val annotations = editor.gutter.textAnnotations
return annotations.filterIsInstance<ActiveAnnotationGutter>().isNotEmpty()
}
private fun isAnnotateShortcutSet(): Boolean {
return KeymapManager.getInstance().activeKeymap.getShortcuts("Annotate").isNotEmpty()
}
private fun TaskTestContext.clickGutter(splitter: DiffSplitter?, partOfEditorText: String, button: MouseButton) {
ideFrame {
val gutter = findGutterComponent(splitter, partOfEditorText, defaultTimeout)
robot.click(gutter, button)
}
}
private fun TaskTestContext.clickAnnotation(splitter: DiffSplitter?,
partOfLineText: String,
rightOriented: Boolean,
button: MouseButton) {
ideFrame {
val gutter = findGutterComponent(splitter, partOfLineText, defaultTimeout)
val annotationRect = gutter.getAnnotationRect(partOfLineText, rightOriented)
?: error("Failed to find text '$partOfLineText' in editor")
robot.click(gutter, Point(annotationRect.centerX.toInt(), annotationRect.centerY.toInt()), button, 1)
}
}
private fun IftTestContainerFixture<IdeFrameImpl>.findGutterComponent(splitter: DiffSplitter?,
partOfEditorText: String,
timeout: Timeout): EditorGutterComponentEx {
return findComponentWithTimeout(timeout) l@{ ui: EditorGutterComponentEx ->
ui.checkInsideSplitterAndRightEditor(splitter, partOfEditorText)
}
}
private fun TaskTestContext.clickAnnotateAction() {
ideFrame { jMenuItem { item: ActionMenuItem -> item.anAction is AnnotateToggleAction }.click() }
}
private fun TaskTestContext.clickShowDiffAction() {
ideFrame {
val showDiffText = ActionsBundle.message("action.Diff.ShowDiff.text")
jMenuItem { item: ActionMenuItem -> item.text?.contains(showDiffText) == true }.click()
}
}
override val helpLinks: Map<String, String> get() = mapOf(
Pair(GitLessonsBundle.message("git.annotate.help.link"),
LessonUtil.getHelpLink("investigate-changes.html#annotate_blame")),
)}
| apache-2.0 | 504a2027f987b001fa783d0b0363dba3 | 43.378897 | 138 | 0.712634 | 5.013817 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveRedundantSpreadOperatorInspection.kt | 2 | 4823 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.isArrayOfMethod
import org.jetbrains.kotlin.idea.refactoring.replaceWithCopyWithResolveCheck
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class RemoveRedundantSpreadOperatorInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return valueArgumentVisitor(fun(argument) {
val spreadElement = argument.getSpreadElement() ?: return
if (argument.isNamed()) return
val argumentExpression = argument.getArgumentExpression() ?: return
val argumentOffset = argument.startOffset
val startOffset = spreadElement.startOffset - argumentOffset
val endOffset =
when (argumentExpression) {
is KtCallExpression -> {
if (!argumentExpression.isArrayOfMethod()) return
if (argumentExpression.valueArguments.isEmpty()) {
val call = argument.getStrictParentOfType<KtCallExpression>()
if (call != null) {
val bindingContext = call.analyze(BodyResolveMode.PARTIAL)
if (call.replaceWithCopyWithResolveCheck(
resolveStrategy = { expr, context -> expr.getResolvedCall(context)?.resultingDescriptor },
context = bindingContext,
preHook = { valueArgumentList?.removeArgument(call.valueArguments.indexOfFirst { it == argument }) }
) == null
) return
}
}
argumentExpression.calleeExpression!!.endOffset - argumentOffset
}
is KtCollectionLiteralExpression -> startOffset + 1
else -> return
}
val problemDescriptor = holder.manager.createProblemDescriptor(
argument,
TextRange(startOffset, endOffset),
KotlinBundle.message("remove.redundant.spread.operator.quickfix.text"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
isOnTheFly,
RemoveRedundantSpreadOperatorQuickfix()
)
holder.registerProblem(problemDescriptor)
})
}
}
class RemoveRedundantSpreadOperatorQuickfix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.spread.operator.quickfix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
// Argument & expression under *
val spreadValueArgument = descriptor.psiElement as? KtValueArgument ?: return
val spreadArgumentExpression = spreadValueArgument.getArgumentExpression() ?: return
val outerArgumentList = spreadValueArgument.getStrictParentOfType<KtValueArgumentList>() ?: return
// Arguments under arrayOf or []
val innerArgumentExpressions =
when (spreadArgumentExpression) {
is KtCallExpression -> spreadArgumentExpression.valueArgumentList?.arguments?.map {
it.getArgumentExpression() to it.isSpread
}
is KtCollectionLiteralExpression -> spreadArgumentExpression.getInnerExpressions().map { it to false }
else -> null
} ?: return
val factory = KtPsiFactory(project)
innerArgumentExpressions.reversed().forEach { (expression, isSpread) ->
outerArgumentList.addArgumentAfter(factory.createArgument(expression, isSpread = isSpread), spreadValueArgument)
}
outerArgumentList.removeArgument(spreadValueArgument)
}
} | apache-2.0 | 1d7fb75e80c1dc2c305c4082620d8376 | 51.434783 | 158 | 0.659548 | 6.167519 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/exclude.kt | 1 | 1701 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
interface ExcludeUrlEntity : WorkspaceEntity {
val url: VirtualFileUrl
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ExcludeUrlEntity, WorkspaceEntity.Builder<ExcludeUrlEntity>, ObjBuilder<ExcludeUrlEntity> {
override var entitySource: EntitySource
override var url: VirtualFileUrl
}
companion object : Type<ExcludeUrlEntity, Builder>() {
operator fun invoke(url: VirtualFileUrl, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ExcludeUrlEntity {
val builder = builder()
builder.url = url
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ExcludeUrlEntity, modification: ExcludeUrlEntity.Builder.() -> Unit) = modifyEntity(
ExcludeUrlEntity.Builder::class.java, entity, modification)
var ExcludeUrlEntity.Builder.contentRoot: ContentRootEntity?
by WorkspaceEntity.extension()
var ExcludeUrlEntity.Builder.library: LibraryEntity?
by WorkspaceEntity.extension()
//endregion
| apache-2.0 | 6b46383fa675389f0e3a2c39a2d9f71c | 38.55814 | 130 | 0.796002 | 5.0625 | false | false | false | false |
GunoH/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/list/GitLabMergeRequestsPanelFactory.kt | 1 | 9151 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.mergerequest.ui.list
import com.intellij.collaboration.async.nestedDisposable
import com.intellij.collaboration.ui.codereview.list.NamedCollection
import com.intellij.collaboration.ui.codereview.list.ReviewListComponentFactory
import com.intellij.collaboration.ui.codereview.list.ReviewListItemPresentation
import com.intellij.collaboration.ui.codereview.list.UserPresentation
import com.intellij.collaboration.ui.icon.IconsProvider
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.CollectionListModel
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBList
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.StatusText
import com.intellij.util.ui.scroll.BoundedRangeModelThresholdListener
import com.intellij.vcs.log.ui.frame.ProgressStripe
import icons.CollaborationToolsIcons
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import org.jetbrains.plugins.gitlab.api.dto.GitLabUserDTO
import org.jetbrains.plugins.gitlab.mergerequest.api.dto.GitLabMergeRequestShortDTO
import org.jetbrains.plugins.gitlab.mergerequest.data.GitLabMergeRequestState
import org.jetbrains.plugins.gitlab.mergerequest.data.GitLabMergeStatus
import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabMergeRequestsListViewModel
import org.jetbrains.plugins.gitlab.mergerequest.ui.filters.GitLabFiltersPanelFactory
import org.jetbrains.plugins.gitlab.mergerequest.ui.filters.GitLabMergeRequestsFiltersValue
import org.jetbrains.plugins.gitlab.util.GitLabBundle
import javax.swing.JComponent
import javax.swing.ScrollPaneConstants
import javax.swing.event.ChangeEvent
internal class GitLabMergeRequestsPanelFactory {
fun create(scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel): JComponent {
val listModel = collectMergeRequests(scope, listVm)
val listMergeRequests = createMergeRequestListComponent(listVm.avatarIconsProvider, listModel)
val listLoaderPanel = createListLoaderPanel(scope, listVm, listMergeRequests)
val searchPanel = createSearchPanel(scope, listVm)
MergeRequestsListEmptyStateController(scope, listVm, listMergeRequests.emptyText)
return JBUI.Panels.simplePanel(listLoaderPanel)
.addToTop(searchPanel)
.andTransparent()
}
private fun collectMergeRequests(scope: CoroutineScope,
listVm: GitLabMergeRequestsListViewModel): CollectionListModel<GitLabMergeRequestShortDTO> {
val listModel = CollectionListModel<GitLabMergeRequestShortDTO>()
scope.launch {
var firstEvent = true
listVm.listDataFlow.collect {
when (it) {
is GitLabMergeRequestsListViewModel.ListDataUpdate.NewBatch -> {
if (firstEvent) listModel.add(it.newList)
else listModel.add(it.batch)
}
GitLabMergeRequestsListViewModel.ListDataUpdate.Clear -> listModel.removeAll()
}
firstEvent = false
}
}
return listModel
}
private fun createMergeRequestListComponent(
avatarIconsProvider: IconsProvider<GitLabUserDTO>,
listModel: CollectionListModel<GitLabMergeRequestShortDTO>
): JBList<GitLabMergeRequestShortDTO> = ReviewListComponentFactory(listModel).create { mergeRequest ->
ReviewListItemPresentation.Simple(
title = mergeRequest.title,
id = "!${mergeRequest.iid}",
createdDate = mergeRequest.createdAt,
author = userPresentation(avatarIconsProvider, mergeRequest.author),
tagGroup = null,
mergeableStatus = getMergeableStatus(mergeRequest.mergeStatusEnum),
buildStatus = null,
state = getMergeStateText(mergeRequest.stateEnum, mergeRequest.draft),
userGroup1 = NamedCollection.create(
GitLabBundle.message("merge.request.list.renderer.user.assignees", mergeRequest.assignees.size),
mergeRequest.assignees.map { assignee -> userPresentation(avatarIconsProvider, assignee) }
),
userGroup2 = NamedCollection.create(
GitLabBundle.message("merge.request.list.renderer.user.reviewers", mergeRequest.reviewers.size),
mergeRequest.reviewers.map { reviewer -> userPresentation(avatarIconsProvider, reviewer) }
),
commentsCounter = null
)
}
private fun userPresentation(
avatarIconsProvider: IconsProvider<GitLabUserDTO>,
user: GitLabUserDTO
): UserPresentation = UserPresentation.Simple(
username = user.username,
fullName = user.name,
avatarIcon = avatarIconsProvider.getIcon(user, AVATAR_SIZE)
)
private fun getMergeableStatus(mergeStatus: GitLabMergeStatus): ReviewListItemPresentation.Status? {
if (mergeStatus == GitLabMergeStatus.CANNOT_BE_MERGED) {
return ReviewListItemPresentation.Status(CollaborationToolsIcons.Review.NonMergeable,
GitLabBundle.message("merge.request.list.renderer.merge.conflict.tooltip"))
}
return null
}
private fun getMergeStateText(mergeRequestState: GitLabMergeRequestState, isDraft: Boolean): @NlsSafe String? {
if (mergeRequestState == GitLabMergeRequestState.OPENED && !isDraft) {
return null
}
return getMergeRequestStateText(mergeRequestState, isDraft)
}
private fun createListLoaderPanel(scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel, list: JComponent): JComponent {
val scrollPane = ScrollPaneFactory.createScrollPane(list, true).apply {
isOpaque = false
viewport.isOpaque = false
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
val model = verticalScrollBar.model
val listener = object : BoundedRangeModelThresholdListener(model, 0.7f) {
override fun onThresholdReached() {
if (listVm.canLoadMoreState.value) {
listVm.requestMore()
}
}
}
model.addChangeListener(listener)
scope.launch {
listVm.listDataFlow.collect {
when (it) {
is GitLabMergeRequestsListViewModel.ListDataUpdate.NewBatch -> {
if (isShowing) {
listener.stateChanged(ChangeEvent(listVm))
}
}
GitLabMergeRequestsListViewModel.ListDataUpdate.Clear -> {
if (isShowing) {
listVm.requestMore()
}
}
}
}
}
}
val progressStripe = ProgressStripe(scrollPane, scope.nestedDisposable(),
ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply {
scope.launch {
listVm.loadingState.collect {
if (it) startLoadingImmediately() else stopLoading()
}
}
}
return progressStripe
}
private fun createSearchPanel(scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel): JComponent {
return GitLabFiltersPanelFactory(listVm.filterVm).create(scope)
}
private class MergeRequestsListEmptyStateController(
scope: CoroutineScope,
private val listVm: GitLabMergeRequestsListViewModel,
private val emptyText: StatusText
) {
init {
scope.launch {
combine(listVm.loadingState, listVm.filterVm.searchState) { isLoading, searchState ->
isLoading to searchState
}.collect { (isLoading, searchState) ->
updateEmptyState(isLoading, searchState, listVm.repository)
}
}
}
private fun updateEmptyState(isLoading: Boolean, searchState: GitLabMergeRequestsFiltersValue, repository: String) {
emptyText.clear()
if (isLoading) {
emptyText.appendText(GitLabBundle.message("merge.request.list.empty.state.loading"))
return
}
if (searchState.filterCount == 0) {
emptyText
.appendText(GitLabBundle.message("merge.request.list.empty.state.matching.nothing", repository))
}
else {
emptyText
.appendText(GitLabBundle.message("merge.request.list.empty.state.matching.nothing.with.filters"))
.appendSecondaryText(GitLabBundle.message("merge.request.list.empty.state.clear.filters"), SimpleTextAttributes.LINK_ATTRIBUTES) {
listVm.filterVm.searchState.value = GitLabMergeRequestsFiltersValue.EMPTY
}
}
}
}
companion object {
private const val AVATAR_SIZE = 20
fun getMergeRequestStateText(mergeRequestState: GitLabMergeRequestState, isDraft: Boolean): @NlsSafe String? =
if (isDraft) GitLabBundle.message("merge.request.list.renderer.state.draft")
else when (mergeRequestState) {
GitLabMergeRequestState.CLOSED -> GitLabBundle.message("merge.request.list.renderer.state.closed")
GitLabMergeRequestState.MERGED -> GitLabBundle.message("merge.request.list.renderer.state.merged")
else -> null
}
}
} | apache-2.0 | c4d3d1b7d43ac9938d897e27b8aaede2 | 40.411765 | 140 | 0.734565 | 4.943814 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/mpp-additional/src/iosX64Main/kotlin/callingCommonized/WCommonizedCalls.kt | 12 | 1021 | // !CHECK_HIGHLIGHTING
package callingCommonized
import kotlinx.cinterop.CEnum
import platform.Accelerate.AtlasConj
import platform.Accelerate.CBLAS_TRANSPOSE
import platform.Accelerate.FFTDirection
import platform.Accelerate.__CLPK_real
import platform.Accounts.ACAccount
import platform.CoreFoundation.CFAllocatorGetTypeID
import platform.CoreFoundation.CFTypeID
import platform.CoreFoundation.__CFByteOrder
import platform.Foundation.NSLog
import platform.darwin.ABDAY_1
import platform.darwin.NSObject
import platform.darwin.PLATFORM_IOS
import platform.posix.DBL_MIN
actual class WCommonizedCalls actual constructor(pc: __CLPK_real) {
val eFunCall: CFTypeID = CFAllocatorGetTypeID() // create actual doesn't work because of this
actual val eClass: NSObject = ACAccount()
actual val enumInteroped: CEnum = __CFByteOrder.CFByteOrderLittleEndian
val somel = NSLog("")
val dfg = DBL_MIN
val device get() = platform.UIKit.UIDevice.currentDevice
val eVal: CBLAS_TRANSPOSE = AtlasConj
}
| apache-2.0 | f9c5fc0aa7dd969ce607bdc052928ddd | 29.939394 | 97 | 0.804114 | 3.795539 | false | false | false | false |
shalupov/idea-cloudformation | src/main/kotlin/com/intellij/aws/cloudformation/CloudFormationInspections.kt | 1 | 28889 | @file:Suppress("IfThenToSafeAccess", "RedundantUnitExpression")
package com.intellij.aws.cloudformation
import com.google.common.collect.ArrayListMultimap
import com.google.common.collect.Multimap
import com.google.common.primitives.Floats
import com.intellij.aws.cloudformation.metadata.CloudFormationResourceType
import com.intellij.aws.cloudformation.metadata.CloudFormationResourceType.Companion.isCustomResourceType
import com.intellij.aws.cloudformation.metadata.awsServerlessFunction
import com.intellij.aws.cloudformation.metadata.awsServerlessNamePrefix
import com.intellij.aws.cloudformation.model.CfnArrayValueNode
import com.intellij.aws.cloudformation.model.CfnFunctionNode
import com.intellij.aws.cloudformation.model.CfnGlobalsNode
import com.intellij.aws.cloudformation.model.CfnMappingsNode
import com.intellij.aws.cloudformation.model.CfnMetadataNode
import com.intellij.aws.cloudformation.model.CfnNameValueNode
import com.intellij.aws.cloudformation.model.CfnNamedNode
import com.intellij.aws.cloudformation.model.CfnNode
import com.intellij.aws.cloudformation.model.CfnObjectValueNode
import com.intellij.aws.cloudformation.model.CfnOutputsNode
import com.intellij.aws.cloudformation.model.CfnParameterNode
import com.intellij.aws.cloudformation.model.CfnParametersNode
import com.intellij.aws.cloudformation.model.CfnResourceConditionNode
import com.intellij.aws.cloudformation.model.CfnResourceDependsOnNode
import com.intellij.aws.cloudformation.model.CfnResourceNode
import com.intellij.aws.cloudformation.model.CfnResourceTypeNode
import com.intellij.aws.cloudformation.model.CfnResourcesNode
import com.intellij.aws.cloudformation.model.CfnRootNode
import com.intellij.aws.cloudformation.model.CfnScalarValueNode
import com.intellij.aws.cloudformation.model.CfnServerlessEntityDefaultsNode
import com.intellij.aws.cloudformation.model.CfnVisitor
import com.intellij.aws.cloudformation.references.CloudFormationEntityReference
import com.intellij.aws.cloudformation.references.CloudFormationMappingFirstLevelKeyReference
import com.intellij.aws.cloudformation.references.CloudFormationMappingSecondLevelKeyReference
import com.intellij.aws.cloudformation.references.CloudFormationReferenceBase
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.yaml.psi.impl.YAMLScalarImpl
import java.util.regex.Pattern
class CloudFormationInspections private constructor(val parsed: CloudFormationParsedFile): CfnVisitor() {
val problems: MutableList<CloudFormationProblem> = mutableListOf()
val references: Multimap<PsiElement, CloudFormationReferenceBase> = ArrayListMultimap.create()
private val numbersPattern = Pattern.compile("^[0-9]+$")!!
private fun addReference(reference: CloudFormationReferenceBase) {
references.put(reference.element, reference)
}
private fun addEntityReference(element: CfnScalarValueNode, sections: Collection<CloudFormationSection>, excludeFromCompletion: Collection<String>? = null, referenceValue: String? = null) {
val psiElement = parsed.getPsiElement(element)
val entityReference = CloudFormationEntityReference(psiElement, sections, excludeFromCompletion, referenceValue = referenceValue)
val scalarImpl = psiElement as? YAMLScalarImpl
if (scalarImpl != null && scalarImpl.contentRanges.isNotEmpty()) {
val startOffset: Int = scalarImpl.contentRanges.first().startOffset
val endOffset: Int = scalarImpl.contentRanges.last().endOffset
entityReference.rangeInElement = TextRange(startOffset, endOffset)
}
addReference(entityReference)
}
/*
private fun addProblem(element: PsiElement, description: String) {
problems.add(Problem(element, description))
}
*/
private fun addProblem(element: CfnNode, description: String) {
// TODO check psi element mapping not exists
val psiElement = if (element is CfnNamedNode && element.name != null) {
parsed.getPsiElement(element.name)
} else {
parsed.getPsiElement(element)
}
problems.add(CloudFormationProblem(psiElement, description))
}
/*private fun addProblemOnNameElement(property: JsonProperty, description: String) {
addProblem(
if (property.firstChild != null) property.firstChild else property,
description)
}
*/
private var currentResource: CfnResourceNode? = null
override fun function(function: CfnFunctionNode) {
val arg0 = function.args.getOrNull(0)
val arg1 = function.args.getOrNull(1)
// TODO make it sealed when some time in the future
@Suppress("UNUSED_VARIABLE")
val _used_to_enforce_exhaustive_check: Unit = when (function.functionId) {
CloudFormationIntrinsicFunction.Ref -> {
if (function.args.size != 1 || arg0 !is CfnScalarValueNode) {
addProblem(function, "Reference expects one string argument")
} else {
val arg0WithoutVersionOrAlias = arg0.value.removeSuffix(".Version").removeSuffix(".Alias")
val resourceNodeWithoutVersionOrAlias = CloudFormationResolve.resolveResource(
parsed, arg0WithoutVersionOrAlias)
val resourceNodeParent = function.parentOfType<CfnResourceNode>(parsed)
val excluded = resourceNodeParent?.let { it.name?.value }?.let { listOf(it) } ?: emptyList()
when {
CloudFormationMetadataProvider.METADATA.predefinedParameters.contains(arg0.value) -> Unit
// Disgusting hack from serverless spec
// https://github.com/awslabs/serverless-application-model/blob/develop/versions/2016-10-31.md#referencing-lambda-version--alias-resources
resourceNodeWithoutVersionOrAlias != null && resourceNodeWithoutVersionOrAlias.isAwsServerlessFunctionWithAutoPublishAlias() &&
arg0WithoutVersionOrAlias != arg0.value -> {
addEntityReference(arg0, CloudFormationSection.ResourcesSingletonList, excludeFromCompletion = excluded, referenceValue = arg0WithoutVersionOrAlias)
}
else -> {
addEntityReference(arg0, CloudFormationSection.ParametersAndResources, excludeFromCompletion = excluded)
}
}
}
Unit
}
CloudFormationIntrinsicFunction.Condition ->
if (function.args.size != 1 || arg0 !is CfnScalarValueNode) {
addProblem(function, "Condition reference expects one string argument")
} else {
addEntityReference(arg0, CloudFormationSection.ConditionsSingletonList)
}
CloudFormationIntrinsicFunction.FnBase64 -> {
if (function.args.size != 1) {
addProblem(function, "Base64 reference expects 1 argument")
}
Unit
}
CloudFormationIntrinsicFunction.FnFindInMap -> {
if (function.args.size != 3) {
addProblem(function, "FindInMap requires 3 arguments")
} else {
val mappingName = function.args[0]
val firstLevelKey = function.args[1]
val secondLevelKey = function.args[2]
if (mappingName is CfnScalarValueNode) {
addEntityReference(mappingName, CloudFormationSection.MappingsSingletonList)
val mapping = CloudFormationResolve.resolveMapping(parsed, mappingName.value)
if (mapping != null && firstLevelKey is CfnScalarValueNode) {
val firstLevelKeyPsiElement = parsed.getPsiElement(firstLevelKey)
addReference(CloudFormationMappingFirstLevelKeyReference(firstLevelKeyPsiElement, mappingName.value))
// TODO resolve possible values if first level key is an expression
if (secondLevelKey is CfnScalarValueNode) {
val secondLevelKeyPsiElement = parsed.getPsiElement(secondLevelKey)
addReference(CloudFormationMappingSecondLevelKeyReference(secondLevelKeyPsiElement, mappingName.value, firstLevelKey.value))
}
}
}
}
Unit
}
CloudFormationIntrinsicFunction.FnGetAtt -> {
val resourceName: String?
val attributeName: String?
if (function.args.size == 1 && arg0 is CfnScalarValueNode && function.name.value == CloudFormationIntrinsicFunction.FnGetAtt.shortForm) {
val dotIndex = arg0.value.indexOf('.')
if (dotIndex < 0) {
addProblem(function, "GetAttr in short form requires argument in the format logicalNameOfResource.attributeName")
resourceName = null
attributeName = null
} else {
resourceName = arg0.value.substring(0, dotIndex)
attributeName = arg0.value.substring(dotIndex + 1)
}
} else if (function.args.size == 2 && arg0 is CfnScalarValueNode) {
resourceName = arg0.value
attributeName = if (arg1 is CfnScalarValueNode) arg1.value else null
} else {
addProblem(function, "GetAtt requires two string arguments in full form or one string argument in short form")
resourceName = null
attributeName = null
}
if (resourceName != null) {
// TODO calculate exact text range and add it to ReferencesTest
val resourceNodeParent = function.parentOfType<CfnResourceNode>(parsed)
val excluded = resourceNodeParent?.let { it.name?.value }?.let { listOf(it) } ?: emptyList()
val resource = CloudFormationResolve.resolveResource(parsed, resourceName)
// From https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
// Role: ARN of an IAM role to use as this function's execution role. If omitted, a default role is created for this function.
// Here we handle this implicitly created role
val resourceNameWithoutRoleSuffix = resourceName.removeSuffix("Role")
val resourceWithoutRoleSuffix = CloudFormationResolve.resolveResource(parsed, resourceNameWithoutRoleSuffix)
if (resource == null && resourceWithoutRoleSuffix?.typeName == awsServerlessFunction.name) {
addEntityReference(arg0 as CfnScalarValueNode, CloudFormationSection.ResourcesSingletonList,
excludeFromCompletion = excluded, referenceValue = resourceNameWithoutRoleSuffix)
if (attributeName != "Arn") {
addProblem(
if (function.args.size == 1) arg0 else (arg1 ?: function),
"Implicit IAM Function Role supports only 'Arn' attribute")
}
} else {
addEntityReference(arg0 as CfnScalarValueNode, CloudFormationSection.ResourcesSingletonList, excludeFromCompletion = excluded, referenceValue = resourceName)
if (attributeName != null) {
val typeName = resource?.typeName
if (typeName != null &&
!CloudFormationResourceType.isCustomResourceType(typeName) &&
!(CloudFormationResourceType.isCloudFormationStack(typeName) && attributeName.startsWith("Outputs.")) &&
!(CloudFormationResourceType.isServerlessApplication(typeName) && attributeName.startsWith("Outputs.")) &&
CloudFormationMetadataProvider.METADATA.findResourceType(typeName, parsed.root) != null) {
if (!resource.getAttributes(parsed.root).containsKey(attributeName)) {
addProblem(
if (function.args.size == 1) arg0 else (arg1 ?: function),
"Unknown attribute in resource type '$typeName': $attributeName")
}
}
}
}
}
Unit
}
CloudFormationIntrinsicFunction.FnGetAZs -> {
// TODO verify string against known regions
// TODO possibility for dataflow checks
if (function.args.size != 1) {
addProblem(function, "GetAZs expects one argument")
}
Unit
}
CloudFormationIntrinsicFunction.FnCidr -> {
if (function.args.size != 2 && function.args.size != 3) {
addProblem(function, "Cidr expects two or three arguments")
}
Unit
}
CloudFormationIntrinsicFunction.FnImportValue -> {
if (function.args.size != 1) {
addProblem(function, "ImportValue expects one argument")
}
Unit
}
CloudFormationIntrinsicFunction.FnJoin -> {
if (function.args.size != 2) {
addProblem(function, "Join expects a string argument and an array argument")
}
Unit
}
CloudFormationIntrinsicFunction.FnSplit -> {
if (function.args.size != 2) {
addProblem(function, "Split expects two string arguments")
}
Unit
}
CloudFormationIntrinsicFunction.FnSelect -> {
if (function.args.size != 2) {
addProblem(function, "Select expects an index argument and an array argument")
} else if (arg0 is CfnScalarValueNode) {
try {
Integer.parseUnsignedInt(arg0.value)
} catch (t: NumberFormatException) {
addProblem(function, "Select index should be a valid non-negative number")
}
}
Unit
}
CloudFormationIntrinsicFunction.FnSub -> {
// TODO Add references to substituted values in a string
// TODO Add references to the mapping
if (function.args.size != 1 && !(function.args.size == 2 && arg1 is CfnObjectValueNode)) {
addProblem(function, "Sub expects one argument plus an optional value map")
}
Unit
}
// TODO Check context, valid only in boolean context
CloudFormationIntrinsicFunction.FnAnd, CloudFormationIntrinsicFunction.FnOr -> {
if (function.args.size < 2) {
addProblem(function, function.functionId.shortForm + " expects at least 2 arguments")
}
Unit
}
CloudFormationIntrinsicFunction.FnEquals -> {
if (function.args.size != 2) {
addProblem(function, "Equals expects exactly 2 arguments")
}
Unit
}
CloudFormationIntrinsicFunction.FnIf ->
if (function.args.size == 3) {
if (arg0 is CfnScalarValueNode) {
addEntityReference(arg0, CloudFormationSection.ConditionsSingletonList)
} else {
addProblem(function, "If's first argument should be a condition name")
}
} else {
addProblem(function, "If expects exactly 3 arguments")
}
CloudFormationIntrinsicFunction.FnNot -> {
if (function.args.size != 1) {
addProblem(function, "Not expects exactly 1 argument")
}
Unit
}
}
super.function(function)
}
override fun resourceDependsOn(resourceDependsOn: CfnResourceDependsOnNode) {
resourceDependsOn.dependsOn.forEach { depend ->
val excludeFromCompletion = mutableListOf<String>()
currentResource!!.name?.value?.let { excludeFromCompletion.add(it) }
resourceDependsOn.dependsOn.forEach { if (depend.value != it.value) excludeFromCompletion.add(it.value) }
addEntityReference(depend, CloudFormationSection.ResourcesSingletonList, excludeFromCompletion)
}
super.resourceDependsOn(resourceDependsOn)
}
override fun resourceCondition(resourceCondition: CfnResourceConditionNode) {
resourceCondition.condition?.let {
addEntityReference(it, CloudFormationSection.ConditionsSingletonList)
}
super.resourceCondition(resourceCondition)
}
override fun resourceType(resourceType: CfnResourceTypeNode) {
val resourceTypeValue = resourceType.value
val typeName = resourceTypeValue?.value
if (resourceTypeValue == null || typeName == null || typeName.isEmpty()) {
addProblem(resourceType, "Type value is required")
return
}
if (!isCustomResourceType(typeName)) {
val resourceTypeMetadata = CloudFormationMetadataProvider.METADATA.findResourceType(typeName, parsed.root)
if (resourceTypeMetadata == null) {
addProblem(resourceTypeValue, CloudFormationBundle.getString("format.unknown.type", typeName))
}
}
super.resourceType(resourceType)
}
override fun outputs(outputs: CfnOutputsNode) {
if (outputs.properties.isEmpty()) {
addProblem(outputs, "Outputs section must declare at least one stack output")
}
if (outputs.properties.size > CloudFormationMetadataProvider.METADATA.limits.maxOutputs) {
addProblem(outputs, CloudFormationBundle.getString("format.max.outputs.exceeded", CloudFormationMetadataProvider.METADATA.limits.maxOutputs))
}
super.outputs(outputs)
}
override fun globals(globals: CfnGlobalsNode) {
if (!parsed.root.transformValues.contains(CloudFormationConstants.awsServerless20161031TransformName)) {
addProblem(globals, "Globals section supported with ${CloudFormationConstants.awsServerless20161031TransformName} transform only")
return
}
if (globals.globals.isEmpty()) {
addProblem(globals, "Globals section must provide defaults for at least one resource")
}
super.globals(globals)
}
override fun serverlessEntityDefaultsNode(serverlessEntityDefaultsNode: CfnServerlessEntityDefaultsNode) {
val name = serverlessEntityDefaultsNode.name?.value
if (name != null) {
val resourceType = CloudFormationConstants.GlobalsResourcesMap.get(name)
if (resourceType == null) {
addProblem(
serverlessEntityDefaultsNode,
"Unsupported globals section '$name'. The following sections are supported: " +
CloudFormationConstants.GlobalsResourcesMap.keys.sorted().joinToString())
} else {
for (nameValueNode in serverlessEntityDefaultsNode.properties) {
val propertyName = nameValueNode.name?.value ?: continue
val property = resourceType.properties.firstOrNull { it.name == propertyName }
if (property == null || property.excludedFromGlobals) {
addProblem(
nameValueNode.name,
"Property $propertyName is unsupported in '$name' sections of Globals")
}
}
}
}
super.serverlessEntityDefaultsNode(serverlessEntityDefaultsNode)
}
override fun parameters(parameters: CfnParametersNode) {
if (parameters.parameters.isEmpty()) {
addProblem(parameters, "Parameters section must declare at least one parameter")
}
if (parameters.parameters.size > CloudFormationMetadataProvider.METADATA.limits.maxParameters) {
addProblem(parameters, CloudFormationBundle.getString("format.max.parameters.exceeded", CloudFormationMetadataProvider.METADATA.limits.maxParameters))
}
super.parameters(parameters)
}
private fun checkValueIsScalar(nameValue: CfnNameValueNode) {
if (nameValue.value !is CfnScalarValueNode && nameValue.value != null) {
addProblem(nameValue, "Expected a string")
}
}
override fun parameter(parameter: CfnParameterNode) {
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html
val type = parameter.properties.firstOrNull { it.name?.value == CloudFormationParameterProperty.Type.id }
if (type != null) checkValueIsScalar(type)
val typeValue = type?.value
val typeName = (typeValue as? CfnScalarValueNode)?.value?.trim()
if (type == null || typeName == null) {
addProblem(parameter, "Required property Type is missing or empty")
return
}
if (!CloudFormationConstants.allParameterTypes.contains(typeName)) {
addProblem(type.value, "Unknown parameter type: $typeName")
return
}
parameter.properties.forEach { property ->
val propertyName = property.name?.value?.trim() ?: return@forEach
val typedPropertyName = CloudFormationParameterProperty.values().singleOrNull { it.id == propertyName }
when (typedPropertyName) {
null -> {
addProblem(parameter, "Unknown parameter property: " + propertyName)
}
CloudFormationParameterProperty.AllowedPattern -> {
checkValueIsScalar(property)
}
CloudFormationParameterProperty.AllowedValues -> {
if (property.value is CfnArrayValueNode) {
property.value.items.forEach {
if (it !is CfnScalarValueNode) {
addProblem(it, "Expected a string")
}
}
} else {
addProblem(property, "Expected an array")
}
Unit
}
CloudFormationParameterProperty.ConstraintDescription -> {
checkValueIsScalar(property)
}
CloudFormationParameterProperty.Default -> {
checkValueIsScalar(property)
}
CloudFormationParameterProperty.Description -> {
checkValueIsScalar(property)
val scalar = property.value as? CfnScalarValueNode
if (scalar != null && scalar.value.length > CloudFormationConstants.ParameterDescriptionLimit) {
addProblem(property, "${CloudFormationParameterProperty.Description.id} is too long (${scalar.value.length} chars), maximum allowed length is ${CloudFormationConstants.ParameterDescriptionLimit}")
}
Unit
}
CloudFormationParameterProperty.MaxLength, CloudFormationParameterProperty.MinLength -> {
checkValueIsScalar(property)
val scalar = property.value as? CfnScalarValueNode
if (scalar != null) {
if (!numbersPattern.matcher(scalar.value).matches()) {
addProblem(property, "Expected a number")
}
if (typeName != CloudFormationParameterType.String.id &&
!CloudFormationConstants.AwsSpecificParameterTypes.contains(typeName) &&
!CloudFormationConstants.SsmParameterTypes.contains(typeName)) {
addProblem(property, "$propertyName property is valid for ${CloudFormationParameterType.String.id} type only")
}
}
Unit
}
CloudFormationParameterProperty.MinValue, CloudFormationParameterProperty.MaxValue -> {
checkValueIsScalar(property)
val scalar = property.value as? CfnScalarValueNode
if (scalar != null) {
if (Floats.tryParse(scalar.value) == null) {
addProblem(property, "Expected an integer or float")
}
if (typeName != CloudFormationParameterType.Number.id) {
addProblem(property, "$propertyName property is valid for ${CloudFormationParameterType.Number.id} type only")
}
}
Unit
}
CloudFormationParameterProperty.NoEcho -> {
checkValueIsScalar(property)
val scalar = property.value as? CfnScalarValueNode
if (scalar != null && !scalar.value.equals("True", ignoreCase = true)) {
addProblem(property, "Only 'True' value is allowed")
}
Unit
}
CloudFormationParameterProperty.Type -> Unit
}.let { } // enforce exhaustive check
}
}
override fun mappings(mappings: CfnMappingsNode) {
if (mappings.mappings.isEmpty()) {
addProblem(mappings, "Mappings section must declare at least one parameter")
}
if (mappings.mappings.size > CloudFormationMetadataProvider.METADATA.limits.maxMappings) {
addProblem(mappings, CloudFormationBundle.getString("format.max.mappings.exceeded", CloudFormationMetadataProvider.METADATA.limits.maxMappings))
}
super.mappings(mappings)
}
private fun calculateMissingProperties(presentProperties: List<String>, metadata: CloudFormationResourceType): List<String> {
val propertiesDefinedInGlobals = if (metadata.name.startsWith(awsServerlessNamePrefix)) {
val globalsSectionName = metadata.name.removePrefix(awsServerlessNamePrefix)
val globals = parsed.root.globalsNode?.
globals?.singleOrNull { it.name?.value == globalsSectionName }
globals?.properties?.mapNotNull { it.name?.value } ?: emptyList()
} else emptyList()
val missingProperties = metadata.requiredProperties.filter {
required -> !presentProperties.contains(required) && !propertiesDefinedInGlobals.contains(required)
}
return missingProperties.sorted()
}
override fun resource(resource: CfnResourceNode) {
currentResource = resource
val resourceType = resource.type
if (resourceType == null) {
addProblem(resource, "Type property is required for resource")
return
}
val metadata = resourceType.metadata(parsed.root)
if (metadata != null) {
val propertiesNode = resource.properties
propertiesNode?.properties?.forEach {
val propertyName = it.name?.value
if (propertyName != null &&
propertyName != CloudFormationConstants.CommentResourcePropertyName &&
!isCustomResourceType(resourceType.value!!.value) &&
metadata.findProperty(propertyName) == null) {
addProblem(it, CloudFormationBundle.getString("format.unknown.resource.type.property", propertyName))
}
}
val presentProperties = propertiesNode?.properties?.mapNotNull { it.name?.value } ?: emptyList()
val missingProperties = calculateMissingProperties(presentProperties, metadata)
if (missingProperties.isNotEmpty()) {
addProblem(
element = propertiesNode ?: resource,
description = CloudFormationBundle.getString("format.required.resource.properties.are.not.set", missingProperties.joinToString(separator = " "))
)
}
}
super.resource(resource)
currentResource = null
}
override fun resources(resources: CfnResourcesNode) {
if (resources.resources.isEmpty()) {
addProblem(resources, "Resources section should declare at least one resource")
return
}
super.resources(resources)
}
override fun metadata(metadata: CfnMetadataNode) {
val cfnInterface = metadata.value?.properties?.singleOrNull {
it.value is CfnObjectValueNode && it.name?.value == CloudFormationConstants.CloudFormationInterfaceType
}?.let { it.value as CfnObjectValueNode }
if (cfnInterface != null) {
val parameterGroups = cfnInterface.properties
.singleOrNull { it.name?.value == CloudFormationConstants.CloudFormationInterfaceParameterGroups }
?.let { it.value as? CfnArrayValueNode }
val predefinedParameters = CloudFormationMetadataProvider.METADATA.predefinedParameters
@Suppress("LoopToCallChain")
for (parameterGroup in parameterGroups?.items?.mapNotNull { it as? CfnObjectValueNode } ?: emptyList()) {
val parameters = parameterGroup.properties
.singleOrNull { it.name?.value == CloudFormationConstants.CloudFormationInterfaceParameters }
?.let { it.value as? CfnArrayValueNode }
for (parameter in parameters?.items ?: emptyList()) {
if (parameter is CfnScalarValueNode) {
addEntityReference(parameter, CloudFormationSection.ParametersSingletonList, predefinedParameters)
} else {
addProblem(parameter, "Expected a string")
}
}
}
val parameterLabels = cfnInterface.properties
.singleOrNull { it.name?.value == CloudFormationConstants.CloudFormationInterfaceParameterLabels }
?.let { it.value as? CfnObjectValueNode }
for (parameterName in parameterLabels?.properties?.mapNotNull { it.name } ?: emptyList()) {
addEntityReference(parameterName, CloudFormationSection.ParametersSingletonList, predefinedParameters)
}
}
super.metadata(metadata)
}
override fun root(root: CfnRootNode) {
if (root.resourcesNode == null && !parsed.getPsiElement(root).textRange.isEmpty) {
addProblem(root, "Resources section is missing")
}
super.root(root)
}
class InspectionResult(
val problems: List<CloudFormationProblem>,
val references: Multimap<PsiElement, CloudFormationReferenceBase>,
val fileModificationStamp: Long
)
companion object {
private val ANALYZED_KEY = Key.create<InspectionResult>("CFN_ANALYZED_FILE")
fun inspectFile(parsed: CloudFormationParsedFile): InspectionResult {
val cached = parsed.psiFile.getUserData(ANALYZED_KEY)
if (cached != null && cached.fileModificationStamp == parsed.psiFile.modificationStamp) {
return cached
}
val inspections = CloudFormationInspections(parsed)
inspections.root(parsed.root)
val inspectionResult = InspectionResult(inspections.problems, inspections.references, parsed.psiFile.modificationStamp)
parsed.psiFile.putUserData(ANALYZED_KEY, inspectionResult)
return inspectionResult
}
}
}
| apache-2.0 | cdd8bad00801b5d543cd0c95e8726ba3 | 39.235376 | 208 | 0.693205 | 4.923142 | false | false | false | false |
kelemen/JTrim | buildSrc/src/main/kotlin/org/jtrim2/build/BuildUtils.kt | 1 | 1150 | package org.jtrim2.build
import java.io.File
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import org.gradle.api.Task
import org.gradle.api.UnknownTaskException
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.named
fun Path.withChildren(children: List<String>): Path = children.fold(this) { parent, child -> parent.resolve(child) }
fun Path.withChildren(vararg children: String): Path = withChildren(children.asList())
fun File.withChildren(children: List<String>): Path = toPath().withChildren(children)
fun File.withChildren(vararg children: String): Path = toPath().withChildren(*children)
fun Path.readTextFile(): String {
return readTextFile(StandardCharsets.UTF_8)
}
fun Path.readTextFile(charset: Charset): String {
val bytes = Files.readAllBytes(this)
return String(bytes, charset)
}
inline fun <reified T : Task> TaskContainer.tryGetTaskRef(name: String): TaskProvider<T>? {
return try {
named<T>(name)
} catch (ex: UnknownTaskException) {
null
}
}
| apache-2.0 | 27b28f0cf57aeace80a9c21d625d8ff7 | 30.081081 | 116 | 0.755652 | 3.721683 | false | false | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventure/impl/AWFAdventure.kt | 1 | 1939 | package pt.joaomneto.titancompanion.adventure.impl
import android.os.Bundle
import android.view.Menu
import java.io.BufferedWriter
import java.io.IOException
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventure.Adventure
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureCombatFragment
import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureNotesFragment
import pt.joaomneto.titancompanion.adventure.impl.fragments.awf.AWFAdventureVitalStatsFragment
import pt.joaomneto.titancompanion.util.AdventureFragmentRunner
class AWFAdventure : Adventure(
arrayOf(
AdventureFragmentRunner(R.string.vitalStats, AWFAdventureVitalStatsFragment::class),
AdventureFragmentRunner(R.string.fights, AdventureCombatFragment::class),
AdventureFragmentRunner(R.string.notes, AdventureNotesFragment::class)
)
) {
var heroPoints: Int = 0
var superPower: String? = null
override val combatSkillValue: Int
get() = if (superPower == getString(R.string.awfSuperStrength)) {
13
} else getCurrentSkill()
override fun onCreate(savedInstanceState: Bundle?) {
try {
super.onCreate(savedInstanceState)
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.adventure, menu)
return true
}
@Throws(IOException::class)
override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) {
bw.write("heroPoints=" + heroPoints + "\n")
bw.write("superPower=" + superPower + "\n")
}
override fun loadAdventureSpecificValuesFromFile() {
heroPoints = Integer.valueOf(savedGame.getProperty("heroPoints"))
superPower = savedGame.getProperty("superPower")
}
companion object {
internal val FRAGMENT_NOTES = 2
}
}
| lgpl-3.0 | 8ff257a1fb06398ae30781a8817c3227 | 31.864407 | 94 | 0.723569 | 4.551643 | false | false | false | false |
egf2-guide/guide-android | app/src/main/kotlin/com/eigengraph/egf2/guide/ui/anko/PostItemUI.kt | 1 | 1676 | package com.eigengraph.egf2.guide.ui.anko
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.eigengraph.egf2.guide.R
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.tintedTextView
class PostItemUI {
fun bind(parent: ViewGroup): View =
parent.context.UI {
verticalLayout {
val p = dip(8)
lparams(width = matchParent, height = wrapContent)
imageView {
id = R.id.post_item_image
scaleType = ImageView.ScaleType.FIT_CENTER
}.lparams(width = matchParent, height = wrapContent)
tintedTextView {
id = R.id.post_item_creator
singleLine = true
ellipsize = TextUtils.TruncateAt.END
topPadding = p
leftPadding = p
rightPadding = p
textSize = 12f
}.lparams(width = matchParent, height = wrapContent)
tintedTextView {
id = R.id.post_item_text
singleLine = true
ellipsize = TextUtils.TruncateAt.END
leftPadding = p
rightPadding = p
textSize = 16f
}.lparams(width = matchParent, height = wrapContent) {
bottomMargin = dip(24)
}
linearLayout {
id = R.id.post_item_admin
visibility = View.GONE
button {
id = R.id.post_item_confirm
text = "Confirm"
}.lparams(width = matchParent, height = wrapContent) {
weight = 1f
}
button {
id = R.id.post_item_cancel
text = "Cancel"
}.lparams(width = matchParent, height = wrapContent) {
weight = 1f
}
}.lparams(width = matchParent, height = wrapContent) {
bottomMargin = dip(24)
}
}
}.view
} | mit | bfdc4ae784746db24fc980538732f75e | 26.95 | 60 | 0.636635 | 3.643478 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/GetVariableAction.kt | 1 | 2404 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKeyOrId
import ch.rmy.android.http_shortcuts.exceptions.ActionException
import ch.rmy.android.http_shortcuts.scripting.ExecutionContext
import ch.rmy.android.http_shortcuts.variables.VariableManager
import ch.rmy.android.http_shortcuts.variables.VariableResolver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class GetVariableAction(val variableKeyOrId: VariableKeyOrId) : BaseAction() {
@Inject
lateinit var variableResolver: VariableResolver
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override suspend fun execute(executionContext: ExecutionContext): String =
try {
getVariableValue(variableKeyOrId, executionContext.variableManager)
} catch (e: VariableNotFoundException) {
try {
resolveVariable(variableKeyOrId, executionContext.variableManager)
getVariableValue(variableKeyOrId, executionContext.variableManager)
} catch (e2: VariableNotFoundException) {
throw ActionException {
getString(R.string.error_variable_not_found_read, variableKeyOrId)
}
}
}
private fun getVariableValue(variableKeyOrId: VariableKeyOrId, variableManager: VariableManager): String =
variableManager.getVariableValueByKeyOrId(variableKeyOrId)
?: throw VariableNotFoundException()
private suspend fun resolveVariable(variableKeyOrId: VariableKeyOrId, variableManager: VariableManager) {
val variable = variableManager.getVariableByKeyOrId(variableKeyOrId)
?: throw VariableNotFoundException()
withContext(Dispatchers.Main) {
variableResolver.resolveVariables(
variablesToResolve = listOf(variable),
preResolvedValues = variableManager.getVariableValues(),
)
.forEach { (variable, value) ->
variableManager.setVariableValue(variable, value)
}
}
}
private class VariableNotFoundException : Throwable()
}
| mit | 6b2d3c59ec915d8f6c5f81c2f5002784 | 41.175439 | 110 | 0.717554 | 5.136752 | false | false | false | false |
kerubistan/kerub | src/test/kotlin/com/github/kerubistan/kerub/audit/AuditManagerImplTest.kt | 2 | 1364 | package com.github.kerubistan.kerub.audit
import com.github.kerubistan.kerub.data.AuditEntryDao
import com.github.kerubistan.kerub.model.AddEntry
import com.github.kerubistan.kerub.model.DeleteEntry
import com.github.kerubistan.kerub.model.UpdateEntry
import com.github.kerubistan.kerub.testVm
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.spy
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Test
class AuditManagerImplTest {
private val auditDao: AuditEntryDao = mock()
@Test
fun testAuditUpdate() {
val auditManager = spy(AuditManagerImpl(auditDao))
doReturn("TEST-USER").whenever(auditManager).getCurrentUser()
auditManager.auditUpdate(testVm, testVm.copy(name = "modified"))
verify(auditDao).add(any<UpdateEntry>())
}
@Test
fun testAuditDelete() {
val auditManager = spy(AuditManagerImpl(auditDao))
doReturn("TEST-USER").whenever(auditManager).getCurrentUser()
auditManager.auditDelete(testVm)
verify(auditDao).add(any<DeleteEntry>())
}
@Test
fun testAuditAdd() {
val auditManager = spy(AuditManagerImpl(auditDao))
doReturn("TEST-USER").whenever(auditManager).getCurrentUser()
auditManager.auditAdd(testVm)
verify(auditDao).add(any<AddEntry>())
}
} | apache-2.0 | ec9b93f559d10dd8b5d23921add9f029 | 27.4375 | 66 | 0.791056 | 3.497436 | false | true | false | false |
intrigus/jtransc | jtransc-gen-haxe/src/com/jtransc/gen/haxe/HaxeLib.kt | 1 | 1454 | package com.jtransc.gen.haxe
import com.jtransc.gen.haxe.HaxeCompiler
import com.jtransc.text.toUcFirst
import com.jtransc.vfs.LocalVfs
object HaxeLib {
data class LibraryRef(val name: String, val version: String) {
val id = name.toUcFirst() // Remove symbols!
val nameWithVersion = if (version.isNotEmpty()) "$name:$version" else "$name"
companion object {
fun fromVersion(it: String): LibraryRef {
val parts = it.split(':')
return LibraryRef(parts.getOrElse(0) { "" }, parts.getOrElse(1) { "" })
}
}
}
val vfs by lazy { HaxeCompiler.ensureHaxeCompilerVfs() }
val haxelibCmd by lazy { vfs["haxelib"].realpathOS }
fun haxelib(vararg args: String) = vfs.passthru(haxelibCmd, *args, env = HaxeCompiler.getExtraEnvs())
fun setup(folder: String) = haxelib("setup", folder)
fun exists(lib: LibraryRef): Boolean {
return haxelib("--always", "path", lib.nameWithVersion).success
}
fun install(lib: LibraryRef) {
if (lib.version.isEmpty()) {
haxelib("--always", "install", lib.name)
} else {
haxelib("--always", "install", lib.name, lib.version)
}
}
fun getHaxelibFolderFile(): String? {
// default folder: /usr/local/lib/haxe/lib
try {
return LocalVfs(System.getProperty("user.home") + "/.haxelib").readString().trim()
} catch (t: Throwable) {
return null
}
}
//fun downloadHaxeCompiler() {
//}
fun installIfNotExists(lib: LibraryRef) {
if (!exists(lib)) {
install(lib)
}
}
}
| apache-2.0 | f50a7b4c439ce807ec95751506550198 | 24.508772 | 102 | 0.676754 | 2.99177 | false | false | false | false |
suitougreentea/f-c-p-l-c | src/io/github/suitougreentea/fcplc/Player.kt | 1 | 2161 | package io.github.suitougreentea.fcplc
import io.github.suitougreentea.fcplc.state.PlayerWrapper
import org.newdawn.slick.Graphics
import org.newdawn.slick.Input
import java.util.*
class Player(val wrapper: PlayerWrapper, val resource: SystemResource, mode: Int, player: Int, maxPlayer: Int): EventHandler {
val logic: GameLogic = GameLogic(6, 12, 5, this)
val renderer = Renderer(resource, mode, player, maxPlayer)
fun update(controller: Controller) {
renderer.increaseTimer()
logic.update(controller)
}
fun render(g: Graphics) {
renderer.render(g, logic)
}
fun attackChain(chain: Int) {
val last = logic.garbageQueue.lastOrNull()
if(last != null && !last.done) last.chainSize = chain - 1
else logic.garbageQueue.add(GarbageQueue(1, chain - 1, ArrayList()))
}
fun attackCombo(combo: Int) {
val last = logic.garbageQueue.lastOrNull()
val size = when(combo) {
4 -> arrayOf(3)
5 -> arrayOf(4)
6 -> arrayOf(5)
7 -> arrayOf(6)
8 -> arrayOf(4, 3)
9 -> arrayOf(4, 4)
10 -> arrayOf(5, 5)
11 -> arrayOf(6, 5)
12 -> arrayOf(6, 6)
in 13..Int.MAX_VALUE -> Array(combo - 10, { 6 })
else -> throw IllegalStateException()
}
if(last != null && !last.done) last.other.addAll(size)
else {
val e = GarbageQueue(1, 0, size.toMutableList())
e.done = true
logic.garbageQueue.add(e)
}
}
fun breakAttack() {
logic.garbageQueue.forEach { it.done = true }
}
override fun erase(logic: GameLogic, chain: Boolean, eraseList: Set<EraseList>, eraseListGarbage: Set<EraseList>) {
renderer.erase(logic, chain, eraseList, eraseListGarbage)
wrapper.erase(logic, chain, eraseList, eraseListGarbage)
}
override fun swap(logic: GameLogic, x: Int, y: Long, left: Block?, right: Block?) {
renderer.swap(logic, x, y, left, right)
wrapper.swap(logic, x, y, left, right)
}
override fun gameOver(logic: GameLogic) {
wrapper.gameOver(logic)
}
override fun endChain(chain: Int) {
wrapper.endChain(chain)
}
override fun attack(chain: Int, combo: Int) {
wrapper.attack(chain, combo)
}
}
| mit | b3dc652bb184079e5cfc666cf3499e2c | 27.434211 | 126 | 0.654327 | 3.376563 | false | false | false | false |
blhps/lifeograph-android | app/src/main/java/net/sourceforge/lifeograph/DialogPassword.kt | 1 | 6702 | /* *********************************************************************************
Copyright (C) 2012-2021 Ahmet Öztürk ([email protected])
This file is part of Lifeograph.
Lifeograph 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.
Lifeograph 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 Lifeograph. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
package net.sourceforge.lifeograph
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
class DialogPassword(context: Context,
private val mDiary: Diary,
private val mAction: DPAction,
private val mListener: Listener) : Dialog(context) {
enum class DPAction {
DPA_LOGIN, DPA_AUTHENTICATE, DPA_ADD, DPAR_AUTH_FAILED // just returned as a result
}
private var mInput1: EditText? = null
private var mInput2: EditText? = null
private var mImage1: ImageView? = null
private var mImage2: ImageView? = null
private var mButtonOk: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.dialog_password)
setCancelable(true)
// mButtonOk must come before mInput as it is referenced there
mButtonOk = findViewById(R.id.passwordButtonPositive)
mButtonOk!!.setOnClickListener { go() }
mInput1 = findViewById(R.id.edit_password_1)
mInput2 = findViewById(R.id.edit_password_2)
mImage1 = findViewById(R.id.image_password_1)
mImage2 = findViewById(R.id.image_password_2)
when(mAction) {
DPAction.DPA_LOGIN -> {
setTitle("Enter password for " + mDiary._name)
mButtonOk!!.text = Lifeograph.getStr(R.string.open)
mInput2!!.visibility = View.GONE
mImage1!!.visibility = View.GONE
mImage2!!.visibility = View.GONE
}
DPAction.DPA_AUTHENTICATE -> {
setTitle("Enter the current password")
mButtonOk!!.text = Lifeograph.getStr(R.string.authenticate)
mInput2!!.visibility = View.GONE
mImage1!!.visibility = View.GONE
mImage2!!.visibility = View.GONE
}
DPAction.DPA_ADD -> {
setTitle("Enter the new password")
mButtonOk!!.text = Lifeograph.getStr(R.string.set_password)
}
DPAction.DPAR_AUTH_FAILED -> Log.d(Lifeograph.TAG, "Auth Failed")
}
if(Lifeograph.screenHeight >= Lifeograph.MIN_HEIGHT_FOR_NO_EXTRACT_UI)
mInput1!!.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
mInput1!!.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
check()
}
})
mInput1!!.setOnEditorActionListener { _: TextView?, _: Int,
_: KeyEvent? ->
if(mAction != DPAction.DPA_ADD &&
mInput1!!.text.length >= Diary.PASSPHRASE_MIN_SIZE) {
go()
true
}
else
false
}
mInput2!!.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
check()
}
})
val buttonNegative = findViewById<Button>(R.id.passwordButtonNegative)
buttonNegative.setOnClickListener { dismiss() }
}
private fun check() {
val passphrase = mInput1!!.text.toString()
val passphrase2 = mInput2!!.text.toString()
if(passphrase.length >= Diary.PASSPHRASE_MIN_SIZE) {
mImage1!!.setImageResource(R.drawable.ic_todo_done)
when {
mAction != DPAction.DPA_ADD -> {
mButtonOk!!.isEnabled = true
}
passphrase == passphrase2 -> {
mImage2!!.setImageResource(R.drawable.ic_check)
mButtonOk!!.isEnabled = true
}
else -> {
mImage2!!.setImageResource(
if(passphrase2.isEmpty()) R.drawable.ic_todo_open
else R.drawable.ic_todo_canceled)
mButtonOk!!.isEnabled = false
}
}
}
else {
mImage1!!.setImageResource(if(passphrase.isEmpty()) R.drawable.ic_todo_open
else R.drawable.ic_todo_canceled)
mImage2!!.setImageResource(if(passphrase2.isEmpty()) R.drawable.ic_todo_open
else R.drawable.ic_todo_canceled)
mButtonOk!!.isEnabled = false
}
}
private fun go() {
when(mAction) {
DPAction.DPA_LOGIN, DPAction.DPA_ADD -> {
mDiary.set_passphrase(mInput1!!.text.toString())
mListener.onDPAction(mAction)
}
DPAction.DPA_AUTHENTICATE ->
if(mDiary.compare_passphrase(mInput1!!.text.toString()))
mListener.onDPAction(mAction)
else
mListener.onDPAction(DPAction.DPAR_AUTH_FAILED)
else ->
Log.d( Lifeograph.TAG, "Unhandled return" )
}
dismiss()
}
interface Listener {
fun onDPAction(action: DPAction)
}
}
| gpl-3.0 | 10af2d4c09a9540a48f1fa62c1a75e28 | 39.853659 | 98 | 0.575373 | 4.698457 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/java/JavaShapeRenderer64BitCrashInspection.kt | 1 | 1728 | /*
* Copyright 2016 Blue Box Ware
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gmail.blueboxware.libgdxplugin.inspections.java
import com.gmail.blueboxware.libgdxplugin.inspections.isProblematicGDXVersionFor64Bit
import com.gmail.blueboxware.libgdxplugin.message
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiNewExpression
class JavaShapeRenderer64BitCrashInspection : LibGDXJavaBaseInspection() {
override fun getStaticDescription() = message("shaperenderer.64bit.crash.html.description")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : JavaElementVisitor() {
override fun visitNewExpression(expression: PsiNewExpression?) {
super.visitNewExpression(expression)
if (expression == null) return
if (expression.classReference?.qualifiedName == "com.badlogic.gdx.graphics.glutils.ShapeRenderer") {
if (isProblematicGDXVersionFor64Bit(expression.project)) {
holder.registerProblem(expression, message("shaperenderer.64bit.crash.problem.descriptor"))
}
}
}
}
}
| apache-2.0 | ba28dc2f639baca04f0cdcd23ea8337a | 37.4 | 112 | 0.740741 | 4.67027 | false | false | false | false |
ChainsDD/RxPreferences | lib/src/main/kotlin/com/noshufou/rxpreferences/RxPreferences.kt | 1 | 5313 | package com.noshufou.rxpreferences
import android.content.Context
import android.content.SharedPreferences
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
/**
* Base class for shared preferences
*
* @constructor creates an instance for accessing SharedPreferences
* @param context the context to get the SparedPreferences instance from
* @param name desired preferences file, defaults to context.packageName
* @param scheduler desired scheduler to read and write on, defaults to Schedulers.io()
*/
class RxPreferences(context: Context,
name: String = context.packageName,
private val scheduler: Scheduler = Schedulers.io()) {
private val prefs = context.getSharedPreferences(name, Context.MODE_PRIVATE)
// Use a ConnectedObservable here so we automatically subscribe and unsubscribe based on
// whether or not anyone is listening
private val changeObservable by lazy { SharedPreferencesChangeObservable(prefs, scheduler).share() }
/**
* Observe a SharedPreference
*
* @param T the type of the shared preference
* @param key the key you'd like to observe
* @param defValue default value to be used if the key doesn't exist
* @return an Observable of the shared preference
*/
@Suppress("UNCHECKED_CAST")
operator fun <T : Any> get(key: String, defValue: T): Observable<T> =
Observable.fromCallable {
when (defValue) {
is Boolean -> prefs.getBoolean(key, defValue) as T
is Float -> prefs.getFloat(key, defValue) as T
is Int -> prefs.getInt(key, defValue) as T
is Long -> prefs.getLong(key, defValue) as T
is String -> prefs.getString(key, defValue) as T
is Set<*> -> {
if (defValue.any { it !is String }) throw UnsupportedOperationException("Only Set<String> is supported")
prefs.getStringSet(key, defValue as Set<String>) as T
}
else -> throw UnsupportedOperationException("no accessor found for type ${defValue::class.java}")
}
}.subscribeOn(scheduler)
.concatWith(changeObservable.subscribeOn(scheduler)
.filter { it.first == key }
.map { it.second }
.map { it as T })
/**
* Obtain a Consumer for the given key
*
* This consumer does not check for the type of SharedPreference it is writing to. If you
* supply a key that was originally a different type, it will be overwritten with a new key
* of the given type. This is inline with how SharedPreferences works.
*
* @param T type of the Consumer, must be Boolean, Float, Int, Long, String or Set<String>
* @param key key for the SharedPreference you want to update
* @return a Consumer<T> that persists each value asynchronously
*/
operator fun <T : Any> get(key: String): Consumer<T> {
return Consumer {
EditorImpl(prefs).apply {
key to it
apply()
}
}
}
/**
* Edit the attached SharedPreferences asynchronously
*
* Similar to SharedPreferences.Editor, no checks are made regarding the type of existing keys.
* If you assign a key to a different type, it is simply overwritten.
*
* @param func lambda with a receiver of the Editor type
* @throws UnsupportedOperationException if a Set<> is used that contains anything other than Strings
*/
fun edit(func: Editor.() -> Unit) {
EditorImpl(prefs).apply {
func()
apply()
}
}
/**
* SharedPreferences.Editor
*/
interface Editor : SharedPreferences.Editor {
/**
* assign a value to a given key
*
* @receiver the key of the preference you want to assign
* @param value value to be assigned to the key, must be Boolean, Float, Int, Long, String, or Set<String>
* @throws UnsupportedOperationException if a Set<> is used that contains anything other than Strings
*/
infix fun String.to(value: Any)
}
private class EditorImpl(prefs: SharedPreferences)
: Editor, SharedPreferences.Editor by prefs.edit() {
override infix fun String.to(value: Any) {
when (value) {
is Boolean -> putBoolean(this, value)
is Float -> putFloat(this, value)
is Int -> putInt(this, value)
is Long -> putLong(this, value)
is String -> putString(this, value)
is Set<*> -> {
if (value.any { it !is String }) throw UnsupportedOperationException("Sets must only contain Strings")
@Suppress("UNCHECKED_CAST")
if (value.isEmpty()) remove(this)
else putStringSet(this, value as Set<String>)
}
else -> throw UnsupportedOperationException("type ${value::class.java} not supported")
}
}
}
}
| mit | c6b81e25dd43b7868c9aaad841d37fca | 39.869231 | 128 | 0.604743 | 5.012264 | false | false | false | false |
AK-47-D/cms | src/main/kotlin/com/ak47/cms/cms/entity/CenterBankRate.kt | 1 | 677 | package com.ak47.cms.cms.entity
import java.util.*
import javax.persistence.*
@Entity
@Table(name = "center_bank_rate")
class CenterBankRate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = -1
@Column(name = "item_id")
var item_id = ""
var title = ""
var rate = ""
@Column(name = "next_meeting_at")
var next_meeting_at = ""
@Column(name = "updated_at")
var updated_at = ""
var country = ""
@Column(name = "date_stamp")
var date_stamp = Date()
}
/*
{
id: 1,
title: "美联储",
rate: "1-1.25%",
next_meeting_at: "12月14日",
updated_at: 2017,
country: "us"
}
*/ | apache-2.0 | e9ebd7a006154dd2209153b76ecd4c69 | 14.534884 | 55 | 0.571214 | 3.031818 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.