repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mctoyama/PixelClient
|
src/main/kotlin/org/pixelndice/table/pixelclient/fx/TableController.kt
|
1
|
8475
|
package org.pixelndice.table.pixelclient.fx
import javafx.application.Platform
import org.pixelndice.table.pixelclient.ApplicationBus
import org.pixelndice.table.pixelclient.*
import com.google.common.eventbus.Subscribe
import javafx.concurrent.Worker
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.control.*
import javafx.scene.image.ImageView
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.paint.Color
import javafx.scene.web.WebEngine
import javafx.scene.web.WebView
import netscape.javascript.JSObject
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.PixelPreferences
import org.pixelndice.table.pixelclient.ds.Account
import org.pixelndice.table.pixelclient.ds.shell.ShellGameTag
import org.pixelndice.table.pixelclient.ds.shell.ShellTextMessage
import javafx.scene.layout.*
import javafx.scene.text.Font
import org.pixelndice.table.pixelclient.ds.ImageCache
private val logger = LogManager.getLogger(TableController::class.java)
class TableController {
private val handler = BusHandler()
@FXML
private var rootBorderPane: BorderPane? = null
@FXML
private var canvasPane: Pane? = null
private var pixelCanvas = PixelCanvas()
@FXML
private var boardSplitPane: SplitPane? = null
@FXML
private var dashboardSplitPane: SplitPane? = null
@FXML
private var cmdOutput: WebView? = null
@FXML
private var cmdTextArea: TextArea? = null
private var webEngine: WebEngine? = null
/** for communication to the Javascript engine. */
private var javascriptConnector: JSObject? = null
// initialize controler
fun initialize() {
ApplicationBus.register(handler)
// changing divider position
rootBorderPane!!.widthProperty().addListener { _ -> layout() }
rootBorderPane!!.heightProperty().addListener { _ -> layout() }
canvasPane!!.children.add(pixelCanvas)
pixelCanvas.widthProperty().bind(canvasPane!!.widthProperty())
pixelCanvas.heightProperty().bind(canvasPane!!.heightProperty())
pixelCanvas.widthProperty().addListener { _ ->
val tmpgc = pixelCanvas.graphicsContext2D
tmpgc.fill = Color.WHITE
tmpgc.fillRect(0.0, 0.0, pixelCanvas.width, pixelCanvas.height)
}
pixelCanvas.heightProperty().addListener { _ ->
val tmpgc = pixelCanvas.graphicsContext2D
tmpgc.fill = Color.WHITE
tmpgc.fillRect(0.0, 0.0, pixelCanvas.width, pixelCanvas.height)
}
cmdOutput!!.maxWidthProperty().bind(dashboardSplitPane!!.widthProperty())
cmdOutput!!.prefWidthProperty().bind(dashboardSplitPane!!.widthProperty())
currentCanvas = pixelCanvas
webEngine = cmdOutput!!.engine
// set up the listener
webEngine!!.loadWorker.stateProperty().addListener { _, _, newValue ->
if (Worker.State.SUCCEEDED == newValue) {
// get the Javascript connector object.
javascriptConnector = webEngine!!.executeScript("getJsConnector()") as JSObject
if( gameTag.isNotEmpty() and isGm() ) {
val gameTag = ShellGameTag(PixelResourceBundle.getString("key.inviteplayers"), gameTag)
ApplicationBus.post(ApplicationBus.ShellDisplay(gameTag))
logger.info("Sending game tag to shell display.")
}
}
}
val url = App::class.java.getResource("/Shell.html").toURI().toURL()
// now load the page
webEngine!!.load(url.toString())
}
@FXML
private fun libraryButtonOnAction(@Suppress("UNUSED_PARAMETER") event: ActionEvent) {
ApplicationBus.post(ApplicationBus.LoadLibrary())
}
@FXML
private fun cmdOnKeyReleased(event: KeyEvent){
if (event.code == KeyCode.ENTER && !event.isControlDown) {
ApplicationBus.post(ApplicationBus.SendTextMessage(myAccount, true, Account(), cmdTextArea!!.text))
cmdTextArea!!.text = ""
}else if (event.code == KeyCode.ENTER && event.isControlDown) {
cmdTextArea!!.appendText(System.getProperty("line.separator"))
}
}
private fun switchTurnOrder() {
if( rootBorderPane!!.top == null ) {
ApplicationBus.post(ApplicationBus.SendShowTurnOrderProtocol())
}else{
ApplicationBus.post(ApplicationBus.SendHideTurnOrderProtocol())
}
}
fun showTurnOrder(){
val pane = HBox()
pane.isFillHeight = true
pane.alignment = Pos.CENTER_LEFT
val title = Label(PixelResourceBundle.getString("key.turnorder"))
title.font = Font(22.0)
val scrollPane = ScrollPane()
HBox.setHgrow(scrollPane, Priority.ALWAYS)
scrollPane.isFitToHeight = true
scrollPane.isFitToWidth = true
// content hbox for GameResources icons
val hbox = HBox()
scrollPane.content = hbox
// menu hbox
val hboxMenu = HBox()
val ascMenu = MenuItem(PixelResourceBundle.getString("key.ascending"))
val descMenu = MenuItem(PixelResourceBundle.getString("key.descending"))
val menuButton = MenuButton(PixelResourceBundle.getString("key.order"), ImageView(ImageCache.getImage(ORDER_ICON_PATH)), ascMenu, descMenu)
HBox.setMargin(menuButton, Insets(7.0, 7.0, 7.0, 7.0))
val buttonNext = Button(PixelResourceBundle.getString("key.next"), ImageView(ImageCache.getImage(NEXT_ICON_PATH)))
HBox.setMargin(buttonNext, Insets(7.0, 7.0, 7.0, 7.0))
hboxMenu.children.addAll(menuButton, buttonNext)
pane.children.addAll(title, scrollPane, hboxMenu)
rootBorderPane!!.top = pane
}
fun hideTurnOrder(){
rootBorderPane!!.top = null
}
// fix layout after stage.maximazed
fun layout() {
// loads boardSplitPane preferences
boardSplitPane!!.setDividerPosition(0, PixelPreferences.getDouble(BOARD_DIVIDER_POSITION, BOARD_DEFAULT_DIVIDER_POSITION))
// loads dashboardSplitPane preferences
dashboardSplitPane!!.setDividerPosition(0,
PixelPreferences.getDouble(DASHBOARD_DIVIDER_POSITION, DASHBOARD_DEFAULT_DIVIDER_POSITION))
}
// executes this method on stage close
fun onClose() {
PixelPreferences.putDouble(BOARD_DIVIDER_POSITION, boardSplitPane!!.dividers[0].position)
PixelPreferences.putDouble(DASHBOARD_DIVIDER_POSITION, dashboardSplitPane!!.dividers[0].position)
}
// ApplicationBus handler
private inner class BusHandler {
@Subscribe
fun handleSwitchTurnOrder(@Suppress("UNUSED_PARAMETER") event: ApplicationBus.SwitchTurnOrder){
switchTurnOrder()
}
@Subscribe
fun handleShowTurnOrder(@Suppress("UNUSED_PARAMETER") event: ApplicationBus.ReceiveShowTurnOrderProtocol){
Platform.runLater {
showTurnOrder()
}
}
@Subscribe
fun handleHideTurnOrder(@Suppress("UNUSED_PARAMETER") event: ApplicationBus.ReceiveHideTurnOrderProtocol){
Platform.runLater {
hideTurnOrder()
}
}
@Subscribe
fun handleReceiveTextMessage(ev: ApplicationBus.ReceiveTextMessage){
val textMessage = ShellTextMessage(ev.from.name, ev.toAll, ev.text)
ApplicationBus.post(ApplicationBus.ShellDisplay(textMessage))
}
@Subscribe
fun handleShellDisplay(ev: ApplicationBus.ShellDisplay) {
Platform.runLater {
javascriptConnector?.call("show", ev.message.json()) ?: run {
logger.warn("Unable to display shell message: ${ev.message}")
}
}
}
}
companion object {
private const val DASHBOARD_DIVIDER_POSITION = "key.dashboardDividerPosition"
private const val DASHBOARD_DEFAULT_DIVIDER_POSITION = 0.66
private const val BOARD_DIVIDER_POSITION = "key.boardDividerPosition"
private const val BOARD_DEFAULT_DIVIDER_POSITION = 0.66
private const val ORDER_ICON_PATH = "/icons/open-iconic-master/png/clock-3x.png"
private const val NEXT_ICON_PATH = "/icons/open-iconic-master/png/arrow-right-3x.png"
}
}
|
bsd-2-clause
|
a23cdf323a4b22d9d648766eedadefde
| 32.105469 | 147 | 0.668791 | 4.623568 | false | false | false | false |
marcelgross90/Cineaste
|
app/src/main/kotlin/de/cineaste/android/activity/MovieSearchActivity.kt
|
1
|
1915
|
package de.cineaste.android.activity
import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.reflect.TypeToken
import de.cineaste.android.R
import de.cineaste.android.adapter.movie.MovieSearchQueryAdapter
import de.cineaste.android.database.dao.BaseDao
import de.cineaste.android.entity.movie.Movie
import de.cineaste.android.network.NetworkClient
import de.cineaste.android.network.NetworkRequest
import java.lang.reflect.Type
class MovieSearchActivity : AbstractSearchActivity() {
private lateinit var movieQueryAdapter: MovieSearchQueryAdapter
override val layout: Int
get() = R.layout.activity_search
override val listAdapter: RecyclerView.Adapter<*>
get() = movieQueryAdapter
override val listType: Type
get() = object : TypeToken<List<Movie>>() {
}.type
override fun getIntentForDetailActivity(itemId: Long): Intent {
val intent = Intent(this, MovieDetailActivity::class.java)
intent.putExtra(BaseDao.MovieEntry.ID, itemId)
intent.putExtra(this.getString(R.string.state), R.string.searchState)
return intent
}
override fun initAdapter() {
movieQueryAdapter = MovieSearchQueryAdapter(this)
}
override fun getSuggestions() {
val client = NetworkClient(NetworkRequest(resources).upcomingMovies)
client.sendRequest(networkCallback)
}
override fun searchRequest(searchQuery: String) {
val client = NetworkClient(NetworkRequest(resources).searchMovie(searchQuery))
client.sendRequest(networkCallback)
}
override fun getRunnable(json: String, listType: Type): Runnable {
return Runnable {
val movies: List<Movie> = gson.fromJson(json, listType)
movieQueryAdapter.addMovies(movies)
progressBar.visibility = View.GONE
}
}
}
|
gpl-3.0
|
d37959e9c80d7fde666dba19a3d9632c
| 32.596491 | 86 | 0.727937 | 4.603365 | false | false | false | false |
BilledTrain380/sporttag-psa
|
app/psa-runtime-service/psa-service-athletics/src/main/kotlin/ch/schulealtendorf/psa/service/athletics/business/CompetitorManagerImpl.kt
|
1
|
4895
|
/*
* Copyright (c) 2018 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.athletics.business
import ch.schulealtendorf.psa.core.toOptional
import ch.schulealtendorf.psa.dto.participation.CompetitorDto
import ch.schulealtendorf.psa.dto.participation.athletics.ResultDto
import ch.schulealtendorf.psa.service.standard.competitorDtoOf
import ch.schulealtendorf.psa.service.standard.entity.CompetitorEntity
import ch.schulealtendorf.psa.service.standard.repository.CompetitorRepository
import ch.schulealtendorf.psa.service.standard.resultDtoOf
import ch.schulealtendorf.psa.shared.rulebook.FormulaModel
import ch.schulealtendorf.psa.shared.rulebook.ResultRuleBook
import mu.KotlinLogging
import org.springframework.stereotype.Component
import java.util.Optional
/**
* {@link CompetitorManager} implementation which uses the repository classes.
*
* @author nmaerchy <[email protected]>
* @since 2.0.0
*/
@Component
class CompetitorManagerImpl(
private val resultRuleBook: ResultRuleBook,
private val competitorRepository: CompetitorRepository
) : CompetitorManager {
private val log = KotlinLogging.logger {}
override fun getCompetitors(): List<CompetitorDto> {
return competitorRepository.findAll().map { competitorDtoOf(it) }
}
override fun getCompetitors(filter: CompetitorFilter): List<CompetitorDto> {
log.info { "Get competitors by filter $filter" }
// Mainly filter the group on the database query if present
// We should not have any performance issues by filtering gender and absent in memory
val competitors: List<CompetitorEntity> = if (filter.group != null) {
competitorRepository.findByParticipantGroupName(filter.group)
} else {
competitorRepository.findAll().toList()
}
return competitors
.filter { filter.filterByGender(it.participant.gender) }
.filter { filter.filterByAbsent(it.participant.absent) }
.map { competitorDtoOf(it) }
}
override fun getCompetitor(id: Int): Optional<CompetitorDto> {
return competitorRepository.findByParticipantId(id).map { competitorDtoOf(it) }
}
override fun updateResult(resultAmend: CompetitorResultAmend): ResultDto {
val competitor = competitorRepository.findByParticipantId(resultAmend.competitorId)
.orElseThrow { NoSuchElementException("Could not find competitor: id=${resultAmend.competitorId}") }
val result = competitor.results
.find { it.id == resultAmend.result.id }
.toOptional()
.orElseThrow { NoSuchElementException("Could not find result: id=${resultAmend.result.id}") }
val formulaModel = FormulaModel(
discipline = result.discipline.name,
distance = result.distance,
result = resultAmend.result.value.toDouble() / result.discipline.unit.factor,
gender = result.competitor.participant.gender
)
result.apply {
value = resultAmend.result.value
points = resultRuleBook.calc(formulaModel)
}
log.info { "Update competitor result: competitor=${competitor.participant.fullName}" }
competitorRepository.save(competitor)
return resultDtoOf(result)
}
override fun deleteCompetitor(startNumber: Int) {
competitorRepository.deleteById(startNumber)
}
}
|
gpl-3.0
|
4c886764a23203e8b005da519ddcfc5e
| 39.708333 | 112 | 0.730399 | 4.381166 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/psi/ext/RsGenericDeclaration.kt
|
2
|
2554
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import org.rust.lang.core.psi.*
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.emptySubstitution
import org.rust.lang.core.types.rawType
import org.rust.lang.core.types.toTypeSubst
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyTypeParameter
interface RsGenericDeclaration : RsElement {
val typeParameterList: RsTypeParameterList?
val whereClause: RsWhereClause?
}
fun RsGenericDeclaration.getGenericParameters(
includeLifetimes: Boolean = true,
includeTypes: Boolean = true,
includeConsts: Boolean = true
): List<RsGenericParameter> = typeParameterList?.getGenericParameters(
includeLifetimes,
includeTypes,
includeConsts
).orEmpty()
val RsGenericDeclaration.typeParameters: List<RsTypeParameter>
get() = typeParameterList?.typeParameterList.orEmpty()
val RsGenericDeclaration.lifetimeParameters: List<RsLifetimeParameter>
get() = typeParameterList?.lifetimeParameterList.orEmpty()
val RsGenericDeclaration.constParameters: List<RsConstParameter>
get() = typeParameterList?.constParameterList.orEmpty()
val RsGenericDeclaration.requiredGenericParameters: List<RsGenericParameter>
get() = getGenericParameters().filter {
when (it) {
is RsTypeParameter -> it.typeReference == null
is RsConstParameter -> it.expr == null
else -> false
}
}
fun <T : RsGenericDeclaration> T.withSubst(vararg subst: Ty): BoundElement<T> {
val typeParameterList = typeParameters
val nonDefaultCount = typeParameterList.asSequence()
.takeWhile { it.typeReference == null }
.count()
val substitution = if (subst.size < nonDefaultCount || subst.size > typeParameterList.size) {
val name = if (this is RsNamedElement) name else "unnamed"
LOG.warn("Item `$name` has ${typeParameterList.size} type parameters but received ${subst.size} types for substitution")
emptySubstitution
} else {
typeParameterList.withIndex().associate { (i, par) ->
val paramTy = TyTypeParameter.named(par)
paramTy to (subst.getOrNull(i) ?: par.typeReference?.rawType ?: paramTy)
}.toTypeSubst()
}
return BoundElement(this, substitution)
}
private val LOG: Logger = logger<RsGenericDeclaration>()
|
mit
|
f2115e40102b27629bb0a81f95867e08
| 36.014493 | 128 | 0.731402 | 4.496479 | false | false | false | false |
yzbzz/beautifullife
|
icore/src/main/java/com/ddu/icore/ui/fragment/DefaultFragment.kt
|
2
|
3775
|
package com.ddu.icore.ui.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ddu.icore.R
import com.ddu.icore.ui.activity.BaseActivity
import com.ddu.icore.ui.activity.ShowDetailActivity
import com.ddu.icore.ui.widget.TitleBar
import com.ddu.icore.util.FragmentUtils
abstract class DefaultFragment : BaseFragment() {
protected lateinit var baseActivity: BaseActivity
protected lateinit var mView: View
var titleBar: TitleBar? = null
protected set
protected var mCustomerTitleBar: View? = null
abstract fun getLayoutId(): Int
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
baseActivity = mActivity as BaseActivity
}
override fun getContentView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (isShowTitleBar()) {
mView = inflater.inflate(R.layout.i_activity_base, container, false)
titleBar = mView.findViewById(R.id.ll_title_bar)
inflater.inflate(getLayoutId(), mView as ViewGroup, true)
} else {
mView = inflater.inflate(getLayoutId(), container, false)
}
return mView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (userDefaultTitle()) {
val title = arguments?.getString("title", "")
if (!title.isNullOrEmpty()) {
setDefaultTitle(title!!)
}
}
initView()
}
open fun userDefaultTitle() = true
abstract fun initView()
fun startFragment(className: Class<out androidx.fragment.app.Fragment>) {
baseActivity?.startFragment(className)
}
fun startFragment(className: String) {
baseActivity?.startFragment(className)
}
fun startFragment(className: String, bundle: Bundle) {
baseActivity?.startFragment(className, bundle)
}
fun startFragment(className: Class<out androidx.fragment.app.Fragment>, bundle: Bundle) {
baseActivity?.startFragment(className, bundle)
}
fun replaceFragment(fragment: androidx.fragment.app.Fragment) {
if (mActivity is ShowDetailActivity) {
(mActivity as ShowDetailActivity).replaceFragment(fragment, FragmentUtils.FRAGMENT_ADD_TO_BACK_STACK)
}
}
fun setTitle(resId: Int) {
if (null != titleBar) {
titleBar!!.setMiddleText(resId)
}
}
fun setTitle(title: String) {
if (null != titleBar) {
titleBar!!.setMiddleText(title)
}
}
fun setDefaultTitle(resId: Int) {
if (null != titleBar) {
titleBar!!.setDefaultTitle(resId) { baseActivity?.onBackPressed() }
}
}
fun setDefaultTitle(title: String) {
if (null != titleBar) {
titleBar!!.setDefaultTitle(title) { baseActivity?.onBackPressed() }
}
}
fun setRightText(text: String, onClickListener: View.OnClickListener) {
if (null != titleBar) {
titleBar!!.setRightText(text, onClickListener)
}
}
fun setRightImg(resId: Int, onClickListener: View.OnClickListener) {
if (null != titleBar) {
titleBar!!.setRightImg(resId, onClickListener)
}
}
fun setTitleBarOnClickListener(onClickListener: View.OnClickListener) {
if (null != titleBar) {
titleBar!!.setOnClickListener(onClickListener)
}
}
fun <T : View> findViewById(resId: Int): T {
return mView.findViewById(resId)
}
companion object {
val ARGUMENT_TASK_ID = "ARGUMENT_TASK_ID"
}
}
|
apache-2.0
|
ed59fe8963ee37498e0117b765b2c849
| 28.960317 | 118 | 0.645828 | 4.654747 | false | false | false | false |
physphil/UnitConverterUltimate
|
v6000/src/main/java/com/physphil/android/unitconverterultimate/ConversionFragment.kt
|
1
|
3710
|
package com.physphil.android.unitconverterultimate
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.core.view.get
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.physphil.android.unitconverterultimate.conversion.ConversionRepository
import com.physphil.android.unitconverterultimate.models.ConversionType
import kotlinx.android.synthetic.main.fragment_conversion.*
import java.math.BigDecimal
class ConversionFragment : Fragment() {
companion object {
const val ARGS_CONVERSION_TYPE = "argConversionType"
}
private lateinit var conversionViewModel: ConversionViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_conversion, container, false)
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
val conversionType = arguments?.getSerializable(ARGS_CONVERSION_TYPE) as? ConversionType
?: throw IllegalArgumentException("Proper conversion type not specified when starting fragment")
val factory = ConversionViewModel.Factory(conversionType, ConversionRepository())
conversionViewModel = ViewModelProviders.of(this, factory).get(ConversionViewModel::class.java)
conversionViewModel.init(this)
initViewListeners()
}
private fun initViewListeners() {
valueTextView.doOnTextChanged { text, _, _, _ ->
val input = when {
text.isNullOrEmpty() -> BigDecimal.ZERO
else -> BigDecimal(text.toString())
}
conversionViewModel.updateValue(input)
}
initialRadioGroupView.setOnCheckedChangeListener { group, checkedId ->
conversionViewModel.updateInitialIndex(checkedId)
}
finalRadioGroupView.setOnCheckedChangeListener { _, checkedId ->
conversionViewModel.updateFinalIndex(checkedId)
}
swapUnitsButtonView.setOnClickListener {
conversionViewModel.swapUnits()
}
}
// FIXME: move to View class
private fun renderView(state: ConversionViewModel.ViewData) {
state.units.forEachIndexed { index, unit ->
val initialButton = RadioButton(this.context).apply {
id = index
text = getString(unit.displayStringResId)
}
initialRadioGroupView.addView(initialButton)
val finalButton = RadioButton(this.context).apply {
id = index
text = getString(unit.displayStringResId)
}
finalRadioGroupView.addView(finalButton)
}
valueTextView.setText(state.value.toPlainString())
}
private fun ConversionViewModel.init(lifecycleOwner: LifecycleOwner) {
viewData.observe(lifecycleOwner, Observer {
renderView(it)
})
selectedUnitsLiveData.observe(lifecycleOwner, Observer {
initialRadioGroupView.checkIndex(it.initialIndex)
finalRadioGroupView.checkIndex(it.finalIndex)
})
resultLiveData.observe(lifecycleOwner, Observer {
resultTextView.text = it.toPlainString()
})
}
private fun RadioGroup.checkIndex(index: Int) {
this.check(this[index].id)
}
}
|
apache-2.0
|
bade2a48437c706aa251fa653f38efdd
| 34.009434 | 108 | 0.69407 | 5.210674 | false | false | false | false |
google/playhvz
|
Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/operations/QuizQuestionDatabaseOperations.kt
|
1
|
5399
|
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz.firebase.operations
import android.util.Log
import com.app.playhvz.firebase.classmodels.QuizQuestion
import com.app.playhvz.firebase.classmodels.QuizQuestion.Companion.FIELD__INDEX
import com.app.playhvz.firebase.constants.QuizQuestionPath
import com.app.playhvz.firebase.firebaseprovider.FirebaseProvider
import com.app.playhvz.firebase.utils.FirebaseDatabaseUtil
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.firestore.CollectionReference
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.DocumentSnapshot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class QuizQuestionDatabaseOperations {
companion object {
private val TAG = QuizQuestionDatabaseOperations::class.qualifiedName
/** Returns a collection reference to the given gameId. */
fun getQuizQuestionCollectionReference(
gameId: String
): CollectionReference {
return QuizQuestionPath.QUIZ_QUESTION_COLLECTION(gameId)
}
/** Returns a document reference to the given questionId. */
fun getQuizQuestionDocumentReference(
gameId: String,
questionId: String
): DocumentReference {
return QuizQuestionPath.QUIZ_QUESTION_DOCUMENT_REFERENCE(gameId, questionId)
}
fun getQuizQuestionDocument(
gameId: String,
questionId: String,
onSuccessListener: OnSuccessListener<DocumentSnapshot>
) {
FirebaseDatabaseUtil.optimizedGet(
QuizQuestionPath.QUIZ_QUESTION_DOCUMENT_REFERENCE(
gameId,
questionId
), onSuccessListener
)
}
suspend fun asyncCreateQuizQuestion(
gameId: String,
questionDraft: QuizQuestion,
successListener: () -> Unit,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
QuizQuestionPath.QUIZ_QUESTION_COLLECTION(gameId).add(
QuizQuestion.createFirebaseObject(questionDraft)
).addOnSuccessListener {
successListener.invoke()
}.addOnFailureListener {
Log.e(TAG, "Failed to create quiz question: " + it)
failureListener.invoke()
}
}
suspend fun asyncUpdateQuizQuestion(
gameId: String,
questionId: String,
questionDraft: QuizQuestion,
successListener: () -> Unit,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
QuizQuestionPath.QUIZ_QUESTION_DOCUMENT_REFERENCE(gameId, questionId).set(
QuizQuestion.createFirebaseObject(questionDraft)
).addOnSuccessListener {
successListener.invoke()
}.addOnFailureListener {
Log.e(TAG, "Failed to update quiz question: " + it)
failureListener.invoke()
}
}
/** Permanently deletes question. */
suspend fun asyncDeleteQuestion(
gameId: String,
questionId: String,
successListener: () -> Unit,
failureListener: () -> Unit
) = withContext(Dispatchers.Default) {
val data = hashMapOf(
"gameId" to gameId,
"questionId" to questionId
)
FirebaseProvider.getFirebaseFunctions()
.getHttpsCallable("deleteQuizQuestion")
.call(data)
.continueWith { task ->
if (!task.isSuccessful) {
failureListener.invoke()
return@continueWith
}
successListener.invoke()
}
}
suspend fun swapQuestionIndexes(
gameId: String,
question1: QuizQuestion,
question2: QuizQuestion
) {
val newQuestion1Index = question2.index!!
val newQuestion2Index = question1.index!!
val question1DocRef = getQuizQuestionDocumentReference(gameId, question1.id!!)
val question2DocRef = getQuizQuestionDocumentReference(gameId, question2.id!!)
FirebaseProvider.getFirebaseFirestore().runTransaction { transaction ->
transaction.update(question1DocRef, FIELD__INDEX, newQuestion1Index)
transaction.update(question2DocRef, FIELD__INDEX, newQuestion2Index)
null
}.addOnSuccessListener { Log.d(TAG, "Transaction success!") }
.addOnFailureListener { e -> Log.w(TAG, "Transaction failure.", e) }
}
}
}
|
apache-2.0
|
5c08d614fe3d9e0d69a3f0c868f3e665
| 37.571429 | 90 | 0.625671 | 5.303536 | false | false | false | false |
nakih/kotlin-koans
|
src/i_introduction/_4_Lambdas/Lambdas.kt
|
1
|
723
|
package i_introduction._4_Lambdas
import util.TODO
import util.doc4
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
Rewrite 'JavaCode4.task4()' in Kotlin using lambdas.
You can find the appropriate function to call on 'collection' through IntelliJ IDEA's code completion feature.
(Don't use the class 'Iterables').
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
fun task4(collection: Collection<Int>): Boolean {
return collection.any { number: Int -> (number % 42) == 0 }
}
|
mit
|
9e66842476287f8e83b07f4b221701fd
| 23.1 | 118 | 0.615491 | 3.688776 | false | false | false | false |
actions-on-google/appactions-common-biis-kotlin
|
app/src/sharedTest/java/com/example/android/architecture/blueprints/todoapp/data/source/local/TasksLocalDataSourceTest.kt
|
1
|
6654
|
/*
* Copyright (C) 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.data.source.local
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.example.android.architecture.blueprints.todoapp.MainCoroutineRule
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource
import com.example.android.architecture.blueprints.todoapp.data.succeeded
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.CoreMatchers.`is`
import org.junit.After
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Integration test for the [TasksDataSource].
*/
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
@MediumTest
class TasksLocalDataSourceTest {
private lateinit var localDataSource: TasksLocalDataSource
private lateinit var database: ToDoDatabase
// Set the main coroutines dispatcher for unit testing.
@ExperimentalCoroutinesApi
@get:Rule
var mainCoroutineRule = MainCoroutineRule()
// Executes each task synchronously using Architecture Components.
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
@Before
fun setup() {
// using an in-memory database for testing, since it doesn't survive killing the process
database = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
ToDoDatabase::class.java
)
.allowMainThreadQueries()
.build()
localDataSource = TasksLocalDataSource(database.taskDao(), Dispatchers.Main)
}
@After
fun cleanUp() {
database.close()
}
@Test
fun saveTask_retrievesTask() = runBlockingTest {
// GIVEN - a new task saved in the database
val newTask = Task("title", "description", true)
localDataSource.saveTask(newTask)
// WHEN - Task retrieved by ID
val result = localDataSource.getTask(newTask.id)
// THEN - Same task is returned
assertThat(result.succeeded, `is`(true))
result as Success
assertThat(result.data.title, `is`("title"))
assertThat(result.data.description, `is`("description"))
assertThat(result.data.isCompleted, `is`(true))
}
@Test
fun completeTask_retrievedTaskIsComplete() = runBlockingTest {
// Given a new task in the persistent repository
val newTask = Task("title")
localDataSource.saveTask(newTask)
// When completed in the persistent repository
localDataSource.completeTask(newTask)
val result = localDataSource.getTask(newTask.id)
// Then the task can be retrieved from the persistent repository and is complete
assertThat(result.succeeded, `is`(true))
result as Success
assertThat(result.data.title, `is`(newTask.title))
assertThat(result.data.isCompleted, `is`(true))
}
@Test
fun activateTask_retrievedTaskIsActive() = runBlockingTest {
// Given a new completed task in the persistent repository
val newTask = Task("Some title", "Some description", true)
localDataSource.saveTask(newTask)
localDataSource.activateTask(newTask)
// Then the task can be retrieved from the persistent repository and is active
val result = localDataSource.getTask(newTask.id)
assertThat(result.succeeded, `is`(true))
result as Success
assertThat(result.data.title, `is`("Some title"))
assertThat(result.data.isCompleted, `is`(false))
}
@Test
fun clearCompletedTask_taskNotRetrievable() = runBlockingTest {
// Given 2 new completed tasks and 1 active task in the persistent repository
val newTask1 = Task("title")
val newTask2 = Task("title2")
val newTask3 = Task("title3")
localDataSource.saveTask(newTask1)
localDataSource.completeTask(newTask1)
localDataSource.saveTask(newTask2)
localDataSource.completeTask(newTask2)
localDataSource.saveTask(newTask3)
// When completed tasks are cleared in the repository
localDataSource.clearCompletedTasks()
// Then the completed tasks cannot be retrieved and the active one can
assertThat(localDataSource.getTask(newTask1.id).succeeded, `is`(false))
assertThat(localDataSource.getTask(newTask2.id).succeeded, `is`(false))
val result3 = localDataSource.getTask(newTask3.id)
assertThat(result3.succeeded, `is`(true))
result3 as Success
assertThat(result3.data, `is`(newTask3))
}
@Test
fun deleteAllTasks_emptyListOfRetrievedTask() = runBlockingTest {
// Given a new task in the persistent repository and a mocked callback
val newTask = Task("title")
localDataSource.saveTask(newTask)
// When all tasks are deleted
localDataSource.deleteAllTasks()
// Then the retrieved tasks is an empty list
val result = localDataSource.getTasks() as Success
assertThat(result.data.isEmpty(), `is`(true))
}
@Test
fun getTasks_retrieveSavedTasks() = runBlockingTest {
// Given 2 new tasks in the persistent repository
val newTask1 = Task("title")
val newTask2 = Task("title")
localDataSource.saveTask(newTask1)
localDataSource.saveTask(newTask2)
// Then the tasks can be retrieved from the persistent repository
val results = localDataSource.getTasks() as Success<List<Task>>
val tasks = results.data
assertThat(tasks.size, `is`(2))
}
}
|
apache-2.0
|
dfc7c82d975960a69492b3febf5a2ddb
| 35.360656 | 96 | 0.706943 | 4.679325 | false | true | false | false |
fengbaicanhe/intellij-community
|
plugins/settings-repository/src/IcsManager.kt
|
1
|
10703
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.ide.ApplicationLoadListener
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.impl.stores.StorageUtil
import com.intellij.openapi.components.impl.stores.StreamProvider
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectLifecycleListener
import com.intellij.openapi.util.AtomicNotNullLazyValue
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.SingleAlarm
import com.intellij.util.SystemProperties
import org.jetbrains.keychain.CredentialsStore
import org.jetbrains.keychain.FileCredentialsStore
import org.jetbrains.keychain.OsXCredentialsStore
import org.jetbrains.keychain.isOSXCredentialsStoreSupported
import org.jetbrains.settingsRepository.git.GitRepositoryManager
import org.jetbrains.settingsRepository.git.GitRepositoryService
import org.jetbrains.settingsRepository.git.processChildren
import java.io.File
import java.io.InputStream
import kotlin.properties.Delegates
val PLUGIN_NAME: String = "Settings Repository"
val LOG: Logger = Logger.getInstance(javaClass<IcsManager>())
val icsManager by Delegates.lazy {
ApplicationLoadListener.EP_NAME.findExtension(javaClass<IcsApplicationLoadListener>()).icsManager
}
class IcsManager(dir: File) {
val credentialsStore = object : AtomicNotNullLazyValue<CredentialsStore>() {
override fun compute(): CredentialsStore {
if (isOSXCredentialsStoreSupported && SystemProperties.getBooleanProperty("ics.use.osx.keychain", true)) {
try {
return OsXCredentialsStore("IntelliJ Platform Settings Repository")
}
catch (e: Throwable) {
LOG.error(e)
}
}
return FileCredentialsStore(File(dir, ".git_auth"))
}
}
val settingsFile = File(dir, "config.json")
val settings: IcsSettings
val repositoryManager: RepositoryManager = GitRepositoryManager(credentialsStore, File(dir, "repository"))
init {
try {
settings = loadSettings(settingsFile)
}
catch (e: Exception) {
settings = IcsSettings()
LOG.error(e)
}
}
val readOnlySourcesManager = ReadOnlySourcesManager(settings, dir)
val repositoryService: RepositoryService = GitRepositoryService()
private val commitAlarm = SingleAlarm(object : Runnable {
override fun run() {
ProgressManager.getInstance().run(object : Task.Backgroundable(null, IcsBundle.message("task.commit.title")) {
override fun run(indicator: ProgressIndicator) {
try {
repositoryManager.commit(indicator)
}
catch (e: Throwable) {
LOG.error(e)
}
}
})
}
}, settings.commitDelay)
private volatile var autoCommitEnabled = true
volatile var repositoryActive = false
private val autoSyncManager = AutoSyncManager(this)
private val syncManager = SyncManager(this, autoSyncManager)
private fun scheduleCommit() {
if (autoCommitEnabled && !ApplicationManager.getApplication()!!.isUnitTestMode()) {
commitAlarm.cancelAndRequest()
}
}
inner class ApplicationLevelProvider : IcsStreamProvider(null) {
override fun delete(fileSpec: String, roamingType: RoamingType) {
if (syncManager.writeAndDeleteProhibited) {
throw IllegalStateException("Delete is prohibited now")
}
repositoryManager.delete(buildPath(fileSpec, roamingType))
scheduleCommit()
}
}
private fun registerProjectLevelProviders(project: Project) {
val storageManager = project.stateStore.getStateStorageManager()
val projectId = storageManager.getStateStorage(StoragePathMacros.WORKSPACE_FILE, RoamingType.DISABLED).getState(ProjectId(), "IcsProjectId", javaClass<ProjectId>(), null)
if (projectId == null || projectId.uid == null) {
// not mapped, if user wants, he can map explicitly, we don't suggest
// we cannot suggest "map to ICS" for any project that user opens, it will be annoying
return
}
storageManager.setStreamProvider(ProjectLevelProvider(projectId.uid!!))
// updateStoragesFromStreamProvider(storageManager, storageManager.getStorageFileNames())
}
private inner class ProjectLevelProvider(projectId: String) : IcsStreamProvider(projectId) {
override fun isAutoCommit(fileSpec: String, roamingType: RoamingType) = !StorageUtil.isProjectOrModuleFile(fileSpec)
override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean {
if (StorageUtil.isProjectOrModuleFile(fileSpec)) {
// applicable only if file was committed to Settings Server explicitly
return repositoryManager.has(buildPath(fileSpec, roamingType, this.projectId))
}
return settings.shareProjectWorkspace || fileSpec != StoragePathMacros.WORKSPACE_FILE
}
}
fun sync(syncType: SyncType, project: Project?, localRepositoryInitializer: (() -> Unit)? = null) = syncManager.sync(syncType, project, localRepositoryInitializer)
private fun cancelAndDisableAutoCommit() {
if (autoCommitEnabled) {
autoCommitEnabled = false
commitAlarm.cancel()
}
}
fun runInAutoCommitDisabledMode(task: ()->Unit) {
cancelAndDisableAutoCommit()
try {
task()
}
finally {
autoCommitEnabled = true
repositoryActive = repositoryManager.isRepositoryExists()
}
}
fun beforeApplicationLoaded(application: Application) {
repositoryActive = repositoryManager.isRepositoryExists()
application.stateStore.getStateStorageManager().setStreamProvider(ApplicationLevelProvider())
autoSyncManager.registerListeners(application)
application.getMessageBus().connect().subscribe(ProjectLifecycleListener.TOPIC, object : ProjectLifecycleListener.Adapter() {
override fun beforeProjectLoaded(project: Project) {
if (project.isDefault()) {
return
}
registerProjectLevelProviders(project)
autoSyncManager.registerListeners(project)
}
override fun afterProjectClosed(project: Project) {
autoSyncManager.autoSync()
}
})
}
open inner class IcsStreamProvider(protected val projectId: String?) : StreamProvider {
override val enabled: Boolean
get() = repositoryActive
override fun listSubFiles(fileSpec: String, roamingType: RoamingType): MutableCollection<String> = repositoryManager.listSubFileNames(buildPath(fileSpec, roamingType, null)) as MutableCollection<String>
override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) {
val fullPath = buildPath(path, roamingType, null)
// first of all we must load read-only schemes - scheme could be overridden if bundled or read-only, so, such schemes must be loaded first
for (repository in readOnlySourcesManager.repositories) {
repository.processChildren(fullPath, filter, { name, input -> processor(name, input, true) })
}
repositoryManager.processChildren(fullPath, filter, { name, input -> processor(name, input, false) })
}
override fun saveContent(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
if (syncManager.writeAndDeleteProhibited) {
throw IllegalStateException("Save is prohibited now")
}
doSave(fileSpec, content, size, roamingType)
if (isAutoCommit(fileSpec, roamingType)) {
scheduleCommit()
}
}
fun doSave(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
repositoryManager.write(buildPath(fileSpec, roamingType, projectId), content, size)
}
protected open fun isAutoCommit(fileSpec: String, roamingType: RoamingType): Boolean = true
override fun loadContent(fileSpec: String, roamingType: RoamingType): InputStream? {
return repositoryManager.read(buildPath(fileSpec, roamingType, projectId))
}
override fun delete(fileSpec: String, roamingType: RoamingType) {
}
}
}
class IcsApplicationLoadListener : ApplicationLoadListener {
var icsManager: IcsManager by Delegates.notNull()
private set
override fun beforeApplicationLoaded(application: Application, configPath: String) {
if (application.isUnitTestMode()) {
return
}
val customPath = System.getProperty("ics.settingsRepository")
val pluginSystemDir = if (customPath == null) File(configPath, "settingsRepository") else File(FileUtil.expandUserHome(customPath))
icsManager = IcsManager(pluginSystemDir)
if (!pluginSystemDir.exists()) {
try {
val oldPluginDir = File(PathManager.getSystemPath(), "settingsRepository")
if (oldPluginDir.exists()) {
FileUtil.rename(oldPluginDir, pluginSystemDir)
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
val repositoryManager = icsManager.repositoryManager
if (repositoryManager.isRepositoryExists() && repositoryManager is GitRepositoryManager) {
repositoryManager.renameDirectory(linkedMapOf(
Pair("\$ROOT_CONFIG$", null),
Pair("_mac/\$ROOT_CONFIG$", "_mac"),
Pair("_windows/\$ROOT_CONFIG$", "_windows"),
Pair("_linux/\$ROOT_CONFIG$", "_linux"),
Pair("_freebsd/\$ROOT_CONFIG$", "_freebsd"),
Pair("_unix/\$ROOT_CONFIG$", "_unix"),
Pair("_unknown/\$ROOT_CONFIG$", "_unknown")
))
}
icsManager.beforeApplicationLoaded(application)
}
}
class NoRemoteRepositoryException(cause: Throwable) : RuntimeException(cause.getMessage(), cause)
|
apache-2.0
|
df1dfa9635c3d392a8848368bc254ab3
| 36.823322 | 206 | 0.733065 | 4.927716 | false | false | false | false |
y2k/JoyReactor
|
core/src/main/kotlin/y2k/joyreactor/model/Comment.kt
|
1
|
917
|
package y2k.joyreactor.model
import com.j256.ormlite.field.DataType
import com.j256.ormlite.field.DatabaseField
import y2k.joyreactor.services.repository.Dto
import java.io.Serializable
/**
* Created by y2k on 28/09/15.
*/
data class Comment(
@DatabaseField val text: String = "",
@DatabaseField val userImage: String? = null,
@DatabaseField val parentId: Long = 0,
@DatabaseField val rating: Float = 0f,
@DatabaseField val postId: Long = 0,
@DatabaseField val level: Int = 0,
@DatabaseField var replies: Int = 0, // TODO: сделать immutable
@DatabaseField(dataType = DataType.SERIALIZABLE) val attachment: Image? = null,
@DatabaseField(id = true) override val id: Long = 0
) : Dto, Serializable {
override fun identify(newId: Long) = copy(id = newId)
val userImageObject: UserImage
get() = if (userImage == null) UserImage() else UserImage(userImage)
}
|
gpl-2.0
|
4acdbbbd233ab1a738a4e3018fe4b9bb
| 32.740741 | 83 | 0.707692 | 3.654618 | false | false | false | false |
inorichi/tachiyomi-extensions
|
src/en/mangaowl/src/eu/kanade/tachiyomi/extension/en/mangaowl/MangaOwl.kt
|
1
|
5036
|
package eu.kanade.tachiyomi.extension.en.mangaowl
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
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 okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.TimeUnit
class MangaOwl : ParsedHttpSource() {
override val name = "MangaOwl"
override val baseUrl = "https://mangaowls.com"
override val lang = "en"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient.newBuilder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.build()
// Popular
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/popular/$page", headers)
}
override fun popularMangaSelector() = "div.col-md-2"
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
element.select("h6 a").let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.text()
}
manga.thumbnail_url = element.select("div.img-responsive").attr("abs:data-background-image")
return manga
}
override fun popularMangaNextPageSelector() = "div.blog-pagenat-wthree li a:contains(>>)"
// Latest
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/lastest/$page", headers)
}
override fun latestUpdatesSelector() = popularMangaSelector()
override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
// Search
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
return GET("$baseUrl/search/$page?search=$query&search_field=110&sort=4&completed=2", headers)
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element)
override fun searchMangaNextPageSelector() = "div.navigation li a:contains(next)"
// Manga summary page
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select("div.single_detail").first()
return SManga.create().apply {
title = infoElement.select("h2").first().ownText()
author = infoElement.select("p.fexi_header_para a.author_link").text()
artist = author
status = parseStatus(infoElement.select("p.fexi_header_para:contains(status)").first().ownText())
genre = infoElement.select("div.col-xs-12.col-md-8.single-right-grid-right > p > a[href*=genres]").joinToString { it.text() }
description = infoElement.select(".description").first().ownText()
thumbnail_url = infoElement.select("img").first()?.let { img ->
if (img.hasAttr("data-src")) img.attr("abs:data-src") else img.attr("abs:src")
}
}
}
private fun parseStatus(status: String?) = when {
status == null -> SManga.UNKNOWN
status.contains("Ongoing") -> SManga.ONGOING
status.contains("Completed") -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
// Chapters
override fun chapterListSelector() = "div.table-chapter-list ul li"
override fun chapterFromElement(element: Element): SChapter {
val chapter = SChapter.create()
element.select("a").let {
// They replace some URLs with a different host getting a path of domain.com/reader/reader/, fix to make usable on baseUrl
chapter.setUrlWithoutDomain(it.attr("href").replace("/reader/reader/", "/reader/"))
chapter.name = it.select("label")[0].text()
}
chapter.date_upload = parseChapterDate(element.select("small:last-of-type").text())
return chapter
}
companion object {
val dateFormat by lazy {
SimpleDateFormat("MM/dd/yyyy", Locale.US)
}
}
private fun parseChapterDate(string: String): Long {
return try {
dateFormat.parse(string)?.time ?: 0
} catch (_: ParseException) {
0
}
}
// Pages
override fun pageListParse(document: Document): List<Page> {
return document.select("div.item img.owl-lazy").mapIndexed { i, img ->
Page(i, "", img.attr("abs:data-src"))
}
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used")
override fun getFilterList() = FilterList()
}
|
apache-2.0
|
c57dd8e63c99a94c3e14c4fef8b30a5e
| 33.731034 | 137 | 0.668785 | 4.520646 | false | false | false | false |
VKCOM/vk-android-sdk
|
core/src/main/java/com/vk/api/sdk/internal/JsonUtils.kt
|
1
|
1274
|
package com.vk.api.sdk.internal
import android.util.JsonReader
import android.util.JsonToken
import android.util.MalformedJsonException
import java.io.Reader
import java.io.StringReader
object JsonUtils {
fun containsElement(jsonString: String, name: String): Boolean {
try {
return containsElementImpl(jsonString, name)
} catch (ex: MalformedJsonException) {
throw MalformedJsonException("${ex.message}. Json: '$jsonString'")
}
}
private fun containsElementImpl(jsonString: String, name: String): Boolean {
if (jsonString.isEmpty()) {
return false
}
val reader = JsonReader(StringReader(jsonString) as Reader) // Fix for bug in IntelliJ
if (reader.hasNext() && reader.peek() == JsonToken.BEGIN_OBJECT) {
reader.beginObject()
} else {
return false
}
while (reader.hasNext()) {
val nextToken = reader.peek()
if (nextToken == JsonToken.END_DOCUMENT) {
break
} else if (nextToken != JsonToken.NAME) {
reader.skipValue()
} else if (name == reader.nextName()) {
return true
}
}
return false
}
}
|
mit
|
fc35c1b0bdfa0f0b61d3cac31853000d
| 29.357143 | 94 | 0.587127 | 4.862595 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/quests/bikeway/CyclewayParser.kt
|
1
|
6188
|
package de.westnordost.streetcomplete.quests.bikeway
import de.westnordost.streetcomplete.quests.bikeway.Cycleway.*
data class LeftAndRightCycleway(val left: Cycleway?, val right: Cycleway?)
/** Returns the Cycleway values for the left and right side using the given tags */
fun createCyclewaySides(tags: Map<String, String>, isLeftHandTraffic: Boolean): LeftAndRightCycleway? {
val isForwardOneway = tags["oneway"] == "yes"
val isReversedOneway = tags["oneway"] == "-1"
val isOneway = isReversedOneway || isForwardOneway
val isReverseSideRight = isReversedOneway xor isLeftHandTraffic
// any unambiguous opposite tagging implies oneway:bicycle = no
val isOpposite = tags["cycleway"]?.startsWith("opposite") == true
val isUnambiguousOppositeSide = tags[if (isReverseSideRight) "cycleway:right" else "cycleway:left"]?.startsWith("opposite") == true
val isAnyUnambiguousOppositeTagging = isOpposite || isUnambiguousOppositeSide
val isOnewayNotForCyclists = isOneway && (tags["oneway:bicycle"] == "no" || isAnyUnambiguousOppositeTagging)
// opposite tagging implies a oneway. So tagging is not understand if tags seem to contradict each other
val isAnyOppositeTagging = tags.filterKeys { it in KNOWN_CYCLEWAY_KEYS }.values.any { it.startsWith("opposite") }
if (!isOneway && isAnyOppositeTagging) return null
var left: Cycleway?
var right: Cycleway?
/* For oneways, the naked "cycleway"-keys should be interpreted differently:
* F.e. a cycleway=lane in a oneway=yes probably means that only in the flow direction, there
* is a lane. F.e. cycleway=opposite_lane means that there is a lane in opposite traffic flow
* direction.
* Whether there is anything each in the other direction, is not defined, so we have to treat
* it that way. */
val cycleway = createCyclewayForSide(tags, null)
if (isOneway && cycleway != null && cycleway != NONE) {
if (isOpposite) {
if (isReverseSideRight) {
left = null
right = cycleway
}
else {
left = cycleway
right = null
}
} else {
if (isReverseSideRight) {
left = cycleway
right = null
}
else {
left = null
right = cycleway
}
}
} else {
// first expand cycleway:both etc into cycleway:left + cycleway:right etc
val expandedTags = expandRelevantSidesTags(tags)
// then get the values for left and right
left = createCyclewayForSide(expandedTags, "left")
right = createCyclewayForSide(expandedTags, "right")
}
/* if there is no cycleway in a direction but it is a oneway in the other direction but not
for cyclists, we have a special selection for that */
if (isOnewayNotForCyclists) {
if ((left == NONE || left == null) && !isReverseSideRight) left = NONE_NO_ONEWAY
if ((right == NONE || right == null) && isReverseSideRight) right = NONE_NO_ONEWAY
}
if (left == null && right == null) return null
return LeftAndRightCycleway(left, right)
}
/** Returns the Cycleway value using the given tags, for the given side (left or right).
* Returns null if nothing (understood) is tagged */
private fun createCyclewayForSide(tags: Map<String, String>, side: String?): Cycleway? {
val sideVal = if (side != null) ":$side" else ""
val cyclewayKey = "cycleway$sideVal"
val cycleway = tags[cyclewayKey]
val cyclewayLane = tags["$cyclewayKey:lane"]
val isDual = tags["$cyclewayKey:oneway"] == "no"
val isSegregated = tags["$cyclewayKey:segregated"] != "no"
val result = when(cycleway) {
"lane", "opposite_lane" -> {
when (cyclewayLane) {
"exclusive", "exclusive_lane", "mandatory" -> {
if (isDual) DUAL_LANE
else EXCLUSIVE_LANE
}
null -> {
if (isDual) DUAL_LANE
else UNSPECIFIED_LANE
}
"advisory", "advisory_lane", "soft_lane", "dashed" -> ADVISORY_LANE
else -> UNKNOWN_LANE
}
}
"shared_lane" -> {
when (cyclewayLane) {
"advisory", "advisory_lane", "soft_lane", "dashed" -> SUGGESTION_LANE
"pictogram" -> PICTOGRAMS
null -> UNSPECIFIED_SHARED_LANE
else -> UNKNOWN_SHARED_LANE
}
}
"track", "opposite_track" -> {
when {
!isSegregated -> SIDEWALK_EXPLICIT
isDual -> DUAL_TRACK
else -> TRACK
}
}
"no", "none", "opposite" -> NONE
"share_busway", "opposite_share_busway" -> BUSWAY
null -> null
else -> UNKNOWN
}
return result
}
private fun expandRelevantSidesTags(tags: Map<String, String>): Map<String, String> {
val result = tags.toMutableMap()
expandSidesTag("cycleway", "", result)
expandSidesTag("cycleway", "lane", result)
expandSidesTag("cycleway", "oneway", result)
expandSidesTag("cycleway", "segregated", result)
expandSidesTag("sidewalk", "bicycle", result)
return result
}
/** Expand my_tag:both and my_tag into my_tag:left and my_tag:right etc */
private fun expandSidesTag(keyPrefix: String, keyPostfix: String, tags: MutableMap<String, String>) {
val pre = keyPrefix
val post = if (keyPostfix.isEmpty()) "" else ":$keyPostfix"
val value = tags["$pre:both$post"] ?: tags["$pre$post"]
if (value != null) {
if (!tags.containsKey("$pre:left$post")) tags["$pre:left$post"] = value
if (!tags.containsKey("$pre:right$post")) tags["$pre:right$post"] = value
}
}
private val KNOWN_CYCLEWAY_KEYS = listOf(
"cycleway", "cycleway:left", "cycleway:right", "cycleway:both"
)
|
gpl-3.0
|
cf5f7772411ee39dce4dc1dd67ef290a
| 40.530201 | 135 | 0.591629 | 4.474331 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/plugin/PluginAnyBooleanNodeTestPsiImpl.kt
|
1
|
1709
|
/*
* Copyright (C) 2016-2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.plugin
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmBooleanNode
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType
import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginAnyBooleanNodeTest
class PluginAnyBooleanNodeTestPsiImpl(node: ASTNode) :
ASTWrapperPsiElement(node), PluginAnyBooleanNodeTest, XpmSyntaxValidationElement {
// region XdmSequenceType
override val typeName: String = "boolean-node()"
override val itemType: XdmItemType
get() = this
override val lowerBound: Int = 1
override val upperBound: Int = 1
// endregion
// region XdmItemType
override val typeClass: Class<*> = XdmBooleanNode::class.java
// endregion
// region XpmSyntaxValidationElement
override val conformanceElement: PsiElement
get() = firstChild
// endregion
}
|
apache-2.0
|
a02062645b0fab035167692aafdcb86e
| 32.509804 | 86 | 0.758923 | 4.427461 | false | true | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/achievement/ui/delegate/AchievementTileDelegate.kt
|
2
|
1849
|
package org.stepik.android.view.achievement.ui.delegate
import android.view.View
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.isGone
import kotlinx.android.synthetic.main.view_achievement_tile.view.*
import org.stepic.droid.R
import org.stepik.android.view.achievement.ui.resolver.AchievementResourceResolver
import org.stepik.android.domain.achievement.model.AchievementItem
import org.stepik.android.view.glide.ui.extension.wrapWithGlide
import org.stepik.android.view.achievement.ui.view.AchievementCircleProgressView
import org.stepik.android.view.achievement.ui.view.VectorRatingBar
class AchievementTileDelegate(
root: View,
private val achievementResourceResolver: AchievementResourceResolver
) {
private val achievementLevels: VectorRatingBar = root.achievementLevels
private val achievementLevelProgress: AchievementCircleProgressView = root.achievementLevelProgress
private val achievementIcon = root.achievementIcon.wrapWithGlide()
private val achievementIconSize = root.resources.getDimensionPixelSize(R.dimen.achievement_tile_width)
private val achievementIconPlaceholder =
AppCompatResources.getDrawable(root.context, R.drawable.ic_achievement_empty)
fun setAchievement(item: AchievementItem) {
achievementLevels.progress = item.currentLevel
achievementLevels.total = item.maxLevel
achievementLevelProgress.progress = item.currentScore.toFloat() / item.targetScore
achievementIcon
.setImagePath(achievementResourceResolver.resolveAchievementIcon(item, achievementIconSize), achievementIconPlaceholder)
val alpha = if (item.isLocked) 0.4f else 1f
achievementIcon.imageView.alpha = alpha
achievementLevelProgress.alpha = alpha
achievementLevels.isGone = item.isLocked
}
}
|
apache-2.0
|
43b28a0ed8ceae8906cfefc59cd257df
| 44.121951 | 132 | 0.803678 | 4.790155 | false | false | false | false |
robfletcher/orca
|
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/metrics/ZombieExecutionCheckingAgentTest.kt
|
3
|
6407
|
/*
* 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.metrics
import com.netflix.spectator.api.Counter
import com.netflix.spectator.api.Registry
import com.netflix.spectator.api.Tag
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.notifications.NotificationClusterLock
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository.ExecutionCriteria
import com.netflix.spinnaker.orca.q.ZombieExecutionService
import com.netflix.spinnaker.q.Activator
import com.netflix.spinnaker.q.metrics.MonitorableQueue
import com.netflix.spinnaker.time.fixedClock
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever
import java.time.Duration
import java.time.Instant.now
import java.time.temporal.ChronoUnit.HOURS
import java.util.Optional
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
import rx.Observable.just
import rx.schedulers.Schedulers
object ZombieExecutionCheckingAgentTest : SubjectSpek<ZombieExecutionCheckingAgent>({
val queue: MonitorableQueue = mock()
val repository: ExecutionRepository = mock()
val clock = fixedClock(instant = now().minus(Duration.ofHours(1)))
val activator: Activator = mock()
val conch: NotificationClusterLock = mock()
val zombieCounter: Counter = mock()
val registry: Registry = mock {
on { counter(eq("queue.zombies"), any<Iterable<Tag>>()) } doReturn zombieCounter
}
subject(GROUP) {
ZombieExecutionCheckingAgent(
ZombieExecutionService(
repository,
queue,
clock,
Optional.of(Schedulers.immediate())
),
registry,
clock,
conch,
10,
true,
10,
queueEnabled = true
)
}
fun resetMocks() =
reset(queue, repository, zombieCounter)
describe("detecting zombie executions") {
val criteria = ExecutionCriteria().setStatuses(RUNNING)
given("the instance is disabled") {
beforeGroup {
whenever(activator.enabled) doReturn false
whenever(conch.tryAcquireLock(eq("zombie"), any())) doReturn true
}
afterGroup {
reset(activator, conch)
}
given("a running pipeline with no associated messages") {
val pipeline = pipeline {
status = RUNNING
buildTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
beforeGroup {
whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline)
whenever(queue.containsMessage(any())) doReturn true
}
afterGroup(::resetMocks)
on("looking for zombies") {
subject.checkForZombies()
it("does not increment zombie counter") {
verifyZeroInteractions(zombieCounter)
}
}
}
}
given("the instance is active and can acquire a cluster lock") {
beforeGroup {
whenever(activator.enabled) doReturn true
whenever(conch.tryAcquireLock(eq("zombie"), any())) doReturn true
}
afterGroup {
reset(activator, conch)
}
given("a non-running pipeline with no associated messages") {
val pipeline = pipeline {
status = SUCCEEDED
buildTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
beforeGroup {
whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline)
whenever(queue.containsMessage(any())) doReturn true
}
afterGroup(::resetMocks)
on("looking for zombies") {
subject.checkForZombies()
it("does not increment the counter") {
verifyZeroInteractions(zombieCounter)
}
}
}
given("a running pipeline with an associated messages") {
val pipeline = pipeline {
status = RUNNING
buildTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
beforeGroup {
whenever(repository.retrieve(pipeline.type, criteria)) doReturn just(pipeline)
whenever(queue.containsMessage(any())) doReturn true
}
afterGroup(::resetMocks)
on("looking for zombies") {
subject.checkForZombies()
it("does not increment the counter") {
verifyZeroInteractions(zombieCounter)
}
}
}
given("a running pipeline with no associated messages") {
val pipeline = pipeline {
status = RUNNING
buildTime = clock.instant().minus(1, HOURS).toEpochMilli()
}
beforeGroup {
whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline)
whenever(queue.containsMessage(any())) doReturn false
}
afterGroup(::resetMocks)
on("looking for zombies") {
subject.checkForZombies()
it("increments the counter") {
verify(zombieCounter).increment()
}
}
}
}
}
})
private fun Sequence<Duration>.average() =
map { it.toMillis() }
.average()
.let { Duration.ofMillis(it.toLong()) }
|
apache-2.0
|
95b001207e2bcaee12b26b970f03ea96
| 29.951691 | 92 | 0.683471 | 4.499298 | false | false | false | false |
Commit451/GitLabAndroid
|
app/src/main/java/com/commit451/gitlab/model/api/Pipeline.kt
|
2
|
695
|
package com.commit451.gitlab.model.api
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.android.parcel.Parcelize
import java.util.Date
/**
* A pipeline.
*/
@Parcelize
data class Pipeline(
@Json(name = "user")
var user: CommitUser? = null,
@Json(name = "id")
var id: Long = 0,
@Json(name = "sha")
var sha: String? = null,
@Json(name = "ref")
var ref: String? = null,
@Json(name = "status")
var status: String? = null,
@Json(name = "created_at")
var createdAt: Date? = null,
@Json(name = "started_at")
var startedAt: Date? = null,
@Json(name = "finished_at")
var finishedAt: Date? = null
) : Parcelable
|
apache-2.0
|
a423ce7303303f0dee5bb2b02eef98ef
| 22.965517 | 39 | 0.625899 | 3.202765 | false | false | false | false |
JesseScott/Make-A-Wish
|
MakeAWish/app/src/main/java/tt/co/jesses/makeawish/helpers/AlarmHelper.kt
|
1
|
3191
|
package tt.co.jesses.makeawish.helpers
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
import tt.co.jesses.makeawish.R
import tt.co.jesses.makeawish.receivers.AlarmReceiver
/**
* Created by jessescott on 2017-02-27.
*/
class AlarmHelper(private val mContext: Context) {
private val mCalendarHelper: CalendarHelper = CalendarHelper()
private val mPreferenceHelper: PreferenceHelper = PreferenceHelper(mContext)
private val mAlarmIntent: PendingIntent
private val mAlarmManager: AlarmManager
init {
val intent = Intent(mContext, AlarmReceiver::class.java)
mAlarmIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0)
mAlarmManager = mContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
}
fun setAlarms() {
// Test to see if we've already set recurring daytime alarms AND/OR if we have enabled them
val daytimeEnabled = mPreferenceHelper.getPrefValueByKey(mContext.getString(R.string.prefs_enable_daytime_alarms))
val daytimeSet = mPreferenceHelper.getPrefValueByKey(mContext.getString(R.string.prefs_daytime_set))
if (!daytimeSet && daytimeEnabled) {
for (calendar in mCalendarHelper.calendarsDaytime) {
if (null != calendar) {
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, mAlarmIntent)
}
}
// Set the Preferences
mPreferenceHelper.setPrefValueByKey(mContext.getString(R.string.prefs_daytime_set), true)
}
// Test to see if we've already set recurring nighttime alarms AND/OR if we have enabled them
val nighttimeEnabled = mPreferenceHelper.getPrefValueByKey(mContext.getString(R.string.prefs_enable_nighttime_alarms))
val nighttimeSet = mPreferenceHelper.getPrefValueByKey(mContext.getString(R.string.prefs_nighttime_set))
if (!nighttimeSet && nighttimeEnabled) {
for (calendar in mCalendarHelper.calendarsNighttime) {
if (null != calendar) {
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, mAlarmIntent)
}
}
// Set the Preferences
mPreferenceHelper.setPrefValueByKey(mContext.getString(R.string.prefs_nighttime_set), true)
}
// Log
val bundle = Bundle()
bundle.putBoolean(mContext.getString(R.string.prefs_enable_daytime_alarms), daytimeEnabled)
bundle.putBoolean(mContext.getString(R.string.prefs_daytime_set), daytimeSet)
bundle.putBoolean(mContext.getString(R.string.prefs_enable_nighttime_alarms), nighttimeEnabled)
bundle.putBoolean(mContext.getString(R.string.prefs_nighttime_set), nighttimeSet)
FirebaseAnalytics.getInstance(mContext).logEvent(mContext.getString(R.string.prefs_log_event), bundle)
}
companion object {
private val TAG = AlarmHelper::class.java.simpleName
}
}
|
gpl-2.0
|
05c80b291735955b520205c5894ecc4a
| 43.943662 | 135 | 0.712943 | 4.365253 | false | false | false | false |
walleth/walleth
|
app/src/main/java/org/walleth/credentials/PINDialog.kt
|
1
|
2973
|
package org.walleth.credentials
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import com.google.android.material.button.MaterialButton
import kotlinx.android.synthetic.main.pinput.view.*
import org.ligi.kaxt.inflate
import org.ligi.kaxt.setVisibility
import org.walleth.R
val KEY_MAP_TOUCH = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val KEY_MAP_NUM_PAD = listOf(7, 8, 9, 4, 5, 6, 1, 2, 3) // mainly for TREZOR
val KEY_MAP_TOUCH_WITH_ZERO = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, null, 0, null)
fun Activity.showPINDialog(
onPIN: (pin: String) -> Unit,
onCancel: () -> Unit,
labelButtons: Boolean = false,
pinPadMapping: List<Int?> = KEY_MAP_TOUCH,
maxLength: Int = 10,
title: Int = R.string.please_enter_your_pin
) {
val view = inflate(R.layout.pinput)
var dialogPin = ""
val displayPin = {
view.pin_textview.text = "*".repeat(dialogPin.length)
view.pin_back.setVisibility(dialogPin.isNotEmpty())
}
displayPin.invoke()
// GridView seems the better choice here - but has a problem I could not overcome:
// https://github.com/walleth/walleth/issues/485
// if anyone can make it work with a GridView (which is nicer code-wise) - PR welcome!
var horizontalButtonContainer = LinearLayout(this)
pinPadMapping.forEachIndexed { index, number ->
if ((index % 3) == 0) {
horizontalButtonContainer = LinearLayout(this)
view.grid_container.addView(horizontalButtonContainer)
}
horizontalButtonContainer.addView(MaterialButton(this).apply {
text = if (labelButtons) number.toString() else "*"
setOnClickListener {
if (dialogPin.length <= maxLength)
dialogPin += number
displayPin.invoke()
}
setTextColor(ContextCompat.getColor(this@showPINDialog, R.color.onAccent))
layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f).apply {
setMargins(5, 5, 5, 5)
}
setVisibility(number != null, View.INVISIBLE)
})
}
view.pin_back.setOnClickListener {
if (dialogPin.isNotEmpty())
dialogPin = dialogPin.substring(0, dialogPin.length - 1)
displayPin.invoke()
}
if (!isFinishing) {
AlertDialog.Builder(this)
.setView(view)
.setTitle(title)
.setPositiveButton(android.R.string.ok) { _, _ ->
onPIN.invoke(dialogPin)
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
onCancel.invoke()
}
.setOnCancelListener {
onCancel.invoke()
}
.show()
}
}
|
gpl-3.0
|
7afa902e7828406ccb3569c234dd32fb
| 34.404762 | 104 | 0.607467 | 4.089409 | false | false | false | false |
android/performance-samples
|
MicrobenchmarkSample/benchmarkable/src/main/java/com/example/benchmark/ui/SortingAlgorithms.kt
|
1
|
1894
|
/*
* 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 com.example.benchmark.ui
/**
* Some trivial sorting algorithms for benchmarks
*/
object SortingAlgorithms {
fun bubbleSort(array: IntArray) {
for (i in 0..array.lastIndex) {
for (j in 0 until array.lastIndex) {
if (array[j] > array[j + 1]) {
swap(array, j, j + 1)
}
}
}
}
fun quickSort(array: IntArray, begin: Int = 0, end: Int = array.lastIndex) {
if (end <= begin) return
val pivot = partition(array, begin, end)
quickSort(array, begin, pivot - 1)
quickSort(array, pivot + 1, end)
}
private fun partition(array: IntArray, begin: Int, end: Int): Int {
var counter = begin
for (i in begin until end) {
if (array[i] < array[end]) {
swap(array, counter, i)
counter++
}
}
swap(array, end, counter)
return counter
}
private fun swap(arr: IntArray, i: Int, j: Int) {
val temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
/**
* Check if the array is already sorted
*/
val IntArray.isSorted
get() = this
.asSequence()
.zipWithNext { a, b -> a <= b }
.all { it }
|
apache-2.0
|
90fc46a0cdf245836ba6c39a5e196a50
| 26.449275 | 80 | 0.579197 | 3.945833 | false | false | false | false |
jdiazcano/modulartd
|
editor/core/src/main/kotlin/com/jdiazcano/modulartd/tabs/BaseTab.kt
|
1
|
3026
|
package com.jdiazcano.modulartd.tabs
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.github.salomonbrys.kodein.instance
import com.jdiazcano.modulartd.beans.Game
import com.jdiazcano.modulartd.injections.kodein
import com.jdiazcano.modulartd.utils.clickListener
import com.jdiazcano.modulartd.utils.translate
import com.kotcrab.vis.ui.util.form.FormValidator
import com.kotcrab.vis.ui.widget.VisTable
import com.kotcrab.vis.ui.widget.VisTextButton
import com.kotcrab.vis.ui.widget.VisTextField
import com.kotcrab.vis.ui.widget.tabbedpane.Tab
/**
* Base tab that all the tabs should extend. This will provide basic information like creating a new
* item of whatever you are configuring at the moment and how to update the ui.
*
* If scriptable, a new button "Script" will be added
*/
abstract class BaseTab<T>(
val title: String,
scriptable: Boolean = false,
instanceable: Boolean = true
): Tab(true, false) {
protected val game = kodein.instance<Game>()
protected val textFields = arrayListOf<VisTextField>()
private val fullContent = VisTable()
protected val content = VisTable()
protected val new = VisTextButton(translate("new"))
protected val script = VisTextButton(translate("script"))
// Ugly hack, I don't really like that a form validator needs a button!
protected val validator = FormValidator(VisTextButton(""), kodein.instance("globalMessageLabel"))
init {
val buttons = VisTable()
if (instanceable) {
buttons.add(new).padRight(10F).expandX().right()
}
if (scriptable) {
buttons.add(script).padRight(10F)
}
fullContent.add(content).expand().fill().row()
fullContent.add(buttons).expandX().right().padBottom(10F)
new.clickListener { _, _, _ -> newItem() }
script.clickListener { _, _, _ -> TODO() } // TODO This is in trello already
}
/**
* Creates a new item. Right now a new item is done by just unselecting the list and then you can save your current one.
* I'm not sure if I should just create an empty one and save it to the list and select it! This seems more common to do
*/
abstract fun newItem()
/**
* Updates the table accordingly to the item passed as argument. The tabs will have a table that contains all the
* information when selecting an item so this is the method that will be called when the selection changes for example.
*/
abstract fun updateUI(item: T)
override fun getContentTable(): Table {
return fullContent
}
override fun getTabTitle() = title
override fun setDirty(dirty: Boolean) {
game.dirty = dirty
}
protected fun enableProgrammaticEvents() {
setProgrammaticEvents(true)
}
protected fun disableProgrammaticEvents() {
setProgrammaticEvents(false)
}
private fun setProgrammaticEvents(value: Boolean) {
textFields.forEach { it.programmaticChangeEvents = value }
}
}
|
apache-2.0
|
7387e9f12478f9dd28fe48d6965d795c
| 33.793103 | 124 | 0.695307 | 4.292199 | false | false | false | false |
paslavsky/music-sync-manager
|
msm-server/src/main/kotlin/net/paslavsky/msm/domain/Settings.kt
|
1
|
790
|
package net.paslavsky.msm.domain
import javax.persistence.Entity
import javax.validation.constraints.Min
import javax.persistence.Column
import javax.persistence.ManyToOne
import javax.persistence.UniqueConstraint
import javax.persistence.Table
import javax.persistence.JoinColumn
import javax.persistence.Lob
/**
* Settings in database
*
* @author Andrey Paslavsky
* @version 1.0
*/
Entity Table(uniqueConstraints = arrayOf(UniqueConstraint(columnNames = arrayOf("user_id", "key"))))
public class Settings: DomainObject() {
public Min(value = 3) Column(nullable = false) var key: String = ""
public Min(value = 3) Column(nullable = false) Lob var value: String = ""
public JoinColumn(nullable=false, updatable=false) ManyToOne(optional = false) var user: User = User()
}
|
apache-2.0
|
c06dd9af46e827cd7c7151dd54623a4e
| 33.391304 | 106 | 0.767089 | 4.030612 | false | false | false | false |
Heiner1/AndroidAPS
|
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetBolusOption.kt
|
1
|
3109
|
package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRSPacketBolusSetBolusOption(
injector: HasAndroidInjector,
private var extendedBolusOptionOnOff: Int = 0,
private var bolusCalculationOption: Int = 0,
private var missedBolusConfig: Int = 0,
private var missedBolus01StartHour: Int = 0,
private var missedBolus01StartMin: Int = 0,
private var missedBolus01EndHour: Int = 0,
private var missedBolus01EndMin: Int = 0,
private var missedBolus02StartHour: Int = 0,
private var missedBolus02StartMin: Int = 0,
private var missedBolus02EndHour: Int = 0,
private var missedBolus02EndMin: Int = 0,
private var missedBolus03StartHour: Int = 0,
private var missedBolus03StartMin: Int = 0,
private var missedBolus03EndHour: Int = 0,
private var missedBolus03EndMin: Int = 0,
private var missedBolus04StartHour: Int = 0,
private var missedBolus04StartMin: Int = 0,
private var missedBolus04EndHour: Int = 0,
private var missedBolus04EndMin: Int = 0
) : DanaRSPacket(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_OPTION
aapsLogger.debug(LTag.PUMPCOMM, "Setting bolus options")
}
override fun getRequestParams(): ByteArray {
val request = ByteArray(19)
request[0] = (extendedBolusOptionOnOff and 0xff).toByte()
request[1] = (bolusCalculationOption and 0xff).toByte()
request[2] = (missedBolusConfig and 0xff).toByte()
request[3] = (missedBolus01StartHour and 0xff).toByte()
request[4] = (missedBolus01StartMin and 0xff).toByte()
request[5] = (missedBolus01EndHour and 0xff).toByte()
request[6] = (missedBolus01EndMin and 0xff).toByte()
request[7] = (missedBolus02StartHour and 0xff).toByte()
request[8] = (missedBolus02StartMin and 0xff).toByte()
request[9] = (missedBolus02EndHour and 0xff).toByte()
request[10] = (missedBolus02EndMin and 0xff).toByte()
request[11] = (missedBolus03StartHour and 0xff).toByte()
request[12] = (missedBolus03StartMin and 0xff).toByte()
request[13] = (missedBolus03EndHour and 0xff).toByte()
request[14] = (missedBolus03EndMin and 0xff).toByte()
request[15] = (missedBolus04StartHour and 0xff).toByte()
request[16] = (missedBolus04StartMin and 0xff).toByte()
request[17] = (missedBolus04EndHour and 0xff).toByte()
request[18] = (missedBolus04EndMin and 0xff).toByte()
return request
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
@Suppress("LiftReturnOrAssignment")
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override val friendlyName: String = "BOLUS__SET_BOLUS_OPTION"
}
|
agpl-3.0
|
35938e969076f864e823cb3d3c4bdf4c
| 41.60274 | 75 | 0.684786 | 3.900878 | false | false | false | false |
exponentjs/exponent
|
android/expoview/src/main/java/host/exp/exponent/experience/splashscreen/LoadingView.kt
|
2
|
2457
|
package host.exp.exponent.experience.splashscreen
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.ProgressBar
import android.widget.RelativeLayout
import host.exp.expoview.R
/**
* The only purpose of this view is to present Android progressBar (spinner) before manifest with experience-related info is available
*/
class LoadingView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
private val progressBar: ProgressBar
private val progressBarHandler = Handler()
private var progressBarShown = false
init {
LayoutInflater.from(context).inflate(R.layout.loading_view, this, true)
progressBar = findViewById(R.id.progressBar)
setBackgroundColor(Color.WHITE)
show()
}
fun show() {
if (progressBarShown) {
return
}
progressBarHandler.postDelayed(
{
progressBar.visibility = View.VISIBLE
progressBar.startAnimation(
AlphaAnimation(0.0f, 1.0f).also {
it.duration = 250
it.interpolator = AccelerateDecelerateInterpolator()
it.fillAfter = true
}
)
progressBarShown = true
},
PROGRESS_BAR_DELAY_MS
)
}
fun hide() {
if (!progressBarShown) {
return
}
progressBarHandler.removeCallbacksAndMessages(null)
progressBar.clearAnimation()
if (progressBar.visibility == View.VISIBLE) {
progressBar.startAnimation(
AlphaAnimation(1.0f, 0.0f).also {
it.duration = 250
it.interpolator = AccelerateDecelerateInterpolator()
it.fillAfter = true
it.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationRepeat(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {
progressBar.visibility = View.GONE
progressBarShown = false
}
})
}
)
}
}
companion object {
private const val PROGRESS_BAR_DELAY_MS = 2500L
}
}
|
bsd-3-clause
|
db668e5e2c275c6cb9acceb98efd099a
| 28.60241 | 134 | 0.687831 | 4.894422 | false | false | false | false |
pambrose/prometheus-proxy
|
src/test/kotlin/io/prometheus/TestUtils.kt
|
1
|
3368
|
/*
* Copyright © 2020 Paul Ambrose ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction")
package io.prometheus
import com.github.pambrose.common.util.getBanner
import io.prometheus.TestConstants.PROXY_PORT
import io.prometheus.agent.AgentOptions
import io.prometheus.common.getVersionDesc
import io.prometheus.proxy.ProxyOptions
import kotlinx.coroutines.CoroutineExceptionHandler
import mu.KLogger
import mu.KLogging
import java.nio.channels.ClosedSelectorException
object TestUtils : KLogging() {
fun startProxy(
serverName: String = "",
adminEnabled: Boolean = false,
debugEnabled: Boolean = false,
metricsEnabled: Boolean = false,
argv: List<String> = emptyList()
): Proxy {
logger.apply {
info { getBanner("banners/proxy.txt", logger) }
info { getVersionDesc(false) }
}
val proxyOptions = ProxyOptions(
mutableListOf<String>()
.apply {
addAll(TestConstants.CONFIG_ARG)
addAll(argv)
add("-Dproxy.admin.enabled=$adminEnabled")
add("-Dproxy.admin.debugEnabled=$debugEnabled")
add("-Dproxy.metrics.enabled=$metricsEnabled")
}
)
return Proxy(
options = proxyOptions,
proxyHttpPort = PROXY_PORT,
inProcessServerName = serverName,
testMode = true
) { startSync() }
}
fun startAgent(
serverName: String = "",
adminEnabled: Boolean = false,
debugEnabled: Boolean = false,
metricsEnabled: Boolean = false,
scrapeTimeoutSecs: Int = -1,
chunkContentSizeKbs: Int = -1,
argv: List<String> = emptyList()
): Agent {
logger.apply {
info { getBanner("banners/agent.txt", logger) }
info { getVersionDesc(false) }
}
val agentOptions = AgentOptions(
mutableListOf<String>()
.apply {
addAll(TestConstants.CONFIG_ARG)
addAll(argv)
add("-Dagent.admin.enabled=$adminEnabled")
add("-Dagent.admin.debugEnabled=$debugEnabled")
add("-Dagent.metrics.enabled=$metricsEnabled")
if (scrapeTimeoutSecs != -1)
add("-Dagent.scrapeTimeoutSecs=$scrapeTimeoutSecs")
if (chunkContentSizeKbs != -1)
add("-Dagent.chunkContentSizeKbs=$chunkContentSizeKbs")
},
false
)
return Agent(options = agentOptions, inProcessServerName = serverName, testMode = true) { startSync() }
}
}
fun exceptionHandler(logger: KLogger) =
CoroutineExceptionHandler { _, e ->
if (e is ClosedSelectorException)
logger.info { "CoroutineExceptionHandler caught: $e" }
else
logger.warn(e) { "CoroutineExceptionHandler caught: $e" }
}
fun String.withPrefix(prefix: String = "http://localhost:") =
if (this.startsWith(prefix)) this else (prefix + this)
|
apache-2.0
|
6118c4347bea4c1e815ca3d010e25aae
| 31.384615 | 107 | 0.678349 | 4.187811 | false | true | false | false |
Maccimo/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/TrailingCommaPostFormatProcessor.kt
|
5
|
5982
|
// 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.formatter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.impl.source.codeStyle.PostFormatProcessor
import com.intellij.psi.impl.source.codeStyle.PostFormatProcessorHelper
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper.findInvalidCommas
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper.lineBreakIsMissing
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper.trailingCommaOrLastElement
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState
import org.jetbrains.kotlin.idea.formatter.trailingComma.addTrailingCommaIsAllowedFor
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespace
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.siblings
class TrailingCommaPostFormatProcessor : PostFormatProcessor {
override fun processElement(source: PsiElement, settings: CodeStyleSettings): PsiElement {
if (source.language != KotlinLanguage.INSTANCE) return source
return TrailingCommaPostFormatVisitor(settings).process(source)
}
override fun processText(source: PsiFile, rangeToReformat: TextRange, settings: CodeStyleSettings): TextRange {
if (source.language != KotlinLanguage.INSTANCE) return rangeToReformat
return TrailingCommaPostFormatVisitor(settings).processText(source, rangeToReformat)
}
}
private class TrailingCommaPostFormatVisitor(private val settings: CodeStyleSettings) : TrailingCommaVisitor() {
private val myPostProcessor = PostFormatProcessorHelper(settings.kotlinCommonSettings)
override fun process(trailingCommaContext: TrailingCommaContext) = processIfInRange(trailingCommaContext.ktElement) {
processCommaOwner(trailingCommaContext)
}
private fun processIfInRange(element: KtElement, block: () -> Unit = {}) {
if (myPostProcessor.isElementPartlyInRange(element)) {
block()
}
}
private fun processCommaOwner(trailingCommaContext: TrailingCommaContext) {
val ktElement = trailingCommaContext.ktElement
val lastElementOrComma = trailingCommaOrLastElement(ktElement) ?: return
updatePsi(ktElement) {
val state = trailingCommaContext.state
when {
state == TrailingCommaState.MISSING && settings.kotlinCustomSettings.addTrailingCommaIsAllowedFor(ktElement) -> {
// add a missing comma
val hasChange = if (trailingCommaAllowedInModule(ktElement)) {
lastElementOrComma.addCommaAfter(KtPsiFactory(ktElement))
true
} else {
false
}
correctCommaPosition(ktElement) || hasChange
}
state == TrailingCommaState.EXISTS -> {
correctCommaPosition(ktElement)
}
state == TrailingCommaState.REDUNDANT -> {
// remove redundant comma
lastElementOrComma.delete()
true
}
else -> false
}
}
}
private fun updatePsi(element: KtElement, updater: () -> Boolean) {
val oldLength = element.parent.textLength
if (!updater()) return
val resultElement = element.reformatted(true)
myPostProcessor.updateResultRange(oldLength, resultElement.parent.textLength)
}
private fun correctCommaPosition(parent: KtElement): Boolean {
var hasChange = false
for (pointerToComma in findInvalidCommas(parent).map { it.createSmartPointer() }) {
pointerToComma.element?.let {
correctComma(it)
hasChange = true
}
}
return hasChange || lineBreakIsMissing(parent)
}
fun process(formatted: PsiElement): PsiElement {
LOG.assertTrue(formatted.isValid)
formatted.accept(this)
return formatted
}
fun processText(
source: PsiFile,
rangeToReformat: TextRange,
): TextRange {
myPostProcessor.resultTextRange = rangeToReformat
source.accept(this)
return myPostProcessor.resultTextRange
}
companion object {
private val LOG = Logger.getInstance(TrailingCommaVisitor::class.java)
}
}
private fun PsiElement.addCommaAfter(factory: KtPsiFactory) {
val comma = factory.createComma()
parent.addAfter(comma, this)
}
private fun correctComma(comma: PsiElement) {
val prevWithComment = comma.leafIgnoringWhitespace(false) ?: return
val prevWithoutComment = comma.leafIgnoringWhitespaceAndComments(false) ?: return
if (prevWithComment != prevWithoutComment) {
val check = { element: PsiElement -> element is PsiWhiteSpace || element is PsiComment }
val firstElement = prevWithComment.siblings(forward = false, withItself = true).takeWhile(check).last()
val commentOwner = prevWithComment.parent
comma.parent.addRangeAfter(firstElement, prevWithComment, comma)
commentOwner.deleteChildRange(firstElement, prevWithComment)
}
}
|
apache-2.0
|
f748c1034edea9cbd48f8f20d01bf27f
| 40.255172 | 158 | 0.712471 | 5.284452 | false | false | false | false |
Hexworks/zircon
|
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/graphics/PersistentTileGraphics.kt
|
1
|
3399
|
package org.hexworks.zircon.internal.graphics
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.persistentHashMapOf
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.graphics.TileGraphics
import org.hexworks.zircon.api.graphics.base.BaseTileGraphics
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.internal.data.PersistentTileGraphicsState
import kotlin.jvm.Synchronized
/**
* This is a thread-safe [TileGraphics] All read / write operations
* ([getTileAt], [state], etc) are consistent even if concurrent write
* operations are being performed. Use this implementation if you want
* to read / write from multiple threads.
*/
class PersistentTileGraphics internal constructor(
initialSize: Size,
initialTileset: TilesetResource,
initialTiles: PersistentMap<Position, Tile> = persistentHashMapOf()
) : BaseTileGraphics(
initialSize = initialSize,
initialTileset = initialTileset
) {
override var tiles: PersistentMap<Position, Tile> = initialTiles
private set
override val state: PersistentTileGraphicsState
get() = PersistentTileGraphicsState(
size = size,
tileset = tileset,
tiles = tiles
)
@Synchronized
override fun draw(tile: Tile, drawPosition: Position) {
if (size.containsPosition(drawPosition)) {
tiles = if (tile.isEmpty) {
tiles.remove(drawPosition)
} else {
tiles.put(drawPosition, tile)
}
}
}
@Synchronized
override fun draw(tileMap: Map<Position, Tile>, drawPosition: Position, drawArea: Size) {
var newTiles = tiles
val tilesToAdd = mutableMapOf<Position, Tile>()
tileMap.asSequence()
.filter { drawArea.containsPosition(it.key) && size.containsPosition(it.key + drawPosition) }
.map { (key, value) -> key + drawPosition to value }
.forEach { (pos, tile) ->
if (tile.isEmpty) {
newTiles = newTiles.remove(pos)
} else {
tilesToAdd[pos] = tile
}
}
newTiles = newTiles.putAll(tilesToAdd)
tiles = newTiles
}
@Synchronized
override fun clear() {
tiles = tiles.clear()
}
@Synchronized
override fun fill(filler: Tile) {
if (filler.isNotEmpty) {
val (currentTiles, _, currentSize) = state
tiles = currentTiles.putAll(
currentSize.fetchPositions()
.minus(currentTiles.filterValues { it.isNotEmpty }.keys)
.map { it to filler }.toMap()
)
}
}
@Synchronized
override fun transform(transformer: (Position, Tile) -> Tile) {
var newTiles = tiles
val tilesToAdd = mutableMapOf<Position, Tile>()
size.fetchPositions().forEach { pos ->
val tile = transformer(pos, newTiles.getOrElse(pos) { Tile.empty() })
if (tile.isEmpty) {
newTiles = newTiles.remove(pos)
} else {
tilesToAdd[pos] = tile
}
}
newTiles = newTiles.putAll(tilesToAdd)
tiles = newTiles
}
}
|
apache-2.0
|
e5d73744fd2be0e6b45de48013a6348c
| 32.323529 | 105 | 0.62283 | 4.562416 | false | false | false | false |
edwardharks/Aircraft-Recognition
|
aircraftdetail/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/aircraftdetail/AircraftDetailActivity.kt
|
1
|
16698
|
package com.edwardharker.aircraftrecognition.ui.aircraftdetail
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.app.ActivityOptions
import android.content.Intent
import android.graphics.Color.argb
import android.graphics.Color.blue
import android.graphics.Color.green
import android.graphics.Color.red
import android.graphics.Typeface.BOLD
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.text.SpannableString
import android.text.style.StyleSpan
import android.transition.Transition
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.*
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import com.edwardharker.aircraftrecognition.aircraftdetail.AircraftDetailView
import com.edwardharker.aircraftrecognition.aircraftdetail.AircraftDetailViewModel
import com.edwardharker.aircraftrecognition.aircraftdetail.R
import com.edwardharker.aircraftrecognition.analytics.Events.aircraftDetailEvent
import com.edwardharker.aircraftrecognition.analytics.Events.youtubeVideoClickEvent
import com.edwardharker.aircraftrecognition.analytics.aircraftDetailScreen
import com.edwardharker.aircraftrecognition.analytics.eventAnalytics
import com.edwardharker.aircraftrecognition.extension.postDelayed
import com.edwardharker.aircraftrecognition.perf.TracerFactory.aircraftDetailActivityContentLoad
import com.edwardharker.aircraftrecognition.ui.AspectRatioImageView
import com.edwardharker.aircraftrecognition.ui.Navigator
import com.edwardharker.aircraftrecognition.ui.TransitionListenerAdapter
import com.edwardharker.aircraftrecognition.ui.bind
import com.edwardharker.aircraftrecognition.ui.doOnLayout
import com.edwardharker.aircraftrecognition.ui.dpToPixels
import com.edwardharker.aircraftrecognition.ui.drawableBottom
import com.edwardharker.aircraftrecognition.ui.feedback.launchFeedbackDialog
import com.edwardharker.aircraftrecognition.ui.loadAircraftImage
import com.edwardharker.aircraftrecognition.ui.navigator
import com.edwardharker.aircraftrecognition.ui.pixelsToDp
import com.edwardharker.aircraftrecognition.youtube.youtubeStandalonePlayerHelper
import kotlin.math.min
private const val AIRCRAFT_ID_EXTRA = "aircraftId"
private const val STARTED_WITH_SHARED_ELEMENT_TRANSITION_EXTRA = "startedWithTransition"
fun Navigator.launchAircraftDetailActivity(
aircraftId: String,
aircraftImage: View,
background: View,
aircraftName: View
) {
launch(
intent = Intent(activity, AircraftDetailActivity::class.java).apply {
putExtra(AIRCRAFT_ID_EXTRA, aircraftId)
},
options = ActivityOptions.makeSceneTransitionAnimation(
activity,
android.util.Pair(
aircraftImage,
activity.getString(R.string.transition_aircraft_image)
),
android.util.Pair(
background,
activity.getString(R.string.transition_aircraft_detail_background)
),
android.util.Pair(aircraftName, activity.getString(R.string.transition_aircraft_name))
).toBundle()
) {
putExtra(STARTED_WITH_SHARED_ELEMENT_TRANSITION_EXTRA, true)
}
}
fun Navigator.launchAircraftDetailActivity(aircraftId: String) {
launch(
intent = Intent(activity, AircraftDetailActivity::class.java).apply {
putExtra(AIRCRAFT_ID_EXTRA, aircraftId)
}
)
}
class AircraftDetailActivity : AppCompatActivity(), AircraftDetailView {
private val aircraftImage by bind<AspectRatioImageView>(R.id.aircraft_image)
private val aircraftImageContainer by bind<View>(R.id.aircraft_image_container)
private val aircraftName by bind<TextView>(R.id.aircraft_name)
private val aircraftDescription by bind<TextView>(R.id.aircraft_description)
private val aircraftMetaDataContainer by bind<ViewGroup>(R.id.aircraft_meta_data_container)
private val toolbar by bind<Toolbar>(R.id.toolbar)
private val scrollView by bind<NestedScrollView>(R.id.scroll_view)
private val photoCarouselButton by bind<View>(R.id.photo_carousel_button)
private val similarAircraftRail by bind<SimilarAircraftView>(R.id.similar_aircraft_rail)
private val aircraftDetailsContainer by bind<View>(R.id.aircraft_details_container)
private val expandLessDrawable by lazy { getDrawable(R.drawable.ic_expand_less_white_24dp) }
private val expandMoreDrawable by lazy { getDrawable(R.drawable.ic_expand_more_white_24dp) }
private val enterTransitionListener = EnterTransitionListener()
private val transitionSlidingViews by lazy {
listOf(
aircraftDescription,
aircraftMetaDataContainer,
similarAircraftRail
)
}
private val transitionFadingViews by lazy {
listOf(
aircraftMetaDataContainer,
aircraftDescription,
aircraftMetaDataContainer
)
}
private val initialInvisibleViews by lazy {
listOf(
toolbar,
aircraftDescription,
aircraftMetaDataContainer,
photoCarouselButton,
similarAircraftRail
)
}
private val transitionExitHideViews by lazy {
listOf(
aircraftDetailsContainer,
photoCarouselButton,
toolbar
)
}
private val aircraftId: String by lazy {
when {
intent.hasExtra(AIRCRAFT_ID_EXTRA) -> intent.getStringExtra(AIRCRAFT_ID_EXTRA)
intent.data != null -> intent.data!!.lastPathSegment
else -> {
finish()
""
}
}
}
private val startedWithSharedElementTransition by lazy {
intent.getBooleanExtra(STARTED_WITH_SHARED_ELEMENT_TRANSITION_EXTRA, false)
}
private val isFromDeepLink by lazy {
intent.data != null
}
private val detailsBackgroundColour by lazy {
ContextCompat.getColor(this@AircraftDetailActivity, R.color.windowBackground)
}
private var animateOnBackPressed = true
private val presenter = aircraftDetailPresenter()
private val youtubeStandalonePlayerHelper = youtubeStandalonePlayerHelper()
private val eventAnalytics = eventAnalytics()
private val aircraftDetailActivityTracer = aircraftDetailActivityContentLoad()
override fun onCreate(savedInstanceState: Bundle?) {
aircraftDetailActivityTracer.start()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_aircraft_detail)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(!isFromDeepLink)
title = ""
toolbar.apply {
setNavigationOnClickListener { onBackPressed() }
if (!isFromDeepLink) {
setNavigationIcon(R.drawable.ic_arrow_back_white_24dp)
}
}
supportPostponeEnterTransition()
Handler().postDelayed(TRANSITION_TIMEOUT) {
supportStartPostponedEnterTransition()
}
animateOnBackPressed = savedInstanceState == null
if (savedInstanceState == null && startedWithSharedElementTransition) {
initialInvisibleViews.forEach { it.alpha = 0f }
aircraftDetailsContainer.background = null
window.sharedElementEnterTransition.addListener(enterTransitionListener)
}
scrollView.setOnScrollChangeListener { _: NestedScrollView?, _: Int, y: Int, _: Int, _: Int ->
onScrollChanged(y)
}
scrollView.scrollTo(0, 0)
onScrollChanged(0)
aircraftImageContainer.setOnClickListener {
navigateToPhotoCarousel()
}
similarAircraftRail.aircraftId = aircraftId
}
override fun onStart() {
super.onStart()
presenter.startPresenting(this, aircraftId)
eventAnalytics.logScreenView(aircraftDetailScreen())
eventAnalytics.logEvent(aircraftDetailEvent(aircraftId))
}
override fun onStop() {
super.onStop()
presenter.stopPresenting()
}
override fun onBackPressed() {
if (scrollView.scrollY > 0 || !animateOnBackPressed) {
finish()
} else {
supportFinishAfterTransition()
window.sharedElementReturnTransition.addListener(ExitTransitionListener())
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_aircraft_detail, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_feedback) {
navigator.launchFeedbackDialog()
return true
}
return super.onOptionsItemSelected(item)
}
override fun showAircraft(aircraftDetailViewModel: AircraftDetailViewModel) {
val aircraft = aircraftDetailViewModel.aircraft
aircraftImage.loadAircraftImage(aircraft) {
aircraftImage.doOnLayout {
supportStartPostponedEnterTransition()
}
}
aircraftName.text = aircraft.name
title = aircraft.name
aircraftDescription.text = aircraft.longDescription
aircraftMetaDataContainer.removeAllViews()
aircraftDetailViewModel.featuredVideoId?.let { addWatchOnYoutubeItem(it) }
aircraft.metaData.forEach { addAircraftMetaDataItem(it.key, it.value) }
addAircraftMetaDataItem(getString(R.string.attribution), aircraft.attribution) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(aircraft.attributionUrl)))
}
aircraftDescription.doOnLayout {
setUpDescription()
}
aircraftDetailActivityTracer.stop()
}
private fun addAircraftMetaDataItem(
label: String,
value: String,
onClick: (() -> Unit)? = null
) {
val metaDataView = LayoutInflater.from(this).inflate(
R.layout.view_meta_data_item,
aircraftMetaDataContainer,
false
) as TextView
val spannable = SpannableString(getString(R.string.meta_data_item, label, value))
spannable.setSpan(StyleSpan(BOLD), spannable.length - value.length, spannable.length, 0)
metaDataView.text = spannable
onClick?.let { _ -> metaDataView.setOnClickListener { onClick.invoke() } }
aircraftMetaDataContainer.addView(metaDataView)
addDivider()
}
private fun addWatchOnYoutubeItem(videoId: String) {
val videoView = LayoutInflater.from(this)
.inflate(R.layout.view_aircraft_featured_video, aircraftMetaDataContainer, false)
videoView.setOnClickListener {
youtubeStandalonePlayerHelper.launchYoutubeStandalonePlayer(this, videoId)
eventAnalytics.logEvent(
youtubeVideoClickEvent(
videoId = videoId,
aircraftId = aircraftId
)
)
}
aircraftMetaDataContainer.addView(videoView)
addDivider()
}
private fun addDivider() {
val divider = View(this)
divider.layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, 1)
divider.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryLight))
aircraftMetaDataContainer.addView(divider)
}
private fun onScrollChanged(scrollY: Int) {
aircraftImage.translationY = (scrollY / PARALLAX_FACTOR).toFloat()
val toolbarAlphaScale = min(scrollY, aircraftImage.height) / aircraftImage.height.toFloat()
val primaryColour = ContextCompat.getColor(this, R.color.colorPrimary)
toolbar.setBackgroundColor(
argb(
(FULL_COLOUR * toolbarAlphaScale).toInt(),
red(primaryColour),
green(primaryColour),
blue(primaryColour)
)
)
toolbar.setTitleTextColor(
argb(
(FULL_COLOUR * toolbarAlphaScale).toInt(),
FULL_COLOUR,
FULL_COLOUR,
FULL_COLOUR
)
)
val toolbarMaxElevation = TOOLBAR_ELEVATION.dpToPixels()
toolbar.elevation = min(scrollY, scrollView.paddingTop).toFloat() /
toolbarMaxElevation.toFloat()
}
private fun navigateToPhotoCarousel() {
navigator.launchPhotoCarouselActivity(aircraftId, aircraftImage)
}
private fun setUpDescription() {
if (aircraftDescription.tag == "always_expanded" ||
aircraftDescription.lineCount <= AIRCRAFT_DESCRIPTION_COLLAPSED_LINES
) {
aircraftDescription.drawableBottom = null
} else {
aircraftDescription.maxLines = AIRCRAFT_DESCRIPTION_COLLAPSED_LINES
aircraftDescription.setOnClickListener {
expandOrCollapseDescription()
}
}
}
private fun expandOrCollapseDescription() {
val newMaxLines: Int
if (aircraftDescription.maxLines == AIRCRAFT_DESCRIPTION_COLLAPSED_LINES) {
newMaxLines = aircraftDescription.lineCount
aircraftDescription.drawableBottom = expandLessDrawable
} else {
newMaxLines = AIRCRAFT_DESCRIPTION_COLLAPSED_LINES
aircraftDescription.drawableBottom = expandMoreDrawable
}
val animation = ObjectAnimator.ofInt(aircraftDescription, "maxLines", newMaxLines)
val duration = (aircraftDescription.lineCount - AIRCRAFT_DESCRIPTION_COLLAPSED_LINES) *
AIRCRAFT_DESCRIPTION_ANIMATION_TIME_MULTIPLIER
animation.setDuration(duration).start()
}
private inner class EnterTransitionListener : TransitionListenerAdapter() {
val slideDistance = SLIDE_DISTANCE.pixelsToDp().toFloat()
override fun onTransitionStart(transition: Transition?) {
super.onTransitionStart(transition)
transitionSlidingViews.forEach { it.translationY = slideDistance }
transitionFadingViews.forEach { it.alpha = 0.0f }
}
override fun onTransitionEnd(transition: Transition?) {
super.onTransitionEnd(transition)
aircraftDetailsContainer.setBackgroundColor(detailsBackgroundColour)
toolbar.animate().alpha(1.0f).start()
photoCarouselButton.animate().alpha(1.0f).start()
val slideAnimators = transitionSlidingViews.map {
ObjectAnimator.ofFloat(it, TRANSLATION_Y, 0.0f)
}
val fadeAnimators = transitionSlidingViews.map {
ObjectAnimator.ofFloat(it, ALPHA, 1.0f)
}
AnimatorSet().apply {
interpolator = LinearOutSlowInInterpolator()
duration = ENTER_ANIMATION_DURATION
playTogether(slideAnimators.append(fadeAnimators))
start()
}
window.sharedElementEnterTransition.removeListener(enterTransitionListener)
}
}
private inner class ExitTransitionListener : TransitionListenerAdapter() {
override fun onTransitionStart(transition: Transition?) {
for (view in transitionExitHideViews) {
view.visibility = GONE
}
}
}
private companion object {
private const val TRANSITION_TIMEOUT = 500L
private const val TOOLBAR_ELEVATION = 4
private const val PARALLAX_FACTOR = 4
private const val FULL_COLOUR = 255
private const val SLIDE_DISTANCE = 400
private const val ENTER_ANIMATION_DURATION = 160L
private const val AIRCRAFT_DESCRIPTION_COLLAPSED_LINES = 6
private const val AIRCRAFT_DESCRIPTION_ANIMATION_TIME_MULTIPLIER = 10L
}
}
// TODO move
private fun <T> List<T>.append(list: List<T>): List<T> =
this.toMutableList().apply {
addAll(list)
}
|
gpl-3.0
|
84573a9874afa4ed24417b06001ed72b
| 38.014019 | 106 | 0.675949 | 5.208359 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnsafeCastFromDynamicInspection.kt
|
1
|
2798
|
// 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.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.expressionVisitor
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isDynamic
import org.jetbrains.kotlin.types.typeUtil.isNullableAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class UnsafeCastFromDynamicInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor =
expressionVisitor(fun(expression) {
val context = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, expression] ?: return
val actualType = expression.getType(context) ?: return
if (actualType.isDynamic() && !expectedType.isDynamic() && !expectedType.isNullableAny() &&
!TypeUtils.noExpectedType(expectedType)
) {
holder.registerProblem(
expression,
KotlinBundle.message("implicit.unsafe.cast.from.dynamic.to.0", expectedType),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
CastExplicitlyFix(expectedType)
)
}
})
}
private class CastExplicitlyFix(private val type: KotlinType) : LocalQuickFix {
override fun getName() = KotlinBundle.message("cast.explicitly.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtExpression ?: return
val typeName = type.constructor.declarationDescriptor?.name ?: return
val pattern = if (type.isMarkedNullable) "$0 as? $1" else "$0 as $1"
val newExpression = KtPsiFactory(expression).createExpressionByPattern(pattern, expression, typeName)
expression.replace(newExpression)
}
}
|
apache-2.0
|
30dba52dfc4eb2b2d7c271af9a6ab454
| 48.982143 | 158 | 0.748034 | 5.005367 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinHighLevelTypeArgumentInfoHandler.kt
|
1
|
5852
|
// 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.parameterInfo
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.calls.KtCallableMemberCall
import org.jetbrains.kotlin.analysis.api.components.KtTypeRendererOptions
import org.jetbrains.kotlin.analysis.api.signatures.KtFunctionLikeSignature
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtTypeAliasSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtTypeParameterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithTypeParameters
import org.jetbrains.kotlin.analysis.api.types.KtClassErrorType
import org.jetbrains.kotlin.analysis.api.types.KtClassType
import org.jetbrains.kotlin.analysis.api.types.KtFlexibleType
import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
/**
* Presents type argument info for class type references (e.g., property type in declaration, base class in super types list).
*/
class KotlinHighLevelClassTypeArgumentInfoHandler : KotlinHighLevelTypeArgumentInfoHandlerBase() {
override fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>? {
val typeReference = argumentList.parentOfType<KtTypeReference>() ?: return null
val ktType = typeReference.getKtType() as? KtClassType ?: return null
return when (ktType) {
is KtNonErrorClassType -> listOfNotNull(ktType.expandedClassSymbol as? KtNamedClassOrObjectSymbol)
is KtClassErrorType -> {
ktType.candidateClassSymbols.mapNotNull { candidateSymbol ->
when (candidateSymbol) {
is KtClassOrObjectSymbol -> candidateSymbol
is KtTypeAliasSymbol -> candidateSymbol.expandedType.expandedClassSymbol
else -> null
} as? KtNamedClassOrObjectSymbol
}
}
}
}
override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java)
}
/**
* Presents type argument info for function calls (including constructor calls).
*/
class KotlinHighLevelFunctionTypeArgumentInfoHandler : KotlinHighLevelTypeArgumentInfoHandlerBase() {
override fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>? {
val callElement = argumentList.parentOfType<KtCallElement>() ?: return null
// A call element may not be syntactically complete (e.g., missing parentheses: `foo<>`). In that case, `callElement.resolveCall()`
// will NOT return a KtCall because there is no FirFunctionCall there. We find the symbols using the callee name instead.
val reference = callElement.calleeExpression?.references?.singleOrNull() as? KtSimpleNameReference ?: return null
val explicitReceiver = callElement.getQualifiedExpressionForSelector()?.receiverExpression
val fileSymbol = callElement.containingKtFile.getFileSymbol()
val symbols = callElement.collectCallCandidates()
.mapNotNull { (it.candidate as? KtCallableMemberCall<*, *>)?.partiallyAppliedSymbol?.signature }
.filterIsInstance<KtFunctionLikeSignature<*>>()
.filter { filterCandidate(it, callElement, fileSymbol, explicitReceiver) }
// Multiple overloads may have the same type parameters (see Overloads.kt test), so we select the distinct ones.
return symbols.distinctBy { buildPresentation(fetchCandidateInfo(it.symbol), -1).first }.map { it.symbol }
}
override fun getArgumentListAllowedParentClasses() = setOf(KtCallElement::class.java)
}
abstract class KotlinHighLevelTypeArgumentInfoHandlerBase : AbstractKotlinTypeArgumentInfoHandler() {
protected abstract fun KtAnalysisSession.findParameterOwners(argumentList: KtTypeArgumentList): Collection<KtSymbolWithTypeParameters>?
override fun fetchCandidateInfos(argumentList: KtTypeArgumentList): List<CandidateInfo>? {
analyze(argumentList) {
val parameterOwners = findParameterOwners(argumentList) ?: return null
return parameterOwners.map { fetchCandidateInfo(it) }
}
}
protected fun KtAnalysisSession.fetchCandidateInfo(parameterOwner: KtSymbolWithTypeParameters): CandidateInfo {
return CandidateInfo(parameterOwner.typeParameters.map { fetchTypeParameterInfo(it) })
}
private fun KtAnalysisSession.fetchTypeParameterInfo(parameter: KtTypeParameterSymbol): TypeParameterInfo {
val upperBounds = parameter.upperBounds.map {
val isNullableAnyOrFlexibleAny = if (it is KtFlexibleType) {
it.lowerBound.isAny && !it.lowerBound.isMarkedNullable && it.upperBound.isAny && it.upperBound.isMarkedNullable
} else {
it.isAny && it.isMarkedNullable
}
val renderedType = it.render(KtTypeRendererOptions.SHORT_NAMES)
UpperBoundInfo(isNullableAnyOrFlexibleAny, renderedType)
}
return TypeParameterInfo(parameter.name.asString(), parameter.isReified, parameter.variance, upperBounds)
}
}
|
apache-2.0
|
db5c7bc193b4d906990474c3b5ac1127
| 58.121212 | 158 | 0.759398 | 5.267327 | false | false | false | false |
DanielGrech/anko
|
dsl/src/org/jetbrains/android/anko/generator/ServiceGenerator.kt
|
3
|
1784
|
/*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.generator
import org.objectweb.asm.tree.FieldNode
class ServiceGenerator : Generator<ServiceElement> {
override fun generate(state: GenerationState): Iterable<ServiceElement> {
return state.classTree.findNode("android/content/Context")?.data?.fields
?.filter { it.name.endsWith("_SERVICE") }
?.map {
val service = state.classTree.findNode("android", it.toServiceClassName())?.data
if (service != null) ServiceElement(service, it.name) else null
}
?.filterNotNull()
?.sortBy { it.name }
?: listOf()
}
private fun FieldNode.toServiceClassName(): String {
var nextCapital = true
val builder = StringBuilder()
for (char in name.replace("_SERVICE", "_MANAGER").toCharArray()) when (char) {
'_' -> nextCapital = true
else -> builder.append(
if (nextCapital) {
nextCapital = false; char
} else Character.toLowerCase(char)
)
}
return builder.toString()
}
}
|
apache-2.0
|
50e4ddfbf9c6fd218ad2355a63950197
| 36.1875 | 100 | 0.617152 | 4.670157 | false | false | false | false |
mdaniel/intellij-community
|
platform/vcs-impl/src/com/intellij/vcs/commit/NonModalCommitPanel.kt
|
2
|
7274
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.editor.colors.EditorColorsListener
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComponentContainer
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.actions.ShowCommitOptionsAction
import com.intellij.openapi.vcs.changes.InclusionListener
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.JBColor
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.awt.RelativePoint.getNorthEastOf
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.EventDispatcher
import com.intellij.util.IJSwingUtilities.updateComponentTreeUI
import com.intellij.util.ui.JBUI.Borders.empty
import com.intellij.util.ui.JBUI.Borders.emptyLeft
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.JBUI.scale
import com.intellij.util.ui.UIUtil.getTreeBackground
import com.intellij.util.ui.UIUtil.uiTraverser
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.LayoutManager
import java.awt.Point
import javax.swing.JComponent
import javax.swing.LayoutFocusTraversalPolicy
import javax.swing.border.Border
import javax.swing.border.EmptyBorder
private fun panel(layout: LayoutManager): JBPanel<*> = JBPanel<JBPanel<*>>(layout)
abstract class NonModalCommitPanel(
val project: Project,
val commitActionsPanel: CommitActionsPanel = CommitActionsPanel(),
val commitAuthorComponent: CommitAuthorComponent = CommitAuthorComponent(project)
) : BorderLayoutPanel(),
NonModalCommitWorkflowUi,
CommitActionsUi by commitActionsPanel,
CommitAuthorTracker by commitAuthorComponent,
ComponentContainer,
EditorColorsListener {
private val inclusionEventDispatcher = EventDispatcher.create(InclusionListener::class.java)
private val dataProviders = mutableListOf<DataProvider>()
private var needUpdateCommitOptionsUi = false
protected val centerPanel = simplePanel()
protected var bottomPanel: JBPanel<*>.() -> Unit = { }
private val actions = ActionManager.getInstance().getAction("ChangesView.CommitToolbar") as ActionGroup
val toolbar = ActionManager.getInstance().createActionToolbar(COMMIT_TOOLBAR_PLACE, actions, true).apply {
setTargetComponent(this@NonModalCommitPanel)
component.isOpaque = false
}
val commitMessage = CommitMessage(project, false, false, true, message("commit.message.placeholder")).apply {
editorField.addSettingsProvider { it.setBorder(emptyLeft(6)) }
}
override val commitMessageUi: CommitMessageUi get() = commitMessage
override fun getComponent(): JComponent = this
override fun getPreferredFocusableComponent(): JComponent = commitMessage.editorField
override fun getData(dataId: String) = getDataFromProviders(dataId) ?: commitMessage.getData(dataId)
fun getDataFromProviders(dataId: String) = dataProviders.asSequence().mapNotNull { it.getData(dataId) }.firstOrNull()
override fun addDataProvider(provider: DataProvider) {
dataProviders += provider
}
override fun addInclusionListener(listener: InclusionListener, parent: Disposable) =
inclusionEventDispatcher.addListener(listener, parent)
protected fun fireInclusionChanged() = inclusionEventDispatcher.multicaster.inclusionChanged()
override fun startBeforeCommitChecks() = Unit
override fun endBeforeCommitChecks(result: CommitChecksResult) = Unit
override fun dispose() = Unit
override fun globalSchemeChange(scheme: EditorColorsScheme?) {
needUpdateCommitOptionsUi = true
commitActionsPanel.border = getButtonPanelBorder()
}
protected fun buildLayout() {
commitActionsPanel.apply {
border = getButtonPanelBorder()
background = getButtonPanelBackground()
setTargetComponent(this@NonModalCommitPanel)
}
centerPanel
.addToCenter(commitMessage)
.addToBottom(panel(VerticalLayout(0)).apply {
background = getButtonPanelBackground()
bottomPanel()
})
addToCenter(centerPanel)
withPreferredHeight(85)
}
private fun getButtonPanelBorder(): Border {
return EmptyBorder(0, scale(3), (scale(6) - commitActionsPanel.getBottomInset()).coerceAtLeast(0), 0)
}
private fun getButtonPanelBackground(): JBColor? {
return JBColor.lazy { (commitMessage.editorField.editor as? EditorEx)?.backgroundColor ?: getTreeBackground() }
}
override fun showCommitOptions(options: CommitOptions, actionName: String, isFromToolbar: Boolean, dataContext: DataContext) {
val commitOptionsPanel = CommitOptionsPanel { actionName }.apply {
focusTraversalPolicy = LayoutFocusTraversalPolicy()
isFocusCycleRoot = true
setOptions(options)
border = empty(0, 10)
// to reflect LaF changes as commit options components are created once per commit
if (needUpdateCommitOptionsUi) {
needUpdateCommitOptionsUi = false
updateComponentTreeUI(this)
}
}
val focusComponent = IdeFocusManager.getInstance(project).getFocusTargetFor(commitOptionsPanel)
val commitOptionsPopup = JBPopupFactory.getInstance()
.createComponentPopupBuilder(commitOptionsPanel, focusComponent)
.setRequestFocus(true)
.addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
options.restoreState()
}
override fun onClosed(event: LightweightWindowEvent) {
options.saveState()
}
})
.createPopup()
showCommitOptions(commitOptionsPopup, isFromToolbar, dataContext)
}
protected open fun showCommitOptions(popup: JBPopup, isFromToolbar: Boolean, dataContext: DataContext) =
if (isFromToolbar) popup.show(getNorthEastOf(toolbar.getShowCommitOptionsButton() ?: toolbar.component))
else popup.showInBestPositionFor(dataContext)
companion object {
internal const val COMMIT_TOOLBAR_PLACE: String = "ChangesView.CommitToolbar"
fun JBPopup.showAbove(component: JComponent) {
val northWest = RelativePoint(component, Point())
addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
val popup = event.asPopup()
val location = Point(popup.locationOnScreen).apply { y = northWest.screenPoint.y - popup.size.height }
popup.setLocation(location)
}
})
show(northWest)
}
}
}
private fun ActionToolbar.getShowCommitOptionsButton(): JComponent? =
uiTraverser(component)
.filter(ActionButton::class.java)
.find { it.action is ShowCommitOptionsAction }
|
apache-2.0
|
bd84a9bac2173dfcf3067d2d425a11c2
| 38.748634 | 128 | 0.775639 | 4.898316 | false | false | false | false |
GunoH/intellij-community
|
platform/build-scripts/src/org/jetbrains/intellij/build/impl/BuildUtils.kt
|
2
|
2104
|
// 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.intellij.build.impl
import com.intellij.openapi.util.text.StringUtilRt
import java.nio.file.Files
import java.nio.file.Path
import java.util.function.BiConsumer
object BuildUtils {
@JvmStatic
@JvmOverloads
fun replaceAll(text: String, replacements: Map<String, String>, marker: String = "__"): String {
var result = text
replacements.forEach(BiConsumer { k, v ->
result = result.replace("$marker${k}$marker", v)
})
return result
}
@JvmStatic
@JvmOverloads
fun copyAndPatchFile(sourcePath: Path,
targetPath: Path,
replacements: Map<String, String>,
marker: String = "__",
lineSeparator: String = "") {
Files.createDirectories(targetPath.parent)
var content = replaceAll(Files.readString(sourcePath), replacements, marker)
if (!lineSeparator.isEmpty()) {
content = StringUtilRt.convertLineSeparators(content, lineSeparator)
}
Files.writeString(targetPath, content)
}
fun propertiesToJvmArgs(properties: List<Pair<String, String>>): List<String> {
val result = ArrayList<String>(properties.size)
for ((key, value) in properties) {
addVmProperty(result, key, value.toString())
}
return result
}
internal fun addVmProperty(args: MutableList<String>, key: String, value: String?) {
if (value != null) {
args.add("-D$key=$value")
}
}
@JvmStatic
fun getPluginJars(pluginPath: Path): List<Path> {
return Files.newDirectoryStream(pluginPath.resolve("lib"), "*.jar").use { it.toList() }
}
val isUnderJpsBootstrap: Boolean
get() = System.getenv("JPS_BOOTSTRAP_COMMUNITY_HOME") != null
}
fun convertLineSeparators(file: Path, newLineSeparator: String) {
val data = Files.readString(file)
val convertedData = StringUtilRt.convertLineSeparators(data, newLineSeparator)
if (data != convertedData) {
Files.writeString(file, convertedData)
}
}
|
apache-2.0
|
c506fb8dc572e8062e486b77d284db0d
| 31.890625 | 120 | 0.679658 | 4.2249 | false | false | false | false |
SDS-Studios/ScoreKeeper
|
app/src/main/java/io/github/sdsstudios/ScoreKeeper/PlayerIconLayout.kt
|
1
|
1234
|
package io.github.sdsstudios.ScoreKeeper
import android.content.Context
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.View
import android.widget.Button
/**
* Created by sethsch1 on 27/11/17.
*/
class PlayerIconLayout(context: Context?, attrs: AttributeSet?)
: ConstraintLayout(context, attrs) {
lateinit var button: Button
private lateinit var mImageViewIcon: CirclePlayerIconView
private val mBrowseString = context!!.getString(R.string.btn_browse)
private val mRemoveString = context!!.getString(R.string.btn_remove)
override fun onViewAdded(view: View?) {
super.onViewAdded(view)
when (view!!.id) {
R.id.buttonEdit -> button = view as Button
R.id.imageViewPlayerIcon -> mImageViewIcon = view as CirclePlayerIconView
}
}
fun buttonIsRemove() = button.text == mRemoveString
fun buttonIsBrowse() = button.text == mBrowseString
fun removeIcon() {
setIcon(null)
button.text = mBrowseString
}
fun setIcon(iconName: String?) {
mImageViewIcon.setIcon(iconName)
if (iconName != null) {
button.text = mRemoveString
}
}
}
|
gpl-3.0
|
25af1538eed7954c7e41aae73ca272bf
| 27.068182 | 85 | 0.683955 | 4.24055 | false | false | false | false |
himikof/intellij-rust
|
src/main/kotlin/org/rust/ide/actions/RsAbstractUpDownMover.kt
|
1
|
3382
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.codeInsight.editorActions.moveUpDown.LineRange
import com.intellij.codeInsight.editorActions.moveUpDown.StatementUpDownMover
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IElementType
import org.rust.ide.utils.findElementAtIgnoreWhitespaceAfter
import org.rust.ide.utils.findElementAtIgnoreWhitespaceBefore
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.elementType
val PsiElement.line: Int? get() = containingFile.viewProvider.document?.getLineNumber(textRange.startOffset)
abstract class RsAbstractUpDownMover : StatementUpDownMover() {
abstract val containers: List<IElementType>
abstract val jumpOver: List<IElementType>
abstract fun collectedElement(element: PsiElement): Pair<PsiElement, List<Int>>?
override fun checkAvailable(editor: Editor, file: PsiFile, info: MoveInfo, down: Boolean): Boolean {
if (file !is RsFile) {
return false
}
val selectionRange = getLineRangeFromSelection(editor)
val start = file.findElementAtIgnoreWhitespaceBefore(
editor.document.getLineStartOffset(selectionRange.startLine)
) ?: return false
val (collectedElement, possibleStartLines) = collectedElement(start) ?: return false
if (!possibleStartLines.contains(selectionRange.startLine)) {
return false
}
val range = LineRange(collectedElement)
info.toMove = range
val line = if (!down) {
info.toMove.startLine - 1
} else {
info.toMove.endLine + 1
}
if (line < 0 || line >= editor.document.lineCount) {
return info.prohibitMove()
}
val offset = editor.document.getLineStartOffset(line)
var element: PsiElement? = if (!down) {
file.findElementAtIgnoreWhitespaceBefore(offset)
} else {
file.findElementAtIgnoreWhitespaceAfter(offset)
} ?: return info.prohibitMove()
while (element != null && element !is RsFile) {
if (containers.any { element?.elementType == it }) {
var parentOfFn = collectedElement.parent
while (parentOfFn !is RsFile) {
if (element == parentOfFn) {
return info.prohibitMove()
}
parentOfFn = parentOfFn.parent
}
}
if (jumpOver.any { element?.elementType == it }) {
break
}
val parent = element.parent
if (parent is RsFile) {
break
}
element = parent
}
if (element != null) {
info.toMove2 = LineRange(element)
}
if (down) {
if (info.toMove2.startLine - 1 == range.endLine || element == collectedElement) {
info.toMove2 = LineRange(line - 1, line)
}
} else {
if (info.toMove2.startLine == range.startLine) {
info.toMove2 = LineRange(line, line + 1)
}
}
return true
}
}
|
mit
|
85017d57308a5f07f0163f56ee34953b
| 34.6 | 108 | 0.61709 | 4.664828 | false | false | false | false |
ktorio/ktor
|
ktor-server/ktor-server-config-yaml/jvm/src/io/ktor/server/config/yaml/YamlConfigJvm.kt
|
1
|
1406
|
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.config.yaml
import io.ktor.server.config.*
import net.mamoe.yamlkt.*
import java.io.*
/**
* Loads a configuration from the YAML file, if found.
* On JVM, loads a configuration from application resources, if exist; otherwise, reads a configuration from a file.
* On Native, always reads a configuration from a file.
*/
public actual fun YamlConfig(path: String?): YamlConfig? {
val resolvedPath = when {
path == null -> DEFAULT_YAML_FILENAME
path.endsWith(".yaml") -> path
else -> return null
}
val resource = Thread.currentThread().contextClassLoader.getResource(resolvedPath)
if (resource != null) {
return resource.openStream().use {
configFromString(String(it.readBytes()))
}
}
val file = File(resolvedPath)
if (file.exists()) {
return configFromString(file.readText())
}
return null
}
private fun configFromString(content: String): YamlConfig {
val yaml = Yaml.decodeYamlFromString(content) as? YamlMap
?: throw ApplicationConfigurationException("Config should be a YAML dictionary")
return YamlConfig(yaml).apply { checkEnvironmentVariables() }
}
internal actual fun getEnvironmentValue(key: String): String? = System.getenv(key)
|
apache-2.0
|
9291d42332c0a7b380fd7edc220117f1
| 33.292683 | 119 | 0.697724 | 4.260606 | false | true | false | false |
ktorio/ktor
|
ktor-client/ktor-client-darwin/darwin/test/DarwinEngineTest.kt
|
1
|
6512
|
import io.ktor.client.*
import io.ktor.client.engine.darwin.*
import io.ktor.client.engine.darwin.internal.*
import io.ktor.client.plugins.websocket.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.client.tests.utils.*
import io.ktor.http.*
import io.ktor.websocket.*
import kotlinx.cinterop.*
import kotlinx.coroutines.*
import platform.Foundation.*
import platform.Foundation.NSHTTPCookieStorage.Companion.sharedHTTPCookieStorage
import kotlin.test.*
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
class DarwinEngineTest {
@Test
fun testRequestInRunBlocking() = runBlocking {
val client = HttpClient(Darwin)
try {
withTimeout(1000) {
val response = client.get(TEST_SERVER)
assertEquals("Hello, world!", response.bodyAsText())
}
} finally {
client.close()
}
}
@Test
fun testQueryWithCyrillic() = runBlocking {
val client = HttpClient(Darwin)
try {
withTimeout(1000) {
val response = client.get("$TEST_SERVER/echo_query?привет")
assertEquals("привет=[]", response.bodyAsText())
}
} finally {
client.close()
}
}
@Test
fun testQueryWithMultipleParams() = runBlocking {
val client = HttpClient(Darwin)
try {
withTimeout(1000) {
val response = client.get("$TEST_SERVER/echo_query?asd=qwe&asd=123&qwe&zxc=vbn")
assertEquals("asd=[qwe, 123], qwe=[], zxc=[vbn]", response.bodyAsText())
}
} finally {
client.close()
}
}
@Test
fun testNSUrlSanitize() {
assertEquals(
"http://127.0.0.1/echo_query?%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82",
stringToNSUrlString("http://127.0.0.1/echo_query?привет")
)
assertEquals(
"http://%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82.%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82/",
stringToNSUrlString("http://привет.привет/")
)
}
@Test
fun testCookieIsNotPersistedByDefault() = runBlocking {
val client = HttpClient(Darwin)
try {
client.get("$TEST_SERVER/cookies")
val result = client.get("$TEST_SERVER/cookies/dump")
.bodyAsText()
assertEquals("Cookies: ", result)
} finally {
client.close()
}
}
@Test
fun testCookiePersistedWithSessionStore() = runBlocking {
val client = HttpClient(Darwin) {
engine {
configureSession {
setHTTPCookieStorage(sharedHTTPCookieStorage)
}
}
}
try {
client.get("$TEST_SERVER/cookies")
val result = client.get("$TEST_SERVER/cookies/dump")
.bodyAsText()
assertEquals("Cookies: hello-cookie=my%2Dawesome%2Dvalue", result)
} finally {
client.close()
}
}
@Test
fun testOverrideDefaultSession(): Unit = runBlocking {
val client = HttpClient(Darwin) {
val delegate = KtorNSURLSessionDelegate()
val session = NSURLSession.sessionWithConfiguration(
NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate,
delegateQueue = NSOperationQueue()
)
engine {
usePreconfiguredSession(session, delegate)
}
}
try {
val response = client.get(TEST_SERVER)
assertEquals("Hello, world!", response.bodyAsText())
} finally {
client.close()
}
}
@Test
fun testOverrideDefaultSessionWithWebSockets(): Unit = runBlocking {
val client = HttpClient(Darwin) {
val delegate = KtorNSURLSessionDelegate()
val session = NSURLSession.sessionWithConfiguration(
NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate,
delegateQueue = NSOperationQueue()
)
engine {
usePreconfiguredSession(session, delegate)
}
install(WebSockets)
}
try {
val session = client.webSocketSession("$TEST_WEBSOCKET_SERVER/websockets/echo")
session.send("test")
val response = session.incoming.receive() as Frame.Text
assertEquals("test", response.readText())
session.close()
} finally {
client.close()
}
}
@Test
fun testConfigureRequest(): Unit = runBlocking {
val client = HttpClient(Darwin) {
engine {
configureRequest {
setValue("my header value", forHTTPHeaderField = "XCustomHeader")
}
}
}
val response = client.get("$TEST_SERVER/headers/echo?headerName=XCustomHeader")
assertEquals(HttpStatusCode.OK, response.status)
assertEquals("my header value", response.bodyAsText())
}
@OptIn(UnsafeNumber::class)
@Test
fun testConfigureWebsocketRequest(): Unit = runBlocking {
var customChallengeCalled = false
val client = HttpClient(Darwin) {
engine {
handleChallenge { _, _, challenge, completionHandler ->
customChallengeCalled = true
challenge.protectionSpace.serverTrust?.let {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
val credential = NSURLCredential.credentialForTrust(it)
completionHandler(NSURLSessionAuthChallengeUseCredential, credential)
}
}
}
}
install(WebSockets)
}
val session = client.webSocketSession("wss://127.0.0.1:8089/websockets/echo")
session.send("test")
val response = session.incoming.receive() as Frame.Text
assertEquals("test", response.readText())
assertTrue(customChallengeCalled)
session.close()
}
private fun stringToNSUrlString(value: String): String {
return Url(value).toNSUrl().absoluteString!!
}
}
|
apache-2.0
|
4ad320cd123fb1fc39faba9ae3ade764
| 30.466019 | 119 | 0.56896 | 4.745242 | false | true | false | false |
RayBa82/DVBViewerController
|
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/DVBViewerPreferenceFragment.kt
|
1
|
1072
|
package org.dvbviewer.controller.ui.fragments
import android.content.Intent
import android.os.Bundle
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.entities.DVBViewerPreferences
import org.dvbviewer.controller.ui.phone.ConnectionPreferencesActivity
class DVBViewerPreferenceFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(bundle: Bundle?, s: String?) {
val prefMgr = preferenceManager
prefMgr.sharedPreferencesName = DVBViewerPreferences.PREFS
addPreferencesFromResource(R.xml.preferences)
val preference = preferenceScreen.findPreference(KEY_RS_SETTINGS)
preference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val settings = Intent(context, ConnectionPreferencesActivity::class.java)
startActivity(settings)
false
}
}
companion object {
private const val KEY_RS_SETTINGS = "KEY_RS_SETTINGS"
}
}
|
apache-2.0
|
4d32019d1c637bda58d3ec6c3b46231e
| 34.733333 | 85 | 0.76306 | 5.386935 | false | false | false | false |
DemonWav/MinecraftDev
|
src/main/kotlin/com/demonwav/mcdev/platform/mcp/srg/SrgManager.kt
|
1
|
2227
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.srg
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.util.mapFirstNotNull
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.createError
import org.jetbrains.concurrency.rejectedPromise
import org.jetbrains.concurrency.runAsync
import java.nio.file.NoSuchFileException
import java.nio.file.Paths
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class SrgManager(val files: Set<String>) {
var srgMap: Promise<McpSrgMap> = rejectedPromise("SRG map not loaded")
@Synchronized get
private set
val srgMapNow: McpSrgMap?
@Synchronized get() = try {
srgMap.blockingGet(1, TimeUnit.NANOSECONDS)
} catch (e: ExecutionException) {
null
} catch (e: TimeoutException) {
null
}
@Synchronized
fun parse() {
if (srgMap.state == Promise.State.PENDING) {
return
}
srgMap = if (files.isNotEmpty()) {
runAsync {
try {
// Load SRG map from files
McpSrgMap.parse(Paths.get(files.find { it.endsWith("mcp-srg.srg") }))
} catch (e: NoSuchFileException) {
throw createError("SRG mapping file does not exist")
}
}
} else {
// Path to SRG files is unknown
rejectedPromise("No mapping data available")
}
}
companion object {
private val map = HashMap<Set<String>, SrgManager>()
fun getInstance(files: Set<String>) = map.computeIfAbsent(files, ::SrgManager)
fun findAnyInstance(project: Project) =
ModuleManager.getInstance(project).modules.mapFirstNotNull {
MinecraftFacet.getInstance(it, McpModuleType)?.srgManager
}
}
}
|
mit
|
b7a118f65dfc56933d934f986b97c8fb
| 29.094595 | 89 | 0.645712 | 4.508097 | false | false | false | false |
Talentica/AndroidWithKotlin
|
customcamera/src/main/java/com/talentica/androidkotlin/customcamera/presenter/landing/LandingActivityPresenterImpl.kt
|
1
|
4458
|
package com.talentica.androidkotlin.customcamera.presenter.landing
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.view.MenuItem
import android.widget.GridView
import android.widget.Toast
import com.talentica.androidkotlin.customcamera.R
import com.talentica.androidkotlin.customcamera.adapter.landing.LandingGalleryAdapter
import com.talentica.androidkotlin.customcamera.ui.landing.LandingActivityView
import com.talentica.androidkotlin.customcamera.utils.Utils
import androidx.core.content.FileProvider
import android.webkit.MimeTypeMap
class LandingActivityPresenterImpl : LandingActivityPresenter {
private lateinit var landingActivityView: LandingActivityView
private lateinit var activity: Activity
private lateinit var landingAdapter:LandingGalleryAdapter
private val STORAGE_PERMISSION = 1212
override fun attach(activityView: LandingActivityView, activity: Activity, savedInstanceState: Bundle?) {
this.landingActivityView = activityView
this.activity = activity
landingAdapter = LandingGalleryAdapter(activity)
activityView.setAdapter(landingAdapter)
}
override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
if (menuItem.itemId == R.id.nav_gallery) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(
"content://media/internal/images/media"))
activity.startActivity(intent)
}
landingActivityView.closeDrawer()
return true;
}
override fun resume() {
checkStoragePermission()
}
override fun pause() {
}
fun checkStoragePermission() {
if (Build.VERSION.SDK_INT >= 23) {
//do your check here
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//File write logic here
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
STORAGE_PERMISSION);
// STORAGE_PERMISSION is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, grantResults: IntArray) {
if (requestCode == STORAGE_PERMISSION) {
if (grantResults != null && grantResults.isNotEmpty()) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(activity, "Thanks", Toast.LENGTH_SHORT).show()
Utils().checkAndMakeDir()
}
}
}
}
override fun addListOfPicsToAdapter(gridView: GridView) {
landingAdapter.refreshFilesFromFolder()
}
override fun lauchPhotoPreview(position: Int) {
val intent = Intent()
intent.action = Intent.ACTION_VIEW
val files = Utils().storageDir.listFiles()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
val file = files.get(position)
val photoURI = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".provider", file)
val ext = file.getName().substring(file.getName().lastIndexOf(".") + 1);
val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext)
intent.setDataAndType(photoURI, type)
} else {
intent.setDataAndType(Uri.parse("file://" + landingAdapter.getItem(position)), "image/*")
}
activity.startActivity(intent)
}
}
|
apache-2.0
|
93f792111516ded3b066755af26d227a
| 40.663551 | 143 | 0.668461 | 5.147806 | false | false | false | false |
Tickaroo/tikxml
|
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/element/polymorphism/constructor/PaperConstructor.kt
|
1
|
1600
|
/*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.element.polymorphism.constructor
import com.tickaroo.tikxml.annotation.Element
import com.tickaroo.tikxml.annotation.ElementNameMatcher
import com.tickaroo.tikxml.annotation.Xml
/**
* @author Hannes Dorfmann
*/
@Xml(name = "paper")
class PaperConstructor(
@param:Element(typesByElement = [
ElementNameMatcher(type = JournalistConstructor::class, name = "journalist"),
ElementNameMatcher(type = OrganisationConstructor::class, name = "organisation")
])
val writer: WriterConstructor?
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is PaperConstructor) return false
val that = other as PaperConstructor?
return if (writer != null) writer == that!!.writer else that!!.writer == null
}
override fun hashCode(): Int {
return writer?.hashCode() ?: 0
}
}
|
apache-2.0
|
e63dccb5fe1fe026d7edc297cc5beea9
| 31.653061 | 92 | 0.698125 | 4.312668 | false | false | false | false |
dbrant/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/edit/EditSectionActivity.kt
|
1
|
25445
|
package org.wikipedia.edit
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.text.TextWatcher
import android.view.*
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.core.os.postDelayed
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import androidx.core.widget.doAfterTextChanged
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.BaseActivity
import org.wikipedia.analytics.EditFunnel
import org.wikipedia.analytics.LoginFunnel
import org.wikipedia.auth.AccountUtil.isLoggedIn
import org.wikipedia.captcha.CaptchaHandler
import org.wikipedia.captcha.CaptchaResult
import org.wikipedia.csrf.CsrfTokenClient
import org.wikipedia.databinding.ActivityEditSectionBinding
import org.wikipedia.databinding.ItemEditActionbarButtonBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.mwapi.MwException
import org.wikipedia.dataclient.mwapi.MwParseResponse
import org.wikipedia.dataclient.mwapi.MwQueryResponse
import org.wikipedia.dataclient.mwapi.MwServiceError
import org.wikipedia.edit.preview.EditPreviewFragment
import org.wikipedia.edit.richtext.SyntaxHighlighter
import org.wikipedia.edit.summaries.EditSummaryFragment
import org.wikipedia.history.HistoryEntry
import org.wikipedia.login.LoginActivity
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.page.PageProperties
import org.wikipedia.page.PageTitle
import org.wikipedia.page.linkpreview.LinkPreviewDialog
import org.wikipedia.settings.Prefs
import org.wikipedia.util.*
import org.wikipedia.util.log.L
import org.wikipedia.views.ViewAnimations
import org.wikipedia.views.ViewUtil
import org.wikipedia.views.WikiTextKeyboardView
import java.io.IOException
import java.util.concurrent.TimeUnit
class EditSectionActivity : BaseActivity() {
private lateinit var binding: ActivityEditSectionBinding
private lateinit var funnel: EditFunnel
private lateinit var textWatcher: TextWatcher
private lateinit var captchaHandler: CaptchaHandler
private lateinit var editPreviewFragment: EditPreviewFragment
private lateinit var editSummaryFragment: EditSummaryFragment
private lateinit var syntaxHighlighter: SyntaxHighlighter
lateinit var pageTitle: PageTitle
private set
private var sectionID = 0
private var sectionHeading: String? = null
private var pageProps: PageProperties? = null
private var textToHighlight: String? = null
private var sectionWikitext: String? = null
private var sectionTextModified = false
private var sectionTextFirstLoad = true
private var editingAllowed = false
// Current revision of the article, to be passed back to the server to detect possible edit conflicts.
private var currentRevision: Long = 0
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
private var actionMode: ActionMode? = null
private val disposables = CompositeDisposable()
private val editTokenThenSave: Unit
get() {
cancelCalls()
binding.editSectionCaptchaContainer.visibility = View.GONE
captchaHandler.hideCaptcha()
editSummaryFragment.saveSummary()
disposables.add(CsrfTokenClient(pageTitle.wikiSite).token
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ doSave(it) }) { showError(it) })
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditSectionBinding.inflate(layoutInflater)
setContentView(binding.root)
setNavigationBarColor(ResourceUtil.getThemedColor(this, android.R.attr.colorBackground))
pageTitle = intent.getParcelableExtra(EXTRA_TITLE)!!
sectionID = intent.getIntExtra(EXTRA_SECTION_ID, 0)
sectionHeading = intent.getStringExtra(EXTRA_SECTION_HEADING)
pageProps = intent.getParcelableExtra(EXTRA_PAGE_PROPS)
textToHighlight = intent.getStringExtra(EXTRA_HIGHLIGHT_TEXT)
supportActionBar?.title = ""
syntaxHighlighter = SyntaxHighlighter(this, binding.editSectionText)
binding.editSectionScroll.isSmoothScrollingEnabled = false
captchaHandler = CaptchaHandler(this, pageTitle.wikiSite, binding.captchaContainer.root,
binding.editSectionText, "", null)
editPreviewFragment = supportFragmentManager.findFragmentById(R.id.edit_section_preview_fragment) as EditPreviewFragment
editSummaryFragment = supportFragmentManager.findFragmentById(R.id.edit_section_summary_fragment) as EditSummaryFragment
editSummaryFragment.title = pageTitle
funnel = WikipediaApp.getInstance().funnelManager.getEditFunnel(pageTitle)
// Only send the editing start log event if the activity is created for the first time
if (savedInstanceState == null) {
funnel.logStart()
}
if (savedInstanceState != null && savedInstanceState.containsKey("hasTemporaryWikitextStored")) {
sectionWikitext = Prefs.getTemporaryWikitext()
}
binding.viewEditSectionError.retryClickListener = View.OnClickListener {
binding.viewEditSectionError.visibility = View.GONE
fetchSectionText()
}
binding.viewEditSectionError.backClickListener = View.OnClickListener { onBackPressed() }
L10nUtil.setConditionalTextDirection(binding.editSectionText, pageTitle.wikiSite.languageCode())
fetchSectionText()
if (savedInstanceState != null && savedInstanceState.containsKey("sectionTextModified")) {
sectionTextModified = savedInstanceState.getBoolean("sectionTextModified")
}
textWatcher = binding.editSectionText.doAfterTextChanged {
if (sectionTextFirstLoad) {
sectionTextFirstLoad = false
return@doAfterTextChanged
}
if (!sectionTextModified) {
sectionTextModified = true
// update the actionbar menu, which will enable the Next button.
invalidateOptionsMenu()
}
}
binding.editKeyboardOverlay.editText = binding.editSectionText
binding.editKeyboardOverlay.callback = WikiTextKeyboardView.Callback {
bottomSheetPresenter.show(supportFragmentManager,
LinkPreviewDialog.newInstance(HistoryEntry(PageTitle(it, pageTitle.wikiSite), HistoryEntry.SOURCE_INTERNAL_LINK), null))
}
binding.editSectionText.setOnClickListener { finishActionMode() }
updateTextSize()
// set focus to the EditText, but keep the keyboard hidden until the user changes the cursor location:
binding.editSectionText.requestFocus()
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
public override fun onStart() {
super.onStart()
updateEditLicenseText()
}
public override fun onDestroy() {
captchaHandler.dispose()
cancelCalls()
binding.editSectionText.removeTextChangedListener(textWatcher)
syntaxHighlighter.cleanup()
super.onDestroy()
}
private fun updateEditLicenseText() {
val editLicenseText = findViewById<TextView>(R.id.edit_section_license_text)
editLicenseText.text = StringUtil.fromHtml(getString(if (isLoggedIn) R.string.edit_save_action_license_logged_in else R.string.edit_save_action_license_anon,
getString(R.string.terms_of_use_url),
getString(R.string.cc_by_sa_3_url)))
editLicenseText.movementMethod = LinkMovementMethodExt { url: String ->
if (url == "https://#login") {
funnel.logLoginAttempt()
val loginIntent = LoginActivity.newIntent(this@EditSectionActivity,
LoginFunnel.SOURCE_EDIT, funnel.sessionToken)
startActivityForResult(loginIntent, Constants.ACTIVITY_REQUEST_LOGIN)
} else {
UriUtil.handleExternalLink(this@EditSectionActivity, url.toUri())
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == Constants.ACTIVITY_REQUEST_LOGIN) {
if (resultCode == LoginActivity.RESULT_LOGIN_SUCCESS) {
updateEditLicenseText()
funnel.logLoginSuccess()
FeedbackUtil.showMessage(this, R.string.login_success_toast)
} else {
funnel.logLoginFailure()
}
}
}
private fun cancelCalls() {
disposables.clear()
}
private fun doSave(token: String) {
var summaryText = if (sectionHeading.isNullOrEmpty() ||
StringUtil.addUnderscores(sectionHeading) == pageTitle.prefixedText) "/* top */" else "/* $sectionHeading */ "
summaryText += editPreviewFragment.summary
// Summaries are plaintext, so remove any HTML that's made its way into the summary
summaryText = StringUtil.fromHtml(summaryText).toString()
if (!isFinishing) {
showProgressBar(true)
}
disposables.add(ServiceFactory.get(pageTitle.wikiSite).postEditSubmit(pageTitle.prefixedText,
sectionID.toString(), null, summaryText, if (isLoggedIn) "user" else null,
binding.editSectionText.text.toString(), null, currentRevision, token,
if (captchaHandler.isActive) captchaHandler.captchaId() else "null",
if (captchaHandler.isActive) captchaHandler.captchaWord() else "null")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result: Edit ->
val editResult = result.edit()
if (result.hasEditResult() && editResult != null) {
when {
editResult.editSucceeded() -> onEditSuccess(EditSuccessResult(editResult.newRevId()))
editResult.hasCaptchaResponse() -> onEditSuccess(CaptchaResult(editResult.captchaId()!!))
editResult.hasSpamBlacklistResponse() -> onEditFailure(MwException(MwServiceError(editResult.code(), editResult.spamblacklist())))
editResult.hasEditErrorCode() -> onEditFailure(MwException(MwServiceError(editResult.code(), editResult.info())))
else -> onEditFailure(IOException("Received unrecognized edit response"))
}
} else {
onEditFailure(IOException("An unknown error occurred."))
}
}) { onEditFailure(it) }
)
}
private fun onEditSuccess(result: EditResult) {
if (result is EditSuccessResult) {
funnel.logSaved(result.revID)
// TODO: remove the artificial delay and use the new revision
// ID returned to request the updated version of the page once
// revision support for mobile-sections is added to RESTBase
// See https://github.com/wikimedia/restbase/pull/729
Handler(mainLooper).postDelayed(TimeUnit.SECONDS.toMillis(2)) {
showProgressBar(false)
// Build intent that includes the section we were editing, so we can scroll to it later
val data = Intent()
data.putExtra(EXTRA_SECTION_ID, sectionID)
setResult(EditHandler.RESULT_REFRESH_PAGE, data)
DeviceUtil.hideSoftKeyboard(this@EditSectionActivity)
finish()
}
return
}
showProgressBar(false)
if (result is CaptchaResult) {
if (captchaHandler.isActive) {
// Captcha entry failed!
funnel.logCaptchaFailure()
}
binding.editSectionCaptchaContainer.visibility = View.VISIBLE
captchaHandler.handleCaptcha(null, result)
funnel.logCaptchaShown()
} else {
funnel.logError(result.result)
// Expand to do everything.
onEditFailure(Throwable())
}
}
private fun onEditFailure(caught: Throwable) {
showProgressBar(false)
if (caught is MwException) {
handleEditingException(caught)
} else {
showRetryDialog(caught)
}
L.e(caught)
}
private fun showRetryDialog(t: Throwable) {
val retryDialog = AlertDialog.Builder(this@EditSectionActivity)
.setTitle(R.string.dialog_message_edit_failed)
.setMessage(t.localizedMessage)
.setPositiveButton(R.string.dialog_message_edit_failed_retry) { dialog, _ ->
editTokenThenSave
dialog.dismiss()
}
.setNegativeButton(R.string.dialog_message_edit_failed_cancel) { dialog, _ -> dialog.dismiss() }.create()
retryDialog.show()
}
/**
* Processes API error codes encountered during editing, and handles them as appropriate.
* @param caught The MwException to handle.
*/
private fun handleEditingException(caught: MwException) {
val code = caught.title
// In the case of certain AbuseFilter responses, they are sent as a code, instead of a
// fully parsed response. We need to make one more API call to get the parsed message:
if (code.startsWith("abusefilter-") && caught.message.contains("abusefilter-") && caught.message.length < 100) {
disposables.add(ServiceFactory.get(pageTitle.wikiSite).parseText("MediaWiki:" + StringUtil.sanitizeAbuseFilterCode(caught.message))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response: MwParseResponse -> showError(MwException(MwServiceError(code, response.text))) }) { showError(it) })
} else if ("editconflict" == code) {
AlertDialog.Builder(this@EditSectionActivity)
.setTitle(R.string.edit_conflict_title)
.setMessage(R.string.edit_conflict_message)
.setPositiveButton(R.string.edit_conflict_dialog_ok_button_text, null)
.show()
resetToStart()
} else {
showError(caught)
}
}
/**
* Executes a click of the actionbar button, and performs the appropriate action
* based on the current state of the button.
*/
fun clickNextButton() {
when {
editSummaryFragment.isActive -> {
// we're showing the custom edit summary window, so close it and
// apply the provided summary.
editSummaryFragment.hide()
editPreviewFragment.setCustomSummary(editSummaryFragment.summary)
}
editPreviewFragment.isActive -> {
// we're showing the Preview window, which means that the next step is to save it!
editTokenThenSave
funnel.logSaveAttempt()
}
else -> {
// we must be showing the editing window, so show the Preview.
DeviceUtil.hideSoftKeyboard(this)
editPreviewFragment.showPreview(pageTitle, binding.editSectionText.text.toString())
funnel.logPreview()
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_save_section -> {
clickNextButton()
true
}
R.id.menu_edit_zoom_in -> {
Prefs.setEditingTextSizeExtra(Prefs.getEditingTextSizeExtra() + 1)
updateTextSize()
true
}
R.id.menu_edit_zoom_out -> {
Prefs.setEditingTextSizeExtra(Prefs.getEditingTextSizeExtra() - 1)
updateTextSize()
true
}
R.id.menu_find_in_editor -> {
showFindInEditor()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_edit_section, menu)
val item = menu.findItem(R.id.menu_save_section)
menu.findItem(R.id.menu_edit_zoom_in).isVisible = !editPreviewFragment.isActive
menu.findItem(R.id.menu_edit_zoom_out).isVisible = !editPreviewFragment.isActive
menu.findItem(R.id.menu_find_in_editor).isVisible = !editPreviewFragment.isActive
item.title = getString(if (editPreviewFragment.isActive) R.string.edit_done else R.string.edit_next)
if (editingAllowed && binding.viewProgressBar.isGone) {
item.isEnabled = sectionTextModified
} else {
item.isEnabled = false
}
val actionBarButtonBinding = ItemEditActionbarButtonBinding.inflate(layoutInflater)
item.actionView = actionBarButtonBinding.root
actionBarButtonBinding.editActionbarButtonText.text = item.title
actionBarButtonBinding.editActionbarButtonText.setTextColor(ResourceUtil.getThemedColor(this,
if (item.isEnabled) R.attr.colorAccent else R.attr.material_theme_de_emphasised_color))
actionBarButtonBinding.root.tag = item
actionBarButtonBinding.root.isEnabled = item.isEnabled
actionBarButtonBinding.root.setOnClickListener { onOptionsItemSelected(it.tag as MenuItem) }
return true
}
override fun onActionModeStarted(mode: ActionMode) {
super.onActionModeStarted(mode)
if (mode.tag == null) {
// since we disabled the close button in the AndroidManifest.xml, we need to manually setup a close button when in an action mode if long pressed on texts.
ViewUtil.setCloseButtonInActionMode(this@EditSectionActivity, mode)
}
}
fun showError(caught: Throwable?) {
DeviceUtil.hideSoftKeyboard(this)
binding.viewEditSectionError.setError(caught)
binding.viewEditSectionError.visibility = View.VISIBLE
}
private fun showFindInEditor() {
startActionMode(object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
actionMode = mode
val menuItem = menu.add(R.string.edit_section_find_in_page)
menuItem.actionProvider = FindInEditorActionProvider(binding.editSectionScroll,
binding.editSectionText, syntaxHighlighter, actionMode!!)
menuItem.expandActionView()
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.tag = "actionModeFindInEditor"
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return false
}
override fun onDestroyActionMode(mode: ActionMode) {
binding.editSectionText.clearMatches(syntaxHighlighter)
binding.editSectionText.setSelection(binding.editSectionText.selectionStart,
binding.editSectionText.selectionStart)
}
})
}
private fun finishActionMode() {
actionMode?.finish()
actionMode = null
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("hasTemporaryWikitextStored", true)
outState.putBoolean("sectionTextModified", sectionTextModified)
Prefs.storeTemporaryWikitext(sectionWikitext)
}
private fun updateTextSize() {
val extra = Prefs.getEditingTextSizeExtra()
binding.editSectionText.textSize = WikipediaApp.getInstance().getFontSize(window) + extra.toFloat()
}
private fun resetToStart() {
if (captchaHandler.isActive) {
captchaHandler.cancelCaptcha()
binding.editSectionCaptchaContainer.visibility = View.GONE
}
if (editSummaryFragment.isActive) {
editSummaryFragment.hide()
}
if (editPreviewFragment.isActive) {
editPreviewFragment.hide(binding.editSectionContainer)
}
}
private fun fetchSectionText() {
editingAllowed = false
if (sectionWikitext == null) {
disposables.add(ServiceFactory.get(pageTitle.wikiSite).getWikiTextForSectionWithInfo(pageTitle.prefixedText, sectionID)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response: MwQueryResponse ->
val firstPage = response.query()!!.firstPage()!!
val rev = firstPage.revisions()[0]
pageTitle = PageTitle(firstPage.title(), pageTitle.wikiSite)
sectionWikitext = rev.content()
currentRevision = rev.revId
val editError = response.query()!!.firstPage()!!.getErrorForAction("edit")
if (editError.isEmpty()) {
editingAllowed = true
} else {
val error = editError[0]
FeedbackUtil.showError(this, MwException(error))
}
displaySectionText()
}) { throwable: Throwable? ->
showProgressBar(false)
showError(throwable)
L.e(throwable)
})
} else {
displaySectionText()
}
}
private fun displaySectionText() {
binding.editSectionText.setText(sectionWikitext)
ViewAnimations.crossFade(binding.viewProgressBar, binding.editSectionContainer)
scrollToHighlight(textToHighlight)
binding.editSectionText.isEnabled = editingAllowed
binding.editKeyboardOverlay.isVisible = editingAllowed
}
private fun scrollToHighlight(highlightText: String?) {
if (highlightText == null || !TextUtils.isGraphic(highlightText)) {
return
}
binding.editSectionText.post {
binding.editSectionScroll.fullScroll(View.FOCUS_DOWN)
binding.editSectionText.postDelayed(500) {
StringUtil.highlightEditText(binding.editSectionText, sectionWikitext!!, highlightText)
}
}
}
fun showProgressBar(enable: Boolean) {
binding.viewProgressBar.isVisible = enable
invalidateOptionsMenu()
}
/**
* Shows the custom edit summary input fragment, where the user may enter a summary
* that's different from the standard summary tags.
*/
fun showCustomSummary() {
editSummaryFragment.show()
}
override fun onBackPressed() {
if (binding.viewProgressBar.isVisible) {
// If it is visible, it means we should wait until all the requests are done.
return
}
showProgressBar(false)
if (captchaHandler.isActive) {
captchaHandler.cancelCaptcha()
binding.editSectionCaptchaContainer.visibility = View.GONE
}
if (binding.viewEditSectionError.isVisible) {
binding.viewEditSectionError.visibility = View.GONE
}
if (editSummaryFragment.handleBackPressed()) {
return
}
if (editPreviewFragment.isActive) {
editPreviewFragment.hide(binding.editSectionContainer)
return
}
DeviceUtil.hideSoftKeyboard(this)
if (sectionTextModified) {
val alert = AlertDialog.Builder(this)
alert.setMessage(getString(R.string.edit_abandon_confirm))
alert.setPositiveButton(getString(R.string.edit_abandon_confirm_yes)) { dialog, _ ->
dialog.dismiss()
finish()
}
alert.setNegativeButton(getString(R.string.edit_abandon_confirm_no)) { dialog, _ -> dialog.dismiss() }
alert.create().show()
} else {
finish()
}
}
companion object {
const val EXTRA_TITLE = "org.wikipedia.edit_section.title"
const val EXTRA_SECTION_ID = "org.wikipedia.edit_section.sectionid"
const val EXTRA_SECTION_HEADING = "org.wikipedia.edit_section.sectionheading"
const val EXTRA_PAGE_PROPS = "org.wikipedia.edit_section.pageprops"
const val EXTRA_HIGHLIGHT_TEXT = "org.wikipedia.edit_section.highlight"
}
}
|
apache-2.0
|
b4b85df358649b886ada6212c9e0a39c
| 43.484266 | 167 | 0.649086 | 5.080871 | false | false | false | false |
nadraliev/DsrWeatherApp
|
app/src/main/java/soutvoid/com/DsrWeatherApp/ui/common/error/ErrorHandler.kt
|
1
|
2059
|
package soutvoid.com.DsrWeatherApp.ui.common.error
import rx.exceptions.CompositeException
import soutvoid.com.DsrWeatherApp.app.log.Logger
import soutvoid.com.DsrWeatherApp.interactor.common.network.error.ConversionException
import soutvoid.com.DsrWeatherApp.interactor.common.network.error.HttpError
import soutvoid.com.DsrWeatherApp.interactor.common.network.error.NetworkException
import soutvoid.com.DsrWeatherApp.interactor.common.network.error.NoInternetException
abstract class ErrorHandler {
fun handleError(t: Throwable) {
Logger.i(t, "ErrorHandler handle error")
if (t is CompositeException) {
handleCompositeException(t)
} else if (t is HttpError) {
handleHttpError(t)
} else if (t is NoInternetException) {
handleNoInternetError(t)
} else if (t is ConversionException) {
handleConversionError(t)
} else {
handleOtherError(t)
}
}
/**
* @param err - CompositeException может возникать при комбинировании Observable
*/
private fun handleCompositeException(err: CompositeException) {
val exceptions = err.exceptions
var networkException: NetworkException? = null
var otherException: Throwable? = null
for (e in exceptions) {
if (e is NetworkException) {
if (networkException == null) {
networkException = e
}
} else if (otherException == null) {
otherException = e
}
}
if (networkException != null) {
handleError(networkException)
}
if (otherException != null) {
handleOtherError(otherException)
}
}
protected abstract fun handleHttpError(e: HttpError)
protected abstract fun handleNoInternetError(e: NoInternetException)
protected abstract fun handleConversionError(e: ConversionException)
protected abstract fun handleOtherError(e: Throwable)
}
|
apache-2.0
|
31c5f0d1b61128991acf9e481f6b40b4
| 32.8 | 85 | 0.662722 | 4.749415 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/git4idea/src/git4idea/GitStashUsageCollector.kt
|
8
|
2013
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.project.Project
class GitStashUsageCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
private val GROUP: EventLogGroup = EventLogGroup("stash.interactions", 4)
private val STASH_PUSH = GROUP.registerIdeActivity("stash.push")
private val STASH_POP = GROUP.registerIdeActivity("stash.pop")
private val STASH_PUSH_DIALOG = GROUP.registerEvent("stash.push.dialog",
EventFields.Boolean("message_entered"),
EventFields.Boolean("keep_index"))
private val STASH_POP_DIALOG = GROUP.registerEvent("stash.pop.dialog",
EventFields.Boolean("create_branch"),
EventFields.Boolean("reinstate_index"),
EventFields.Boolean("pop_stash"))
@JvmStatic
fun logStashPush(project: Project): StructuredIdeActivity {
return STASH_PUSH.started(project)
}
@JvmStatic
fun logStashPop(project: Project): StructuredIdeActivity {
return STASH_POP.started(project)
}
@JvmStatic
fun logStashPushDialog(messageEntered: Boolean, keepIndex: Boolean) {
STASH_PUSH_DIALOG.log(messageEntered, keepIndex)
}
@JvmStatic
fun logStashPopDialog(createBranch: Boolean, reinstateIndex: Boolean, popStash: Boolean) {
STASH_POP_DIALOG.log(createBranch, reinstateIndex, popStash)
}
}
}
|
apache-2.0
|
f17dd2beb2affb8b10417c71d2bd139a
| 40.958333 | 120 | 0.661202 | 4.933824 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/workspaceModel/IdeModifiableModelsProviderBridge.kt
|
7
|
9704
|
// 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 org.jetbrains.idea.maven.importing.workspaceModel
import com.intellij.facet.FacetManager
import com.intellij.facet.ModifiableFacetModel
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.externalSystem.model.project.*
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider.EP_NAME
import com.intellij.openapi.externalSystem.service.project.ModifiableModel
import com.intellij.openapi.externalSystem.service.project.ModifiableModelsProviderExtension
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.UnloadedModuleDescription
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
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.util.Key
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ClassMap
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetManagerBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge
import com.intellij.workspaceModel.ide.legacyBridge.ProjectLibraryTableBridge
import org.jetbrains.idea.maven.utils.MavenLog
class IdeModifiableModelsProviderBridge(val project: Project,
builder: MutableEntityStorage) : IdeModifiableModelsProvider {
private val legacyBridgeModuleManagerComponent = ModuleManagerBridgeImpl.getInstance(project)
private val myProductionModulesForTestModules = HashMap<Module, String>()
private val myModifiableModels = ClassMap<ModifiableModel>()
private val myUserData = UserDataHolderBase()
private val modifiableFacetsModels = HashMap<Module, ModifiableFacetModel>()
var diff = builder
init {
EP_NAME.forEachExtensionSafe { extension: ModifiableModelsProviderExtension<ModifiableModel?> ->
val pair = extension.create(
project, this)
myModifiableModels.put(pair.first, pair.second)
}
}
private val modifiableModuleModel = lazy {
legacyBridgeModuleManagerComponent.getModifiableModel(diff)
}
private val bridgeProjectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project) as ProjectLibraryTableBridge
private val librariesModel = lazy {
bridgeProjectLibraryTable.getModifiableModel(diff)
}
override fun findIdeLibrary(libraryData: LibraryData): Library? {
return getAllLibraries().filter { it.name == libraryData.internalName }.firstOrNull()
}
override fun getAllDependentModules(module: Module): List<Module> {
return ModuleRootComponentBridge.getInstance(module).dependencies.toList()
}
override fun <T : ModifiableModel?> getModifiableModel(instanceOf: Class<T>): T {
return myModifiableModels.get(instanceOf) as? T ?: throw NotImplementedError("${instanceOf.canonicalName} not implemented")
}
override fun getModifiableFacetModel(module: Module): ModifiableFacetModel {
return modifiableFacetsModels.computeIfAbsent(module) {
(it.getComponent(FacetManager::class.java) as FacetManagerBridge).createModifiableModel(diff)
}
}
override fun findIdeModule(module: ModuleData): Module? {
return findIdeModule(module.moduleName)
}
override fun findIdeModule(ideModuleName: String): Module? {
return legacyBridgeModuleManagerComponent.findModuleByName(ideModuleName)
}
override fun newModule(filePath: String, moduleTypeId: String?): Module {
if (moduleTypeId == null) {
throw IllegalArgumentException("moduleTypeId")
}
val modifiableModel = modifiableModuleModel.value
legacyBridgeModuleManagerComponent.incModificationCount()
val module = modifiableModel.newModule(filePath, moduleTypeId)
return module
}
override fun newModule(moduleData: ModuleData): Module {
val modifiableModel = modifiableModuleModel.value
legacyBridgeModuleManagerComponent.incModificationCount()
val newModule = modifiableModel.newModule(moduleData.moduleFileDirectoryPath, moduleData.moduleTypeId)
return newModule
}
override fun getModifiableProjectLibrariesModel(): LibraryTable.ModifiableModel {
return librariesModel.value
}
override fun getProductionModuleName(module: Module?): String? {
return myProductionModulesForTestModules[module]
}
override fun getModifiableLibraryModel(library: Library?): Library.ModifiableModel {
val bridgeLibrary = library as LibraryBridge
return bridgeLibrary.getModifiableModel(diff)
}
override fun getModifiableModuleModel(): ModifiableModuleModel {
return modifiableModuleModel.value
}
override fun commit() {
if(modifiableModuleModel.isInitialized()) {
modifiableModuleModel.value.commit()
}
}
override fun setTestModuleProperties(testModule: Module, productionModuleName: String) {
myProductionModulesForTestModules[testModule] = productionModuleName
}
override fun trySubstitute(ownerModule: Module?,
libraryOrderEntry: LibraryOrderEntry?,
publicationId: ProjectCoordinate?): ModuleOrderEntry? {
// MavenLog.LOG.error("trySubstitute not implemented")
return null
}
override fun findIdeModuleDependency(dependency: ModuleDependencyData, module: Module): ModuleOrderEntry? {
MavenLog.LOG.error("findIdeModuleDependency not implemented")
return null
}
override fun <T : Any?> putUserData(key: Key<T>, value: T?) {
myUserData.putUserData(key, value)
}
override fun getUnloadedModuleDescription(moduleData: ModuleData): UnloadedModuleDescription? {
MavenLog.LOG.error("getUnloadedModuleDescription not implemented")
return null
}
override fun createLibrary(name: String?): Library {
return bridgeProjectLibraryTable.createLibrary(name)
}
override fun createLibrary(name: String?, externalSource: ProjectModelExternalSource?): Library {
return bridgeProjectLibraryTable.createLibrary(name)
}
override fun getModules(): Array<Module> {
return legacyBridgeModuleManagerComponent.modules
}
override fun getModules(projectData: ProjectData): Array<Module> {
return legacyBridgeModuleManagerComponent.modules
}
override fun registerModulePublication(module: Module?, modulePublication: ProjectCoordinate?) {
//MavenLog.LOG.error("registerModulePublication not implemented")
}
override fun getAllLibraries(): Array<Library> {
return bridgeProjectLibraryTable.libraries +
legacyBridgeModuleManagerComponent.modules.map { ModuleRootComponentBridge(it) }
.flatMap { it.getModuleLibraryTable().libraries.asIterable() }
}
override fun removeLibrary(library: Library?) {
MavenLog.LOG.error("removeLibrary not implemented")
}
override fun getSourceRoots(module: Module): Array<VirtualFile> {
return ModuleRootComponentBridge.getInstance(module).sourceRoots
}
override fun getSourceRoots(module: Module, includingTests: Boolean): Array<VirtualFile> {
return ModuleRootComponentBridge.getInstance(module).getSourceRoots(includingTests)
}
override fun getModifiableRootModel(module: Module): ModifiableRootModel {
return ModuleRootComponentBridge.getInstance(module).getModifiableModel()
}
override fun isSubstituted(libraryName: String?): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getContentRoots(module: Module): Array<VirtualFile> {
return ModuleRootComponentBridge.getInstance(module).contentRoots
}
override fun <T : ModifiableModel?> findModifiableModel(instanceOf: Class<T>): T? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun findModuleByPublication(publicationId: ProjectCoordinate?): String? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun findIdeModuleOrderEntry(data: DependencyData<*>): OrderEntry? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun findIdeModuleLibraryOrderEntries(moduleData: ModuleData,
libraryDependencyDataList: MutableList<LibraryDependencyData>): Map<LibraryOrderEntry, LibraryDependencyData> {
TODO("Not yet implemented")
}
override fun getLibraryUrls(library: Library, type: OrderRootType): Array<String> {
return library.getUrls(type)
}
override fun getLibraryByName(name: String): Library? {
return bridgeProjectLibraryTable.getLibraryByName(name)
}
override fun <T : Any?> getUserData(key: Key<T>): T? {
return myUserData.getUserData(key)
}
override fun getOrderEntries(module: Module): Array<OrderEntry> {
return ModuleRootComponentBridge.getInstance(module).orderEntries
}
override fun getModalityStateForQuestionDialogs(): ModalityState {
return ModalityState.NON_MODAL
}
override fun dispose() {
}
}
|
apache-2.0
|
5b25e78829b1c9c061ddce91251e8ef1
| 38.934156 | 159 | 0.779163 | 5.194861 | false | false | false | false |
awsdocs/aws-doc-sdk-examples
|
kotlin/services/forecast/src/main/kotlin/com/kotlin/forecast/DeleteDataset.kt
|
1
|
1708
|
// snippet-sourcedescription:[DeleteDataset.kt demonstrates how to delete a data set that belongs to the Amazon Forecast service.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon Forecast]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.forecast
// snippet-start:[forecast.kotlin.delete_forecast_dataset.import]
import aws.sdk.kotlin.services.forecast.ForecastClient
import aws.sdk.kotlin.services.forecast.model.DeleteDatasetRequest
import kotlin.system.exitProcess
// snippet-end:[forecast.kotlin.delete_forecast_dataset.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:
<dataSetARN>
Where:
dataSetARN - The ARN of the data set to delete.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val dataSetARN = args[0]
deleteForecastDataSet(dataSetARN)
}
// snippet-start:[forecast.kotlin.delete_forecast_dataset.main]
suspend fun deleteForecastDataSet(myDataSetARN: String?) {
val request = DeleteDatasetRequest {
datasetArn = myDataSetARN
}
ForecastClient { region = "us-west-2" }.use { forecast ->
forecast.deleteDataset(request)
println("$myDataSetARN data set was deleted")
}
}
// snippet-end:[forecast.kotlin.delete_forecast_dataset.main]
|
apache-2.0
|
b5a3f226976a503b38469f90e52d8b73
| 27.964912 | 130 | 0.697892 | 3.935484 | false | false | false | false |
leonardoaramaki/kadb
|
src/main/kotlin/kadb/Main.kt
|
1
|
2753
|
package kadb
import org.apache.commons.cli.*
fun main(args: Array<String>) {
val options = Options()
options.addOption("d", "devices", false, "list connected devices")
options.addOption(Option.builder("s")
.hasArg()
.argName("SERIAL")
.desc("use device with given serial number")
.build())
options.addOption(Option.builder()
.longOpt("push")
.numberOfArgs(2)
.argName("LOCAL")
.argName("REMOTE")
.desc("copy local files/directories to device")
.build())
options.addOption(Option.builder()
.longOpt("pull")
.numberOfArgs(2)
.optionalArg(true)
.argName("REMOTE")
.argName("LOCAL")
.desc("copy files/dirs from device")
.build())
options.addOption(Option.builder("sh")
.longOpt("shell")
.argName("COMMAND")
.desc("run remote shell command")
.hasArg()
.build())
try {
val cmd = DefaultParser().parse(options, args)
val serial = if (cmd.hasOption("s") && cmd.getOptionValues("s").isNotEmpty()) cmd.getOptionValues("s")[0] else null
val adbCli = AdbClient(settings { Set device serial })
when {
cmd.hasOption("d") || cmd.hasOption("devices") -> adbCli.devices()
cmd.hasOption("push") -> {
if (cmd.getOptionValues("push").isEmpty()) {
showUsage(options)
return
}
if (cmd.getOptionValues("push").size == 2) {
adbCli.push(cmd.getOptionValues("push")[0], cmd.getOptionValues("push")[1])
} else {
showUsage(options)
}
}
cmd.hasOption("pull") -> {
if (cmd.getOptionValues("pull") == null || cmd.getOptionValues("pull").isEmpty()) {
showUsage(options)
return
}
if (cmd.getOptionValues("pull").size > 1) {
adbCli.pull(cmd.getOptionValues("pull")[0], cmd.getOptionValues("pull")[1])
} else {
adbCli.pull(cmd.getOptionValues("pull")[0])
}
}
(cmd.hasOption("sh") || cmd.hasOption("shell") && cmd.getOptionValues("sh").isNotEmpty()) -> {
adbCli.shell(cmd.getOptionValues("sh")[0])
}
else -> showUsage(options)
}
} catch (e: MissingArgumentException) {
showUsage(options)
}
}
fun showUsage(options: Options) {
HelpFormatter().printHelp(1024, "adb", "----------", options, null)
}
|
apache-2.0
|
a5ed589aeb7d53f4bdabb9eb73ca719c
| 33 | 123 | 0.499455 | 4.411859 | false | false | false | false |
TheMrMilchmann/lwjgl3
|
modules/lwjgl/spvc/src/templates/kotlin/spvc/templates/Spvc.kt
|
1
|
51746
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package spvc.templates
import spvc.*
import org.lwjgl.generator.*
val SPVC_BINDING = simpleBinding(
Module.SPVC,
libraryExpression = """Configuration.SPVC_LIBRARY_NAME.get(Platform.mapLibraryNameBundled("spirv-cross"))""",
bundledWithLWJGL = true
)
val Spvc = "Spvc".nativeClass(Module.SPVC, prefix = "SPVC_", prefixMethod = "spvc_", binding = SPVC_BINDING) {
documentation =
"""
Native bindings to the C API of ${url("https://github.com/KhronosGroup/SPIRV-Cross", "SPIRV-Cross")}.
SPIRV-Cross is a tool designed for parsing and converting SPIR-V to other shader languages.
${ul(
"Convert SPIR-V to readable, usable and efficient GLSL",
"Convert SPIR-V to readable, usable and efficient Metal Shading Language (MSL)",
"Convert SPIR-V to readable, usable and efficient HLSL",
"Convert SPIR-V to debuggable C++ [DEPRECATED]",
"Convert SPIR-V to a JSON reflection format [EXPERIMENTAL]",
"Reflection API to simplify the creation of Vulkan pipeline layouts",
"Reflection API to modify and tweak OpDecorations",
"Supports \"all\" of vertex, fragment, tessellation, geometry and compute shaders."
)}
SPIRV-Cross tries hard to emit readable and clean output from the SPIR-V. The goal is to emit GLSL or MSL that looks like it was written by a human and
not awkward IR/assembly-like code.
"""
IntConstant("", "C_API_VERSION_MAJOR".."0")
IntConstant("", "C_API_VERSION_MINOR".."49")
IntConstant("", "C_API_VERSION_PATCH".."0")
IntConstant("", "COMPILER_OPTION_COMMON_BIT"..0x1000000)
IntConstant("", "COMPILER_OPTION_GLSL_BIT"..0x2000000)
IntConstant("", "COMPILER_OPTION_HLSL_BIT"..0x4000000)
IntConstant("", "COMPILER_OPTION_MSL_BIT"..0x8000000)
IntConstant("", "COMPILER_OPTION_LANG_BITS"..0x0f000000)
IntConstant("", "COMPILER_OPTION_ENUM_BITS"..0xffffff)
IntConstant(
"Special constant used in a {@code MSLResourceBinding} {@code desc_set} element to indicate the bindings for the push constants.",
"MSL_PUSH_CONSTANT_DESC_SET".."~0"
)
IntConstant(
"Special constant used in a {@code MSLResourceBinding} binding element to indicate the bindings for the push constants.",
"MSL_PUSH_CONSTANT_BINDING".."0"
)
IntConstant(
"Special constant used in a {@code MSLResourceBinding} binding element to indicate the buffer binding for swizzle buffers.",
"MSL_SWIZZLE_BUFFER_BINDING".."~1"
)
IntConstant(
"""
Special constant used in a {@code MSLResourceBinding} binding element to indicate the buffer binding for buffer size buffers to support
{@code OpArrayLength}.
""",
"MSL_BUFFER_SIZE_BUFFER_BINDING".."~2"
)
IntConstant(
"""
Special constant used in a {@code MSLResourceBinding} binding element to indicate the buffer binding used for the argument buffer itself.
This buffer binding should be kept as small as possible as all automatic bindings for buffers will start at {@code max(kArgumentBufferBinding) + 1}.
""",
"MSL_ARGUMENT_BUFFER_BINDING".."~3"
)
IntConstant("", "MSL_AUX_BUFFER_STRUCT_VERSION"..1)
EnumConstant(
"{@code spvc_result}",
"SUCCESS".enum("Success.", "0"),
"ERROR_INVALID_SPIRV".enum("The SPIR-V is invalid. Should have been caught by validation ideally.", "-1"),
"ERROR_UNSUPPORTED_SPIRV".enum(
"The SPIR-V might be valid or invalid, but SPIRV-Cross currently cannot correctly translate this to your target language.",
"-2"
),
"ERROR_OUT_OF_MEMORY".enum("If for some reason we hit this, new or malloc failed.", "-3"),
"ERROR_INVALID_ARGUMENT".enum("Invalid API argument.", "-4")
)
EnumConstant(
"{@code spvc_capture_mode}",
"CAPTURE_MODE_COPY".enum("The Parsed IR payload will be copied, and the handle can be reused to create other compiler instances.", "0"),
"CAPTURE_MODE_TAKE_OWNERSHIP".enum(
"""
The payload will now be owned by the compiler. parsed_ir should now be considered a dead blob and must not be used further. This is optimal for
performance and should be the go-to option.
"""
)
)
EnumConstant(
"{@code spvc_backend}",
"BACKEND_NONE".enum("This backend can only perform reflection, no compiler options are supported. Maps to spirv_cross::Compiler.", "0"),
"BACKEND_GLSL".enum("spirv_cross::CompilerGLSL"),
"BACKEND_HLSL".enum("CompilerHLSL"),
"BACKEND_MSL".enum("CompilerMSL"),
"BACKEND_CPP".enum("CompilerCPP"),
"BACKEND_JSON".enum("CompilerReflection w/ JSON backend")
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_resource_type})
""",
"RESOURCE_TYPE_UNKNOWN".enum("", "0"),
"RESOURCE_TYPE_UNIFORM_BUFFER".enum,
"RESOURCE_TYPE_STORAGE_BUFFER".enum,
"RESOURCE_TYPE_STAGE_INPUT".enum,
"RESOURCE_TYPE_STAGE_OUTPUT".enum,
"RESOURCE_TYPE_SUBPASS_INPUT".enum,
"RESOURCE_TYPE_STORAGE_IMAGE".enum,
"RESOURCE_TYPE_SAMPLED_IMAGE".enum,
"RESOURCE_TYPE_ATOMIC_COUNTER".enum,
"RESOURCE_TYPE_PUSH_CONSTANT".enum,
"RESOURCE_TYPE_SEPARATE_IMAGE".enum,
"RESOURCE_TYPE_SEPARATE_SAMPLERS".enum,
"RESOURCE_TYPE_ACCELERATION_STRUCTURE".enum,
"RESOURCE_TYPE_RAY_QUERY".enum
)
EnumConstant(
"{@code spvc_builtin_resource_type}",
"BUILTIN_RESOURCE_TYPE_UNKNOWN".enum("", "0"),
"BUILTIN_RESOURCE_TYPE_STAGE_INPUT".enum,
"BUILTIN_RESOURCE_TYPE_STAGE_OUTPUT".enum
)
EnumConstant(
"""
Maps to spirv_cross::SPIRType::BaseType.
({@code spvc_basetype})
""",
"BASETYPE_UNKNOWN".enum("", "0"),
"BASETYPE_VOID".enum,
"BASETYPE_BOOLEAN".enum,
"BASETYPE_INT8".enum,
"BASETYPE_UINT8".enum,
"BASETYPE_INT16".enum,
"BASETYPE_UINT16".enum,
"BASETYPE_INT32".enum,
"BASETYPE_UINT32".enum,
"BASETYPE_INT64".enum,
"BASETYPE_UINT64".enum,
"BASETYPE_ATOMIC_COUNTER".enum,
"BASETYPE_FP16".enum,
"BASETYPE_FP32".enum,
"BASETYPE_FP64".enum,
"BASETYPE_STRUCT".enum,
"BASETYPE_IMAGE".enum,
"BASETYPE_SAMPLED_IMAGE".enum,
"BASETYPE_SAMPLER".enum,
"BASETYPE_ACCELERATION_STRUCTURE".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_platform})
""",
"MSL_PLATFORM_IOS".enum("", "0"),
"MSL_PLATFORM_MACOS".enum
)
EnumConstant(
"""
The type of index in the index buffer, if present.
({@code spvc_msl_index_type})
""",
"MSL_INDEX_TYPE_NONE".enum("", "0"),
"MSL_INDEX_TYPE_UINT16".enum,
"MSL_INDEX_TYPE_UINT32".enum
)
EnumConstant(
"""
Indicates the format of a shader input.
Currently limited to specifying if the input is an 8-bit unsigned integer, 16-bit unsigned integer, or some other format.
({@code spvc_msl_shader_input_format})
""",
"MSL_SHADER_INPUT_FORMAT_OTHER".enum("", "0"),
"MSL_SHADER_INPUT_FORMAT_UINT8".enum,
"MSL_SHADER_INPUT_FORMAT_UINT16".enum,
"MSL_SHADER_INPUT_FORMAT_ANY16".enum,
"MSL_SHADER_INPUT_FORMAT_ANY32".enum
)
EnumConstant(
"""
Deprecated.
({@code spvc_msl_vertex_format})
""",
"MSL_VERTEX_FORMAT_OTHER".enum("", "SPVC_MSL_SHADER_INPUT_FORMAT_OTHER"),
"MSL_VERTEX_FORMAT_UINT8".enum("", "SPVC_MSL_SHADER_INPUT_FORMAT_UINT8"),
"MSL_VERTEX_FORMAT_UINT16".enum("", "SPVC_MSL_SHADER_INPUT_FORMAT_UINT16")
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_sampler_coord})
""",
"MSL_SAMPLER_COORD_NORMALIZED".enum("", "0"),
"MSL_SAMPLER_COORD_PIXEL".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_sampler_filter})
""",
"MSL_SAMPLER_FILTER_NEAREST".enum("", "0"),
"MSL_SAMPLER_FILTER_LINEAR".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_sampler_mip_filter})
""",
"MSL_SAMPLER_MIP_FILTER_NONE".enum("", "0"),
"MSL_SAMPLER_MIP_FILTER_NEAREST".enum,
"MSL_SAMPLER_MIP_FILTER_LINEAR".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_sampler_address})
""",
"MSL_SAMPLER_ADDRESS_CLAMP_TO_ZERO".enum("", "0"),
"MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE".enum,
"MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER".enum,
"MSL_SAMPLER_ADDRESS_REPEAT".enum,
"MSL_SAMPLER_ADDRESS_MIRRORED_REPEAT".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_sampler_compare_func})
""",
"MSL_SAMPLER_COMPARE_FUNC_NEVER".enum("", "0"),
"MSL_SAMPLER_COMPARE_FUNC_LESS".enum,
"MSL_SAMPLER_COMPARE_FUNC_LESS_EQUAL".enum,
"MSL_SAMPLER_COMPARE_FUNC_GREATER".enum,
"MSL_SAMPLER_COMPARE_FUNC_GREATER_EQUAL".enum,
"MSL_SAMPLER_COMPARE_FUNC_EQUAL".enum,
"MSL_SAMPLER_COMPARE_FUNC_NOT_EQUAL".enum,
"MSL_SAMPLER_COMPARE_FUNC_ALWAYS".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_sampler_border_color})
""",
"MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK".enum("", "0"),
"MSL_SAMPLER_BORDER_COLOR_OPAQUE_BLACK".enum,
"MSL_SAMPLER_BORDER_COLOR_OPAQUE_WHITE".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_format_resolution})
""",
"MSL_FORMAT_RESOLUTION_444".enum("", "0"),
"MSL_FORMAT_RESOLUTION_422".enum,
"MSL_FORMAT_RESOLUTION_420".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_chroma_location})
""",
"MSL_CHROMA_LOCATION_COSITED_EVEN".enum("", "0"),
"MSL_CHROMA_LOCATION_MIDPOINT".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_component_swizzle})
""",
"MSL_COMPONENT_SWIZZLE_IDENTITY".enum("", "0"),
"MSL_COMPONENT_SWIZZLE_ZERO".enum,
"MSL_COMPONENT_SWIZZLE_ONE".enum,
"MSL_COMPONENT_SWIZZLE_R".enum,
"MSL_COMPONENT_SWIZZLE_G".enum,
"MSL_COMPONENT_SWIZZLE_B".enum,
"MSL_COMPONENT_SWIZZLE_A".enum
)
EnumConstant(
"""
Maps to C++ API.
({@code spvc_msl_sampler_ycbcr_model_conversion})
""",
"MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY".enum("", "0"),
"MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY".enum,
"MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709".enum,
"MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601".enum,
"MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020".enum
)
EnumConstant(
"""
Maps to C+ API.
({@code spvc_msl_sampler_ycbcr_range})
""",
"MSL_SAMPLER_YCBCR_RANGE_ITU_FULL".enum("", "0"),
"MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW".enum
)
EnumConstant(
"""
Maps to the various spirv_cross::Compiler*::Option structures. See C++ API for defaults and details.
({@code spvc_hlsl_binding_flags})
""",
"HLSL_BINDING_AUTO_NONE_BIT".enum("", "0"),
"HLSL_BINDING_AUTO_PUSH_CONSTANT_BIT".enum(
"""
Push constant (root constant) resources will be declared as CBVs (b-space) without a register() declaration.
A register will be automatically assigned by the D3D compiler, but must therefore be reflected in D3D-land. Push constants do not normally have a
{@code DecorationBinding} set, but if they do, this can be used to ignore it.
""",
"1 << 0"
),
"HLSL_BINDING_AUTO_CBV_BIT".enum(
"""
{@code cbuffer} resources will be declared as CBVs (b-space) without a register() declaration.
A register will be automatically assigned, but must be reflected in D3D-land.
""",
"1 << 1"
),
"HLSL_BINDING_AUTO_SRV_BIT".enum("All SRVs (t-space) will be declared without a {@code register()} declaration.", "1 << 2"),
"HLSL_BINDING_AUTO_UAV_BIT".enum("All UAVs (u-space) will be declared without a {@code register()} declaration.", "1 << 3"),
"HLSL_BINDING_AUTO_SAMPLER_BIT".enum("All samplers (s-space) will be declared without a {@code register()} declaration.", "1 << 4"),
"HLSL_BINDING_AUTO_ALL".enum("No resources will be declared with {@code register()}.", 0x7fffffff)
)
IntConstant(
"Special constant used in an HLSL {@code ResourceBinding} {@code desc_set} element to indicate the bindings for the push constants.",
"HLSL_PUSH_CONSTANT_DESC_SET".."~0"
)
IntConstant(
"Special constant used in an HLSL {@code ResourceBinding} binding element to indicate the bindings for the push constants.",
"HLSL_PUSH_CONSTANT_BINDING".."0"
)
EnumConstant(
"""
Maps to the various spirv_cross::Compiler*::Option structures. See C++ API for defaults and details.
({@code spvc_compiler_option})
""",
"COMPILER_OPTION_UNKNOWN".enum("", "0"),
"COMPILER_OPTION_FORCE_TEMPORARY".enum("", "1 | SPVC_COMPILER_OPTION_COMMON_BIT"),
"COMPILER_OPTION_FLATTEN_MULTIDIMENSIONAL_ARRAYS".enum("", "2 | SPVC_COMPILER_OPTION_COMMON_BIT"),
"COMPILER_OPTION_FIXUP_DEPTH_CONVENTION".enum("", "3 | SPVC_COMPILER_OPTION_COMMON_BIT"),
"COMPILER_OPTION_FLIP_VERTEX_Y".enum("", "4 | SPVC_COMPILER_OPTION_COMMON_BIT"),
"COMPILER_OPTION_GLSL_SUPPORT_NONZERO_BASE_INSTANCE".enum("", "5 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_GLSL_SEPARATE_SHADER_OBJECTS".enum("", "6 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_GLSL_ENABLE_420PACK_EXTENSION".enum("", "7 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_GLSL_VERSION".enum("", "8 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_GLSL_ES".enum("", "9 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_GLSL_VULKAN_SEMANTICS".enum("", "10 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_GLSL_ES_DEFAULT_FLOAT_PRECISION_HIGHP".enum("", "11 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_GLSL_ES_DEFAULT_INT_PRECISION_HIGHP".enum("", "12 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_HLSL_SHADER_MODEL".enum("", "13 | SPVC_COMPILER_OPTION_HLSL_BIT"),
"COMPILER_OPTION_HLSL_POINT_SIZE_COMPAT".enum("", "14 | SPVC_COMPILER_OPTION_HLSL_BIT"),
"COMPILER_OPTION_HLSL_POINT_COORD_COMPAT".enum("", "15 | SPVC_COMPILER_OPTION_HLSL_BIT"),
"COMPILER_OPTION_HLSL_SUPPORT_NONZERO_BASE_VERTEX_BASE_INSTANCE".enum("", "16 | SPVC_COMPILER_OPTION_HLSL_BIT"),
"COMPILER_OPTION_MSL_VERSION".enum("", "17 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_TEXEL_BUFFER_TEXTURE_WIDTH".enum("", "18 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_AUX_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "19 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_SWIZZLE_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "19 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_INDIRECT_PARAMS_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "20 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_SHADER_OUTPUT_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "21 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_SHADER_PATCH_OUTPUT_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "22 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_SHADER_TESS_FACTOR_OUTPUT_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "23 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_SHADER_INPUT_WORKGROUP_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "24 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_ENABLE_POINT_SIZE_BUILTIN".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "25 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_DISABLE_RASTERIZATION".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "26 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_CAPTURE_OUTPUT_TO_BUFFER".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "27 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_SWIZZLE_TEXTURE_SAMPLES".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "28 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_PAD_FRAGMENT_OUTPUT_COMPONENTS".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "29 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_TESS_DOMAIN_ORIGIN_LOWER_LEFT".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "30 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_PLATFORM".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "31 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_ARGUMENT_BUFFERS".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "32 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_GLSL_EMIT_PUSH_CONSTANT_AS_UNIFORM_BUFFER".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "33 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_MSL_TEXTURE_BUFFER_NATIVE".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "34 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_GLSL_EMIT_UNIFORM_BUFFER_AS_PLAIN_UNIFORMS".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "35 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_MSL_BUFFER_SIZE_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "36 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_EMIT_LINE_DIRECTIVES".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "37 | SPVC_COMPILER_OPTION_COMMON_BIT"),
"COMPILER_OPTION_MSL_MULTIVIEW".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "38 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_VIEW_MASK_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "39 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_DEVICE_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "40 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_VIEW_INDEX_FROM_DEVICE_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "41 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_DISPATCH_BASE".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "42 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_DYNAMIC_OFFSETS_BUFFER_INDEX".enum("Obsolete, use SWIZZLE_BUFFER_INDEX instead.", "43 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_TEXTURE_1D_AS_2D".enum("", "44 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_ENABLE_BASE_INDEX_ZERO".enum("", "45 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_IOS_FRAMEBUFFER_FETCH_SUBPASS".enum("", "46 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_FRAMEBUFFER_FETCH_SUBPASS".enum("", "46 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_INVARIANT_FP_MATH".enum("", "47 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_EMULATE_CUBEMAP_ARRAY".enum("", "48 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_ENABLE_DECORATION_BINDING".enum("", "49 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_FORCE_ACTIVE_ARGUMENT_BUFFER_RESOURCES".enum("", "50 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_FORCE_NATIVE_ARRAYS".enum("", "51 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_ENABLE_STORAGE_IMAGE_QUALIFIER_DEDUCTION".enum("", "52 | SPVC_COMPILER_OPTION_COMMON_BIT"),
"COMPILER_OPTION_HLSL_FORCE_STORAGE_BUFFER_AS_UAV".enum("", "53 | SPVC_COMPILER_OPTION_HLSL_BIT"),
"COMPILER_OPTION_FORCE_ZERO_INITIALIZED_VARIABLES".enum("", "54 | SPVC_COMPILER_OPTION_COMMON_BIT"),
"COMPILER_OPTION_HLSL_NONWRITABLE_UAV_TEXTURE_AS_SRV".enum("", "55 | SPVC_COMPILER_OPTION_HLSL_BIT"),
"COMPILER_OPTION_MSL_ENABLE_FRAG_OUTPUT_MASK".enum("", "56 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_ENABLE_FRAG_DEPTH_BUILTIN".enum("", "57 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_ENABLE_FRAG_STENCIL_REF_BUILTIN".enum("", "58 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_ENABLE_CLIP_DISTANCE_USER_VARYING".enum("", "59 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_HLSL_ENABLE_16BIT_TYPES".enum("", "60 | SPVC_COMPILER_OPTION_HLSL_BIT"),
"COMPILER_OPTION_MSL_MULTI_PATCH_WORKGROUP".enum("", "61 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_SHADER_INPUT_BUFFER_INDEX".enum("", "62 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_SHADER_INDEX_BUFFER_INDEX".enum("", "63 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_VERTEX_FOR_TESSELLATION".enum("", "64 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_VERTEX_INDEX_TYPE".enum("", "65 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_GLSL_FORCE_FLATTENED_IO_BLOCKS".enum("", "66 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_MSL_MULTIVIEW_LAYERED_RENDERING".enum("", "67 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_ARRAYED_SUBPASS_INPUT".enum("", "68 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_R32UI_LINEAR_TEXTURE_ALIGNMENT".enum("", "69 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_R32UI_ALIGNMENT_CONSTANT_ID".enum("", "70 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_HLSL_FLATTEN_MATRIX_VERTEX_INPUT_SEMANTICS".enum("", "71 | SPVC_COMPILER_OPTION_HLSL_BIT"),
"COMPILER_OPTION_MSL_IOS_USE_SIMDGROUP_FUNCTIONS".enum("", "72 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_EMULATE_SUBGROUPS".enum("", "73 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_FIXED_SUBGROUP_SIZE".enum("", "74 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_FORCE_SAMPLE_RATE_SHADING".enum("", "75 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_MSL_IOS_SUPPORT_BASE_VERTEX_INSTANCE".enum("", "76 | SPVC_COMPILER_OPTION_MSL_BIT"),
"COMPILER_OPTION_GLSL_OVR_MULTIVIEW_VIEW_COUNT".enum("", "77 | SPVC_COMPILER_OPTION_GLSL_BIT"),
"COMPILER_OPTION_RELAX_NAN_CHECKS".enum("", "78 | SPVC_COMPILER_OPTION_COMMON_BIT")
)
void(
"get_version",
"Gets the {@code SPVC_C_API_VERSION_*} used to build this library. Can be used to check for ABI mismatch if so-versioning did not catch it.",
Check(1)..unsigned_int.p("major", ""),
Check(1)..unsigned_int.p("minor", ""),
Check(1)..unsigned_int.p("patch", "")
)
charUTF8.const.p(
"get_commit_revision_and_timestamp",
"Gets a human readable version string to identify which commit a particular binary was created from.",
void()
)
void(
"msl_vertex_attribute_init",
"Initializes the vertex attribute struct.",
spvc_msl_vertex_attribute.p("attr", "")
)
void(
"msl_shader_input_init",
"Initializes the shader input struct.",
spvc_msl_shader_input.p("input", "")
)
void(
"msl_resource_binding_init",
"Initializes the resource binding struct. The defaults are non-zero.",
spvc_msl_resource_binding.p("binding", "")
)
unsigned_int(
"msl_get_aux_buffer_struct_version",
"Runtime check for incompatibility. Obsolete.",
void()
)
void(
"msl_constexpr_sampler_init",
"Initializes the {@code constexpr} sampler struct. The defaults are non-zero.",
spvc_msl_constexpr_sampler.p("sampler", "")
)
void(
"msl_sampler_ycbcr_conversion_init",
"Initializes the {@code constexpr} sampler struct. The defaults are non-zero.",
spvc_msl_sampler_ycbcr_conversion.p("conv", "")
)
void(
"hlsl_resource_binding_init",
"""
Initializes the resource binding struct.
The defaults are non-zero.
""",
spvc_hlsl_resource_binding.p("binding", "")
)
spvc_result(
"context_create",
"""
Context is the highest-level API construct.
The context owns all memory allocations made by its child object hierarchy, including various non-opaque structs and strings. This means that the API
user only has to care about one "destroy" call ever when using the C API. All pointers handed out by the APIs are only valid as long as the context is
alive and #context_release_allocations() has not been called.
""",
Check(1)..spvc_context.p("context", "")
)
void(
"context_destroy",
"Frees all memory allocations and objects associated with the context and its child objects.",
spvc_context("context", "")
)
void(
"context_release_allocations",
"Frees all memory allocations and objects associated with the context and its child objects, but keeps the context alive.",
spvc_context("context", "")
)
charUTF8.const.p(
"context_get_last_error_string",
"Get the string for the last error which was logged.",
spvc_context("context", "")
)
void(
"context_set_error_callback",
"Get notified in a callback when an error triggers. Useful for debugging.",
spvc_context("context", ""),
spvc_error_callback("cb", ""),
nullable..opaque_p("userdata", "")
)
spvc_result(
"context_parse_spirv",
"SPIR-V parsing interface. Maps to {@code Parser} which then creates a {@code ParsedIR}, and that IR is extracted into the handle.",
spvc_context("context", ""),
Check(1)..SpvId.const.p("spirv", ""),
size_t("word_count", ""),
Check(1)..spvc_parsed_ir.p("parsed_ir", "")
)
spvc_result(
"context_create_compiler",
"""
Create a compiler backend.
Capture mode controls if we construct by copy or move semantics. It is always recommended to use #CAPTURE_MODE_TAKE_OWNERSHIP if you only intend to
cross-compile the IR once.
""",
spvc_context("context", ""),
spvc_backend("backend", ""),
spvc_parsed_ir("parsed_ir", ""),
spvc_capture_mode("mode", ""),
Check(1)..spvc_compiler.p("compiler", "")
)
unsigned_int(
"compiler_get_current_id_bound",
"Maps directly to C++ API.",
spvc_compiler("compiler", "")
)
spvc_result(
"compiler_create_compiler_options",
"Create compiler options, which will initialize defaults.",
spvc_compiler("compiler", ""),
Check(1)..spvc_compiler_options.p("options", "")
)
spvc_result(
"compiler_options_set_bool",
"Override options. Will return error if e.g. MSL options are used for the HLSL backend, etc.",
spvc_compiler_options("options", ""),
spvc_compiler_option("option", ""),
spvc_bool("value", "")
)
spvc_result(
"compiler_options_set_uint",
"",
spvc_compiler_options("options", ""),
spvc_compiler_option("option", ""),
unsigned_int("value", "")
)
spvc_result(
"compiler_install_compiler_options",
"Set compiler options.",
spvc_compiler("compiler", ""),
spvc_compiler_options("options", "")
)
spvc_result(
"compiler_compile",
"Compile IR into a string.",
spvc_compiler("compiler", ""),
Check(1)..charUTF8.const.p.p("source", "owned by the context, and caller must not free it themselves")
)
spvc_result(
"compiler_add_header_line",
"Maps to C++ API.",
spvc_compiler("compiler", ""),
charUTF8.const.p("line", "")
)
spvc_result(
"compiler_require_extension",
"",
spvc_compiler("compiler", ""),
charUTF8.const.p("ext", "")
)
spvc_result(
"compiler_flatten_buffer_block",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", "")
)
spvc_bool(
"compiler_variable_is_depth_or_compare",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", "")
)
spvc_result(
"compiler_mask_stage_output_by_location",
"",
spvc_compiler("compiler", ""),
unsigned("location", ""),
unsigned("component", "")
)
spvc_result(
"compiler_mask_stage_output_by_builtin",
"",
spvc_compiler("compiler", ""),
SpvBuiltIn("builtin", "")
)
spvc_result(
"compiler_hlsl_set_root_constants_layout",
"HLSL specifics. Maps to C++ API.",
spvc_compiler("compiler", ""),
spvc_hlsl_root_constants.const.p("constant_info", ""),
size_t("count", "")
)
spvc_result(
"compiler_hlsl_add_vertex_attribute_remap",
"",
spvc_compiler("compiler", ""),
spvc_hlsl_vertex_attribute_remap.const.p("remap", ""),
size_t("remaps", "")
)
spvc_variable_id(
"compiler_hlsl_remap_num_workgroups_builtin",
"",
spvc_compiler("compiler", "")
)
spvc_result(
"compiler_hlsl_set_resource_binding_flags",
"",
spvc_compiler("compiler", ""),
spvc_hlsl_binding_flags("flags", "")
)
spvc_result(
"compiler_hlsl_add_resource_binding",
"",
spvc_compiler("compiler", ""),
spvc_hlsl_resource_binding.const.p("binding", "")
)
spvc_bool(
"compiler_hlsl_is_resource_used",
"",
spvc_compiler("compiler", ""),
SpvExecutionModel("model", ""),
unsigned("set", ""),
unsigned("binding", "")
)
spvc_bool(
"compiler_msl_is_rasterization_disabled",
"MSL specifics. Maps to C++ API.",
spvc_compiler("compiler", "")
)
spvc_bool(
"compiler_msl_needs_swizzle_buffer",
"",
spvc_compiler("compiler", "")
)
spvc_bool(
"compiler_msl_needs_buffer_size_buffer",
"",
spvc_compiler("compiler", "")
)
spvc_bool(
"compiler_msl_needs_output_buffer",
"",
spvc_compiler("compiler", "")
)
spvc_bool(
"compiler_msl_needs_patch_output_buffer",
"",
spvc_compiler("compiler", "")
)
spvc_bool(
"compiler_msl_needs_input_threadgroup_mem",
"",
spvc_compiler("compiler", "")
)
spvc_result(
"compiler_msl_add_vertex_attribute",
"",
spvc_compiler("compiler", ""),
spvc_msl_vertex_attribute.const.p("attrs", "")
)
spvc_result(
"compiler_msl_add_resource_binding",
"",
spvc_compiler("compiler", ""),
spvc_msl_resource_binding.const.p("binding", "")
)
spvc_result(
"compiler_msl_add_shader_input",
"",
spvc_compiler("compiler", ""),
spvc_msl_shader_input.const.p("input", "")
)
spvc_result(
"compiler_msl_add_discrete_descriptor_set",
"",
spvc_compiler("compiler", ""),
unsigned_int("desc_set", "")
)
spvc_result(
"compiler_msl_set_argument_buffer_device_address_space",
"",
spvc_compiler("compiler", ""),
unsigned("desc_set", ""),
spvc_bool("device_address", "")
)
spvc_bool(
"compiler_msl_is_vertex_attribute_used",
"Obsolete, use #compiler_msl_is_shader_input_used().",
spvc_compiler("compiler", ""),
unsigned_int("location", "")
)
spvc_bool(
"compiler_msl_is_shader_input_used",
"",
spvc_compiler("compiler", ""),
unsigned("location", "")
)
spvc_bool(
"compiler_msl_is_resource_used",
"",
spvc_compiler("compiler", ""),
SpvExecutionModel("model", ""),
unsigned_int("set", ""),
unsigned_int("binding", "")
)
spvc_result(
"compiler_msl_remap_constexpr_sampler",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", ""),
spvc_msl_constexpr_sampler.const.p("sampler", "")
)
spvc_result(
"compiler_msl_remap_constexpr_sampler_by_binding",
"",
spvc_compiler("compiler", ""),
unsigned_int("desc_set", ""),
unsigned_int("binding", ""),
spvc_msl_constexpr_sampler.const.p("sampler", "")
)
spvc_result(
"compiler_msl_remap_constexpr_sampler_ycbcr",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", ""),
spvc_msl_constexpr_sampler.const.p("sampler", ""),
spvc_msl_sampler_ycbcr_conversion.const.p("conv", "")
)
spvc_result(
"compiler_msl_remap_constexpr_sampler_by_binding_ycbcr",
"",
spvc_compiler("compiler", ""),
unsigned_int("desc_set", ""),
unsigned_int("binding", ""),
spvc_msl_constexpr_sampler.const.p("sampler", ""),
spvc_msl_sampler_ycbcr_conversion.const.p("conv", "")
)
spvc_result(
"compiler_msl_set_fragment_output_components",
"",
spvc_compiler("compiler", ""),
unsigned_int("location", ""),
unsigned_int("components", "")
)
unsigned_int(
"compiler_msl_get_automatic_resource_binding",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", "")
)
unsigned_int(
"compiler_msl_get_automatic_resource_binding_secondary",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", "")
)
spvc_result(
"compiler_msl_add_dynamic_buffer",
"",
spvc_compiler("compiler", ""),
unsigned_int("desc_set", ""),
unsigned_int("binding", ""),
unsigned_int("index", "")
)
spvc_result(
"compiler_msl_add_inline_uniform_block",
"",
spvc_compiler("compiler", ""),
unsigned_int("desc_set", ""),
unsigned_int("binding", "")
)
spvc_result(
"compiler_msl_set_combined_sampler_suffix",
"",
spvc_compiler("compiler", ""),
charUTF8.const.p("suffix", "")
)
charUTF8.const.p(
"compiler_msl_get_combined_sampler_suffix",
"",
spvc_compiler("compiler", "")
)
spvc_result(
"compiler_get_active_interface_variables",
"Reflect resources. Maps almost 1:1 to C++ API.",
spvc_compiler("compiler", ""),
Check(1)..spvc_set.p("set", "")
)
spvc_result(
"compiler_set_enabled_interface_variables",
"",
spvc_compiler("compiler", ""),
spvc_set("set", "")
)
spvc_result(
"compiler_create_shader_resources",
"",
spvc_compiler("compiler", ""),
Check(1)..spvc_resources.p("resources", "")
)
spvc_result(
"compiler_create_shader_resources_for_active_variables",
"",
spvc_compiler("compiler", ""),
Check(1)..spvc_resources.p("resources", ""),
spvc_set("active", "")
)
spvc_result(
"resources_get_resource_list_for_type",
"",
spvc_resources("resources", ""),
spvc_resource_type("type", ""),
Check(1)..spvc_reflected_resource.const.p.p("resource_list", ""),
Check(1)..size_t.p("resource_size", "")
)
spvc_result(
"resources_get_builtin_resource_list_for_type",
"",
spvc_resources("resources", ""),
spvc_builtin_resource_type("type", ""),
Check(1)..spvc_reflected_builtin_resource.const.p.p("resource_list", ""),
Check(1)..size_t.p("resource_size", "")
)
void(
"compiler_set_decoration",
"Decorations. Maps to C++ API.",
spvc_compiler("compiler", ""),
SpvId("id", ""),
SpvDecoration("decoration", ""),
unsigned_int("argument", "")
)
void(
"compiler_set_decoration_string",
"",
spvc_compiler("compiler", ""),
SpvId("id", ""),
SpvDecoration("decoration", ""),
charUTF8.const.p("argument", "")
)
void(
"compiler_set_name",
"",
spvc_compiler("compiler", ""),
SpvId("id", ""),
charUTF8.const.p("argument", "")
)
void(
"compiler_set_member_decoration",
"",
spvc_compiler("compiler", ""),
spvc_type_id("id", ""),
unsigned_int("member_index", ""),
SpvDecoration("decoration", ""),
unsigned_int("argument", "")
)
void(
"compiler_set_member_decoration_string",
"",
spvc_compiler("compiler", ""),
spvc_type_id("id", ""),
unsigned_int("member_index", ""),
SpvDecoration("decoration", ""),
charUTF8.const.p("argument", "")
)
void(
"compiler_set_member_name",
"",
spvc_compiler("compiler", ""),
spvc_type_id("id", ""),
unsigned_int("member_index", ""),
charUTF8.const.p("argument", "")
)
void(
"compiler_unset_decoration",
"",
spvc_compiler("compiler", ""),
SpvId("id", ""),
SpvDecoration("decoration", "")
)
void(
"compiler_unset_member_decoration",
"",
spvc_compiler("compiler", ""),
spvc_type_id("id", ""),
unsigned_int("member_index", ""),
SpvDecoration("decoration", "")
)
spvc_bool(
"compiler_has_decoration",
"",
spvc_compiler("compiler", ""),
SpvId("id", ""),
SpvDecoration("decoration", "")
)
spvc_bool(
"compiler_has_member_decoration",
"",
spvc_compiler("compiler", ""),
spvc_type_id("id", ""),
unsigned_int("member_index", ""),
SpvDecoration("decoration", "")
)
charUTF8.const.p(
"compiler_get_name",
"",
spvc_compiler("compiler", ""),
SpvId("id", "")
)
unsigned_int(
"compiler_get_decoration",
"",
spvc_compiler("compiler", ""),
SpvId("id", ""),
SpvDecoration("decoration", "")
)
charUTF8.const.p(
"compiler_get_decoration_string",
"",
spvc_compiler("compiler", ""),
SpvId("id", ""),
SpvDecoration("decoration", "")
)
unsigned_int(
"compiler_get_member_decoration",
"",
spvc_compiler("compiler", ""),
spvc_type_id("id", ""),
unsigned_int("member_index", ""),
SpvDecoration("decoration", "")
)
charUTF8.const.p(
"compiler_get_member_decoration_string",
"",
spvc_compiler("compiler", ""),
spvc_type_id("id", ""),
unsigned_int("member_index", ""),
SpvDecoration("decoration", "")
)
charUTF8.const.p(
"compiler_get_member_name",
"",
spvc_compiler("compiler", ""),
spvc_type_id("id", ""),
unsigned_int("member_index", "")
)
spvc_result(
"compiler_get_entry_points",
"Entry points. Maps to C++ API.",
spvc_compiler("compiler", ""),
Check(1)..spvc_entry_point.const.p.p("entry_points", ""),
Check(1)..size_t.p("num_entry_points", "")
)
spvc_result(
"compiler_set_entry_point",
"",
spvc_compiler("compiler", ""),
charUTF8.const.p("name", ""),
SpvExecutionModel("model", "")
)
spvc_result(
"compiler_rename_entry_point",
"",
spvc_compiler("compiler", ""),
charUTF8.const.p("old_name", ""),
charUTF8.const.p("new_name", ""),
SpvExecutionModel("model", "")
)
charUTF8.const.p(
"compiler_get_cleansed_entry_point_name",
"",
spvc_compiler("compiler", ""),
charUTF8.const.p("name", ""),
SpvExecutionModel("model", "")
)
void(
"compiler_set_execution_mode",
"",
spvc_compiler("compiler", ""),
SpvExecutionMode("mode", "")
)
void(
"compiler_unset_execution_mode",
"",
spvc_compiler("compiler", ""),
SpvExecutionMode("mode", "")
)
void(
"compiler_set_execution_mode_with_arguments",
"",
spvc_compiler("compiler", ""),
SpvExecutionMode("mode", ""),
unsigned_int("arg0", ""),
unsigned_int("arg1", ""),
unsigned_int("arg2", "")
)
spvc_result(
"compiler_get_execution_modes",
"",
spvc_compiler("compiler", ""),
Check(1)..SpvExecutionMode.const.p.p("modes", ""),
Check(1)..size_t.p("num_modes", "")
)
unsigned_int(
"compiler_get_execution_mode_argument",
"",
spvc_compiler("compiler", ""),
SpvExecutionMode("mode", "")
)
unsigned_int(
"compiler_get_execution_mode_argument_by_index",
"",
spvc_compiler("compiler", ""),
SpvExecutionMode("mode", ""),
unsigned_int("index", "")
)
SpvExecutionModel(
"compiler_get_execution_model",
"",
spvc_compiler("compiler", "")
)
void(
"compiler_update_active_builtins",
"",
spvc_compiler("compiler", "")
)
spvc_bool(
"compiler_has_active_builtin",
"",
spvc_compiler("compiler", ""),
SpvBuiltIn("builtin", ""),
SpvStorageClass("storage", "")
)
spvc_type(
"compiler_get_type_handle",
"Type query interface. Maps to C++ API, except it's read-only.",
spvc_compiler("compiler", ""),
spvc_type_id("id", "")
)
spvc_type_id(
"type_get_base_type_id",
"""
Pulls out {@code SPIRType::self}.
This effectively gives the type ID without array or pointer qualifiers. This is necessary when reflecting decoration/name information on members of a
struct, which are placed in the base type, not the qualified type. This is similar to {@code spvc_reflected_resource::base_type_id}.
""",
spvc_type("type", "")
)
spvc_basetype(
"type_get_basetype",
"",
spvc_type("type", "")
)
unsigned_int(
"type_get_bit_width",
"",
spvc_type("type", "")
)
unsigned_int(
"type_get_vector_size",
"",
spvc_type("type", "")
)
unsigned_int(
"type_get_columns",
"",
spvc_type("type", "")
)
unsigned_int(
"type_get_num_array_dimensions",
"",
spvc_type("type", "")
)
spvc_bool(
"type_array_dimension_is_literal",
"",
spvc_type("type", ""),
unsigned_int("dimension", "")
)
SpvId(
"type_get_array_dimension",
"",
spvc_type("type", ""),
unsigned_int("dimension", "")
)
unsigned_int(
"type_get_num_member_types",
"",
spvc_type("type", "")
)
spvc_type_id(
"type_get_member_type",
"",
spvc_type("type", ""),
unsigned_int("index", "")
)
SpvStorageClass(
"type_get_storage_class",
"",
spvc_type("type", "")
)
spvc_type_id(
"type_get_image_sampled_type",
"Image type query.",
spvc_type("type", "")
)
SpvDim(
"type_get_image_dimension",
"",
spvc_type("type", "")
)
spvc_bool(
"type_get_image_is_depth",
"",
spvc_type("type", "")
)
spvc_bool(
"type_get_image_arrayed",
"",
spvc_type("type", "")
)
spvc_bool(
"type_get_image_multisampled",
"",
spvc_type("type", "")
)
spvc_bool(
"type_get_image_is_storage",
"",
spvc_type("type", "")
)
SpvImageFormat(
"type_get_image_storage_format",
"",
spvc_type("type", "")
)
SpvAccessQualifier(
"type_get_image_access_qualifier",
"",
spvc_type("type", "")
)
spvc_result(
"compiler_get_declared_struct_size",
"Buffer layout query. Maps to C++ API.",
spvc_compiler("compiler", ""),
spvc_type("struct_type", ""),
Check(1)..size_t.p("size", "")
)
spvc_result(
"compiler_get_declared_struct_size_runtime_array",
"",
spvc_compiler("compiler", ""),
spvc_type("struct_type", ""),
size_t("array_size", ""),
Check(1)..size_t.p("size", "")
)
spvc_result(
"compiler_get_declared_struct_member_size",
"",
spvc_compiler("compiler", ""),
spvc_type("type", ""),
unsigned_int("index", ""),
Check(1)..size_t.p("size", "")
)
spvc_result(
"compiler_type_struct_member_offset",
"",
spvc_compiler("compiler", ""),
spvc_type("type", ""),
unsigned_int("index", ""),
Check(1)..unsigned_int.p("offset", "")
)
spvc_result(
"compiler_type_struct_member_array_stride",
"",
spvc_compiler("compiler", ""),
spvc_type("type", ""),
unsigned_int("index", ""),
Check(1)..unsigned_int.p("stride", "")
)
spvc_result(
"compiler_type_struct_member_matrix_stride",
"",
spvc_compiler("compiler", ""),
spvc_type("type", ""),
unsigned_int("index", ""),
Check(1)..unsigned_int.p("stride", "")
)
spvc_result(
"compiler_build_dummy_sampler_for_combined_images",
"Workaround helper functions. Maps to C++ API.",
spvc_compiler("compiler", ""),
Check(1)..spvc_variable_id.p("id", "")
)
spvc_result(
"compiler_build_combined_image_samplers",
"",
spvc_compiler("compiler", "")
)
spvc_result(
"compiler_get_combined_image_samplers",
"",
spvc_compiler("compiler", ""),
Check(1)..spvc_combined_image_sampler.const.p.p("samplers", ""),
Check(1)..size_t.p("num_samplers", "")
)
spvc_result(
"compiler_get_specialization_constants",
"Constants Maps to C++ API.",
spvc_compiler("compiler", ""),
Check(1)..spvc_specialization_constant.const.p.p("constants", ""),
Check(1)..size_t.p("num_constants", "")
)
spvc_constant(
"compiler_get_constant_handle",
"",
spvc_compiler("compiler", ""),
spvc_constant_id("id", "")
)
spvc_constant_id(
"compiler_get_work_group_size_specialization_constants",
"",
spvc_compiler("compiler", ""),
spvc_specialization_constant.p("x", ""),
spvc_specialization_constant.p("y", ""),
spvc_specialization_constant.p("z", "")
)
spvc_result(
"compiler_get_active_buffer_ranges",
"Buffer ranges Maps to C++ API.",
spvc_compiler("compiler", ""),
spvc_variable_id("id", ""),
Check(1)..spvc_buffer_range.const.p.p("ranges", ""),
Check(1)..size_t.p("num_ranges", "")
)
float(
"constant_get_scalar_fp16",
"""
No stdint.h until C99, sigh :( For smaller types, the result is sign or zero-extended as appropriate. Maps to C++ API. TODO: The SPIRConstant query
interface and modification interface is not quite complete.
""",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
float(
"constant_get_scalar_fp32",
"",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
double(
"constant_get_scalar_fp64",
"",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
unsigned_int(
"constant_get_scalar_u32",
"",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
int(
"constant_get_scalar_i32",
"",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
unsigned_int(
"constant_get_scalar_u16",
"",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
int(
"constant_get_scalar_i16",
"",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
unsigned_int(
"constant_get_scalar_u8",
"",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
int(
"constant_get_scalar_i8",
"",
spvc_constant("constant", ""),
unsigned_int("column", ""),
unsigned_int("row", "")
)
void(
"constant_get_subconstants",
"",
spvc_constant("constant", ""),
Check(1)..spvc_constant_id.const.p.p("constituents", ""),
Check(1)..size_t.p("count", "")
)
spvc_type_id(
"constant_get_type",
"",
spvc_constant("constant", "")
)
spvc_bool(
"compiler_get_binary_offset_for_decoration",
"Misc reflection Maps to C++ API.",
spvc_compiler("compiler", ""),
spvc_variable_id("id", ""),
SpvDecoration("decoration", ""),
Check(1)..unsigned_int.p("word_offset", "")
)
spvc_bool(
"compiler_buffer_is_hlsl_counter_buffer",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", "")
)
spvc_bool(
"compiler_buffer_get_hlsl_counter_buffer",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", ""),
Check(1)..spvc_variable_id.p("counter_id", "")
)
spvc_result(
"compiler_get_declared_capabilities",
"",
spvc_compiler("compiler", ""),
Check(1)..SpvCapability.const.p.p("capabilities", ""),
Check(1)..size_t.p("num_capabilities", "")
)
spvc_result(
"compiler_get_declared_extensions",
"",
spvc_compiler("compiler", ""),
Check(1)..charUTF8.const.p.p.p("extensions", ""),
Check(1)..size_t.p("num_extensions", "")
)
charUTF8.const.p(
"compiler_get_remapped_declared_block_name",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", "")
)
spvc_result(
"compiler_get_buffer_block_decorations",
"",
spvc_compiler("compiler", ""),
spvc_variable_id("id", ""),
Check(1)..SpvDecoration.const.p.p("decorations", ""),
Check(1)..size_t.p("num_decorations", "")
)
}
|
bsd-3-clause
|
bb475ceb00e320d9d14164d3a48c6ba1
| 28.569143 | 159 | 0.567754 | 3.690081 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/view/OutsideDrawerLayout.kt
|
1
|
2616
|
package jp.juggler.subwaytooter.view
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import jp.juggler.util.cast
import java.util.*
/*
「Viewからはみ出した部分の描画」を実現する。
子孫Viewとコールバックを登録すると、onDraw時に子孫Viewの位置とcanvasをコールバックに渡す。
*/
class OutsideDrawerLayout : LinearLayout {
constructor(context: Context) :
super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) :
super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) :
super(context, attrs, defStyleAttr) {
init()
}
fun init() {
setWillNotDraw(false)
}
private class Callback(
val view: View,
val draw: (
canvas: Canvas,
parent: ViewGroup,
descendant: View,
left: Int,
top: Int,
) -> Unit,
)
private val callbackList = LinkedList<Callback>()
fun addOutsideDrawer(
view: View,
draw: (
canvas: Canvas,
parent: ViewGroup,
descendant: View,
left: Int,
top: Int,
) -> Unit,
) {
if (callbackList.none { it.view == view && it.draw == draw }) {
callbackList.add(Callback(view, draw))
}
}
@Suppress("unused")
fun removeOutsideDrawer(view: View) {
val it = callbackList.iterator()
while (it.hasNext()) {
val cb = it.next()
if (cb.view == view) it.remove()
}
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas ?: return
val it = callbackList.iterator()
while (it.hasNext()) {
val drawer = it.next()
var left = 0
var top = 0
var v = drawer.view
while (true) {
if (v == this) break
val parent = v.parent.cast<ViewGroup>() ?: break
left += v.left
top += v.top
v = parent
}
canvas.save()
try {
drawer.draw(canvas, this, drawer.view, left, top)
} finally {
canvas.restore()
}
}
}
}
|
apache-2.0
|
d2146380a74c87f54f5c4ddee1f8077b
| 23.06 | 75 | 0.501596 | 4.291096 | false | false | false | false |
imageprocessor/cv4j
|
app/src/main/java/com/cv4j/app/fragment/FiltersFragment.kt
|
1
|
2646
|
package com.cv4j.app.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cv4j.app.R
import com.cv4j.app.activity.*
import com.cv4j.app.app.BaseFragment
import kotlinx.android.synthetic.main.fragment_filters.*
/**
*
* @FileName:
* com.cv4j.app.fragment.FiltersFragment
* @author: Tony Shen
* @date: 2020-05-04 11:27
* @version: V1.0 <描述当前版本功能>
*/
class FiltersFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_filters, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
text1.setOnClickListener {
val i = Intent(mContext, SelectFilterActivity::class.java)
i.putExtra("Title", text1.text.toString())
startActivity(i)
}
text2.setOnClickListener {
val i = Intent(mContext, CompositeFilersActivity::class.java)
i.putExtra("Title", text2.text.toString())
startActivity(i)
}
text3.setOnClickListener {
val i = Intent(mContext, UseFilterWithRxActivity::class.java)
i.putExtra("Title", text3.text.toString())
startActivity(i)
}
text4.setOnClickListener {
val i = Intent(mContext, DslActivity::class.java)
i.putExtra("Title", text4.text.toString())
startActivity(i)
}
text5.setOnClickListener {
val i = Intent(mContext, GridViewFilterActivity::class.java)
i.putExtra("Title", text5.text.toString())
startActivity(i)
}
text6.setOnClickListener {
val i = Intent(mContext, ColorFilterActivity::class.java)
i.putExtra("Title", text6.text.toString())
startActivity(i)
}
text7.setOnClickListener {
val i = Intent(mContext, GaussianBlurActivity::class.java)
i.putExtra("Title", text7.text.toString())
startActivity(i)
}
text8.setOnClickListener {
val i = Intent(mContext, BeautySkinActivity::class.java)
i.putExtra("Title", text8.text.toString())
startActivity(i)
}
text9.setOnClickListener {
val i = Intent(mContext, PaintActivity::class.java)
i.putExtra("Title", text9.text.toString())
startActivity(i)
}
}
}
|
apache-2.0
|
b599a8db3c258dd379c7c21b52a83b8d
| 31.481481 | 177 | 0.628517 | 4.269481 | false | false | false | false |
google/intellij-community
|
plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleJvmSupportMatrices.kt
|
2
|
3295
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("GradleJvmSupportMatrices")
package org.jetbrains.plugins.gradle.util
import com.intellij.util.lang.JavaVersion
import org.gradle.util.GradleVersion
// Java versions which can be suggested to use with Intellij Idea
private val SUPPORTED_JAVA_VERSIONS = listOf(
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18
).map(JavaVersion::compose)
val MINIMUM_SUPPORTED_JAVA = SUPPORTED_JAVA_VERSIONS.first()
val MAXIMUM_SUPPORTED_JAVA = SUPPORTED_JAVA_VERSIONS.last()
// Gradle versions which can be suggested to use with Intellij Idea
private val SUPPORTED_GRADLE_VERSIONS = listOf(
"3.0", "3.1", "3.2", "3.3", "3.4", "3.5",
"4.0", "4.1", "4.2", "4.3", "4.4", "4.5", "4.5.1", "4.6", "4.7", "4.8", "4.9", "4.10", "4.10.3",
"5.0", "5.1", "5.2", "5.3", "5.3.1", "5.4", "5.4.1", "5.5", "5.5.1", "5.6", "5.6.2",
"6.0", "6.0.1", "6.1", "6.2", "6.3", "6.4", "6.5", "6.6", "6.7", "6.8", "6.8.3", "6.9",
"7.0", "7.1", "7.2", "7.3", "7.4", "7.5"
).map(GradleVersion::version)
// Sync with https://docs.gradle.org/current/userguide/compatibility.html
private val COMPATIBILITY = listOf(
// https://docs.gradle.org/5.0/release-notes.html#potential-breaking-changes
range(6 to 8) to range(INF to "5.0"),
// Gradle older than 2.0 unofficially compatible with Java 8
// Gradle from 5.1 to 7.1 and Java 8 aren't compatible
// https://github.com/gradle/gradle/issues/8285
range(8 to 9) to range(INF to "5.1", "7.2" to INF),
range(9 to 10) to range("4.3" to INF),
range(10 to 11) to range("4.7" to INF),
range(11 to 12) to range("5.0" to INF),
range(12 to 13) to range("5.4" to INF),
range(13 to 14) to range("6.0" to INF),
range(14 to 15) to range("6.3" to INF),
// Many builds might work with Java 15 but there are some known issues
// https://github.com/gradle/gradle/issues/13532
range(15 to 16) to range("6.7" to INF),
range(16 to 17) to range("7.0" to INF),
// Gradle 7.2 and Java 17 are partially compatible
// https://github.com/gradle/gradle/issues/16857
range(17 to 18) to range("7.2" to INF),
range(18 to INF) to range("7.5" to INF)
).map {
it.first.map(JavaVersion::compose) to
it.second.map(GradleVersion::version)
}
fun isSupported(gradleVersion: GradleVersion, javaVersion: JavaVersion): Boolean {
return COMPATIBILITY.any { (javaVersions, gradleVersions) ->
javaVersion in javaVersions && gradleVersion in gradleVersions
}
}
fun suggestGradleVersion(javaVersion: JavaVersion): GradleVersion? {
val gradleVersion = GradleVersion.current()
if (isSupported(gradleVersion, javaVersion)) {
return gradleVersion
}
return SUPPORTED_GRADLE_VERSIONS.reversed().find { isSupported(it, javaVersion) }
}
fun suggestJavaVersion(gradleVersion: GradleVersion): JavaVersion? {
return SUPPORTED_JAVA_VERSIONS.reversed().find { isSupported(gradleVersion, it) }
}
fun suggestOldestCompatibleGradleVersion(javaVersion: JavaVersion): GradleVersion? {
return SUPPORTED_GRADLE_VERSIONS.find { isSupported(it, javaVersion) }
}
fun suggestOldestCompatibleJavaVersion(gradleVersion: GradleVersion): JavaVersion? {
return SUPPORTED_JAVA_VERSIONS.find { isSupported(gradleVersion, it) }
}
|
apache-2.0
|
88f7315ddba69f2f5a8e41839061ce74
| 42.355263 | 140 | 0.690137 | 3.070829 | false | false | false | false |
fedepaol/BikeSharing
|
app/src/main/java/com/whiterabbit/pisabike/screens/map/MapItem.kt
|
1
|
899
|
package com.whiterabbit.pisabike.screens.map
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.clustering.ClusterItem
import com.whiterabbit.pisabike.model.Station
/**
* Created by fedepaol on 03/06/17.
*/
class MapItem(val station : Station) : ClusterItem {
val myLocation = LatLng(station.latitude, station.longitude)
var isSelected = false
override fun getSnippet(): String {
return station.name
}
override fun getTitle(): String {
return station.name
}
override fun getPosition(): LatLng {
return myLocation
}
override fun hashCode(): Int {
return station.name.hashCode()
}
override fun equals(other: Any?): Boolean {
if (other != null) {
val otherItem = other as MapItem
return otherItem.station == station
}
return false
}
}
|
gpl-3.0
|
1cd452f25ddc40d273f0c70643a66344
| 22.051282 | 64 | 0.650723 | 4.280952 | false | false | false | false |
google/intellij-community
|
plugins/kotlin/base/statistics/src/org/jetbrains/kotlin/idea/statistics/WizardStatsService.kt
|
3
|
16297
|
// 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.statistics
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.eventLog.events.StringListEventField
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfoById
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
import kotlin.math.abs
import kotlin.random.Random
interface WizardStats {
fun toPairs(): ArrayList<EventPair<*>>
}
class WizardStatsService : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
// Collector ID
private val GROUP = EventLogGroup("kotlin.ide.new.project", 10)
// Whitelisted values for the events fields
private val allowedProjectTemplates = listOf( // Modules
"JVM_|_IDEA",
"JS_|_IDEA",
// Java and Gradle groups
"Kotlin/JVM",
// Gradle group
"Kotlin/JS",
"Kotlin/JS_for_browser",
"Kotlin/JS_for_Node.js",
"Kotlin/Multiplatform_as_framework",
"Kotlin/Multiplatform",
// Kotlin group
"backendApplication",
"consoleApplication",
"multiplatformMobileApplication",
"multiplatformMobileLibrary",
"multiplatformApplication",
"multiplatformLibrary",
"nativeApplication",
"frontendApplication",
"fullStackWebApplication",
"nodejsApplication",
"reactApplication",
"composeDesktopApplication",
"composeMultiplatformApplication",
"none",
// AppCode KMM
"multiplatformMobileApplicationUsingAppleGradlePlugin",
"multiplatformMobileApplicationUsingHybridProject",
)
private val allowedModuleTemplates = listOf(
"composeAndroid",
"composeDesktopTemplate",
"composeMppModule",
"consoleJvmApp",
"ktorServer",
"mobileMppModule",
"nativeConsoleApp",
"reactJsClient",
"simpleJsClient",
"simpleNodeJs",
"none",
)
private val allowedWizardsGroups = listOf("Java", "Kotlin", "Gradle")
private val allowedBuildSystems = listOf(
"gradleKotlin",
"gradleGroovy",
"jps",
"maven"
)
private val settings = Settings(
SettingIdWithPossibleValues.Enum(
id = "buildSystem.type",
values = listOf(
"GradleKotlinDsl",
"GradleGroovyDsl",
"Jps",
"Maven",
)
),
SettingIdWithPossibleValues.Enum(
id = "testFramework",
values = listOf(
"NONE",
"JUNIT4",
"JUNIT5",
"TEST_NG",
"JS",
"COMMON",
)
),
SettingIdWithPossibleValues.Enum(
id = "targetJvmVersion",
values = listOf(
"JVM_1_6",
"JVM_1_8",
"JVM_9",
"JVM_10",
"JVM_11",
"JVM_12",
"JVM_13",
)
),
SettingIdWithPossibleValues.Enum(
id = "androidPlugin",
values = listOf(
"APPLICATION",
"LIBRARY",
)
),
SettingIdWithPossibleValues.Enum(
id = "serverEngine",
values = listOf(
"Netty",
"Tomcat",
"Jetty",
)
),
SettingIdWithPossibleValues.Enum(
id = "kind",
idToLog = "js.project.kind",
values = listOf(
"LIBRARY",
"APPLICATION",
)
),
SettingIdWithPossibleValues.Enum(
id = "compiler",
idToLog = "js.compiler",
values = listOf(
"IR",
"LEGACY",
"BOTH",
)
),
SettingIdWithPossibleValues.Enum(
id = "projectTemplates.template",
values = allowedProjectTemplates
),
SettingIdWithPossibleValues.Enum(
id = "module.template",
values = allowedModuleTemplates
),
SettingIdWithPossibleValues.Enum(
id = "buildSystem.type",
values = allowedBuildSystems
),
SettingIdWithPossibleValues.Boolean(
id = "javaSupport",
idToLog = "jvm.javaSupport"
),
SettingIdWithPossibleValues.Boolean(
id = "cssSupport",
idToLog = "js.cssSupport"
),
SettingIdWithPossibleValues.Boolean(
id = "useReactRouterDom",
idToLog = "js.useReactRouterDom"
),
SettingIdWithPossibleValues.Boolean(
id = "useReactRedux",
idToLog = "js.useReactRedux"
),
)
private val allowedModuleTypes = listOf(
"androidNativeArm32Target",
"androidNativeArm64Target",
"iosArm32Target",
"iosArm64Target",
"iosX64Target",
"iosTarget",
"linuxArm32HfpTarget",
"linuxMips32Target",
"linuxMipsel32Target",
"linuxX64Target",
"macosX64Target",
"mingwX64Target",
"mingwX86Target",
"nativeForCurrentSystem",
"jsBrowser",
"jsNode",
"commonTarget",
"jvmTarget",
"androidTarget",
"multiplatform",
"JVM_Module",
"android",
"IOS_Module",
"jsBrowserSinglePlatform",
"jsNodeSinglePlatform",
)
val settingIdField = EventFields.String("setting_id", settings.allowedIds)
val settingValueField = EventFields.String("setting_value", settings.possibleValues)
// Event fields
val groupField = EventFields.String("group", allowedWizardsGroups)
val projectTemplateField = EventFields.String("project_template", allowedProjectTemplates)
val buildSystemField = EventFields.String("build_system", allowedBuildSystems)
val modulesCreatedField = EventFields.Int("modules_created")
val modulesRemovedField = EventFields.Int("modules_removed")
val moduleTemplateChangedField = EventFields.Int("module_template_changed")
val moduleTemplateField = EventFields.String("module_template", allowedModuleTemplates)
val sessionIdField = EventFields.Int("session_id")
val modulesListField = StringListEventField.ValidatedByAllowedValues("project_modules_list", allowedModuleTypes)
val moduleTypeField = EventFields.String("module_type", allowedModuleTypes)
private val pluginInfoField = EventFields.PluginInfo.with(getPluginInfoById(KotlinIdePlugin.id))
// Events
private val projectCreatedEvent = GROUP.registerVarargEvent(
"project_created",
groupField,
projectTemplateField,
buildSystemField,
modulesCreatedField,
modulesRemovedField,
moduleTemplateChangedField,
modulesListField,
sessionIdField,
EventFields.PluginInfo
)
private val projectOpenedByHyperlinkEvent = GROUP.registerVarargEvent(
"wizard_opened_by_hyperlink",
projectTemplateField,
sessionIdField,
EventFields.PluginInfo
)
private val moduleTemplateCreatedEvent = GROUP.registerVarargEvent(
"module_template_created",
projectTemplateField,
moduleTemplateField,
sessionIdField,
EventFields.PluginInfo
)
private val settingValueChangedEvent = GROUP.registerVarargEvent(
"setting_value_changed",
settingIdField,
settingValueField,
sessionIdField,
EventFields.PluginInfo,
)
private val jdkChangedEvent = GROUP.registerVarargEvent(
"jdk_changed",
sessionIdField,
EventFields.PluginInfo,
)
private val nextClickedEvent = GROUP.registerVarargEvent(
"next_clicked",
sessionIdField,
EventFields.PluginInfo,
)
private val prevClickedEvent = GROUP.registerVarargEvent(
"prev_clicked",
sessionIdField,
EventFields.PluginInfo,
)
private val moduleCreatedEvent = GROUP.registerVarargEvent(
"module_created",
moduleTypeField,
sessionIdField,
EventFields.PluginInfo,
)
private val moduleRemovedEvent = GROUP.registerVarargEvent(
"module_removed",
moduleTypeField,
sessionIdField,
EventFields.PluginInfo,
)
// Log functions
fun logDataOnProjectGenerated(session: WizardLoggingSession?, project: Project?, projectCreationStats: ProjectCreationStats) {
projectCreatedEvent.log(
project,
*projectCreationStats.toPairs().toTypedArray(),
*session?.let { arrayOf(sessionIdField with it.id) }.orEmpty(),
pluginInfoField
)
}
fun logDataOnSettingValueChanged(
session: WizardLoggingSession,
settingId: String,
settingValue: String
) {
val idToLog = settings.getIdToLog(settingId) ?: return
settingValueChangedEvent.log(
settingIdField with idToLog,
settingValueField with settingValue,
sessionIdField with session.id,
pluginInfoField,
)
}
fun logDataOnJdkChanged(
session: WizardLoggingSession,
) {
jdkChangedEvent.log(
sessionIdField with session.id,
pluginInfoField,
)
}
fun logDataOnNextClicked(
session: WizardLoggingSession,
) {
nextClickedEvent.log(
sessionIdField with session.id,
pluginInfoField,
)
}
fun logDataOnPrevClicked(
session: WizardLoggingSession,
) {
prevClickedEvent.log(
sessionIdField with session.id,
pluginInfoField,
)
}
fun logOnModuleCreated(
session: WizardLoggingSession,
moduleType: String,
) {
moduleCreatedEvent.log(
sessionIdField with session.id,
moduleTypeField with moduleType.withSpacesRemoved(),
pluginInfoField,
)
}
fun logOnModuleRemoved(
session: WizardLoggingSession,
moduleType: String,
) {
moduleRemovedEvent.log(
sessionIdField with session.id,
moduleTypeField with moduleType.withSpacesRemoved(),
pluginInfoField,
)
}
fun logDataOnProjectGenerated(
session: WizardLoggingSession?,
project: Project?,
projectCreationStats: ProjectCreationStats,
uiEditorUsageStats: UiEditorUsageStats
) {
projectCreatedEvent.log(
project,
*projectCreationStats.toPairs().toTypedArray(),
*uiEditorUsageStats.toPairs().toTypedArray(),
*session?.let { arrayOf(sessionIdField with it.id) }.orEmpty(),
pluginInfoField
)
}
fun logUsedModuleTemplatesOnNewWizardProjectCreated(
session: WizardLoggingSession,
project: Project?,
projectTemplateId: String,
moduleTemplates: List<String>
) {
moduleTemplates.forEach { moduleTemplateId ->
logModuleTemplateCreation(session, project, projectTemplateId, moduleTemplateId)
}
}
fun logWizardOpenByHyperlink(session: WizardLoggingSession, project: Project?, templateId: String?) {
projectOpenedByHyperlinkEvent.log(
project,
projectTemplateField.with(templateId ?: "none"),
sessionIdField with session.id,
pluginInfoField
)
}
private fun logModuleTemplateCreation(
session: WizardLoggingSession,
project: Project?,
projectTemplateId: String,
moduleTemplateId: String
) {
moduleTemplateCreatedEvent.log(
project,
projectTemplateField.with(projectTemplateId),
moduleTemplateField.with(moduleTemplateId),
sessionIdField with session.id,
pluginInfoField
)
}
}
data class ProjectCreationStats(
val group: String,
val projectTemplateId: String,
val buildSystemType: String,
val moduleTypes: List<String> = emptyList(),
) : WizardStats {
override fun toPairs(): ArrayList<EventPair<*>> = arrayListOf(
groupField.with(group),
projectTemplateField.with(projectTemplateId),
buildSystemField.with(buildSystemType),
modulesListField with moduleTypes,
)
}
data class UiEditorUsageStats(
var modulesCreated: Int = 0,
var modulesRemoved: Int = 0,
var moduleTemplateChanged: Int = 0
) : WizardStats {
override fun toPairs(): ArrayList<EventPair<*>> = arrayListOf(
modulesCreatedField.with(modulesCreated),
modulesRemovedField.with(modulesRemoved),
moduleTemplateChangedField.with(moduleTemplateChanged)
)
}
}
private fun String.withSpacesRemoved(): String =
replace(' ', '_')
private sealed class SettingIdWithPossibleValues {
abstract val id: String
abstract val idToLog: String
abstract val values: List<String>
data class Enum(
override val id: String,
override val idToLog: String = id,
override val values: List<String>
) : SettingIdWithPossibleValues()
data class Boolean(
override val id: String,
override val idToLog: String = id,
) : SettingIdWithPossibleValues() {
override val values: List<String> get() = listOf(true.toString(), false.toString())
}
}
private class Settings(settingIdWithPossibleValues: List<SettingIdWithPossibleValues>) {
constructor(vararg settingIdWithPossibleValues: SettingIdWithPossibleValues) : this(settingIdWithPossibleValues.toList())
val allowedIds = settingIdWithPossibleValues.map { it.idToLog }
val possibleValues = settingIdWithPossibleValues.flatMap { it.values }.distinct()
private val id2IdToLog = settingIdWithPossibleValues.associate { it.id to it.idToLog }
fun getIdToLog(id: String): String? = id2IdToLog.get(id)
}
class WizardLoggingSession private constructor(val id: Int) {
companion object {
fun createWithRandomId(): WizardLoggingSession =
WizardLoggingSession(id = abs(Random.nextInt()))
}
}
|
apache-2.0
|
00e09334d60f057c189e1bf6a202cc26
| 32.261224 | 134 | 0.563907 | 5.592656 | false | false | false | false |
StepicOrg/stepik-android
|
app/src/main/java/org/stepik/android/domain/certificate/interactor/CertificatesInteractor.kt
|
1
|
2011
|
package org.stepik.android.domain.certificate.interactor
import io.reactivex.Single
import org.stepic.droid.model.CertificateListItem
import ru.nobird.app.core.model.PagedList
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.certificate.repository.CertificateRepository
import org.stepik.android.domain.course.repository.CourseRepository
import org.stepik.android.model.Certificate
import org.stepik.android.model.Course
import javax.inject.Inject
class CertificatesInteractor
@Inject
constructor(
private val certificateRepository: CertificateRepository,
private val courseRepository: CourseRepository
) {
fun getCertificates(userId: Long, page: Int = 1, sourceType: DataSourceType = DataSourceType.CACHE): Single<PagedList<CertificateListItem.Data>> =
certificateRepository.getCertificates(userId, page, sourceType)
.flatMap { certificates ->
val courseIds =
certificates.map(Certificate::course)
courseRepository
.getCourses(courseIds)
.map { courses ->
val coursesMap =
courses.associateBy(Course::id)
PagedList(
certificates.map { certificate ->
CertificateListItem.Data(
certificate,
coursesMap[certificate.course]?.title,
coursesMap[certificate.course]?.cover
)
},
page = certificates.page,
hasNext = certificates.hasNext,
hasPrev = certificates.hasPrev
)
}
}
fun saveCertificate(certificate: Certificate): Single<Certificate> =
certificateRepository.saveCertificate(certificate)
}
|
apache-2.0
|
e6370bda3562065f44de403d25fe0e44
| 40.061224 | 150 | 0.591248 | 5.985119 | false | false | false | false |
allotria/intellij-community
|
platform/lang-impl/src/com/intellij/codeInsight/actions/ReaderModeListener.kt
|
2
|
4099
|
// 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.codeInsight.actions
import com.intellij.application.options.colors.ReaderModeStatsCollector
import com.intellij.codeInsight.actions.ReaderModeSettings.Companion.applyReaderMode
import com.intellij.codeInsight.actions.ReaderModeSettingsListener.Companion.applyToAllEditors
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions
import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.options.ex.Settings
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.ui.HyperlinkLabel
import com.intellij.util.messages.Topic
import com.intellij.util.ui.UIUtil
import java.beans.PropertyChangeListener
import java.util.*
import javax.swing.event.HyperlinkListener
interface ReaderModeListener : EventListener {
fun modeChanged(project: Project)
}
class ReaderModeSettingsListener : ReaderModeListener {
companion object {
@Topic.ProjectLevel
@JvmStatic
val TOPIC = Topic(ReaderModeListener::class.java, Topic.BroadcastDirection.NONE)
fun applyToAllEditors(project: Project, preferGlobalSettings: Boolean = false) {
FileEditorManager.getInstance(project).allEditors.forEach {
if (it !is TextEditor) return
applyReaderMode(project, it.editor, it.file, fileIsOpenAlready = true, preferGlobalSettings = preferGlobalSettings)
}
EditorFactory.getInstance().allEditors.forEach {
if (it !is EditorImpl) return
applyReaderMode(project, it, FileDocumentManager.getInstance().getFile(it.document),
fileIsOpenAlready = true, preferGlobalSettings = preferGlobalSettings)
}
}
fun createReaderModeComment() = HyperlinkLabel().apply {
setTextWithHyperlink(IdeBundle.message("checkbox.also.in.reader.mode"))
font = UIUtil.getFont(UIUtil.FontSize.SMALL, font)
foreground = UIUtil.getLabelFontColor(UIUtil.FontColor.BRIGHTER)
addHyperlinkListener(HyperlinkListener {
DataManager.getInstance().dataContextFromFocusAsync.onSuccess { context ->
context?.let { dataContext ->
Settings.KEY.getData(dataContext)?.let { settings ->
settings.select(settings.find("editor.reader.mode"))
ReaderModeStatsCollector.logSeeAlsoNavigation()
}
}
}
})
}
}
override fun modeChanged(project: Project) = applyToAllEditors(project)
}
internal class ReaderModeEditorSettingsListener : StartupActivity, DumbAware {
override fun runActivity(project: Project) {
val propertyChangeListener = PropertyChangeListener { event ->
when (event.propertyName) {
EditorSettingsExternalizable.PROP_DOC_COMMENT_RENDERING -> {
ReaderModeSettings.instance(project).showRenderedDocs = EditorSettingsExternalizable.getInstance().isDocCommentRenderingEnabled
applyToAllEditors(project, true)
}
}
}
EditorSettingsExternalizable.getInstance().addPropertyChangeListener(propertyChangeListener, project)
val fontPreferences = AppEditorFontOptions.getInstance().fontPreferences as FontPreferencesImpl
fontPreferences.changeListener = Runnable {
fontPreferences.changeListener
ReaderModeSettings.instance(project).showLigatures = fontPreferences.useLigatures()
applyToAllEditors(project, true)
}
Disposer.register(project) { fontPreferences.changeListener = null }
}
}
|
apache-2.0
|
35e4758da6f25455296c0b9e6d0032dc
| 43.086022 | 140 | 0.773847 | 4.891408 | false | false | false | false |
allotria/intellij-community
|
plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsConfigurable.kt
|
2
|
3576
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.ui
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.options.BoundConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.ui.layout.*
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.authentication.accounts.AccountTokenChangedListener
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubProjectDefaultAccountHolder
import org.jetbrains.plugins.github.authentication.ui.GHAccountsPanel
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.util.CachingGHUserAvatarLoader
import org.jetbrains.plugins.github.util.GithubSettings
import org.jetbrains.plugins.github.util.GithubUtil
internal class GithubSettingsConfigurable internal constructor(private val project: Project) : BoundConfigurable(GithubUtil.SERVICE_DISPLAY_NAME, "settings.github") {
override fun createPanel(): DialogPanel {
val defaultAccountHolder = project.service<GithubProjectDefaultAccountHolder>()
val accountManager = service<GithubAccountManager>()
val settings = GithubSettings.getInstance()
return panel {
row {
val accountsPanel = GHAccountsPanel(project, GithubApiRequestExecutor.Factory.getInstance(),
CachingGHUserAvatarLoader.getInstance()).apply {
Disposer.register(disposable!!, this)
}
component(accountsPanel)
.onIsModified { accountsPanel.isModified(accountManager.accounts, defaultAccountHolder.account) }
.onReset {
val accountsMap = accountManager.accounts.associateWith { accountManager.getTokenForAccount(it) }
accountsPanel.setAccounts(accountsMap, defaultAccountHolder.account)
accountsPanel.clearNewTokens()
accountsPanel.loadExistingAccountsDetails()
}
.onApply {
val (accountsTokenMap, defaultAccount) = accountsPanel.getAccounts()
accountManager.accounts = accountsTokenMap.keys
accountsTokenMap.filterValues { it != null }.forEach(accountManager::updateAccountToken)
defaultAccountHolder.account = defaultAccount
accountsPanel.clearNewTokens()
}
ApplicationManager.getApplication().messageBus.connect(disposable!!)
.subscribe(GithubAccountManager.ACCOUNT_TOKEN_CHANGED_TOPIC,
object : AccountTokenChangedListener {
override fun tokenChanged(account: GithubAccount) {
if (!isModified) reset()
}
})
}
row {
checkBox(GithubBundle.message("settings.clone.ssh"), settings::isCloneGitUsingSsh, settings::setCloneGitUsingSsh)
}
row {
cell {
label(GithubBundle.message("settings.timeout"))
intTextField({ settings.connectionTimeout / 1000 }, { settings.connectionTimeout = it * 1000 }, columns = 2, range = 0..60)
label(GithubBundle.message("settings.timeout.seconds"))
}
}
}
}
}
|
apache-2.0
|
6c6bf2f4baf4bd530994100eae4c895f
| 50.826087 | 166 | 0.724553 | 5.353293 | false | false | false | false |
michaeimm/PlurkConnection
|
library/src/main/java/tw/shounenwind/plurkconnection/Tls12SocketFactory.kt
|
1
|
4688
|
package tw.shounenwind.plurkconnection
import android.net.TrafficStats
import android.os.Build
import android.util.Log
import okhttp3.*
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import java.net.SocketException
import java.security.KeyStore
import java.util.*
import javax.net.ssl.*
/**
* Enables TLS v1.2 when creating SSLSockets.
*
*
* For some reason, android supports TLS v1.2 from API 16, but enables it by
* default only from API 20.
*
* @link https://developer.android.com/reference/javax/net/ssl/SSLSocket.html
* @see SSLSocketFactory
*/
class Tls12SocketFactory private constructor(private val delegate: SSLSocketFactory) : SSLSocketFactory() {
override fun getDefaultCipherSuites(): Array<String> {
return delegate.defaultCipherSuites
}
override fun getSupportedCipherSuites(): Array<String> {
return delegate.supportedCipherSuites
}
@Throws(IOException::class)
override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket {
return patch(delegate.createSocket(s, host, port, autoClose))
}
@Throws(IOException::class)
override fun createSocket(host: String, port: Int): Socket {
return patch(delegate.createSocket(host, port))
}
@Throws(IOException::class)
override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int): Socket {
return patch(delegate.createSocket(host, port, localHost, localPort))
}
@Throws(IOException::class)
override fun createSocket(host: InetAddress, port: Int): Socket {
return patch(delegate.createSocket(host, port))
}
@Throws(IOException::class)
override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int): Socket {
return patch(delegate.createSocket(address, port, localAddress, localPort))
}
@Throws(IOException::class)
override fun createSocket(): Socket {
return patch(delegate.createSocket())
}
private fun patch(s: Socket): Socket {
if (s is SSLSocket) {
s.enabledProtocols = TLS_V12_ONLY
}
try {
TrafficStats.tagSocket(s)
} catch (e: SocketException) {
e.printStackTrace()
}
return s
}
class TrafficStatInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
var mTrafficTag = Thread.currentThread().hashCode()
if (mTrafficTag < 0) {
mTrafficTag = -mTrafficTag
} else if (mTrafficTag == 0) {
mTrafficTag = Integer.MAX_VALUE
}
TrafficStats.setThreadStatsTag(mTrafficTag)
return chain.proceed(chain.request())
}
}
companion object {
private const val TAG = "SocketFactory"
private val TLS_V12_ONLY = arrayOf("TLSv1.2")
fun enableTls12OnPreLollipop(client: OkHttpClient.Builder): OkHttpClient.Builder {
if (Build.VERSION.SDK_INT in 16..21) {
try {
val sc = SSLContext.getInstance("TLSv1.2")
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val trustManagers = trustManagerFactory.trustManagers
if (trustManagers.size != 1 || trustManagers[0] !is X509TrustManager) {
throw IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers))
}
val trustManager = trustManagers[0] as X509TrustManager
sc.init(null, arrayOf<TrustManager>(trustManager), null)
client.sslSocketFactory(Tls12SocketFactory(sc.socketFactory), trustManager)
val cs = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build()
val specs = ArrayList<ConnectionSpec>().apply {
add(cs)
add(ConnectionSpec.COMPATIBLE_TLS)
add(ConnectionSpec.CLEARTEXT)
}
client.connectionSpecs(specs)
} catch (exc: Exception) {
Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc)
}
}
client.addNetworkInterceptor(TrafficStatInterceptor())
return client
}
}
}
|
apache-2.0
|
92684e603c4068fad19a03290ef807cb
| 33.992537 | 122 | 0.623507 | 4.847983 | false | false | false | false |
grover-ws-1/http4k
|
http4k-aws/src/test/kotlin/org/http4k/aws/AwsAuthClientFilterTest.kt
|
1
|
2035
|
package org.http4k.aws
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.then
import org.http4k.filter.AwsAuth
import org.http4k.filter.ClientFilters
import org.junit.Test
import java.time.Clock.fixed
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
class AwsClientFilterTest {
private val scope = AwsCredentialScope("us-east", "s3")
private val credentials = AwsCredentials("access", "secret")
private val clock = fixed(LocalDateTime.of(2016, 1, 27, 15, 32, 50, 27).toInstant(ZoneOffset.UTC), ZoneId.of("UTC"))
val audit = AuditHandler()
private val client = ClientFilters.AwsAuth(scope, credentials, clock).then(audit)
@Test
fun `adds authorization header`() {
client(Request(Method.GET, "http://amazon/test").header("content-length", "0"))
assertThat(audit.captured?.header("Authorization"),
equalTo("AWS4-HMAC-SHA256 Credential=access/20160127/us-east/s3/aws4_request, SignedHeaders=content-length;host;x-amz-date, Signature=8afa7ee258c3eaa39b2764cbd52144fd7bbbe401876d4c9f359318963b82244d"))
}
@Test
fun `adds time header`() {
client(Request(Method.GET, "http://amazon/test").header("content-length", "0"))
assertThat(audit.captured?.header("x-amz-date"), equalTo("20160127T153250Z"))
}
@Test
fun adds_content_sha256() {
client(Request(Method.GET, "http://amazon/test").header("content-length", "0"))
assertThat(audit.captured?.header("x-amz-content-sha256"),
equalTo("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"))
}
}
class AuditHandler() : HttpHandler {
var captured: Request? = null
override fun invoke(request: Request): Response {
captured = request
return Response(Status.OK)
}
}
|
apache-2.0
|
ee11f9655207311fbd66b51d7bd7e4a8
| 31.822581 | 213 | 0.722359 | 3.397329 | false | true | false | false |
Raizlabs/DBFlow
|
processor/src/main/kotlin/com/dbflow5/processor/definition/DatabaseHolderDefinition.kt
|
1
|
2468
|
package com.dbflow5.processor.definition
import com.dbflow5.processor.ClassNames
import com.dbflow5.processor.DatabaseHandler
import com.dbflow5.processor.ProcessorManager
import com.dbflow5.processor.utils.rawTypeName
import com.grosner.kpoet.`public final class`
import com.grosner.kpoet.constructor
import com.grosner.kpoet.extends
import com.grosner.kpoet.modifiers
import com.grosner.kpoet.public
import com.grosner.kpoet.statement
import com.squareup.javapoet.TypeSpec
/**
* Description: Top-level writer that handles writing all [DatabaseDefinition]
* and [com.dbflow5.annotation.TypeConverter]
*/
class DatabaseHolderDefinition(private val processorManager: ProcessorManager) : TypeDefinition {
val className: String
init {
var _className = ""
val options = this.processorManager.processingEnvironment.options
if (options.containsKey(OPTION_TARGET_MODULE_NAME)) {
_className = options[OPTION_TARGET_MODULE_NAME] ?: ""
}
_className += ClassNames.DATABASE_HOLDER_STATIC_CLASS_NAME
className = _className
}
override val typeSpec: TypeSpec = `public final class`(this.className) {
extends(ClassNames.DATABASE_HOLDER)
constructor {
modifiers(public)
processorManager.getTypeConverters().forEach { tc ->
statement("\$L.put(\$T.class, new \$T())",
DatabaseHandler.TYPE_CONVERTER_MAP_FIELD_NAME,
tc.modelTypeName?.rawTypeName(),
tc.className)
tc.allowedSubTypes.forEach { subType ->
statement("\$L.put(\$T.class, new \$T())",
DatabaseHandler.TYPE_CONVERTER_MAP_FIELD_NAME,
subType.rawTypeName(), tc.className)
}
}
processorManager.getDatabaseHolderDefinitionList()
.asSequence()
.mapNotNull { it.databaseDefinition?.outputClassName }
.sortedBy { it.simpleName() }
.forEach { statement("new \$T(this)", it) }
this
}
}
/**
* If none of the database holder databases exist, don't generate a holder.
*/
fun isGarbage() = processorManager.getDatabaseHolderDefinitionList()
.none { it.databaseDefinition?.outputClassName != null }
companion object {
const val OPTION_TARGET_MODULE_NAME = "targetModuleName"
}
}
|
mit
|
845ba18e2ebc4a519242f61a2be55f50
| 32.364865 | 97 | 0.641815 | 4.709924 | false | false | false | false |
leafclick/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/AbstractCommonCheckinAction.kt
|
1
|
6043
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.actions
import com.intellij.configurationStore.StoreUtil
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.UpdateInBackground
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsDataKeys.COMMIT_WORKFLOW_HANDLER
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.ui.CommitChangeListDialog
import com.intellij.util.containers.ContainerUtil.concat
import com.intellij.util.ui.UIUtil.removeMnemonic
import com.intellij.vcs.commit.ChangesViewCommitWorkflowHandler
import com.intellij.vcs.commit.CommitWorkflowHandler
private val LOG = logger<AbstractCommonCheckinAction>()
private fun getChangesIn(project: Project, roots: Array<FilePath>): Set<Change> {
val manager = ChangeListManager.getInstance(project)
return roots.flatMap { manager.getChangesIn(it) }.toSet()
}
internal fun Project.getNonModalCommitWorkflowHandler() = ChangesViewManager.getInstanceEx(this).commitWorkflowHandler
internal fun AnActionEvent.isProjectUsesNonModalCommit() = getProjectCommitWorkflowHandler() != null
internal fun AnActionEvent.getProjectCommitWorkflowHandler(): ChangesViewCommitWorkflowHandler? = project?.getNonModalCommitWorkflowHandler()
internal fun AnActionEvent.getContextCommitWorkflowHandler(): CommitWorkflowHandler? = getData(COMMIT_WORKFLOW_HANDLER)
abstract class AbstractCommonCheckinAction : AbstractVcsAction(), UpdateInBackground {
override fun update(vcsContext: VcsContext, presentation: Presentation) {
val project = vcsContext.project
if (project == null || !ProjectLevelVcsManager.getInstance(project).hasActiveVcss()) {
presentation.isEnabledAndVisible = false
}
else if (!approximatelyHasRoots(vcsContext)) {
presentation.isEnabled = false
}
else {
getActionName(vcsContext)?.let { presentation.text = "$it..." }
presentation.isEnabled = !ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning
presentation.isVisible = true
}
}
protected abstract fun approximatelyHasRoots(dataContext: VcsContext): Boolean
protected open fun getActionName(dataContext: VcsContext): String? = null
public override fun actionPerformed(context: VcsContext) {
LOG.debug("actionPerformed. ")
val project = context.project!!
val actionName = getActionName(context)?.let { removeMnemonic(it) } ?: templatePresentation.text
val isFreezedDialogTitle = actionName?.let { "Can not $it now" }
if (ChangeListManager.getInstance(project).isFreezedWithNotification(isFreezedDialogTitle)) {
LOG.debug("ChangeListManager is freezed. returning.")
}
else if (ProjectLevelVcsManager.getInstance(project).isBackgroundVcsOperationRunning) {
LOG.debug("Background operation is running. returning.")
}
else {
val roots = prepareRootsForCommit(getRoots(context), project)
queueCheckin(project, context, roots)
}
}
protected open fun queueCheckin(
project: Project,
context: VcsContext,
roots: Array<FilePath>
) {
ChangeListManager.getInstance(project).invokeAfterUpdate(
{ performCheckIn(context, project, roots) }, InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE,
message("waiting.changelists.update.for.show.commit.dialog.message"), ModalityState.current()
)
}
@Deprecated("getActionName() will be used instead")
protected open fun getMnemonicsFreeActionName(context: VcsContext): String? = null
protected abstract fun getRoots(dataContext: VcsContext): Array<FilePath>
protected open fun prepareRootsForCommit(roots: Array<FilePath>, project: Project): Array<FilePath> {
StoreUtil.saveDocumentsAndProjectSettings(project)
return DescindingFilesFilter.filterDescindingFiles(roots, project)
}
protected open fun isForceUpdateCommitStateFromContext(): Boolean = false
protected open fun performCheckIn(context: VcsContext, project: Project, roots: Array<FilePath>) {
LOG.debug("invoking commit dialog after update")
val selectedChanges = context.selectedChanges
val selectedUnversioned = context.selectedUnversionedFilePaths
val initialChangeList = getInitiallySelectedChangeList(context, project)
val changesToCommit: Collection<Change>
val included: Collection<Any>
if (selectedChanges.isNullOrEmpty() && selectedUnversioned.isEmpty()) {
changesToCommit = getChangesIn(project, roots)
included = initialChangeList.changes.intersect(changesToCommit)
}
else {
changesToCommit = selectedChanges.orEmpty().toList()
included = concat(changesToCommit, selectedUnversioned)
}
val executor = getExecutor(project)
val workflowHandler = project.getNonModalCommitWorkflowHandler()
if (executor == null && workflowHandler != null) {
workflowHandler.run {
setCommitState(initialChangeList, included, isForceUpdateCommitStateFromContext())
activate()
}
}
else {
CommitChangeListDialog.commitChanges(project, changesToCommit, included, initialChangeList, executor, null)
}
}
protected open fun getInitiallySelectedChangeList(context: VcsContext, project: Project): LocalChangeList {
val manager = ChangeListManager.getInstance(project)
return context.selectedChangeLists?.firstOrNull()?.let { manager.findChangeList(it.name) }
?: context.selectedChanges?.firstOrNull()?.let { manager.getChangeList(it) }
?: manager.defaultChangeList
}
protected open fun getExecutor(project: Project): CommitExecutor? = null
}
|
apache-2.0
|
62c5b09affe00ebc0d9c42dc30fea323
| 42.47482 | 141 | 0.776105 | 4.985974 | false | false | false | false |
leafclick/intellij-community
|
platform/execution-impl/src/com/intellij/execution/ui/RunContentManagerImpl.kt
|
1
|
26699
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.ui
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.Executor
import com.intellij.execution.KillableProcess
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.dashboard.RunDashboardManager
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.ui.layout.impl.DockableGridContainerFactory
import com.intellij.ide.DataManager
import com.intellij.ide.impl.ContentManagerWatcher
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Key
import com.intellij.openapi.wm.RegisterToolWindowTask
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.AppUIUtil
import com.intellij.ui.content.*
import com.intellij.ui.docking.DockManager
import com.intellij.util.ObjectUtils
import com.intellij.util.SmartList
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.UIUtil
import gnu.trove.THashMap
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.function.Predicate
import javax.swing.Icon
private val LOG = logger<RunContentManagerImpl>()
private val EXECUTOR_KEY: Key<Executor> = Key.create("Executor")
private val CLOSE_LISTENER_KEY: Key<ContentManagerListener> = Key.create("CloseListener")
class RunContentManagerImpl(private val project: Project) : RunContentManager {
private val toolWindowIdToBaseIcon: MutableMap<String, Icon> = THashMap()
private val toolWindowIdZBuffer = ConcurrentLinkedDeque<String>()
init {
val containerFactory = DockableGridContainerFactory()
DockManager.getInstance(project).register(DockableGridContainerFactory.TYPE, containerFactory, project)
AppUIExecutor.onUiThread().expireWith(project).submit { init() }
}
companion object {
@JvmField
val ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY = Key.create<Boolean>("ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY")
@ApiStatus.Internal
@JvmField
val TEMPORARY_CONFIGURATION_KEY = Key.create<RunnerAndConfigurationSettings>("TemporaryConfiguration")
@JvmStatic
fun copyContentAndBehavior(descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) {
if (contentToReuse != null) {
val attachedContent = contentToReuse.attachedContent
if (attachedContent != null && attachedContent.isValid) {
descriptor.setAttachedContent(attachedContent)
}
if (contentToReuse.isReuseToolWindowActivation) {
descriptor.isActivateToolWindowWhenAdded = contentToReuse.isActivateToolWindowWhenAdded
}
descriptor.contentToolWindowId = contentToReuse.contentToolWindowId
descriptor.isSelectContentWhenAdded = contentToReuse.isSelectContentWhenAdded
}
}
@JvmStatic
fun isTerminated(content: Content): Boolean {
val processHandler = getRunContentDescriptorByContent(content)?.processHandler ?: return true
return processHandler.isProcessTerminated
}
@JvmStatic
fun getRunContentDescriptorByContent(content: Content): RunContentDescriptor? {
return content.getUserData(RunContentDescriptor.DESCRIPTOR_KEY)
}
@JvmStatic
fun getExecutorByContent(content: Content): Executor? = content.getUserData(EXECUTOR_KEY)
}
// must be called on EDT
private fun init() {
project.messageBus.connect().subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
toolWindowIdZBuffer.retainAll(toolWindowManager.toolWindowIdSet)
val activeToolWindowId = toolWindowManager.activeToolWindowId
if (activeToolWindowId != null && toolWindowIdZBuffer.remove(activeToolWindowId)) {
toolWindowIdZBuffer.addFirst(activeToolWindowId)
}
}
})
}
private fun registerToolWindow(executor: Executor, toolWindowManager: ToolWindowManager): ContentManager {
val toolWindowId = executor.toolWindowId
var toolWindow = toolWindowManager.getToolWindow(toolWindowId)
if (toolWindow != null) {
return toolWindow.contentManager
}
toolWindow = toolWindowManager.registerToolWindow(RegisterToolWindowTask(id = toolWindowId, icon = executor.toolWindowIcon))
val contentManager = toolWindow.contentManager
contentManager.addDataProvider(object : DataProvider {
private var myInsideGetData = 0
override fun getData(dataId: String): Any? {
myInsideGetData++
return try {
if (PlatformDataKeys.HELP_ID.`is`(dataId)) {
executor.helpId
}
else {
if (myInsideGetData == 1) DataManager.getInstance().getDataContext(contentManager.component).getData(dataId) else null
}
}
finally {
myInsideGetData--
}
}
})
ContentManagerWatcher.watchContentManager(toolWindow, contentManager)
initToolWindow(executor, toolWindowId, executor.toolWindowIcon, contentManager)
return contentManager
}
private fun initToolWindow(executor: Executor?, toolWindowId: String, toolWindowIcon: Icon, contentManager: ContentManager) {
toolWindowIdToBaseIcon.put(toolWindowId, toolWindowIcon)
contentManager.addContentManagerListener(object : ContentManagerListener {
override fun selectionChanged(event: ContentManagerEvent) {
if (event.operation != ContentManagerEvent.ContentOperation.add) {
return
}
val content = event.content
var contentExecutor = executor
if (contentExecutor == null) {
// Content manager contains contents related with different executors.
// Try to get executor from content.
contentExecutor = getExecutorByContent(content)
// Must contain this user data since all content is added by this class.
LOG.assertTrue(contentExecutor != null)
}
syncPublisher.contentSelected(getRunContentDescriptorByContent(content), contentExecutor!!)
content.helpId = contentExecutor.helpId
}
})
Disposer.register(contentManager, Disposable {
contentManager.removeAllContents(true)
toolWindowIdZBuffer.remove(toolWindowId)
toolWindowIdToBaseIcon.remove(toolWindowId)
})
toolWindowIdZBuffer.addLast(toolWindowId)
}
private val syncPublisher: RunContentWithExecutorListener
get() = project.messageBus.syncPublisher(RunContentManager.TOPIC)
override fun toFrontRunContent(requestor: Executor, handler: ProcessHandler) {
val descriptor = getDescriptorBy(handler, requestor) ?: return
toFrontRunContent(requestor, descriptor)
}
override fun toFrontRunContent(requestor: Executor, descriptor: RunContentDescriptor) {
ApplicationManager.getApplication().invokeLater(Runnable {
val contentManager = getContentManagerForRunner(requestor, descriptor)
val content = getRunContentByDescriptor(contentManager, descriptor)
if (content != null) {
contentManager.setSelectedContent(content)
getToolWindowManager().getToolWindow(getToolWindowIdForRunner(requestor, descriptor))!!.show(null)
}
}, project.disposed)
}
override fun hideRunContent(executor: Executor, descriptor: RunContentDescriptor) {
ApplicationManager.getApplication().invokeLater(Runnable {
val toolWindow = getToolWindowManager().getToolWindow(getToolWindowIdForRunner(executor, descriptor))
toolWindow?.hide(null)
}, project.disposed)
}
override fun getSelectedContent(): RunContentDescriptor? {
for (activeWindow in toolWindowIdZBuffer) {
val contentManager = getContentManagerByToolWindowId(activeWindow) ?: continue
val selectedContent = contentManager.selectedContent
?: if (contentManager.contentCount == 0) {
// continue to the next window if the content manager is empty
continue
}
else {
// stop iteration over windows because there is some content in the window and the window is the last used one
break
}
// here we have selected content
return getRunContentDescriptorByContent(selectedContent)
}
return null
}
override fun removeRunContent(executor: Executor, descriptor: RunContentDescriptor): Boolean {
val contentManager = getContentManagerForRunner(executor, descriptor)
val content = getRunContentByDescriptor(contentManager, descriptor)
return content != null && contentManager.removeContent(content, true)
}
override fun showRunContent(executor: Executor, descriptor: RunContentDescriptor) {
showRunContent(executor, descriptor, descriptor.executionId)
}
private fun showRunContent(executor: Executor, descriptor: RunContentDescriptor, executionId: Long) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return
}
val contentManager = getContentManagerForRunner(executor, descriptor)
val toolWindowId = getToolWindowIdForRunner(executor, descriptor)
val oldDescriptor = chooseReuseContentForDescriptor(contentManager, descriptor, executionId, descriptor.displayName, getReuseCondition(toolWindowId))
val content: Content?
if (oldDescriptor == null) {
content = createNewContent(descriptor, executor)
}
else {
content = oldDescriptor.attachedContent!!
syncPublisher.contentRemoved(oldDescriptor, executor)
Disposer.dispose(oldDescriptor) // is of the same category, can be reused
}
content.executionId = executionId
content.component = descriptor.component
content.setPreferredFocusedComponent(descriptor.preferredFocusComputable)
content.putUserData(RunContentDescriptor.DESCRIPTOR_KEY, descriptor)
content.putUserData(EXECUTOR_KEY, executor)
content.displayName = descriptor.displayName
descriptor.setAttachedContent(content)
val toolWindow = getToolWindowManager().getToolWindow(toolWindowId)
val processHandler = descriptor.processHandler
if (processHandler != null) {
val processAdapter = object : ProcessAdapter() {
override fun startNotified(event: ProcessEvent) {
UIUtil.invokeLaterIfNeeded {
content.icon = ExecutionUtil.getLiveIndicator(descriptor.icon)
toolWindow!!.setIcon(ExecutionUtil.getLiveIndicator(toolWindowIdToBaseIcon[toolWindowId]))
}
}
override fun processTerminated(event: ProcessEvent) {
AppUIUtil.invokeLaterIfProjectAlive(project) {
val manager = getContentManagerByToolWindowId(toolWindowId) ?: return@invokeLaterIfProjectAlive
val alive = isAlive(manager)
setToolWindowIcon(alive, toolWindow!!)
val icon = descriptor.icon
content.icon = if (icon == null) executor.disabledIcon else IconLoader.getTransparentIcon(icon)
}
}
}
processHandler.addProcessListener(processAdapter)
val disposer = content.disposer
if (disposer != null) {
Disposer.register(disposer, Disposable { processHandler.removeProcessListener(processAdapter) })
}
}
if (oldDescriptor == null) {
contentManager.addContent(content)
content.putUserData(CLOSE_LISTENER_KEY, CloseListener(content, executor))
}
if (descriptor.isSelectContentWhenAdded /* also update selection when reused content is already selected */
|| oldDescriptor != null && contentManager.isSelected(content)) {
content.manager!!.setSelectedContent(content)
}
if (!descriptor.isActivateToolWindowWhenAdded) {
return
}
ApplicationManager.getApplication().invokeLater(Runnable {
// let's activate tool window, but don't move focus
//
// window.show() isn't valid here, because it will not
// mark the window as "last activated" windows and thus
// some action like navigation up/down in stacktrace wont
// work correctly
getToolWindowManager().getToolWindow(toolWindowId)!!.activate(
descriptor.activationCallback,
descriptor.isAutoFocusContent,
descriptor.isAutoFocusContent)
}, project.disposed)
}
private fun getContentManagerByToolWindowId(toolWindowId: String): ContentManager? {
project.serviceIfCreated<RunDashboardManager>()?.let {
if (it.toolWindowId == toolWindowId) {
return if (toolWindowIdToBaseIcon.contains(toolWindowId)) it.dashboardContentManager else null
}
}
return getToolWindowManager().getToolWindow(toolWindowId)?.contentManagerIfCreated
}
override fun getReuseContent(executionEnvironment: ExecutionEnvironment): RunContentDescriptor? {
if (ApplicationManager.getApplication().isUnitTestMode) {
return null
}
val contentToReuse = executionEnvironment.contentToReuse
if (contentToReuse != null) {
return contentToReuse
}
val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment)
val reuseCondition: Predicate<Content>?
val contentManager: ContentManager
if (toolWindowId == null) {
contentManager = getContentManagerForRunner(executionEnvironment.executor, null)
reuseCondition = null
}
else {
contentManager = getOrCreateContentManagerForToolWindow(toolWindowId, executionEnvironment.executor)
reuseCondition = getReuseCondition(toolWindowId)
}
return chooseReuseContentForDescriptor(contentManager, null, executionEnvironment.executionId, executionEnvironment.toString(), reuseCondition)
}
private fun getReuseCondition(toolWindowId: String): Predicate<Content>? {
val runDashboardManager = RunDashboardManager.getInstance(project)
return if (runDashboardManager.toolWindowId == toolWindowId) runDashboardManager.reuseCondition else null
}
override fun findContentDescriptor(requestor: Executor, handler: ProcessHandler): RunContentDescriptor? {
return getDescriptorBy(handler, requestor)
}
override fun showRunContent(info: Executor, descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) {
copyContentAndBehavior(descriptor, contentToReuse)
showRunContent(info, descriptor, descriptor.executionId)
}
private fun getContentManagerForRunner(executor: Executor, descriptor: RunContentDescriptor?): ContentManager {
return getOrCreateContentManagerForToolWindow(getToolWindowIdForRunner(executor, descriptor), executor)
}
private fun getOrCreateContentManagerForToolWindow(id: String, executor: Executor): ContentManager {
val contentManager = getContentManagerByToolWindowId(id)
if (contentManager != null) return contentManager
val dashboardManager = RunDashboardManager.getInstance(project)
if (dashboardManager.toolWindowId == id) {
initToolWindow(null, dashboardManager.toolWindowId, dashboardManager.toolWindowIcon, dashboardManager.dashboardContentManager)
return dashboardManager.dashboardContentManager
}
return registerToolWindow(executor, getToolWindowManager())
}
override fun getToolWindowByDescriptor(descriptor: RunContentDescriptor): ToolWindow? {
descriptor.contentToolWindowId?.let {
return getToolWindowManager().getToolWindow(it)
}
processToolWindowContentManagers { toolWindow, contentManager ->
if (getRunContentByDescriptor(contentManager, descriptor) != null) {
return toolWindow
}
}
return null
}
private inline fun processToolWindowContentManagers(processor: (ToolWindow, ContentManager) -> Unit) {
val toolWindowManager = getToolWindowManager()
for (executor in Executor.EXECUTOR_EXTENSION_NAME.extensionList) {
val toolWindow = toolWindowManager.getToolWindow(executor.id) ?: continue
processor(toolWindow, toolWindow.contentManagerIfCreated ?: continue)
}
project.serviceIfCreated<RunDashboardManager>()?.let {
val toolWindowId = it.toolWindowId
if (toolWindowIdToBaseIcon.contains(toolWindowId)) {
processor(toolWindowManager.getToolWindow(toolWindowId) ?: return, it.dashboardContentManager)
}
}
}
override fun getAllDescriptors(): List<RunContentDescriptor> {
val descriptors: MutableList<RunContentDescriptor> = SmartList()
processToolWindowContentManagers { _, contentManager ->
for (content in contentManager.contents) {
getRunContentDescriptorByContent(content)?.let {
descriptors.add(it)
}
}
}
return descriptors
}
override fun selectRunContent(descriptor: RunContentDescriptor) {
processToolWindowContentManagers { _, contentManager ->
val content = getRunContentByDescriptor(contentManager, descriptor) ?: return@processToolWindowContentManagers
contentManager.setSelectedContent(content)
return
}
}
private fun getToolWindowManager() = ToolWindowManager.getInstance(project)
override fun getContentDescriptorToolWindowId(configuration: RunConfiguration?): String? {
if (configuration != null) {
val runDashboardManager = RunDashboardManager.getInstance(project)
if (runDashboardManager.isShowInDashboard(configuration)) {
return runDashboardManager.toolWindowId
}
}
return null
}
override fun getToolWindowIdByEnvironment(executionEnvironment: ExecutionEnvironment): String {
// Also there are some places where ToolWindowId.RUN or ToolWindowId.DEBUG are used directly.
// For example, HotSwapProgressImpl.NOTIFICATION_GROUP. All notifications for this group is shown in Debug tool window,
// however such notifications should be shown in Run Dashboard tool window, if run content is redirected to Run Dashboard tool window.
val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment)
return toolWindowId ?: executionEnvironment.executor.toolWindowId
}
private fun getDescriptorBy(handler: ProcessHandler, runnerInfo: Executor): RunContentDescriptor? {
fun find(contents: Array<Content>): RunContentDescriptor? {
for (content in contents) {
val runContentDescriptor = getRunContentDescriptorByContent(content)
if (runContentDescriptor?.processHandler === handler) {
return runContentDescriptor
}
}
return null
}
find(getContentManagerForRunner(runnerInfo, null).contents)?.let {
return it
}
find(getContentManagerByToolWindowId(project.serviceIfCreated<RunDashboardManager>()?.toolWindowId ?: return null)?.contents ?: return null)?.let {
return it
}
return null
}
fun moveContent(executor: Executor, descriptor: RunContentDescriptor) {
val content = descriptor.attachedContent ?: return
val oldContentManager = content.manager
val newContentManager = getContentManagerForRunner(executor, descriptor)
if (oldContentManager == null || oldContentManager === newContentManager) return
val listener = content.getUserData(CLOSE_LISTENER_KEY)
if (listener != null) {
oldContentManager.removeContentManagerListener(listener)
}
oldContentManager.removeContent(content, false)
if (isAlive(descriptor)) {
if (!isAlive(oldContentManager)) {
updateToolWindowIcon(oldContentManager, false)
}
if (!isAlive(newContentManager)) {
updateToolWindowIcon(newContentManager, true)
}
}
newContentManager.addContent(content)
if (listener != null) {
newContentManager.addContentManagerListener(listener)
}
}
private fun updateToolWindowIcon(contentManagerToUpdate: ContentManager, alive: Boolean) {
processToolWindowContentManagers { toolWindow, contentManager ->
if (contentManagerToUpdate == contentManager) {
setToolWindowIcon(alive, toolWindow)
return
}
}
}
private fun setToolWindowIcon(alive: Boolean, toolWindow: ToolWindow) {
val base = toolWindowIdToBaseIcon.get(toolWindow.id)
toolWindow.setIcon(if (alive) ExecutionUtil.getLiveIndicator(base) else ObjectUtils.notNull(base, EmptyIcon.ICON_13))
}
private inner class CloseListener(content: Content, private val myExecutor: Executor) : BaseContentCloseListener(content, project) {
override fun disposeContent(content: Content) {
try {
val descriptor = getRunContentDescriptorByContent(content)
syncPublisher.contentRemoved(descriptor, myExecutor)
if (descriptor != null) {
Disposer.dispose(descriptor)
}
}
finally {
content.release()
}
}
override fun closeQuery(content: Content, projectClosing: Boolean): Boolean {
val descriptor = getRunContentDescriptorByContent(content) ?: return true
val processHandler = descriptor.processHandler
if (processHandler == null || processHandler.isProcessTerminated) {
return true
}
val sessionName = descriptor.displayName
val killable = processHandler is KillableProcess && (processHandler as KillableProcess).canKillProcess()
val task = object : WaitForProcessTask(processHandler, sessionName, projectClosing, project) {
override fun onCancel() {
if (killable && !processHandler.isProcessTerminated) {
(processHandler as KillableProcess).killProcess()
}
}
}
if (killable) {
val cancelText = ExecutionBundle.message("terminating.process.progress.kill")
task.cancelText = cancelText
task.cancelTooltipText = cancelText
}
return askUserAndWait(processHandler, sessionName, task)
}
}
}
private fun chooseReuseContentForDescriptor(contentManager: ContentManager,
descriptor: RunContentDescriptor?,
executionId: Long,
preferredName: String?,
reuseCondition: Predicate<in Content>?): RunContentDescriptor? {
var content: Content? = null
if (descriptor != null) {
//Stage one: some specific descriptors (like AnalyzeStacktrace) cannot be reused at all
if (descriptor.isContentReuseProhibited) {
return null
}
// stage two: try to get content from descriptor itself
val attachedContent = descriptor.attachedContent
if (attachedContent != null && attachedContent.isValid
&& contentManager.getIndexOfContent(attachedContent) != -1 && (Comparing.equal(descriptor.displayName,
attachedContent.displayName) || !attachedContent.isPinned)) {
content = attachedContent
}
}
// stage three: choose the content with name we prefer
if (content == null) {
content = getContentFromManager(contentManager, preferredName, executionId, reuseCondition)
}
if (content == null || !RunContentManagerImpl.isTerminated(content) || content.executionId == executionId && executionId != 0L) {
return null
}
val oldDescriptor = RunContentManagerImpl.getRunContentDescriptorByContent(content) ?: return null
if (oldDescriptor.isContentReuseProhibited) {
return null
}
if (descriptor == null || oldDescriptor.reusePolicy.canBeReusedBy(descriptor)) {
return oldDescriptor
}
return null
}
private fun getContentFromManager(contentManager: ContentManager,
preferredName: String?,
executionId: Long,
reuseCondition: Predicate<in Content>?): Content? {
val contents = contentManager.contents.toMutableList()
val first = contentManager.selectedContent
if (first != null && contents.remove(first)) {
//selected content should be checked first
contents.add(0, first)
}
if (preferredName != null) {
// try to match content with specified preferred name
for (c in contents) {
if (canReuseContent(c, executionId) && preferredName == c.displayName) {
return c
}
}
}
// return first "good" content
return contents.firstOrNull {
canReuseContent(it, executionId) && (reuseCondition == null || reuseCondition.test(it))
}
}
private fun canReuseContent(c: Content, executionId: Long): Boolean {
return !c.isPinned && RunContentManagerImpl.isTerminated(c) && !(c.executionId == executionId && executionId != 0L)
}
private fun getToolWindowIdForRunner(executor: Executor, descriptor: RunContentDescriptor?): String {
return descriptor?.contentToolWindowId ?: executor.toolWindowId
}
private fun createNewContent(descriptor: RunContentDescriptor, executor: Executor): Content {
val content = ContentFactory.SERVICE.getInstance().createContent(descriptor.component, descriptor.displayName, true)
content.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE)
content.icon = descriptor.icon ?: executor.toolWindowIcon
return content
}
private fun getRunContentByDescriptor(contentManager: ContentManager, descriptor: RunContentDescriptor): Content? {
return contentManager.contents.firstOrNull {
descriptor == RunContentManagerImpl.getRunContentDescriptorByContent(it)
}
}
private fun isAlive(contentManager: ContentManager): Boolean {
return contentManager.contents.any {
val descriptor = RunContentManagerImpl.getRunContentDescriptorByContent(it)
descriptor != null && isAlive(descriptor)
}
}
private fun isAlive(descriptor: RunContentDescriptor): Boolean {
val handler = descriptor.processHandler
return handler != null && !handler.isProcessTerminated
}
|
apache-2.0
|
80cfba897609d67851479fa34e39a855
| 41.583732 | 153 | 0.733548 | 5.349429 | false | false | false | false |
leafclick/intellij-community
|
java/java-impl/src/com/intellij/codeInsight/completion/ml/JavaMLRankingProvider.kt
|
1
|
900
|
// 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.codeInsight.completion.ml
import com.intellij.internal.ml.*
import com.intellij.internal.ml.completion.CompletionRankingModelBase
import com.intellij.internal.ml.completion.JarCompletionModelProvider
import com.intellij.lang.Language
import com.jetbrains.completion.ranker.model.java.MLGlassBox
class JavaMLRankingProvider : JarCompletionModelProvider("Java", "java_features") {
override fun createModel(metadata: ModelMetadata): DecisionFunction {
return object : CompletionRankingModelBase(metadata) {
override fun predict(features: DoubleArray?): Double = MLGlassBox.makePredict(features)
}
}
override fun isLanguageSupported(language: Language): Boolean = language.id.compareTo("java", ignoreCase = true) == 0
}
|
apache-2.0
|
5e284761c4fcf9a5e7c28e0d0850902b
| 49.055556 | 140 | 0.8 | 4.411765 | false | false | false | false |
SmokSmog/smoksmog-android
|
app/src/main/kotlin/com/antyzero/smoksmog/user/User.kt
|
1
|
1073
|
package com.antyzero.smoksmog.user
import android.content.Context
import java.util.*
/**
* User management
*/
class User(context: Context) {
val identifier: String
init {
val preferences = context.getSharedPreferences(PREFERENCES_USER, Context.MODE_PRIVATE)
if (!preferences.contains(KEY_USER_ID)) {
identifier = createIdentifier()
preferences.edit().putString(KEY_USER_ID, identifier).apply()
} else {
identifier = preferences.getString(KEY_USER_ID, DEF_VALUE)
if (identifier == DEF_VALUE) {
throw IllegalStateException("Missing identifier for user")
}
}
}
private fun createIdentifier(): String {
val value = Random().nextInt(Integer.MAX_VALUE)
val hashCode = value.toString().hashCode()
return "ID-" + Math.abs(hashCode).toString()
}
companion object {
private val PREFERENCES_USER = "USER"
private val KEY_USER_ID = "KEY_USER_ID_V3"
private val DEF_VALUE = "DEF_VALUE"
}
}
|
gpl-3.0
|
90b44f64873d8b2bb7007625f91cd261
| 25.170732 | 94 | 0.61603 | 4.34413 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/argumentOrder/argumentOrderInSuperCall.kt
|
1
|
278
|
var result = "fail"
open class Base(val o: String, val k: String)
class Derived : Base(k = { result = "O"; "K"}() , o = {result += "K"; "O"}()) {}
fun box(): String {
val derived = Derived()
if (result != "OK") return "fail $result"
return derived.o + derived.k
}
|
apache-2.0
|
7d5774679abca7271390b4e488583cef
| 24.363636 | 80 | 0.564748 | 3.021739 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddOrderEntryActionFactory.kt
|
3
|
2674
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix
import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixActionRegistrarImpl
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference.ShorteningMode
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.runWhenSmart
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElement
import org.jetbrains.kotlin.psi.psiUtil.startOffset
object KotlinAddOrderEntryActionFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val simpleExpression = diagnostic.psiElement as? KtSimpleNameExpression ?: return emptyList()
if (!ProjectRootsUtil.isInProjectSource(simpleExpression, includeScriptsOutsideSourceRoots = false)) return emptyList()
val refElement = simpleExpression.getQualifiedElement()
val reference = object : PsiReferenceBase<KtElement>(refElement) {
override fun resolve() = null
override fun getVariants() = PsiReference.EMPTY_ARRAY
override fun getRangeInElement(): TextRange {
val offset = simpleExpression.startOffset - refElement.startOffset
return TextRange(offset, offset + simpleExpression.textLength)
}
override fun getCanonicalText() = refElement.text
override fun bindToElement(element: PsiElement): PsiElement {
val project = element.project
project.runWhenSmart {
project.executeWriteCommand("") {
simpleExpression.mainReference.bindToElement(element, ShorteningMode.FORCED_SHORTENING)
}
}
return element
}
}
@Suppress("UNCHECKED_CAST")
return OrderEntryFix.registerFixes(QuickFixActionRegistrarImpl(null), reference) as List<IntentionAction>? ?: emptyList()
}
}
|
apache-2.0
|
64bb56017caa51d2d7f03f6a77162d12
| 46.75 | 158 | 0.743455 | 5.305556 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt
|
2
|
4415
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.daemon.RainbowVisitor
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors.*
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinTargetElementEvaluator
import org.jetbrains.kotlin.idea.util.isAnonymousFunction
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.parents
class KotlinRainbowVisitor : RainbowVisitor() {
companion object {
val KOTLIN_TARGET_ELEMENT_EVALUATOR = KotlinTargetElementEvaluator()
}
override fun suitableForFile(file: PsiFile) = file is KtFile
override fun clone() = KotlinRainbowVisitor()
override fun visit(element: PsiElement) {
when {
element.isRainbowDeclaration() -> {
val rainbowElement = (element as KtNamedDeclaration).nameIdentifier ?: return
addRainbowHighlight(element, rainbowElement)
}
element is KtSimpleNameExpression -> {
val qualifiedExpression = PsiTreeUtil.getParentOfType(
element, KtQualifiedExpression::class.java, true,
KtLambdaExpression::class.java, KtValueArgumentList::class.java
)
if (qualifiedExpression?.selectorExpression?.isAncestor(element) == true) return
val reference = element.mainReference
val targetElement = reference.resolve()
if (targetElement != null) {
if (targetElement.isRainbowDeclaration()) {
addRainbowHighlight(targetElement, element)
}
} else if (element.getReferencedName() == "it") {
val itTargetElement =
KOTLIN_TARGET_ELEMENT_EVALUATOR.getElementByReference(reference, TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED)
if (itTargetElement != null) {
addRainbowHighlight(itTargetElement, element)
}
}
}
element is KDocName -> {
val target = element.reference?.resolve() ?: return
if (target.isRainbowDeclaration()) {
addRainbowHighlight(target, element, KDOC_LINK)
}
}
}
}
private fun addRainbowHighlight(target: PsiElement, rainbowElement: PsiElement, attributesKey: TextAttributesKey? = null) {
val lambdaSequenceIterator = target.parents
.takeWhile { it !is KtDeclaration || it.isAnonymousFunction || it is KtFunctionLiteral }
.filter { it is KtLambdaExpression || it.isAnonymousFunction }
.iterator()
val attributesKeyToUse = attributesKey ?: (if (target is KtParameter) PARAMETER else LOCAL_VARIABLE)
if (lambdaSequenceIterator.hasNext()) {
var lambda = lambdaSequenceIterator.next()
var lambdaNestingLevel = 0
while (lambdaSequenceIterator.hasNext()) {
lambdaNestingLevel++
lambda = lambdaSequenceIterator.next()
}
addInfo(getInfo(lambda, rainbowElement, "$lambdaNestingLevel${rainbowElement.text}", attributesKeyToUse))
return
}
val context = target.getStrictParentOfType<KtDeclarationWithBody>()
?: target.getStrictParentOfType<KtAnonymousInitializer>()
?: return
addInfo(getInfo(context, rainbowElement, rainbowElement.text, attributesKeyToUse))
}
private fun PsiElement.isRainbowDeclaration(): Boolean =
(this is KtProperty && isLocal) ||
(this is KtParameter && getStrictParentOfType<KtPrimaryConstructor>() == null) ||
this is KtDestructuringDeclarationEntry
}
|
apache-2.0
|
69b80e99dc41c501d5b340f9bdae64aa
| 43.59596 | 158 | 0.660702 | 5.51875 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/baseTransformations.kt
|
3
|
6072
|
// 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.loopToCallChain
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.resolve.scopes.utils.findFunction
import org.jetbrains.kotlin.resolve.scopes.utils.findPackage
import org.jetbrains.kotlin.resolve.scopes.utils.findVariable
/**
* Base class for [ResultTransformation]'s that replaces the loop-expression with the result call chain
*/
abstract class ReplaceLoopResultTransformation(final override val loop: KtForExpression) : ResultTransformation {
override val commentSavingRange = PsiChildRange.singleElement(loop.unwrapIfLabeled())
override fun generateExpressionToReplaceLoopAndCheckErrors(resultCallChain: KtExpression): KtExpression {
return resultCallChain
}
override fun convertLoop(resultCallChain: KtExpression, commentSavingRangeHolder: CommentSavingRangeHolder): KtExpression {
return loop.unwrapIfLabeled().replaced(resultCallChain)
}
}
/**
* Base class for [ResultTransformation]'s that replaces initialization of a variable with the result call chain
*/
abstract class AssignToVariableResultTransformation(
final override val loop: KtForExpression,
protected val initialization: VariableInitialization
) : ResultTransformation {
override val commentSavingRange = PsiChildRange(initialization.initializationStatement, loop.unwrapIfLabeled())
override fun generateExpressionToReplaceLoopAndCheckErrors(resultCallChain: KtExpression): KtExpression {
val psiFactory = KtPsiFactory(resultCallChain)
val initializationStatement = initialization.initializationStatement
return if (initializationStatement is KtVariableDeclaration) {
val resolutionScope = loop.getResolutionScope()
fun isUniqueName(name: String): Boolean {
val identifier = Name.identifier(name)
return resolutionScope.findVariable(identifier, NoLookupLocation.FROM_IDE) == null
&& resolutionScope.findFunction(identifier, NoLookupLocation.FROM_IDE) == null
&& resolutionScope.findClassifier(identifier, NoLookupLocation.FROM_IDE) == null
&& resolutionScope.findPackage(identifier) == null
}
val uniqueName = KotlinNameSuggester.suggestNameByName("test", ::isUniqueName)
val copy = initializationStatement.copied()
copy.initializer!!.replace(resultCallChain)
copy.setName(uniqueName)
copy
} else {
psiFactory.createExpressionByPattern("$0 = $1", initialization.variable.nameAsSafeName, resultCallChain, reformat = false)
}
}
override fun convertLoop(resultCallChain: KtExpression, commentSavingRangeHolder: CommentSavingRangeHolder): KtExpression {
initialization.initializer.replace(resultCallChain)
val variable = initialization.variable
if (variable.isVar && variable.countWriteUsages() == variable.countWriteUsages(loop)) { // change variable to 'val' if possible
variable.valOrVarKeyword.replace(KtPsiFactory(variable).createValKeyword())
}
val loopUnwrapped = loop.unwrapIfLabeled()
// move initializer to the loop if needed
var initializationStatement = initialization.initializationStatement
if (initializationStatement.nextStatement() != loopUnwrapped) {
val block = loopUnwrapped.parent
assert(block is KtBlockExpression)
val movedInitializationStatement = block.addBefore(initializationStatement, loopUnwrapped) as KtExpression
block.addBefore(KtPsiFactory(block).createNewLine(), loopUnwrapped)
commentSavingRangeHolder.remove(initializationStatement)
initializationStatement.delete()
initializationStatement = movedInitializationStatement
}
loopUnwrapped.delete()
return initializationStatement
}
companion object {
fun createDelegated(delegate: ResultTransformation, initialization: VariableInitialization): AssignToVariableResultTransformation {
return object : AssignToVariableResultTransformation(delegate.loop, initialization) {
override val presentation: String
get() = delegate.presentation
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
return delegate.generateCode(chainedCallGenerator)
}
override val lazyMakesSense: Boolean
get() = delegate.lazyMakesSense
}
}
}
}
/**
* [ResultTransformation] that replaces initialization of a variable with the call chain produced by the given [SequenceTransformation]
*/
class AssignSequenceResultTransformation(
private val sequenceTransformation: SequenceTransformation,
initialization: VariableInitialization
) : AssignToVariableResultTransformation(sequenceTransformation.loop, initialization) {
override val presentation: String
get() = sequenceTransformation.presentation
override fun buildPresentation(prevTransformationsPresentation: String?): String {
return sequenceTransformation.buildPresentation(prevTransformationsPresentation)
}
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
return sequenceTransformation.generateCode(chainedCallGenerator)
}
}
|
apache-2.0
|
4b8e4b08f3f91e0ea4d3ea697627cbc7
| 44.661654 | 158 | 0.741107 | 5.771863 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/j2k/IdeaDocCommentConverter.kt
|
2
|
9548
|
// 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.j2k
import com.intellij.ide.highlighter.HtmlFileType
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.html.HtmlTag
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.javadoc.PsiDocTag
import com.intellij.psi.javadoc.PsiDocToken
import com.intellij.psi.javadoc.PsiInlineDocTag
import com.intellij.psi.xml.XmlFile
import com.intellij.psi.xml.XmlTag
import com.intellij.psi.xml.XmlText
import com.intellij.psi.xml.XmlTokenType
object IdeaDocCommentConverter : DocCommentConverter {
override fun convertDocComment(docComment: PsiDocComment): String {
val html = buildString {
appendJavadocElements(docComment.descriptionElements)
tagsLoop@
for (tag in docComment.tags) {
when (tag.name) {
"deprecated" -> continue@tagsLoop
"see" -> append("@see ${convertJavadocLink(tag.content())}\n")
else -> {
appendJavadocElements(tag.children)
if (!endsWithNewline()) append("\n")
}
}
}
}
if (html.trim().isEmpty() && docComment.findTagByName("deprecated") != null) {
// @deprecated was the only content of the doc comment; we can drop the comment
return ""
}
val htmlFile = PsiFileFactory.getInstance(docComment.project).createFileFromText(
"javadoc.html", HtmlFileType.INSTANCE, html
)
val htmlToMarkdownConverter = HtmlToMarkdownConverter()
htmlFile.accept(htmlToMarkdownConverter)
return htmlToMarkdownConverter.result
}
private fun StringBuilder.appendJavadocElements(elements: Array<PsiElement>): StringBuilder {
elements.forEach {
if (it is PsiInlineDocTag) {
append(convertInlineDocTag(it))
} else {
if (it.node?.elementType != JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) {
append(it.text)
}
}
}
return this
}
/**
* Returns true if the builder ends with a new-line optionally followed by some spaces
*/
private fun StringBuilder.endsWithNewline(): Boolean {
for (i in length - 1 downTo 0) {
val c = get(i)
if (c.isWhitespace()) {
if (c == '\n' || c == '\r') return true
} else {
return false
}
}
return false
}
private fun convertInlineDocTag(tag: PsiInlineDocTag) = when (tag.name) {
"code", "literal" -> {
val text = tag.dataElements.joinToString("") { it.text }
val escaped = StringUtil.escapeXml(text.trimStart())
if (tag.name == "code") "<code>$escaped</code>" else escaped
}
"link", "linkplain" -> {
val valueElement = tag.linkElement()
val labelText = tag.dataElements.firstOrNull { it is PsiDocToken }?.text ?: ""
val kdocLink = convertJavadocLink(valueElement?.text)
val linkText = if (labelText.isEmpty()) kdocLink else StringUtil.escapeXml(labelText)
"<a docref=\"$kdocLink\">$linkText</a>"
}
else -> tag.text
}
private fun convertJavadocLink(link: String?): String = link?.substringBefore('(')?.replace('#', '.') ?: ""
private fun PsiDocTag.linkElement(): PsiElement? = valueElement ?: dataElements.firstOrNull { it !is PsiWhiteSpace }
private fun XmlTag.attributesAsString() = if (attributes.isNotEmpty())
attributes.joinToString(separator = " ", prefix = " ") { it.text }
else
""
private class HtmlToMarkdownConverter() : XmlRecursiveElementVisitor() {
private enum class ListType { Ordered, Unordered; }
data class MarkdownSpan(val prefix: String, val suffix: String) {
companion object {
val Empty = MarkdownSpan("", "")
fun wrap(text: String) = MarkdownSpan(text, text)
fun prefix(text: String) = MarkdownSpan(text, "")
fun preserveTag(tag: XmlTag) =
MarkdownSpan("<${tag.name}${tag.attributesAsString()}>", "</${tag.name}>")
}
}
val result: String
get() = markdownBuilder.toString()
private val markdownBuilder = StringBuilder("/**")
private var afterLineBreak = false
private var whitespaceIsPartOfText = true
private var currentListType = ListType.Unordered
override fun visitWhiteSpace(space: PsiWhiteSpace) {
super.visitWhiteSpace(space)
if (whitespaceIsPartOfText) {
appendPendingText()
val lines = space.text.lines()
if (lines.size == 1) {
markdownBuilder.append(space.text)
} else {
//several lines of spaces:
//drop first line - it contains trailing spaces before the first new-line;
//do not add star for the last line, it is handled by appendPendingText()
//and it is not needed in the end of the comment
lines.drop(1).dropLast(1).forEach {
markdownBuilder.append("\n * ")
}
markdownBuilder.append("\n")
afterLineBreak = true
}
}
}
override fun visitElement(element: PsiElement) {
super.visitElement(element)
when (element.node.elementType) {
XmlTokenType.XML_DATA_CHARACTERS -> {
appendPendingText()
markdownBuilder.append(element.text)
}
XmlTokenType.XML_CHAR_ENTITY_REF -> {
appendPendingText()
val grandParent = element.parent.parent
if (grandParent is HtmlTag && (grandParent.name == "code" || grandParent.name == "literal"))
markdownBuilder.append(StringUtil.unescapeXml(element.text))
else
markdownBuilder.append(element.text)
}
}
}
override fun visitXmlTag(tag: XmlTag) {
withWhitespaceAsPartOfText(false) {
val oldListType = currentListType
val atLineStart = afterLineBreak
appendPendingText()
val (openingMarkdown, closingMarkdown) = getMarkdownForTag(tag, atLineStart)
markdownBuilder.append(openingMarkdown)
super.visitXmlTag(tag)
//appendPendingText()
markdownBuilder.append(closingMarkdown)
currentListType = oldListType
}
}
override fun visitXmlText(text: XmlText) {
withWhitespaceAsPartOfText(true) {
super.visitXmlText(text)
}
}
private inline fun withWhitespaceAsPartOfText(newValue: Boolean, block: () -> Unit) {
val oldValue = whitespaceIsPartOfText
whitespaceIsPartOfText = newValue
try {
block()
} finally {
whitespaceIsPartOfText = oldValue
}
}
private fun getMarkdownForTag(tag: XmlTag, atLineStart: Boolean): MarkdownSpan = when (tag.name) {
"b", "strong" -> MarkdownSpan.wrap("**")
"p" -> if (atLineStart) MarkdownSpan.prefix("\n * ") else MarkdownSpan.prefix("\n *\n *")
"i", "em" -> MarkdownSpan.wrap("*")
"s", "del" -> MarkdownSpan.wrap("~~")
"code" -> {
val innerText = tag.value.text.trim()
if (innerText.startsWith('`') && innerText.endsWith('`'))
MarkdownSpan("`` ", " ``")
else
MarkdownSpan.wrap("`")
}
"a" -> {
if (tag.getAttributeValue("docref") != null) {
val docRef = tag.getAttributeValue("docref")
val innerText = tag.value.text
if (docRef == innerText) MarkdownSpan("[", "]") else MarkdownSpan("[", "][$docRef]")
} else if (tag.getAttributeValue("href") != null) {
MarkdownSpan("[", "](${tag.getAttributeValue("href") ?: ""})")
} else {
MarkdownSpan.preserveTag(tag)
}
}
"ul" -> {
currentListType = ListType.Unordered; MarkdownSpan.Empty
}
"ol" -> {
currentListType = ListType.Ordered; MarkdownSpan.Empty
}
"li" -> if (currentListType == ListType.Unordered) MarkdownSpan.prefix(" * ") else MarkdownSpan.prefix(" 1. ")
else -> MarkdownSpan.preserveTag(tag)
}
private fun appendPendingText() {
if (afterLineBreak) {
markdownBuilder.append(" * ")
afterLineBreak = false
}
}
override fun visitXmlFile(file: XmlFile) {
super.visitXmlFile(file)
markdownBuilder.append(" */")
}
}
}
|
apache-2.0
|
89110c9fd96472dc6490697e71fe26f1
| 36.151751 | 158 | 0.548911 | 4.952282 | false | false | false | false |
afollestad/assent
|
core/src/main/java/com/afollestad/assent/Contexts.kt
|
1
|
3254
|
/**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.assent
import android.content.Context
import android.content.pm.PackageManager.PERMISSION_GRANTED
import androidx.annotation.CheckResult
import androidx.core.content.ContextCompat
import com.afollestad.assent.internal.Assent.Companion.get
import com.afollestad.assent.internal.PendingRequest
import com.afollestad.assent.internal.PermissionFragment
import com.afollestad.assent.internal.equalsPermissions
import com.afollestad.assent.internal.log
import com.afollestad.assent.rationale.RationaleHandler
import com.afollestad.assent.rationale.ShouldShowRationale
/** @return `true` if ALL given [permissions] have been granted. */
@CheckResult fun Context.isAllGranted(vararg permissions: Permission): Boolean {
return permissions.all {
ContextCompat.checkSelfPermission(
this,
it.value
) == PERMISSION_GRANTED
}
}
internal fun <T : Any> T.startPermissionRequest(
ensure: (T) -> PermissionFragment,
permissions: Array<out Permission>,
requestCode: Int = 20,
shouldShowRationale: ShouldShowRationale,
rationaleHandler: RationaleHandler? = null,
callback: Callback
) {
log("startPermissionRequest(%s)", permissions.joinToString())
// This invalidates the `shouldShowRationale` cache to help detect permanently denied early.
permissions.forEach { shouldShowRationale.check(it) }
if (rationaleHandler != null) {
rationaleHandler.requestPermissions(permissions, requestCode, callback)
return
}
val currentRequest: PendingRequest? = get().currentPendingRequest
if (currentRequest != null &&
currentRequest.permissions.equalsPermissions(*permissions)
) {
// Request matches permissions, append a callback
log(
"Callback appended to existing matching request for %s",
permissions.joinToString()
)
currentRequest.callbacks.add(callback)
return
}
// Create a new pending request since none exist for these permissions
val newPendingRequest = PendingRequest(
permissions = permissions.toSet(),
requestCode = requestCode,
callbacks = mutableListOf(callback)
)
if (currentRequest == null) {
// There is no active request so we can execute immediately
get().currentPendingRequest = newPendingRequest
log("New request, performing now")
ensure(this).perform(newPendingRequest)
} else {
// There is an active request, append this new one to the queue
if (currentRequest.requestCode == requestCode) {
newPendingRequest.requestCode = requestCode + 1
}
log("New request queued for when the current is complete")
get().requestQueue += newPendingRequest
}
}
|
apache-2.0
|
0c233d1961f20ca38a860b761c0c0827
| 35.155556 | 94 | 0.754763 | 4.589563 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OHUploadWorker.kt
|
1
|
2874
|
package info.nightscout.androidaps.plugins.general.openhumans
import android.app.Notification
import android.content.Context
import android.net.wifi.WifiManager
import androidx.core.app.NotificationCompat
import androidx.work.ForegroundInfo
import androidx.work.RxWorker
import androidx.work.WorkerParameters
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader.Companion.NOTIFICATION_CHANNEL
import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader.Companion.UPLOAD_NOTIFICATION_ID
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.Single
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class OHUploadWorker(context: Context, workerParameters: WorkerParameters)
: RxWorker(context, workerParameters) {
@Inject
lateinit var sp: SP
@Inject
lateinit var openHumansUploader: OpenHumansUploader
@Inject
lateinit var resourceHelper: ResourceHelper
override fun createWork(): Single<Result> = Single.defer {
// Here we inject every time we create work
// We could build our own WorkerFactory with dagger but this will create conflicts with other Workers
// (see https://medium.com/wonderquill/how-to-pass-custom-parameters-to-rxworker-worker-using-dagger-2-f4cfbc9892ba)
// This class will be replaced with new DB
(applicationContext as MainApp).androidInjector().inject(this)
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
val wifiOnly = sp.getBoolean("key_oh_wifi_only", true)
val isConnectedToWifi = wifiManager?.isWifiEnabled ?: false && wifiManager?.connectionInfo?.networkId != -1
if (!wifiOnly || (wifiOnly && isConnectedToWifi)) {
setForegroundAsync(createForegroundInfo())
openHumansUploader.uploadDataSegmentally()
.andThen(Single.just(Result.success()))
.onErrorResumeNext { Single.just(Result.retry()) }
} else {
Single.just(Result.retry())
}
}
private fun createForegroundInfo(): ForegroundInfo {
val title = resourceHelper.gs(info.nightscout.androidaps.R.string.open_humans)
val notification: Notification = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL)
.setContentTitle(title)
.setTicker(title)
.setContentText(resourceHelper.gs(info.nightscout.androidaps.R.string.your_phone_is_upload_data))
.setSmallIcon(info.nightscout.androidaps.R.drawable.notif_icon)
.setOngoing(true)
.setProgress(0, 0 , true)
.build()
return ForegroundInfo(UPLOAD_NOTIFICATION_ID, notification)
}
}
|
agpl-3.0
|
a21f3ba7f3bbf828418741154d30f911
| 41.910448 | 124 | 0.736256 | 4.688418 | false | false | false | false |
siosio/intellij-community
|
platform/credential-store/src/NativeCredentialStoreWrapper.kt
|
1
|
5970
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.credentialStore.keePass.InMemoryCredentialStore
import com.intellij.jna.JnaLoader
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.Conditions
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.concurrency.QueueProcessor
import org.jetbrains.annotations.TestOnly
import java.io.Closeable
import java.util.concurrent.TimeUnit
import java.util.function.BiConsumer
internal val NOTIFICATION_MANAGER by lazy { SingletonNotificationManager("Password Safe", NotificationType.ERROR) }
private val REMOVED_CREDENTIALS = Credentials("REMOVED_CREDENTIALS")
// used only for native keychains, not for KeePass, so `postponedCredentials` and others do not add any overhead when KeePass is used
private class NativeCredentialStoreWrapper(
private val store: CredentialStore,
private val queueProcessor: QueueProcessor<() -> Unit>
) : CredentialStore, Closeable {
constructor(store: CredentialStore): this(store, QueueProcessor<() -> Unit> { it() })
private val fallbackStore = lazy { InMemoryCredentialStore() }
private val postponedCredentials = InMemoryCredentialStore()
private val deniedItems = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<CredentialAttributes, Boolean>()
override fun get(attributes: CredentialAttributes): Credentials? {
postponedCredentials.get(attributes)?.let {
return if (it == REMOVED_CREDENTIALS) null else it
}
if (attributes.cacheDeniedItems && deniedItems.getIfPresent(attributes) != null) {
LOG.warn("User denied access to $attributes")
return ACCESS_TO_KEY_CHAIN_DENIED
}
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
val value = store.get(attributes)
if (attributes.cacheDeniedItems && value === ACCESS_TO_KEY_CHAIN_DENIED) {
deniedItems.put(attributes, true)
}
return value
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
return store.get(attributes)
}
catch (e: Throwable) {
LOG.error(e)
return null
}
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
if (fallbackStore.isInitialized()) {
fallbackStore.value.set(attributes, credentials)
return
}
val postponed = credentials ?: REMOVED_CREDENTIALS
postponedCredentials.set(attributes, postponed)
queueProcessor.add {
try {
var store = if (fallbackStore.isInitialized()) fallbackStore.value else store
try {
store.set(attributes, credentials)
}
catch (e: UnsatisfiedLinkError) {
store = fallbackStore.value
notifyUnsatisfiedLinkError(e)
store.set(attributes, credentials)
}
catch (e: Throwable) {
LOG.error(e)
}
}
catch (e: ProcessCanceledException) {
throw e
}
finally {
val currentPostponed = postponedCredentials.get(attributes)
if (postponed == currentPostponed) {
postponedCredentials.set(attributes, null)
}
}
}
}
override fun close() {
if (store is Closeable) {
queueProcessor.waitFor()
store.close()
}
}
}
private fun notifyUnsatisfiedLinkError(e: UnsatisfiedLinkError) {
LOG.error(e)
var message = CredentialStoreBundle.message("notification.content.native.keychain.unavailable",
ApplicationNamesInfo.getInstance().fullProductName)
if (SystemInfo.isLinux) {
message += "\n"
message += CredentialStoreBundle.message("notification.content.native.keychain.unavailable.linux.addition")
}
NOTIFICATION_MANAGER.notify(CredentialStoreBundle.message("notification.title.native.keychain.unavailable"), message, null)
}
private class MacOsCredentialStoreFactory : CredentialStoreFactory {
override fun create(): CredentialStore? = when {
isMacOsCredentialStoreSupported && JnaLoader.isLoaded() -> NativeCredentialStoreWrapper(KeyChainCredentialStore())
else -> null
}
}
private class LinuxCredentialStoreFactory : CredentialStoreFactory {
override fun create(): CredentialStore? = when {
SystemInfo.isLinux -> {
@Suppress("SpellCheckingInspection") val preferWallet = Registry.`is`("credentialStore.linux.prefer.kwallet", false)
var res: CredentialStore? = if (preferWallet)
KWalletCredentialStore.create()
else
null
if (res == null && JnaLoader.isLoaded()) {
try {
res = SecretCredentialStore.create("com.intellij.credentialStore.Credential")
}
catch (e: UnsatisfiedLinkError) {
res = if (!preferWallet) KWalletCredentialStore.create() else null
if (res == null) notifyUnsatisfiedLinkError(e)
}
}
if (res == null && !preferWallet) res = KWalletCredentialStore.create()
res?.let { NativeCredentialStoreWrapper(it) }
}
else -> null
}
}
@TestOnly
fun wrappedInMemory(): CredentialStore = NativeCredentialStoreWrapper(InMemoryCredentialStore(), QueueProcessor<() -> Unit>(
BiConsumer { item, continuation ->
try {
QueueProcessor.runSafely(item)
}
finally {
continuation.run()
}
}, true, QueueProcessor.ThreadToUse.AWT, Conditions.alwaysFalse<Any>()))
|
apache-2.0
|
462c372472a8da305406af250ac26e77
| 35.402439 | 158 | 0.71608 | 4.71564 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinMemberInplaceRenameHandler.kt
|
3
|
3803
|
// 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.refactoring.rename
import com.intellij.lang.Language
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.rename.inplace.MemberInplaceRenameHandler
import com.intellij.refactoring.rename.inplace.MemberInplaceRenamer
import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer
import org.jetbrains.kotlin.idea.core.unquote
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
class KotlinMemberInplaceRenameHandler : MemberInplaceRenameHandler() {
private class RenamerImpl(
elementToRename: PsiNamedElement,
substitutedElement: PsiElement?,
editor: Editor,
currentName: String,
oldName: String
) : MemberInplaceRenamer(elementToRename, substitutedElement, editor, currentName, oldName) {
override fun isIdentifier(newName: String?, language: Language?): Boolean {
if (newName == "" && (variable as? KtObjectDeclaration)?.isCompanion() == true) return true
return super.isIdentifier(newName, language)
}
override fun acceptReference(reference: PsiReference): Boolean {
val refElement = reference.element
val textRange = reference.rangeInElement
val referenceText = refElement.text.substring(textRange.startOffset, textRange.endOffset).unquote()
return referenceText == myElementToRename.name
}
override fun startsOnTheSameElement(handler: RefactoringActionHandler?, element: PsiElement?): Boolean {
return variable == element && (handler is MemberInplaceRenameHandler || handler is KotlinRenameDispatcherHandler)
}
override fun createInplaceRenamerToRestart(variable: PsiNamedElement, editor: Editor, initialName: String): VariableInplaceRenamer {
return RenamerImpl(variable, substituted, editor, initialName, myOldName)
}
}
private fun PsiElement.substitute(): PsiElement {
if (this is KtPrimaryConstructor) return getContainingClassOrObject()
return this
}
override fun createMemberRenamer(element: PsiElement, elementToRename: PsiNameIdentifierOwner, editor: Editor): MemberInplaceRenamer {
val currentElementToRename = elementToRename.substitute() as PsiNameIdentifierOwner
val nameIdentifier = currentElementToRename.nameIdentifier
// Move caret if constructor range doesn't intersect with the one of the containing class
val offset = editor.caretModel.offset
val editorPsiFile = PsiDocumentManager.getInstance(element.project).getPsiFile(editor.document)
if (nameIdentifier != null && editorPsiFile == elementToRename.containingFile && elementToRename is KtPrimaryConstructor && offset !in nameIdentifier.textRange && offset in elementToRename.textRange) {
editor.caretModel.moveToOffset(nameIdentifier.textOffset)
}
val currentName = nameIdentifier?.text ?: ""
return RenamerImpl(currentElementToRename, element, editor, currentName, currentName)
}
override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile): Boolean {
if (!editor.settings.isVariableInplaceRenameEnabled) return false
val currentElement = element?.substitute() as? KtNamedDeclaration ?: return false
return currentElement.nameIdentifier != null && !KotlinVariableInplaceRenameHandler.isInplaceRenameAvailable(currentElement)
}
}
|
apache-2.0
|
c555fda83a5652b36b5df337c6e76646
| 52.56338 | 209 | 0.751249 | 5.592647 | false | false | false | false |
DmytroTroynikov/aemtools
|
aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/common/FileVariablesResolver.kt
|
1
|
3233
|
package com.aemtools.completion.htl.common
import com.aemtools.codeinsight.htl.model.HtlVariableDeclaration
import com.aemtools.codeinsight.htl.util.extractDeclarations
import com.aemtools.codeinsight.htl.util.filterForPosition
import com.aemtools.common.util.findChildrenByType
import com.aemtools.common.util.getHtmlFile
import com.aemtools.lang.util.getHtlFile
import com.aemtools.lang.util.htlAttributes
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.lang.StdLanguages
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.xml.XmlAttribute
/**
* Resolves variables declared within htl (html) file.
*
* @author Dmytro Troynikov
*/
object FileVariablesResolver {
/**
* Find declaration of variable in file.
* @param variableName the name of variable
* @param element the element
* @return the declaration element
*/
fun findDeclaration(variableName: String,
element: PsiElement): HtlVariableDeclaration? {
val htmlFile = element.containingFile.getHtmlFile() ?: return null
val xmlAttributes = htmlFile.findChildrenByType(XmlAttribute::class.java)
.toList()
val elements = xmlAttributes.htlAttributes()
val result = elements.extractDeclarations()
.filterForPosition(element)
.find { it.variableName == variableName }
return result
}
/**
* Check if given variable is valid in given position.
*
* @param variableName variable name
* @param position position to start variable lookup
* @return *true* if variable with given name is valid in given context
*/
fun validVariable(variableName: String,
position: PsiElement): Boolean =
findDeclaration(variableName, position) != null
/**
* Collect [HtlVariableDeclaration] objects suitable for given position.
* @param position location against which variables should be filtered
* @param completionParameters the completion parameters
* @return list of htl variable declarations
*/
fun declarationsForPosition(position: PsiElement, completionParameters: CompletionParameters)
: List<HtlVariableDeclaration> {
val htlFile = completionParameters.originalFile
val htmlFile = htlFile.viewProvider.getPsi(StdLanguages.HTML)
val attributes: List<XmlAttribute> = PsiTreeUtil.findChildrenOfType(htmlFile, XmlAttribute::class.java)
.toList()
return attributes.extractDeclarations()
.filterForPosition(position).toList()
}
/**
* Collect [HtlVariableDeclaration] object suitable for given position.
* @param position location against which variables should be filtered
* @return list of htl variable declarations
*/
fun declarationsForPosition(position: PsiElement): List<HtlVariableDeclaration> {
val htlFile = position.containingFile.originalFile.getHtlFile()
?: return emptyList()
val htmlFile = htlFile.getHtmlFile()
?: return emptyList()
val attributes: List<XmlAttribute> = PsiTreeUtil.findChildrenOfType(htmlFile, XmlAttribute::class.java)
.toList()
return attributes.extractDeclarations()
.filterForPosition(position).toList()
}
}
|
gpl-3.0
|
7911531b18a1152b03155bb590ebbdaa
| 34.527473 | 107 | 0.745747 | 4.83982 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ParentChainEntityImpl.kt
|
2
|
7678
|
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneChildOfParent
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ParentChainEntityImpl(val dataSource: ParentChainEntityData) : ParentChainEntity, WorkspaceEntityBase() {
companion object {
internal val ROOT_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentChainEntity::class.java, CompositeAbstractEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
val connections = listOf<ConnectionId>(
ROOT_CONNECTION_ID,
)
}
override val root: CompositeAbstractEntity?
get() = snapshot.extractOneToAbstractOneChild(ROOT_CONNECTION_ID, this)
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ParentChainEntityData?) : ModifiableWorkspaceEntityBase<ParentChainEntity, ParentChainEntityData>(
result), ParentChainEntity.Builder {
constructor() : this(ParentChainEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ParentChainEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ParentChainEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var root: CompositeAbstractEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneChild(ROOT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
ROOT_CONNECTION_ID)] as? CompositeAbstractEntity
}
else {
this.entityLinks[EntityLink(true, ROOT_CONNECTION_ID)] as? CompositeAbstractEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, ROOT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToAbstractOneChildOfParent(ROOT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, ROOT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, ROOT_CONNECTION_ID)] = value
}
changedProperty.add("root")
}
override fun getEntityClass(): Class<ParentChainEntity> = ParentChainEntity::class.java
}
}
class ParentChainEntityData : WorkspaceEntityData<ParentChainEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ParentChainEntity> {
val modifiable = ParentChainEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ParentChainEntity {
return getCached(snapshot) {
val entity = ParentChainEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ParentChainEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ParentChainEntity(entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ParentChainEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ParentChainEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
|
apache-2.0
|
6c343fa6706d76722aeeff964ccaa7ad
| 34.546296 | 150 | 0.707085 | 5.240956 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/FacetModelBridgeTest.kt
|
1
|
8450
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide
import com.intellij.facet.FacetManager
import com.intellij.facet.impl.FacetUtil
import com.intellij.facet.mock.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.UsefulTestCase.assertOneElement
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.testFramework.workspaceModel.updateProjectModel
import com.intellij.workspaceModel.ide.impl.WorkspaceModelInitialTestContent
import com.intellij.workspaceModel.ide.impl.jps.serialization.toConfigLocation
import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetManagerBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.ModifiableFacetModelBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.FacetEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addFacetEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addModuleEntity
import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity
import com.intellij.workspaceModel.storage.toBuilder
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import junit.framework.AssertionFailedError
import org.junit.Assert.*
import org.junit.Before
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
class FacetModelBridgeTest {
companion object {
@ClassRule
@JvmField
val application = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule()
@Rule
@JvmField
val disposableRule = DisposableRule()
private val virtualFileManager: VirtualFileUrlManager
get() = VirtualFileUrlManager.getInstance(projectModel.project)
@Before
fun registerFacetType() {
ProjectLoadingErrorsHeadlessNotifier.setErrorHandler(disposableRule.disposable) {}
registerFacetType(MockFacetType(), disposableRule.disposable)
registerFacetType(AnotherMockFacetType(), disposableRule.disposable)
}
@Test
fun `test changed facet config saved correctly`() {
val facetData = "mock"
val module = projectModel.createModule()
val facet = MockFacet(module, facetData)
val facetManager = FacetManager.getInstance(module)
facetManager.createModifiableModel().let { modifiableModel ->
modifiableModel.addFacet(facet)
assertTrue(facet.configuration.data.isEmpty())
facet.configuration.data = facetData
runWriteActionAndWait { modifiableModel.commit() }
}
val facetConfigXml = FacetUtil.saveFacetConfiguration(facet)?.let { JDOMUtil.write(it) }
val facetByType = facetManager.getFacetByType(MockFacetType.ID)
assertNotNull(facetByType)
assertEquals(facetData, facetByType!!.configuration.data)
val entityStorage = WorkspaceModel.getInstance(projectModel.project).entityStorage
val facetEntity = entityStorage.current.entities(FacetEntity::class.java).first()
assertEquals(facetConfigXml, facetEntity.configurationXmlTag)
facetManager.createModifiableModel().let { modifiableModel ->
modifiableModel as ModifiableFacetModelBridgeImpl
assertEquals(facetConfigXml, modifiableModel.getEntity(facet)!!.configurationXmlTag)
}
}
@Test
fun `facet with caching`() {
val builder = MutableEntityStorage.create()
val baseDir = projectModel.baseProjectDir.rootPath.resolve("test")
val iprFile = baseDir.resolve("testProject.ipr")
val configLocation = toConfigLocation(iprFile, virtualFileManager)
val source = JpsFileEntitySource.FileInDirectory(configLocation.baseDirectoryUrl, configLocation)
val moduleEntity = builder.addModuleEntity(name = "test", dependencies = emptyList(), source = source)
builder.addFacetEntity("MyFacet", "MockFacetId", """<configuration data="foo" />""", moduleEntity,
null, source)
WorkspaceModelInitialTestContent.withInitialContent(builder.toSnapshot()) {
val project = PlatformTestUtil.loadAndOpenProject(iprFile, disposableRule.disposable)
Disposer.register(disposableRule.disposable, Disposable {
PlatformTestUtil.forceCloseProjectWithoutSaving(project)
})
val module = ModuleManager.getInstance(project).findModuleByName("test") ?: throw AssertionFailedError("Module wasn't loaded")
val facets = FacetManager.getInstance(module).allFacets
val facet = assertOneElement(facets) as MockFacet
assertEquals("MyFacet", facet.name)
assertEquals("foo", facet.configuration.data)
assertTrue(facet.isInitialized)
}
}
@Test
fun `facet config immutable collections deserialization`() {
val builder = MutableEntityStorage.create()
val baseDir = projectModel.baseProjectDir.rootPath.resolve("test")
val iprFile = baseDir.resolve("testProject.ipr")
val configLocation = toConfigLocation(iprFile, virtualFileManager)
val source = JpsFileEntitySource.FileInDirectory(configLocation.baseDirectoryUrl, configLocation)
val moduleEntity = builder.addModuleEntity(name = "test", dependencies = emptyList(), source = source)
builder.addFacetEntity("AnotherMockFacet", "AnotherMockFacetId", """
<AnotherFacetConfigProperties>
<firstElement>
<field>Android</field>
</firstElement>
<secondElement>
<field>Spring</field>
</secondElement>
</AnotherFacetConfigProperties>""", moduleEntity, null, source)
WorkspaceModelInitialTestContent.withInitialContent(builder.toSnapshot()) {
val project = PlatformTestUtil.loadAndOpenProject(iprFile, disposableRule.disposable)
Disposer.register(disposableRule.disposable, Disposable {
PlatformTestUtil.forceCloseProjectWithoutSaving(project)
})
val module = ModuleManager.getInstance(project).findModuleByName("test") ?: throw AssertionFailedError("Module wasn't loaded")
val facets = FacetManager.getInstance(module).allFacets
val facet = assertOneElement(facets) as AnotherMockFacet
assertEquals("AnotherMockFacet", facet.name)
val configProperties = facet.configuration.myProperties
assertEquals("Android", configProperties.firstElement[0])
assertEquals("Spring", configProperties.secondElement[0])
assertTrue(facet.isInitialized)
}
}
@Test
fun `update facet configuration via entity`() {
val module = projectModel.createModule()
val facet = projectModel.addFacet(module, MockFacetType.getInstance(), MockFacetConfiguration("foo"))
assertEquals("foo", facet.configuration.data)
runWriteActionAndWait {
WorkspaceModel.getInstance(projectModel.project).updateProjectModel { builder ->
val facetEntity = builder.entities(FacetEntity::class.java).single()
builder.modifyEntity(facetEntity) {
configurationXmlTag = """<configuration data="bar" />"""
}
}
}
assertEquals("bar", facet.configuration.data)
}
@Test
fun `getting module facets after module rename`() {
val module = projectModel.createModule()
val facet = projectModel.addFacet(module, MockFacetType.getInstance(), MockFacetConfiguration("foo"))
val diff = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.toBuilder()
val modifiableModuleModel = (ModuleManager.getInstance(projectModel.project) as ModuleManagerBridgeImpl).getModifiableModel(diff)
val modifiableFacetModel = (FacetManager.getInstance(module) as FacetManagerBridge).createModifiableModel(diff)
var existingFacet = assertOneElement(modifiableFacetModel.allFacets)
assertEquals(facet.name, existingFacet.name)
modifiableModuleModel.renameModule(module, "newModuleName")
existingFacet = assertOneElement(modifiableFacetModel.allFacets)
assertEquals(facet.name, existingFacet.name)
}
}
|
apache-2.0
|
e04c72de86ef72d7cca3951a9bfc77bf
| 43.708995 | 140 | 0.77858 | 5.261519 | false | true | false | false |
jwren/intellij-community
|
plugins/git4idea/src/git4idea/actions/branch/GitSingleBranchAction.kt
|
2
|
2591
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.actions.branch
import com.intellij.dvcs.DvcsUtil
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsActions
import git4idea.GitBranch
import git4idea.repo.GitRepository
import java.util.function.Supplier
abstract class GitSingleBranchAction(dynamicText: Supplier<@NlsActions.ActionText String>) : DumbAwareAction(dynamicText) {
constructor() : this(Presentation.NULL_STRING)
open val disabledForLocal: Boolean = false
open val disabledForRemote: Boolean = false
open val disabledForCurrent: Boolean = false
final override fun update(e: AnActionEvent) {
val project = e.project
val repositories = e.getData(GitBranchActionsUtil.REPOSITORIES_KEY)
val branches = e.getData(GitBranchActionsUtil.BRANCHES_KEY)
e.presentation.isEnabledAndVisible = isEnabledAndVisible(project, repositories, branches)
//TODO: check and i18n
DvcsUtil.disableActionIfAnyRepositoryIsFresh(e, repositories.orEmpty(), "Action")
if (e.presentation.isEnabledAndVisible) {
updateIfEnabledAndVisible(e, project!!, repositories!!, branches!!.single())
}
}
private fun isEnabledAndVisible(project: Project?, repositories: List<GitRepository>?, branches: List<GitBranch>?): Boolean {
if (project == null) return false
if (repositories.isNullOrEmpty()) return false
if (branches.isNullOrEmpty()) return false
if (branches.size != 1) return false
val branch = branches.single()
if (disabledForLocal) {
if (!branch.isRemote) return false
}
if (disabledForRemote) {
if (branch.isRemote) return false
}
if (disabledForCurrent) {
if (repositories.any { it.currentBranch == branch }) return false
}
return true
}
open fun updateIfEnabledAndVisible(e: AnActionEvent, project: Project, repositories: List<GitRepository>, branch: GitBranch) {}
final override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val repositories = e.getRequiredData(GitBranchActionsUtil.REPOSITORIES_KEY)
val branch = e.getRequiredData(GitBranchActionsUtil.BRANCHES_KEY).single()
actionPerformed(e, project, repositories, branch)
}
abstract fun actionPerformed(e: AnActionEvent, project: Project, repositories: List<GitRepository>, branch: GitBranch)
}
|
apache-2.0
|
fa55d633648683cf1617207b3f669c71
| 36.565217 | 129 | 0.760324 | 4.626786 | false | false | false | false |
loxal/FreeEthereum
|
free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/suite/validators/OutputValidator.kt
|
1
|
2241
|
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.jsontestsuite.suite.validators
import org.spongycastle.util.encoders.Hex
import java.util.ArrayList
import org.ethereum.jsontestsuite.suite.Utils.parseData
object OutputValidator {
fun valid(origOutput: String, postOutput: String): List<String> {
val results = ArrayList<String>()
if (postOutput.startsWith("#")) {
val postLen = Integer.parseInt(postOutput.substring(1))
if (postLen != origOutput.length / 2) {
results.add("Expected output length: " + postLen + ", actual: " + origOutput.length / 2)
}
} else {
val postOutputFormated = Hex.toHexString(parseData(postOutput))
if (origOutput != postOutputFormated) {
val formattedString = String.format("HReturn: wrong expected: %s, current: %s",
postOutputFormated, origOutput)
results.add(formattedString)
}
}
return results
}
}
|
mit
|
c2580466f2ad52bb9df94e77ae389de2
| 36.983051 | 104 | 0.690317 | 4.376953 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddEqEqTrueFix.kt
|
3
|
1071
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
class AddEqEqTrueFix(expression: KtExpression) : KotlinQuickFixAction<KtExpression>(expression) {
override fun getText() = KotlinBundle.message("fix.add.eq.eq.true")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val expression = element ?: return
expression.replace(KtPsiFactory(expression).createExpressionByPattern("$0 == true", expression))
}
}
|
apache-2.0
|
e2d9461daba15151f557d26d47a3f4e4
| 45.565217 | 158 | 0.792717 | 4.353659 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/multiplatform/smartCastOnPropertyFromDependentModule/jvm2/jvm2.kt
|
12
|
615
|
fun test(c1: CommonDataClass1, c2: CommonDataClass2, c3: CommonDataClass3, c4: CommonDataClass4, jvm: JvmDataClass) {
if (c1.property != null) {
<!DEBUG_INFO_SMARTCAST!>c1.property<!>.doSomething()
}
if (c2.property != null) {
<!DEBUG_INFO_SMARTCAST!>c2.property<!>.doSomething()
}
if (c3.property != null) {
<!DEBUG_INFO_SMARTCAST!>c3.property<!>.doSomething()
}
if (c4.property != null) {
<!DEBUG_INFO_SMARTCAST!>c4.property<!>.doSomething()
}
if (jvm.property != null) {
<!SMARTCAST_IMPOSSIBLE!>jvm.property<!>.doSomething()
}
}
|
apache-2.0
|
14d258ba81bb3776ad1969c5f10f6083
| 28.333333 | 117 | 0.604878 | 3.379121 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/slicer/inflow/dataClassCopy.kt
|
13
|
325
|
// FLOW: IN
data class DataClass(val value1: Int, val value2: Int)
fun foo(dataClass: DataClass) {
val <caret>v = dataClass.value1
}
fun bar() {
val dataClass = DataClass(1, 2)
foo(dataClass)
foo(dataClass.copy(value1 = 10))
foo(dataClass.copy(value2 = 11))
foo(DataClass(value1 = 1, value2 = 2))
}
|
apache-2.0
|
d98ab7a3f2d56a3a64d9e60ad63351a6
| 20.733333 | 54 | 0.649231 | 3.037383 | false | false | false | false |
TimePath/launcher
|
src/main/kotlin/com/timepath/launcher/LauncherUtils.kt
|
1
|
1792
|
package com.timepath.launcher
import com.timepath.Utils
import com.timepath.util.logging.DBInbox
import java.io.File
import java.io.IOException
import java.lang.management.ManagementFactory
import java.text.MessageFormat
import java.util.prefs.Preferences
public object LauncherUtils {
public val USER: String = MessageFormat.format("{0}@{1}",
System.getProperty("user.name"), ManagementFactory.getRuntimeMXBean().getName().splitBy("@")[1])
private fun initVersion(): Long {
val impl = javaClass<LauncherUtils>().getPackage().getSpecificationVersion()
if (impl != null) {
try {
return java.lang.Long.parseLong(impl)
} catch (ignored: NumberFormatException) {
}
}
return 0
}
public val CURRENT_VERSION: Long = initVersion()
public val DEBUG: Boolean = CURRENT_VERSION == 0L
public val SETTINGS: Preferences = Preferences.userRoot().node("timepath")
public val START_TIME: Long = ManagementFactory.getRuntimeMXBean().getStartTime()
public val UPDATE: File = File("update.tmp")
public val CURRENT_FILE: File = Utils.currentFile(javaClass<LauncherUtils>())
public val WORK_DIR: File = CURRENT_FILE.getParentFile()
public fun log(name: String, dir: String, o: Any) {
logThread(name, dir, o.toString()).start()
}
public fun logThread(fileName: String, directory: String, str: String): Thread = object : Thread() {
override fun run() {
fun debug(o: Any) = System.out.println(o)
try {
debug("Response: ${DBInbox.send("dbinbox.timepath.ddns.info", "timepath", fileName, directory, str)}")
} catch (ioe: IOException) {
debug(ioe)
}
}
}
}
|
artistic-2.0
|
7cf514ded576815ab14d80ed77a9eec9
| 34.84 | 118 | 0.644531 | 4.349515 | false | false | false | false |
NlRVANA/Unity
|
app/src/main/java/com/zwq65/unity/utils/AppConstants.kt
|
1
|
962
|
/*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.utils
/**
* ================================================
*
* Created by NIRVANA on 2017/09/29
* Contact with <[email protected]>
* ================================================
*/
object AppConstants {
const val DB_NAME = "unity.db"
const val PREF_NAME = "unity_pref"
}
|
apache-2.0
|
1632585801e311a6f73a2acb04c95590
| 32.206897 | 78 | 0.619543 | 4.164502 | false | false | false | false |
DuckDeck/AndroidDemo
|
app/src/main/java/stan/androiddemo/project/Mito/DynamicMitoActivity.kt
|
1
|
1313
|
package stan.androiddemo.project.Mito
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_mito.*
import stan.androiddemo.PageAdapter
import stan.androiddemo.R
class DynamicMitoActivity : AppCompatActivity() {
lateinit var mAdapter: PageAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dynamic_mito)
setSupportActionBar(toolbar)
toolbar.setNavigationOnClickListener { onBackPressed() }
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val titles = arrayListOf("全部", "娱乐明星","网络红人","歌曲舞蹈","影视大全","动漫卡通","游戏天地","动物萌宠","风景名胜","天生尤物","其他视频")
val fragments = arrayListOf<DynamicMitoFragment>()
for (i in 0 until titles.size){
val fra = DynamicMitoFragment.createFragment()
val bundle = Bundle()
bundle.putString("cat",titles[i])
fra.arguments = bundle
fragments.add(fra)
}
mAdapter = PageAdapter(supportFragmentManager,fragments,titles)
viewPager.adapter = mAdapter
tabLayout.setupWithViewPager(viewPager)
}
}
|
mit
|
7f5e655047682797beec956d461e6319
| 32.216216 | 109 | 0.69406 | 4.208904 | false | false | false | false |
hsz/idea-gitignore
|
src/main/kotlin/mobi/hsz/idea/gitignore/util/Properties.kt
|
1
|
2402
|
// 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 mobi.hsz.idea.gitignore.util
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.NonNls
/**
* [Properties] util class that holds project specified settings using [PropertiesComponent].
*/
object Properties {
/** Ignore missing gitignore property key. */
@NonNls
private val IGNORE_MISSING_GITIGNORE = "ignore_missing_gitignore"
/** Dismissed ignored editing notification key. */
@NonNls
private val DISMISSED_IGNORED_EDITING_NOTIFICATION = "add_unversioned_files"
/**
* Checks value of [.IGNORE_MISSING_GITIGNORE] key in [PropertiesComponent].
*
* @param project current project
* @return [.IGNORE_MISSING_GITIGNORE] value
*/
fun isIgnoreMissingGitignore(project: Project) = project.service<PropertiesComponent>()
.getBoolean(IGNORE_MISSING_GITIGNORE, false)
/**
* Sets value of [.IGNORE_MISSING_GITIGNORE] key in [PropertiesComponent] to `true`.
*
* @param project current project
*/
fun setIgnoreMissingGitignore(project: Project) = project.service<PropertiesComponent>()
.setValue(IGNORE_MISSING_GITIGNORE, true)
/**
* Checks if user already dismissed notification about editing ignored file.
*
* @param project current project
* @param file current file
* @return notification was dismissed
*/
fun isDismissedIgnoredEditingNotification(project: Project, file: VirtualFile) = project.service<PropertiesComponent>()
.getValues(DISMISSED_IGNORED_EDITING_NOTIFICATION)?.contains(file.canonicalPath) ?: false
/**
* Stores information about dismissed notification about editing ignored file.
*
* @param project current project
* @param file current file
*/
fun setDismissedIgnoredEditingNotification(project: Project, file: VirtualFile) {
project.service<PropertiesComponent>().run {
val values = getValues(DISMISSED_IGNORED_EDITING_NOTIFICATION) ?: emptyArray()
setValues(DISMISSED_IGNORED_EDITING_NOTIFICATION, values + file.canonicalPath)
}
}
}
|
mit
|
fcd526ac4be86bffb5c0a679dde81d08
| 37.741935 | 140 | 0.714821 | 4.747036 | false | false | false | false |
chiken88/passnotes
|
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/core/viewmodel/GroupCellViewModel.kt
|
1
|
1734
|
package com.ivanovsky.passnotes.presentation.core.viewmodel
import com.ivanovsky.passnotes.R
import com.ivanovsky.passnotes.domain.ResourceProvider
import com.ivanovsky.passnotes.presentation.core.BaseCellViewModel
import com.ivanovsky.passnotes.presentation.core.event.Event.Companion.toEvent
import com.ivanovsky.passnotes.presentation.core.event.EventProvider
import com.ivanovsky.passnotes.presentation.core.model.GroupCellModel
class GroupCellViewModel(
override val model: GroupCellModel,
private val eventProvider: EventProvider,
private val resourceProvider: ResourceProvider
) : BaseCellViewModel(model) {
val title = model.group.title ?: ""
val description = formatCountsForGroup(model.noteCount, model.childGroupCount)
fun onClicked() {
eventProvider.send((CLICK_EVENT to model.id).toEvent())
}
fun onLongClicked() {
eventProvider.send((LONG_CLICK_EVENT to model.id).toEvent())
}
private fun formatCountsForGroup(noteCount: Int, childGroupCount: Int): String {
return if (noteCount == 0 && childGroupCount == 0) {
""
} else if (noteCount > 0 && childGroupCount == 0) {
resourceProvider.getString(R.string.notes_with_count, noteCount)
} else if (noteCount == 0 && childGroupCount > 0) {
resourceProvider.getString(R.string.groups_with_count, childGroupCount)
} else {
resourceProvider.getString(R.string.groups_and_notes_with_count, childGroupCount, noteCount)
}
}
companion object {
val CLICK_EVENT = GroupCellViewModel::class.qualifiedName + "_clickEvent"
val LONG_CLICK_EVENT = GroupCellViewModel::class.qualifiedName + "_longClickEvent"
}
}
|
gpl-2.0
|
8c4d01170b72c09d5a53650604de4c58
| 38.431818 | 104 | 0.7203 | 4.32419 | false | false | false | false |
quran/quran_android
|
app/src/test/java/com/quran/labs/androidquran/util/AudioUtilsTest.kt
|
2
|
3315
|
package com.quran.labs.androidquran.util
import com.google.common.truth.Truth.assertThat
import com.quran.data.core.QuranInfo
import com.quran.data.model.SuraAyah
import com.quran.data.pageinfo.common.MadaniDataSource
import com.quran.data.source.PageProvider
import com.quran.labs.androidquran.common.audio.util.QariUtil
import org.junit.Assert
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.`when` as whenever
class AudioUtilsTest {
@Test
fun testGetLastAyahWithNewSurahOnNextPageForMadani() {
val pageProviderMock = Mockito.mock(PageProvider::class.java)
whenever(pageProviderMock.getDataSource())
.thenReturn(MadaniDataSource())
val quranInfo = QuranInfo(MadaniDataSource())
val audioUtils =
AudioUtils(
quranInfo,
Mockito.mock(QuranFileUtils::class.java),
Mockito.mock(QariUtil::class.java)
)
// mode 1 is PAGE
val lastAyah = audioUtils.getLastAyahToPlay(
SuraAyah(sura = 109, ayah = 1),
currentPage = 603,
mode = 1,
isDualPageVisible = false
)
Assert.assertNotNull(lastAyah)
Assert.assertEquals(5, lastAyah!!.ayah.toLong())
Assert.assertEquals(111, lastAyah.sura.toLong())
}
@Test
fun testGetLastAyahWhenPlayingWithSuraBounds() {
val pageProviderMock = Mockito.mock(PageProvider::class.java)
whenever(pageProviderMock.getDataSource())
.thenReturn(MadaniDataSource())
val quranInfo = QuranInfo(MadaniDataSource())
val audioUtils =
AudioUtils(
quranInfo,
Mockito.mock(QuranFileUtils::class.java),
Mockito.mock(QariUtil::class.java)
)
// mode 2 is SURA
val lastAyah = audioUtils.getLastAyahToPlay(SuraAyah(2, 6), 3, 2, false)
Assert.assertNotNull(lastAyah)
Assert.assertEquals(286, lastAyah!!.ayah.toLong())
Assert.assertEquals(2, lastAyah.sura.toLong())
}
@Test
fun testSuraTawbaDoesNotNeedBasmallah() {
val quranInfo = QuranInfo(MadaniDataSource())
val audioUtils =
AudioUtils(
quranInfo,
Mockito.mock(QuranFileUtils::class.java),
Mockito.mock(QariUtil::class.java)
)
// start after ayah 1 of sura anfal
val start = SuraAyah(8, 2)
// finish in sura tawbah, so no basmallah needed here
val ending = SuraAyah(9, 100)
// overall don't need a basmallah
Assert.assertFalse(audioUtils.doesRequireBasmallah(start, ending))
}
@Test
fun testNeedBasmallahAcrossRange() {
val quranInfo = QuranInfo(MadaniDataSource())
val audioUtils =
AudioUtils(
quranInfo,
Mockito.mock(QuranFileUtils::class.java),
Mockito.mock(QariUtil::class.java)
)
val start = SuraAyah(8, 1)
val ending = SuraAyah(10, 2)
// should need a basmallah due to 10:1
Assert.assertTrue(audioUtils.doesRequireBasmallah(start, ending))
}
@Test
fun testLastAyahForFirstAyahWithPageDownload() {
val audioUtils = AudioUtils(
QuranInfo(MadaniDataSource()),
Mockito.mock(QuranFileUtils::class.java),
Mockito.mock(QariUtil::class.java)
)
val start = SuraAyah(56, 51)
val end = audioUtils.getLastAyahToPlay(
start,
currentPage = 536,
mode = 1,
isDualPageVisible = false
)
assertThat(end).isEqualTo(SuraAyah(56, 76))
}
}
|
gpl-3.0
|
dddb59f24d275a0136ae370eca29f7e6
| 29.412844 | 76 | 0.694721 | 3.886284 | false | true | false | false |
SDILogin/RouteTracker
|
app/src/main/java/me/sdidev/simpleroutetracker/db/DbPosition.kt
|
1
|
687
|
package me.sdidev.simpleroutetracker.db
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
import me.sdidev.simpleroutetracker.core.Position
import me.sdidev.simpleroutetracker.util.DbUtil
@DatabaseTable(tableName = "position")
class DbPosition constructor() {
@DatabaseField(id = true, canBeNull = false)
lateinit var latLngKey: String
@DatabaseField
var latitude: Double = 0.0
@DatabaseField
var longitude: Double = 0.0
constructor(position: Position) : this() {
latLngKey = DbUtil.createCompositeKeyForPosition(position)
latitude = position.latitude
longitude = position.longitude
}
}
|
mit
|
e7999f463a4d10c1294603713d00867c
| 26.48 | 66 | 0.742358 | 4.163636 | false | false | false | false |
oversecio/oversec_crypto
|
crypto/src/main/java/io/oversec/one/crypto/Issues.kt
|
1
|
3647
|
package io.oversec.one.crypto
import java.util.*
object Issues {
private val PACKAGES_WITH_ISSUES = HashSet<String>()
private val PACKAGES_WITH_SERIOUS_ISSUES = HashSet<String>()
private val PACKAGES_WHERE_INVISIBLE_ENCODING_DOESNT_WORK = HashSet<String>()
private val PACKAGES_WITH_LIMITED_INPUT_FIELDS = HashMap<String, Int>()
private val PACKAGES_THAT_NEED_TO_SCRAPE_NON_IMPORTANT_VIEWS = HashSet<String>()
val packagesThatNeedIncludeNonImportantViews: Collection<String>
get() = PACKAGES_THAT_NEED_TO_SCRAPE_NON_IMPORTANT_VIEWS
private val PACKAGES_THAT_NEED_COMPOSE_BUTTON = HashSet<String>()
val packagesThatNeedComposeButton: Collection<String>
get() = PACKAGES_THAT_NEED_COMPOSE_BUTTON
private val PACKAGES_THAT_NEED_SPREAD_INVISIBLE_ENCODING = HashSet<String>()
val packagesThatNeedSpreadInvisibleEncoding: Collection<String>
get() = PACKAGES_THAT_NEED_SPREAD_INVISIBLE_ENCODING
fun hasKnownIssues(packagename: String): Boolean {
return PACKAGES_WITH_ISSUES.contains(packagename)
}
fun hasSeriousIssues(packagename: String): Boolean {
return PACKAGES_WITH_SERIOUS_ISSUES.contains(packagename)
}
fun cantHandleInvisibleEncoding(packagename: String): Boolean {
return PACKAGES_WHERE_INVISIBLE_ENCODING_DOESNT_WORK.contains(packagename)
}
fun getInputFieldLimit(packagename: String): Int? {
return PACKAGES_WITH_LIMITED_INPUT_FIELDS[packagename]
}
init {
PACKAGES_WITH_ISSUES.add("com.android.messaging")
PACKAGES_WITH_ISSUES.add("com.google.android.apps.inbox")
PACKAGES_WITH_ISSUES.add("com.google.android.apps.messaging")
PACKAGES_WITH_ISSUES.add("com.google.android.gm")
PACKAGES_WITH_ISSUES.add("com.evernote")
PACKAGES_WITH_ISSUES.add("com.google.android.talk")
PACKAGES_WITH_ISSUES.add("org.telegram.messenger")
PACKAGES_WITH_ISSUES.add("org.thoughtcrime.securesms")
PACKAGES_WITH_ISSUES.add("com.instagram.android")
PACKAGES_WITH_ISSUES.add("com.facebook.orca")
PACKAGES_WITH_ISSUES.add("com.google.android.apps.fireball") //allo
PACKAGES_WITH_SERIOUS_ISSUES.add("org.telegram.messenger") //telegram
PACKAGES_WITH_SERIOUS_ISSUES.add("org.thoughtcrime.securesms") //signal
PACKAGES_WITH_SERIOUS_ISSUES.add("com.wire") //wire
PACKAGES_WHERE_INVISIBLE_ENCODING_DOESNT_WORK.add("com.google.android.apps.inbox") //Inbox by Gmail
PACKAGES_WHERE_INVISIBLE_ENCODING_DOESNT_WORK.add("com.google.android.gm") //Gmail
PACKAGES_WHERE_INVISIBLE_ENCODING_DOESNT_WORK.add("com.evernote") //Evernote
PACKAGES_WHERE_INVISIBLE_ENCODING_DOESNT_WORK.add(" com.moez.QKSMS") //QKSMS
PACKAGES_WITH_LIMITED_INPUT_FIELDS["com.google.android.apps.messaging"] = 2000 //new Google Messenger
PACKAGES_THAT_NEED_TO_SCRAPE_NON_IMPORTANT_VIEWS.add("com.google.android.talk")//Hangouts
PACKAGES_THAT_NEED_TO_SCRAPE_NON_IMPORTANT_VIEWS.add("com.google.android.apps.messaging") //new Messaging
PACKAGES_THAT_NEED_TO_SCRAPE_NON_IMPORTANT_VIEWS.add("com.google.android.apps.fireball") //Allo
PACKAGES_THAT_NEED_COMPOSE_BUTTON.add("com.google.android.gm") //Gmail
PACKAGES_THAT_NEED_COMPOSE_BUTTON.add("com.google.android.apps.inbox")//Inbox By Gmail
PACKAGES_THAT_NEED_COMPOSE_BUTTON.add("com.evernote")//Inbox By Gmail
PACKAGES_THAT_NEED_SPREAD_INVISIBLE_ENCODING.add("com.facebook.orca")//Facebook Messenger
PACKAGES_THAT_NEED_SPREAD_INVISIBLE_ENCODING.add("com.instagram.android") //Instagram
}
}
|
gpl-3.0
|
cae6c8530f783b8bdae580895a83c21a
| 46.986842 | 113 | 0.720866 | 3.571988 | false | false | false | false |
savoirfairelinux/ring-client-android
|
ring-android/app/src/main/java/cx/ring/tv/main/SpinnerFragment.kt
|
1
|
849
|
package cx.ring.tv.main
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.widget.FrameLayout
import android.view.Gravity
import android.view.View
import android.widget.ProgressBar
import androidx.fragment.app.Fragment
class SpinnerFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val progressBar = ProgressBar(container!!.context)
if (container is FrameLayout) {
val layoutParams = FrameLayout.LayoutParams(SPINNER_WIDTH, SPINNER_HEIGHT, Gravity.CENTER)
progressBar.layoutParams = layoutParams
}
return progressBar
}
companion object {
private const val SPINNER_WIDTH = 100
private const val SPINNER_HEIGHT = 100
}
}
|
gpl-3.0
|
49cc40100190e9efd11422aadf5b3110
| 31.692308 | 115 | 0.733804 | 4.851429 | false | false | false | false |
rfcx/rfcx-guardian-android
|
role-guardian/src/main/java/org/rfcx/guardian/guardian/activity/LoginWebViewActivity.kt
|
1
|
7240
|
package org.rfcx.guardian.guardian.activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.StrictMode
import androidx.appcompat.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.auth0.android.result.Credentials
import kotlinx.android.synthetic.main.activity_login_webview.*
import org.json.JSONObject
import org.rfcx.guardian.guardian.R
import org.rfcx.guardian.guardian.entity.Err
import org.rfcx.guardian.guardian.entity.Ok
import org.rfcx.guardian.guardian.manager.CredentialKeeper
import org.rfcx.guardian.guardian.manager.CredentialVerifier
import org.rfcx.guardian.utility.http.TLSSocketFactory
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.URL
import java.net.URLEncoder
import javax.net.ssl.HttpsURLConnection
class LoginWebViewActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_webview)
setSupportActionBar(toolbar)
toolBarInit()
val uri = intent.data
if(uri != null){
val code = uri.getQueryParameter("code")
if(code != null){
preparePost(code)
}
}else{
Log.d("LoginWebViewActivity", baseUrl)
val webpage = Uri.parse(baseUrl)
val intent = Intent(Intent.ACTION_VIEW, webpage)
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
finish()
}
}
codeEditText.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) {
if(count < 0 ){
sendButton.isEnabled = false
sendButton.alpha = 0.5f
}else{
sendButton.isEnabled = true
sendButton.alpha = 1.0f
}
}
})
sendButton.setOnClickListener {
preparePost(null)
}
}
private fun toolBarInit() {
val toolbar = supportActionBar
toolbar?.title = "Login"
}
private fun preparePost(code: String?){
val handler = Handler()
loginProgressBar.visibility = View.VISIBLE
loginLayout.visibility = View.INVISIBLE
//dismiss keyboard
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(codeEditText.windowToken, 0)
val runnable = Runnable {
val policy = StrictMode.ThreadPolicy.Builder()
.permitAll().build()
StrictMode.setThreadPolicy(policy)
val postUrl = "https://auth.rfcx.org/oauth/token"
val body = hashMapOf<String, String>(
"grant_type" to "authorization_code",
"client_id" to clientId,
"code" to (code ?: codeEditText.text.toString()),
"redirect_uri" to redirectUrl
)
val postResponse = post(postUrl, body)
Log.d("LoginWebViewActivity", postResponse)
if(postResponse.isNotEmpty()){
val response = JSONObject(postResponse)
val idToken = response.getString("id_token")
val accessToken = response.getString("access_token")
val credentials = Credentials(idToken, accessToken,null, null, 86400000)
val result = CredentialVerifier(this).verify(credentials)
when(result){
is Err -> {
Log.d("LoginWebViewActivity", "login error")
loginProgressBar.visibility = View.INVISIBLE
loginLayout.visibility = View.VISIBLE
}
is Ok -> {
CredentialKeeper(this).save(result.value)
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
Log.d("LoginWebViewActivity", credentials.idToken)
}else{
Log.d("LoginWebViewActivity", "post failed")
Toast.makeText(this, "code is incorrect.", Toast.LENGTH_LONG).show()
loginProgressBar.visibility = View.INVISIBLE
loginLayout.visibility = View.VISIBLE
}
codeEditText.text = null
}
handler.post(runnable)
}
private fun post(url: String, params: HashMap<String, String>): String{
var response = ""
try {
val url = URL(url)
val conn = url.openConnection() as HttpsURLConnection
conn.sslSocketFactory = TLSSocketFactory()
conn.readTimeout = 15000
conn.connectTimeout = 15000
conn.requestMethod = "POST"
conn.doInput = true
conn.doOutput = true
val os = conn.outputStream
val writer = BufferedWriter(
OutputStreamWriter(os, "UTF-8")
)
writer.write(getPostDataString(params))
writer.flush()
writer.close()
os.close()
val responseCode = conn.responseCode
if (responseCode == HttpsURLConnection.HTTP_OK) {
var line: String? = ""
val br = BufferedReader(InputStreamReader(conn.inputStream))
while ((line) != null) {
line = br.readLine()
response += line
}
} else {
response = ""
}
} catch (e: Exception) {
e.printStackTrace()
}
return response
}
private fun getPostDataString(params: HashMap<String, String>): String{
val result = StringBuilder()
var first = true
for (entry in params.entries) {
if (first)
first = false
else
result.append("&")
result.append(URLEncoder.encode(entry.key, "UTF-8"))
result.append("=")
result.append(URLEncoder.encode(entry.value, "UTF-8"))
}
return result.toString()
}
companion object{
private const val redirectUrl = "rfcx://login"
private const val audience = "https://rfcx.org"
private const val scope = "openid%20profile"
private const val clientId = "CdlIIeJDapQxW29kn93wDw26fTTNyDkp"
const val baseUrl = "https://auth.rfcx.org/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUrl}&audience=${audience}&scope=${scope}"
}
}
|
apache-2.0
|
2d37d036c1944653401f0b6e06dfdc42
| 34.665025 | 166 | 0.586602 | 5.003455 | false | false | false | false |
grote/Liberario
|
app/src/androidTest/java/de/grobox/transportr/map/MapActivityTest.kt
|
1
|
5910
|
/*
* Transportr
*
* Copyright (c) 2013 - 2018 Torsten Grote
*
* This program is Free Software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.grobox.transportr.map
import android.Manifest
import androidx.lifecycle.Observer
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.isPlatformPopup
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.rule.GrantPermissionRule
import de.grobox.transportr.R
import de.grobox.transportr.ScreengrabTest
import de.grobox.transportr.data.DbTest
import de.grobox.transportr.data.locations.FavoriteLocation
import de.grobox.transportr.data.locations.FavoriteLocation.FavLocationType.FROM
import de.grobox.transportr.data.locations.FavoriteLocation.FavLocationType.TO
import de.grobox.transportr.data.locations.LocationRepository
import de.grobox.transportr.data.searches.SearchesRepository
import de.grobox.transportr.favorites.trips.FavoriteTripItem
import de.grobox.transportr.networks.TransportNetwork
import de.grobox.transportr.networks.TransportNetworkManager
import de.grobox.transportr.waitForId
import org.hamcrest.CoreMatchers.anything
import org.junit.*
import org.junit.Assert.assertEquals
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
import javax.inject.Inject
@LargeTest
@RunWith(AndroidJUnit4::class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class MapActivityTest : ScreengrabTest() {
@Rule
@JvmField
val activityRule = ActivityTestRule(MapActivity::class.java)
@Rule
@JvmField
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(Manifest.permission.ACCESS_FINE_LOCATION)
@Inject
lateinit var manager: TransportNetworkManager
@Inject
lateinit var locationRepository: LocationRepository
@Inject
lateinit var searchesRepository: SearchesRepository
@Before
override fun setUp() {
super.setUp()
activityRule.runOnUiThread {
component.inject(this)
val transportNetwork: TransportNetwork = manager.getTransportNetworkByNetworkId(networkId) ?: throw RuntimeException()
manager.setTransportNetwork(transportNetwork)
// ensure networkId got updated before continuing
assertEquals(networkId, DbTest.getValue(manager.networkId))
}
}
@Test
@Ignore // TODO fix
fun favoritesTest() {
locationRepository.setHomeLocation(getFrom(0))
locationRepository.setWorkLocation(getTo(0))
locationRepository.addFavoriteLocation(getFrom(1), FROM)
locationRepository.addFavoriteLocation(getTo(1), TO)
locationRepository.addFavoriteLocation(getFrom(2), FROM)
locationRepository.addFavoriteLocation(getTo(2), TO)
onView(isRoot()).perform(waitForId(R.id.title))
locationRepository.favoriteLocations.observe(activityRule.activity, Observer { this.addSavedSearches(it) })
onView(isRoot()).perform(waitForId(R.id.fromIcon))
sleep(2500)
makeScreenshot("2_SavedSearches")
}
@Test
fun searchLocationShowDeparturesTest() {
// search for station
onView(withId(R.id.location))
.perform(typeText(departureStation))
// click station
onData(anything())
.inRoot(isPlatformPopup())
.atPosition(0)
.perform(click())
// assert bottom sheet is shown
onView(withId(R.id.bottomSheet))
.check(matches(isDisplayed()))
onView(withId(R.id.locationName))
.check(matches(withText(departureStation)))
onView(withId(R.id.locationIcon))
.check(matches(isDisplayed()))
// expand bottom sheet
onView(withId(R.id.locationName))
.perform(click())
onView(withId(R.id.departuresButton))
.check(matches(isDisplayed()))
// wait for departures to load and then make screenshot
onView(isRoot()).perform(waitForId(R.id.linesLayout))
makeScreenshot("5_Station")
// click departure button
onView(withId(R.id.departuresButton))
.perform(click())
onView(isRoot()).perform(waitForId(R.id.line))
makeScreenshot("6_Departures")
}
private fun addSavedSearches(list: List<FavoriteLocation>?) {
if (list == null || list.size < 4) return
Thread {
// copy the list to avoid it changing mid-flight
val locations = list.toList()
for (i in 1 until locations.size step 2) {
val uid = searchesRepository.storeSearch(locations[i - 1], null, locations[i])
if (i == 1) {
val item = FavoriteTripItem(uid, locations[i - 1], null, locations[i])
item.favorite = true
searchesRepository.updateFavoriteState(item)
}
}
}.start()
}
}
|
gpl-3.0
|
899f3cc5f1c67c1bdffd3088bd1f14b1
| 35.708075 | 130 | 0.704738 | 4.46712 | false | true | false | false |
xwiki-contrib/android-authenticator
|
app/src/main/java/org/xwiki/android/sync/utils/IntentUtils.kt
|
1
|
1961
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.android.sync.utils
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.webkit.WebView
/**
* Check url (warning, url must start with "https://" or other protocol if you want not use
* http) and open browser or other application which can open that url.
*
* @param url Url to prepare
* @return NOT STARTED, but prepared intent
*/
fun openLink(url: String): Intent {
var url = url
// if protocol isn't defined use https by default
if (!TextUtils.isEmpty(url) && !url.contains("://")) {
url = "https://$url"
}
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.data = Uri.parse(url)
return intent
}
fun WebView.openLink(url: String) {
var url = url
if (!TextUtils.isEmpty(url) && !url.contains("://")) {
url = "https://$url"
}
this.loadUrl(url)
this.settings.javaScriptEnabled = true
}
/**
* Utils for simple work with intents
*
* @version $Id: 922f8db5323030152468f37a681e4a3e612c4503 $
*/
class IntentUtils
|
lgpl-2.1
|
df0dc6a4926c161ca0197a658bb49e10
| 30.629032 | 91 | 0.706272 | 3.875494 | false | false | false | false |
shymmq/librus-client-kotlin
|
app/src/main/kotlin/com/wabadaba/dziennik/ui/events/EventsViewModel.kt
|
1
|
2039
|
package com.wabadaba.dziennik.ui.events
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.wabadaba.dziennik.api.EntityRepository
import com.wabadaba.dziennik.ui.monthEnd
import com.wabadaba.dziennik.ui.monthNameNominative
import com.wabadaba.dziennik.ui.multiPut
import com.wabadaba.dziennik.ui.weekEnd
import com.wabadaba.dziennik.vo.Event
import io.reactivex.android.schedulers.AndroidSchedulers
import org.joda.time.LocalDate
import org.joda.time.Months
import java.util.*
class EventsViewModel(entityRepo: EntityRepository) : ViewModel() {
val eventData = MutableLiveData<EventData>()
init {
entityRepo.events.observeOn(AndroidSchedulers.mainThread())
.subscribe { events ->
val result = EventData()
events.filter { it.date != null }
.filter { !it.date!!.isBefore(LocalDate.now()) }
.forEach { event ->
val date = event.date!!
val header = when (event.date) {
LocalDate.now() -> EventHeader(0, "Dzisiaj")
LocalDate.now().plusDays(1) -> EventHeader(1, "Jutro")
in LocalDate.now()..weekEnd() -> EventHeader(2, "Ten tydzień")
in LocalDate.now()..monthEnd() -> EventHeader(3, "Ten miesiąc")
else -> EventHeader(4 + Months.monthsBetween(LocalDate.now(), date).months,
date.monthNameNominative().capitalize())
}
result.multiPut(header, event)
}
eventData.value = result
}
}
}
class EventData : TreeMap<EventHeader, List<Event>>({ (order1), (order2) -> order1.compareTo(order2) })
data class EventHeader(val order: Int, val title: String)
|
gpl-3.0
|
3f285dd994d554ec829ae6889a056198
| 43.304348 | 111 | 0.56161 | 4.726218 | false | false | false | false |
duftler/orca
|
orca-test-kotlin/src/main/kotlin/com/netflix/spinnaker/orca/fixture/PipelineBuilder.kt
|
2
|
2629
|
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.fixture
import com.netflix.spinnaker.orca.pipeline.model.DefaultTrigger
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.model.Task
import com.netflix.spinnaker.orca.pipeline.tasks.NoOpTask
import java.lang.System.currentTimeMillis
/**
* Build a pipeline.
*/
fun pipeline(init: Execution.() -> Unit = {}): Execution {
val pipeline = Execution(PIPELINE, "covfefe")
pipeline.trigger = DefaultTrigger("manual")
pipeline.buildTime = currentTimeMillis()
pipeline.init()
return pipeline
}
/**
* Build a stage outside the context of an execution.
*/
fun stage(init: Stage.() -> Unit): Stage {
val stage = Stage()
stage.execution = pipeline()
stage.type = "test"
stage.refId = "1"
stage.execution.stages.add(stage)
stage.init()
return stage
}
/**
* Build a top-level stage. Use in the context of [#pipeline].
*
* Automatically hooks up execution.
*/
fun Execution.stage(init: Stage.() -> Unit): Stage {
val stage = Stage()
stage.execution = this
stage.type = "test"
stage.refId = "1"
stages.add(stage)
stage.init()
return stage
}
/**
* Build a synthetic stage. Use in the context of [#stage].
*
* Automatically hooks up execution and parent stage.
*/
fun Stage.stage(init: Stage.() -> Unit): Stage {
val stage = Stage()
stage.execution = execution
stage.type = "test"
stage.refId = "$refId<1"
stage.parentStageId = id
stage.syntheticStageOwner = STAGE_BEFORE
execution.stages.add(stage)
stage.init()
return stage
}
/**
* Build a task. Use in the context of [#stage].
*/
fun Stage.task(init: Task.() -> Unit): Task {
val task = Task()
task.implementingClass = NoOpTask::class.java.name
task.name = "dummy"
tasks.add(task)
task.init()
return task
}
|
apache-2.0
|
4e420b61fe55d7e948fd0d087cf53d1e
| 26.968085 | 81 | 0.720426 | 3.739687 | false | false | false | false |
Takhion/android-extras-delegates
|
library/src/main/java/me/eugeniomarletti/extras/intent/base/ArrayList.kt
|
1
|
1857
|
@file:Suppress("NOTHING_TO_INLINE")
package me.eugeniomarletti.extras.intent.base
import android.os.Parcelable
import me.eugeniomarletti.extras.intent.IntentExtra
import me.eugeniomarletti.extras.intent.IntentPropertyDelegate
import java.util.ArrayList
inline fun IntentExtra.CharSequenceArrayList(name: String? = null, customPrefix: String? = null) =
CharSequenceArrayList({ it }, { it }, name, customPrefix)
inline fun IntentExtra.CharSequenceArrayList(defaultValue: ArrayList<CharSequence?>, name: String? = null, customPrefix: String? = null) =
CharSequenceArrayList({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.StringArrayList(name: String? = null, customPrefix: String? = null) =
StringArrayList({ it }, { it }, name, customPrefix)
inline fun IntentExtra.StringArrayList(defaultValue: ArrayList<String?>, name: String? = null, customPrefix: String? = null) =
StringArrayList({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun IntentExtra.IntArrayList(name: String? = null, customPrefix: String? = null) =
IntArrayList({ it }, { it }, name, customPrefix)
inline fun IntentExtra.IntArrayList(defaultValue: ArrayList<Int?>, name: String? = null, customPrefix: String? = null) =
IntArrayList({ it ?: defaultValue }, { it }, name, customPrefix)
inline fun <T : Parcelable> IntentExtra.ParcelableArrayList(
name: String? = null,
customPrefix: String? = null
): IntentPropertyDelegate<ArrayList<T?>?> =
ParcelableArrayList<ArrayList<T?>?, T>({ it }, { it }, name, customPrefix)
inline fun <T : Parcelable> IntentExtra.ParcelableArrayList(
defaultValue: ArrayList<T?>,
name: String? = null,
customPrefix: String? = null
): IntentPropertyDelegate<ArrayList<T?>?> =
ParcelableArrayList<ArrayList<T?>?, T>({ it ?: defaultValue }, { it }, name, customPrefix)
|
mit
|
02136ae817bf226b7fb5e3eaf6b9e781
| 46.615385 | 138 | 0.73021 | 4.191874 | false | false | false | false |
AlmasB/FXGL
|
fxgl-samples/src/main/kotlin/sandbox/subscene/NavigateEvent.kt
|
1
|
673
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.subscene
import javafx.event.Event
import javafx.event.EventType
val NAVIGATION: EventType<NavigateEvent> = EventType(Event.ANY, "NAVIGATION")
val MAIN_VIEW: EventType<NavigateEvent> = EventType(NAVIGATION, "MAIN")
val OPTIONS_VIEW: EventType<NavigateEvent> = EventType(NAVIGATION, "OPTIONS")
val ABOUT_VIEW: EventType<NavigateEvent> = EventType(NAVIGATION, "ABOUT")
val PLAY_VIEW: EventType<NavigateEvent> = EventType(NAVIGATION, "PLAY")
class NavigateEvent(eventType: EventType<out Event?>?) : Event(eventType)
|
mit
|
5eabee8d7db7bb47bde985be3d1a5579
| 28.26087 | 77 | 0.759287 | 3.738889 | false | false | false | false |
yuzumone/bergamio
|
app/src/main/kotlin/net/yuzumone/bergamio/fragment/CouponFragment.kt
|
1
|
2191
|
package net.yuzumone.bergamio.fragment
import android.content.Context
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import net.yuzumone.bergamio.R
import net.yuzumone.bergamio.databinding.FragmentCouponBinding
import net.yuzumone.bergamio.databinding.ItemCouponBinding
import net.yuzumone.bergamio.model.Coupon
import net.yuzumone.bergamio.view.ArrayRecyclerAdapter
import net.yuzumone.bergamio.view.BindingHolder
import java.util.*
class CouponFragment : BaseFragment() {
private lateinit var binding: FragmentCouponBinding
private val coupons: List<Coupon> by lazy {
arguments!!.getParcelableArrayList<Coupon>(ARG_COUPON)
}
companion object {
private const val ARG_COUPON = "coupon"
fun newInstance(coupon: ArrayList<Coupon>): CouponFragment {
return CouponFragment().apply {
arguments = Bundle().apply {
putParcelableArrayList(ARG_COUPON, coupon)
}
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_coupon, container, false)
initView()
return binding.root
}
private fun initView() {
val adapter = CouponAdapter(activity!!)
adapter.addAllWithNotify(coupons)
binding.recyclerView.adapter = adapter
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
}
class CouponAdapter(context: Context) : ArrayRecyclerAdapter<Coupon,
BindingHolder<ItemCouponBinding>>(context) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder<ItemCouponBinding> {
return BindingHolder(context, parent, R.layout.item_coupon)
}
override fun onBindViewHolder(holder: BindingHolder<ItemCouponBinding>, position: Int) {
val item = getItem(position)
holder.binding.coupon = item
}
}
}
|
apache-2.0
|
c48c6e58927cef989635ef3bd415a021
| 34.934426 | 116 | 0.712916 | 4.612632 | false | false | false | false |
lice-lang/lice
|
src/main/kotlin/org/lice/core/functions.kt
|
1
|
14857
|
@file:Suppress("FunctionName", "unused")
package org.lice.core
import org.lice.Lice
import org.lice.lang.Echoer
import org.lice.lang.NumberOperator
import org.lice.model.*
import org.lice.parse.*
import org.lice.util.*
import org.lice.util.InterpretException.Factory.notSymbol
import org.lice.util.InterpretException.Factory.tooFewArgument
import java.lang.reflect.Modifier
import java.nio.file.Paths
import java.util.*
/**
* `$` in the function names will be replaced with `>`,
* `&` in the function names will be replaced with `<`,
* `_` in the function names will be replaced with `/`.
* `#` in the function names will be replaced with `.`.
* `{` in the function names will be replaced with `[`.
* `}` in the function names will be replaced with `]`.
* @author ice1000
*/
class FunctionMangledHolder(private val symbolList: SymbolList) {
fun `|$`(meta: MetaData, ls: List<Any?>) = ls.lastOrNull()
fun `-$str`(meta: MetaData, it: List<Any?>) = it.first(meta).toString()
fun `-$double`(meta: MetaData, it: List<Any?>) = cast<Number>(it.first(meta)).toDouble()
fun `-$int`(meta: MetaData, it: List<Any?>) = cast<Number>(it.first(meta)).toInt()
fun `&`(meta: MetaData, ls: List<Any?>) =
(1 until ls.size).all { NumberOperator.compare(cast(ls[it - 1], meta), cast(ls[it], meta), meta) < 0 }
fun `$`(meta: MetaData, ls: List<Any?>) =
(1 until ls.size).all { NumberOperator.compare(cast(ls[it - 1], meta), cast(ls[it], meta), meta) > 0 }
fun `&=`(meta: MetaData, ls: List<Any?>) =
(1 until ls.size).all { NumberOperator.compare(cast(ls[it - 1], meta), cast(ls[it], meta), meta) <= 0 }
fun `$=`(meta: MetaData, ls: List<Any?>) =
(1 until ls.size).all { NumberOperator.compare(cast(ls[it - 1], meta), cast(ls[it], meta), meta) >= 0 }
fun `_`(meta: MetaData, ls: List<Any?>): Number {
val init = cast<Number>(ls.first(meta), meta)
return when (ls.size) {
0 -> 1
1 -> init
else -> ls.drop(1)
.fold(NumberOperator(init)) { sum, value ->
if (value is Number) sum.div(value, meta)
else InterpretException.typeMisMatch("Number", value, meta)
}.result
}
}
fun `str-$int`(meta: MetaData, ls: List<Any?>): Int {
val res = ls.first(meta).toString()
return when {
res.isOctInt() -> res.toOctInt()
res.isInt() -> res.toInt()
res.isBinInt() -> res.toBinInt()
res.isHexInt() -> res.toHexInt()
else -> throw InterpretException("give string: \"$res\" cannot be parsed as a number!", meta)
}
}
fun `int-$hex`(meta: MetaData, ls: List<Any?>): String {
val a = ls.first()
return if (a is Number) "0x${Integer.toHexString(a.toInt())}"
else InterpretException.typeMisMatch("Int", a, meta)
}
fun `int-$bin`(meta: MetaData, ls: List<Any?>): String {
val a = ls.first()
return if (a is Number) "0b${Integer.toBinaryString(a.toInt())}"
else InterpretException.typeMisMatch("Int", a, meta)
}
fun `int-$oct`(meta: MetaData, ls: List<Any?>): String {
val a = ls.first()
return if (a is Number) "0o${Integer.toOctalString(a.toInt())}"
else InterpretException.typeMisMatch("Int", a, meta)
}
fun `join-$str`(meta: MetaData, ls: List<Any?>) =
cast<Iterable<*>>(ls.first()).joinToString(ls.getOrNull(1)?.toString().orEmpty())
fun `{|}`(meta: MetaData, ls: List<Any?>) = ls.reduceRight(::Pair)
fun `{|`(meta: MetaData, ls: List<Any?>): Any? {
val a = ls.first(meta)
return when (a) {
is Pair<*, *> -> a.first
is Iterable<*> -> a.first()
is Array<*> -> a.first()
else -> null
}
}
fun `|}`(meta: MetaData, ls: List<Any?>): Any? {
val a = ls.first(meta)
return when (a) {
is Pair<*, *> -> a.second
is Iterable<*> -> a.drop(1)
is Array<*> -> a.drop(1)
else -> null
}
}
fun `##`(metaData: MetaData, ls: List<Any?>): Iterable<Int> {
if (ls.size < 2) tooFewArgument(2, ls.size, metaData)
val a = ls.first()
val b = ls[1]
return when {
a is Number && b is Number -> {
val begin = a.toInt()
val end = b.toInt()
if (begin <= end) (begin..end)
else (end..begin).reversed()
}
else -> InterpretException.typeMisMatch("Number", a as? Number ?: b, metaData)
}
}
fun `list-$array`(meta: MetaData, it: List<Any?>) = cast<List<*>>(it.first(meta)).toTypedArray()
fun `array-$list`(meta: MetaData, it: List<Any?>) = cast<Array<*>>(it.first(meta)).toList()
fun `-$chars`(meta: MetaData, it: List<Any?>) = it.joinToString("").toCharArray()
}
class FunctionHolders(private val symbolList: SymbolList) {
fun print(it: List<Any?>) = it.forEach(Echoer::echo)
fun type(it: List<Any?>) = it.firstOrNull()?.javaClass ?: Nothing::class.java
fun exit(it: List<Any?>) = System.exit(it.firstOrNull() as? Int ?: 0)
fun rand(it: List<Any?>) = Math.random()
fun `&&`(it: List<Any?>) = it.all(Any?::booleanValue)
fun `||`(it: List<Any?>) = it.any(Any?::booleanValue)
fun `str-con`(it: List<Any?>) = it.joinToString(transform = Any?::toString, separator = "")
fun `===`(it: List<Any?>) = (1 until it.size).all { i -> it[i] == it[i - 1] }
fun `!==`(it: List<Any?>) = (1 until it.size).none { i -> it[i] == it[i - 1] }
fun list(it: List<Any?>) = it
fun array(it: List<Any?>) = it.toTypedArray()
fun println(it: List<Any?>): Any? {
it.forEach(Echoer::echo)
Echoer.echo("\n")
return it.lastOrNull()
}
}
class FunctionWithMetaHolders(private val symbolList: SymbolList) {
fun `-`(meta: MetaData, it: List<Any?>) = when (it.size) {
0 -> 0
1 -> it.first(meta)
else -> it.drop(1).fold(NumberOperator(it.first() as Number)) { sum, value ->
if (value is Number) sum.minus(value, meta)
else InterpretException.typeMisMatch("Number", value, meta)
}.result
}
fun `+`(meta: MetaData, it: List<Any?>) =
it.fold(NumberOperator(0)) { sum, value ->
if (value is Number) sum.plus(value, meta)
else InterpretException.typeMisMatch("Number", value, meta)
}.result
fun extern(meta: MetaData, it: List<Any?>): Any? {
val name = it[1, meta].toString()
val clazz = it.first(meta).toString()
val method = Class.forName(clazz).declaredMethods
.firstOrNull { Modifier.isStatic(it.modifiers) && it.name == name }
?: throw UnsatisfiedLinkError("Method $name not found for class $clazz\nat line: ${meta.beginLine}")
symbolList.provideFunction(name) { runReflection { method.invoke(null, *it.toTypedArray()) } }
return name
}
fun `==`(meta: MetaData, ls: List<Any?>) = (1 until ls.size)
.all { NumberOperator.compare(cast(ls[it - 1]), cast(ls[it]), meta) == 0 }
fun `!=`(meta: MetaData, ls: List<Any?>) = (1 until ls.size)
.none { NumberOperator.compare(cast(ls[it - 1]), cast(ls[it]), meta) == 0 }
fun `%`(meta: MetaData, ls: List<Any?>) = when (ls.size) {
0 -> 0
1 -> ls.first()
else -> ls.drop(1)
.fold(NumberOperator(cast(ls.first()))) { sum, value ->
if (value is Number) sum.rem(value, meta)
else InterpretException.typeMisMatch("Number", value, meta)
}.result
}
fun `*`(meta: MetaData, ls: List<Any?>) = ls.fold(NumberOperator(1)) { sum, value ->
if (value is Number) sum.times(value, meta)
else InterpretException.typeMisMatch("Number", value, meta)
}.result
fun format(meta: MetaData, ls: List<Any?>) =
String.format(ls.first(meta).toString(), *ls.subList(1, ls.size).toTypedArray())
fun sqrt(meta: MetaData, it: List<Any?>) = Math.sqrt(cast<Number>(it.first(meta)).toDouble())
fun sin(meta: MetaData, it: List<Any?>) = Math.sin(cast<Number>(it.first(meta)).toDouble())
fun cos(meta: MetaData, it: List<Any?>) = Math.cos(cast<Number>(it.first(meta)).toDouble())
fun tan(meta: MetaData, it: List<Any?>) = Math.tan(cast<Number>(it.first(meta)).toDouble())
fun asin(meta: MetaData, it: List<Any?>) = Math.asin(cast<Number>(it.first(meta)).toDouble())
fun acos(meta: MetaData, it: List<Any?>) = Math.acos(cast<Number>(it.first(meta)).toDouble())
fun atan(meta: MetaData, it: List<Any?>) = Math.atan(cast<Number>(it.first(meta)).toDouble())
fun sinh(meta: MetaData, it: List<Any?>) = Math.sinh(cast<Number>(it.first(meta)).toDouble())
fun cosh(meta: MetaData, it: List<Any?>) = Math.cosh(cast<Number>(it.first(meta)).toDouble())
fun tanh(meta: MetaData, it: List<Any?>) = Math.tanh(cast<Number>(it.first(meta)).toDouble())
fun exp(meta: MetaData, it: List<Any?>) = Math.exp(cast<Number>(it.first(meta)).toDouble())
fun log(meta: MetaData, it: List<Any?>) = Math.log(cast<Number>(it.first(meta)).toDouble())
fun log10(meta: MetaData, it: List<Any?>) = Math.log10(cast<Number>(it.first(meta)).toDouble())
fun eval(meta: MetaData, it: List<Any?>) = Lice.run(it.first(meta).toString(), symbolList = symbolList)
fun `load-file`(meta: MetaData, it: List<Any?>) = Lice.run(Paths.get(it.first(meta).toString()), symbolList)
fun `!`(meta: MetaData, it: List<Any?>) = it.first(meta).booleanValue().not()
fun `~`(meta: MetaData, it: List<Any?>) = cast<Int>(it.first(meta)).inv()
fun `!!`(meta: MetaData, it: List<Any?>): Any? {
val a = it.first(meta)
return when (a) {
is Iterable<*> -> a.toList()[cast(it[1])]
is Array<*> -> a[cast(it[1])]
else -> null
}
}
private val liceScanner = Scanner(System.`in`)
fun getInts(meta: MetaData, it: List<Any?>) = (1..cast(it.first(meta) ?: 1)).map { liceScanner.nextInt() }
fun getFloats(meta: MetaData, it: List<Any?>) = (1..cast(it.first(meta))).map { liceScanner.nextFloat() }
fun getDoubles(meta: MetaData, it: List<Any?>) = (1..cast(it.first(meta))).map { liceScanner.nextDouble() }
fun getLines(meta: MetaData, it: List<Any?>) = (1..cast(it.first(meta))).map { liceScanner.nextLine() }
fun getTokens(meta: MetaData, it: List<Any?>) = (1..cast(it.first(meta))).map { liceScanner.next() }
fun getBigInts(meta: MetaData, it: List<Any?>) = (1..cast(it.first(meta))).map { liceScanner.nextBigInteger() }
fun getBigDecs(meta: MetaData, it: List<Any?>) = (1..cast(it.first(meta))).map { liceScanner.nextBigDecimal() }
fun `in?`(meta: MetaData, it: List<Any?>) =
it[1, meta] in cast<Iterable<*>>(it.first(meta).let { (it as? Array<*>)?.toList() ?: it })
fun size(meta: MetaData, it: List<Any?>) = cast<Iterable<*>>(it.first(meta)).count()
fun last(meta: MetaData, it: List<Any?>) = cast<Iterable<*>>(it.first(meta)).last()
fun reverse(meta: MetaData, it: List<Any?>) = cast<Iterable<*>>(it.first(meta)).reversed()
fun distinct(meta: MetaData, it: List<Any?>) = cast<Iterable<*>>(it.first(meta)).distinct()
fun subtract(meta: MetaData, it: List<Any?>) = cast<Iterable<*>>(it.first(meta)).subtract(cast(it[1, meta]))
fun intersect(meta: MetaData, it: List<Any?>) = cast<Iterable<*>>(it.first(meta)).intersect(cast(it[1, meta]))
fun union(meta: MetaData, it: List<Any?>) = cast<Iterable<*>>(it.first(meta)).union(cast(it[1, meta]))
fun `++`(meta: MetaData, it: List<Any?>) = cast<Iterable<*>>(it.first(meta)) + cast<Iterable<*>>(it[1, meta])
fun sort(meta: MetaData, it: List<Any?>) = cast<Iterable<Comparable<Comparable<*>>>>(it.first(meta)).sorted()
fun split(meta: MetaData, it: List<Any?>) = it.first(meta).toString().split(it[1].toString()).toList()
fun count(meta: MetaData, it: List<Any?>) =
it[1, meta].let { e -> cast<Iterable<*>>(it.first(meta)).count { it == e } }
fun `&`(meta: MetaData, it: List<Any?>) =
it.map { cast<Number>(it, meta).toInt() }.reduce { last, self -> last and self }
fun `|`(meta: MetaData, it: List<Any?>) =
it.map { cast<Number>(it, meta).toInt() }.reduce { last, self -> last or self }
fun `^`(meta: MetaData, it: List<Any?>) =
it.map { cast<Number>(it, meta).toInt() }.reduce { last, self -> last xor self }
}
/**
* `$` in the function names will be replaced with `>`.
* @author ice1000
*/
class FunctionDefinedMangledHolder(private val symbolList: SymbolList) {
fun `def?`(meta: MetaData, it: List<Node>): Node {
val a = (it.first(meta) as? SymbolNode ?: InterpretException.notSymbol(meta)).name
return ValueNode(symbolList.isVariableDefined(a), meta)
}
fun `force|$`(meta: MetaData, ls: List<Node>): Node {
var ret: Any? = null
forceRun { ls.forEach { node -> ret = node.eval() } }
return ValueNode(ret, meta)
}
fun `str-$sym`(meta: MetaData, ls: List<Node>) = SymbolNode(symbolList, ls.first(meta).eval().toString(), meta)
fun `sym-$str`(meta: MetaData, ls: List<Node>): Node {
val a = ls.first()
return if (a is SymbolNode) ValueNode(a.name, meta)
else InterpretException.typeMisMatch("Symbol", a, meta)
}
fun `-$`(meta: MetaData, ls: List<Node>): Node {
if (ls.size < 2) tooFewArgument(2, ls.size, meta)
symbolList.defineVariable(cast<SymbolNode>(ls.first()).name, ValueNode(ls[1].eval()))
return ls.first()
}
}
class FunctionDefinedHolder(private val symbolList: SymbolList) {
fun `if`(meta: MetaData, ls: List<Node>): Node {
if (ls.size < 2) tooFewArgument(2, ls.size, meta)
val a = ls.first().eval()
val condition = a.booleanValue()
return when {
condition -> ls[1]
ls.size >= 3 -> ls[2]
else -> ValueNode(null, meta)
}
}
fun `when`(meta: MetaData, ls: List<Node>): Node {
for (i in (0..ls.size - 2) step 2) {
val a = ls[i].eval()
val condition = a.booleanValue()
if (condition) return ls[i + 1]
}
return if (ls.size % 2 == 0) ValueNode(null, meta) else ls.last()
}
fun `while`(meta: MetaData, ls: List<Node>): Node {
if (ls.size < 2) tooFewArgument(2, ls.size, meta)
var a = ls.first().eval()
var ret: Node = ValueNode(null, meta)
while (a.booleanValue()) {
// execute loop
ret.eval()
ret = ls[1]
// update a
a = ls.first().eval()
}
return ret
}
fun undef(meta: MetaData, it: List<Node>): Node {
val a = (it.first(meta) as? SymbolNode ?: InterpretException.notSymbol(meta)).name
return ValueNode(null != symbolList.removeVariable(a), meta)
}
fun `for-each`(meta: MetaData, ls: List<Node>): Node {
if (ls.size < 3) tooFewArgument(3, ls.size, meta)
val i = (ls.first() as SymbolNode).name
val a = ls[1].eval().let { (it as? Array<*>)?.toList() ?: it }
return if (a is Iterable<*>) {
var ret: Any? = null
a.forEach {
symbolList.defineVariable(i, ValueNode(it, meta))
ret = ls[2].eval()
}
ValueNode(ret, meta)
} else InterpretException.typeMisMatch("List", a, meta)
}
fun alias(meta: MetaData, ls: List<Node>): Node {
val function = symbolList.getVariable(cast<SymbolNode>(ls.first(meta)).name) ?: return ValueNode(false, meta)
ls.indices.forEach { index ->
if (index != 0) {
val name = cast<SymbolNode>(ls[index]).name
if (function is Node) symbolList.defineVariable(name, function)
else symbolList.defineFunction(name, cast(function, meta))
}
}
return ValueNode(true, meta)
}
fun `variable?`(meta: MetaData, ls: List<Node>) =
ValueNode(symbolList.variables[(ls.first(meta) as? SymbolNode)?.name ?: notSymbol(meta)] is Node, meta)
fun `function?`(meta: MetaData, ls: List<Node>) =
ValueNode(symbolList.variables[(ls.first(meta) as? SymbolNode)?.name ?: notSymbol(meta)] as? Func != null, meta)
}
|
gpl-3.0
|
ad52cea6ca6bc41af616d282e1f41c20
| 40.384401 | 115 | 0.642391 | 2.943146 | false | false | false | false |
coil-kt/coil
|
coil-base/src/main/java/coil/util/DebugLogger.kt
|
1
|
1199
|
package coil.util
import android.util.Log
import coil.ImageLoader
import java.io.PrintWriter
import java.io.StringWriter
/**
* A [Logger] implementation that writes to Android's [Log].
*
* NOTE: You **should not** enable this in release builds. Adding this to your [ImageLoader]
* reduces performance. Additionally, this will log URLs which can contain
* [PII](https://en.wikipedia.org/wiki/Personal_data).
*/
class DebugLogger @JvmOverloads constructor(level: Int = Log.DEBUG) : Logger {
override var level = level
set(value) {
assertValidLevel(value)
field = value
}
init {
assertValidLevel(level)
}
override fun log(tag: String, priority: Int, message: String?, throwable: Throwable?) {
if (message != null) {
Log.println(priority, tag, message)
}
if (throwable != null) {
val writer = StringWriter()
throwable.printStackTrace(PrintWriter(writer))
Log.println(priority, tag, writer.toString())
}
}
private fun assertValidLevel(value: Int) {
require(value in Log.VERBOSE..Log.ASSERT) { "Invalid log level: $value" }
}
}
|
apache-2.0
|
9fd8d2266ba14535c355e7b8169b2092
| 27.547619 | 92 | 0.637198 | 4.207018 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.