repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
savvasdalkitsis/gameframe | bitmap/src/main/java/com/savvasdalkitsis/gameframe/feature/bitmap/injector/BitmapInjector.kt | 1 | 1094 | /**
* Copyright 2018 Savvas Dalkitsis
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.bitmap.injector
import com.savvasdalkitsis.gameframe.feature.bitmap.usecase.AndroidViewBitmapFileUseCase
import com.savvasdalkitsis.gameframe.feature.bitmap.usecase.BmpUseCase
import com.savvasdalkitsis.gameframe.infra.injector.ApplicationInjector.application
object BitmapInjector {
fun bitmapFileUseCase() = AndroidViewBitmapFileUseCase(application())
fun bmpUseCase() = BmpUseCase()
} | apache-2.0 |
savvasdalkitsis/gameframe | device/src/main/java/com/savvasdalkitsis/gameframe/feature/device/model/AlreadyExistsOnDeviceException.kt | 1 | 809 | /**
* Copyright 2017 Savvas Dalkitsis
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.device.model
class AlreadyExistsOnDeviceException(msg: String, cause: Throwable? = null) : Exception(msg, cause)
| apache-2.0 |
spkingr/50-android-kotlin-projects-in-100-days | ProjectObjectBox/app/src/main/java/me/liuqingwen/android/projectobjectbox/ContactListFragment.kt | 1 | 13214 | package me.liuqingwen.android.projectobjectbox
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.constraint.ConstraintLayout.LayoutParams.PARENT_ID
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.ListPreloader
import com.bumptech.glide.RequestBuilder
import es.dmoral.toasty.Toasty
import io.objectbox.Box
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import org.jetbrains.anko.*
import org.jetbrains.anko.constraint.layout.ConstraintSetBuilder.Side.*
import org.jetbrains.anko.constraint.layout.applyConstraintSet
import org.jetbrains.anko.constraint.layout.constraintLayout
import org.jetbrains.anko.constraint.layout.matchConstraint
import org.jetbrains.anko.design.snackbar
import org.jetbrains.anko.recyclerview.v7.recyclerView
import org.jetbrains.anko.support.v4.*
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Qingwen on 2018-3-2, project: ProjectObjectBox.
*
* @Author: Qingwen
* @DateTime: 2018-3-2
* @Package: me.liuqingwen.android.projectobjectbox.view in project: ProjectObjectBox
*
* Notice: If you are using this class or file, check it and do some modification.
*/
@SuppressLint("CheckResult")
class ContactListFragment: BasicFragment(), AnkoLogger
{
interface IFragmentInteractionListener:IJobHolder
{
fun onContactSelect(contact: Contact)
}
companion object
{
fun newInstance() = ContactListFragment()
}
private var fragmentInteractionListener: IFragmentInteractionListener? = null
private lateinit var contactBox: Box<Contact>
private lateinit var layoutSwipeRefreshLayout: SwipeRefreshLayout
private lateinit var recyclerView: RecyclerView
private val contactList by lazy(LazyThreadSafetyMode.NONE) { mutableListOf<Contact>() }
private val adapter by lazy(LazyThreadSafetyMode.NONE) {ContactListAdapter(this.contactList,super.getGlideRequest {
this.placeholder(R.mipmap.ic_launcher_round)
this.error(R.mipmap.ic_launcher_round)
this.circleCrop() }, { this.updateData(it) }, { this.selectContact(it) }, { this.popUpMenuFor(it) })
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = UI {
layoutSwipeRefreshLayout = swipeRefreshLayout {
onRefresh {
launch(contextJob + UI) {
loadData()
isRefreshing = false
}
}
recyclerView = recyclerView {
adapter = [email protected]
layoutManager = LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
addItemDecoration(DividerItemDecoration(this.context, DividerItemDecoration.VERTICAL))
}
}
}.view
fun updateOrInsert(id: Long)
{
val contact = this.contactBox.get(id)
if (id > 0)
{
val index = this.contactList.withIndex().find { it.value.id == id }?.index
if (index != null)
{
this.contactList[index] = contact
this.adapter.notifyItemChanged(index)
}
else
{
this.contactList.add(contact)
this.adapter.notifyItemInserted(this.contactList.size - 1)
}
}
}
private suspend fun loadData()
{
val listCount = this.contactList.size.toLong()
val dataCount = this.contactBox.count()
if (dataCount == listCount && this.contactBox.all.containsAll(this.contactList))
{
this.toast("")
if (dataCount <= 0) Toasty.warning(this.ctx,"Contact list is empty!", Toast.LENGTH_SHORT, true).show() else Toasty.info(this.ctx,"Already the newest list.", Toast.LENGTH_SHORT, true).show()
}
else
{
this.contactList.clear()
this.contactList += this.contactBox.all
if (listCount >= 0)
{
this.adapter.notifyDataSetChanged()
}
Toasty.success(this.ctx, "Contact list refreshed!", Toast.LENGTH_SHORT, true).show()
}
//Simulate the http or io processing
delay(1000)
}
private suspend fun updateData(contact: Contact)
{
this.contactBox.put(contact)
//Simulate the http or io processing
delay(500)
Toasty.success(this.ctx, "Contact saved successfully!", Toast.LENGTH_SHORT, true).show()
}
private suspend fun saveData(contact: Contact, position: Int)
{
this.updateData(contact)
this.contactList.add(position, contact)
this.adapter.notifyItemInserted(position)
}
private fun selectContact(contact: Contact)
{
this.fragmentInteractionListener?.onContactSelect(contact)
}
private fun popUpMenuFor(contact: Contact)
{
val position = contactList.indexOf(contact)
selector("[ ${contact.name} ]", listOf("Contact Information", "Copy As New", "Delete Contact")){_, selection ->
when(selection)
{
0 -> {
this.selectContact(contact)
}
1 -> {
val newContact = contact.copy(id = 0)
this.contactBox.put(newContact)
this.contactList.add(newContact)
this.adapter.notifyItemInserted(this.contactList.size - 1)
}
2 -> {
alert("Are your sure DELETE [ ${contact.name} ] from your contact list? The action cannot be restored!", "Warning") {
positiveButton("Cancel"){}
negativeButton("Delete"){
[email protected](contact.id)
[email protected](position)
[email protected](position)
val view = [email protected]
snackbar(view, "Mis-operation?", "Undo"){
launch(view.contextJob + UI) {
[email protected](contact, position)
}
}
}
}.show()
}
else -> Unit
}
}
}
override fun onAttach(context: Context?)
{
super.onAttach(context)
val app = context!!.applicationContext as MyApplication
this.contactBox = app.objectBoxStore.boxFor(Contact::class.java)
this.fragmentInteractionListener = context as? IFragmentInteractionListener
//I can load data before view created, because I just load the data without refresh the list!
launch(context.contextJob + UI) {
[email protected]()
}
}
override fun onDestroy()
{
super.onDestroy()
this.fragmentInteractionListener?.job?.cancel()
}
}
/**
* Here is the bug after the list scroll, the frist click will not be responsed!
* And the issue is opened here: [https://issuetracker.google.com/issues/66996774?pli=1]
*/
class ContactViewHolder(itemView: View):RecyclerView.ViewHolder(itemView)
{
fun bind(contact: Contact, requestBuilder: RequestBuilder<Drawable>?, actionCheck: (suspend (Contact) -> Unit)?, actionClick: ((Contact) -> Unit)?, actionLongClick: ((Contact) -> Unit)?)
{
val (_, name, _, birthday, address, imageUrl, isStar, _) = contact
this.itemView.find<TextView>(ID_LABEL_NAME).text = name
this.itemView.find<TextView>(
ID_LABEL_BIRTHDAY).text = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(birthday)
this.itemView.find<TextView>(ID_LABEL_ADDRESS).text = address
val checkboxStar = this.itemView.find<CheckBox>(
ID_CHECKBOX_STAR)
checkboxStar.isChecked = isStar
checkboxStar.setOnCheckedChangeListener { checkBox, isChecked ->
contact.isStarContact = isChecked
checkBox.isEnabled = false
launch(UI) {
actionCheck?.invoke(contact)
checkBox.isEnabled = true
}
}
val imageHead = this.itemView.find<ImageView>(
ID_IMAGE_HEAD)
requestBuilder?.load(imageUrl)?.into(imageHead)
actionClick?.run { [email protected] { this.invoke(contact) } }
actionLongClick?.run { [email protected] { this.invoke(contact); true } }
}
}
class ContactListAdapter(private val contactList: List<Contact>, private val requestBuilder: RequestBuilder<Drawable>? = null, val onItemCheckListener: (suspend (Contact) -> Unit)? = null, val onItemClickListener: ((Contact) -> Unit)? = null, val onItemLongClickListener: ((Contact) -> Unit)? = null):
RecyclerView.Adapter<ContactViewHolder>(), ListPreloader.PreloadModelProvider<Contact>
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ContactViewHolder(
ContactListUI().createView(
AnkoContext.create(parent.context, parent)))
override fun getItemCount() = this.contactList.size
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) = holder.bind(this.contactList[position], this.requestBuilder, this.onItemCheckListener, this.onItemClickListener, this.onItemLongClickListener)
override fun getPreloadItems(position: Int) = this.contactList.slice(position until position + 1)
override fun getPreloadRequestBuilder(item: Contact) = this.requestBuilder
}
private var ID_IMAGE_HEAD = 0x01
private var ID_LABEL_NAME = 0x02
private var ID_LABEL_BIRTHDAY = 0x03
private var ID_LABEL_ADDRESS = 0x04
private var ID_CHECKBOX_STAR = 0x05
class ContactListUI : AnkoComponent<ViewGroup>
{
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) {
constraintLayout {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
imageView {
id = ID_IMAGE_HEAD
}.lparams(width = matchConstraint, height = dip(80))
textView {
id = ID_LABEL_NAME
typeface = Typeface.DEFAULT_BOLD
}.lparams(width = wrapContent, height = wrapContent)
textView {
id = ID_LABEL_BIRTHDAY
textSize = 12.0f
}.lparams(width = wrapContent, height = wrapContent)
textView {
id = ID_LABEL_ADDRESS
textSize = 12.0f
}.lparams(width = matchConstraint, height = matchConstraint)
checkBox {
id = ID_CHECKBOX_STAR
}.lparams(width = wrapContent, height = wrapContent)
applyConstraintSet {
setDimensionRatio(ID_IMAGE_HEAD, "w,1:1")
connect(
START of ID_IMAGE_HEAD to START of PARENT_ID margin dip(8),
TOP of ID_IMAGE_HEAD to TOP of PARENT_ID margin dip(4),
BOTTOM of ID_IMAGE_HEAD to BOTTOM of PARENT_ID margin dip(4),
START of ID_LABEL_NAME to END of ID_IMAGE_HEAD margin dip(8),
TOP of ID_LABEL_NAME to TOP of PARENT_ID margin dip(4),
START of ID_LABEL_BIRTHDAY to START of ID_LABEL_NAME,
TOP of ID_LABEL_BIRTHDAY to BOTTOM of ID_LABEL_NAME margin dip(8),
START of ID_LABEL_ADDRESS to START of ID_LABEL_NAME,
END of ID_LABEL_ADDRESS to START of ID_CHECKBOX_STAR margin dip(8),
TOP of ID_LABEL_ADDRESS to BOTTOM of ID_LABEL_BIRTHDAY margin dip(4),
BOTTOM of ID_LABEL_ADDRESS to BOTTOM of PARENT_ID,
END of ID_CHECKBOX_STAR to END of PARENT_ID margin dip(8),
TOP of ID_CHECKBOX_STAR to TOP of PARENT_ID margin dip(8),
BOTTOM of ID_CHECKBOX_STAR to BOTTOM of PARENT_ID margin dip(8)
)
}
}
}
} | mit |
Sulion/marco-paolo | src/main/kotlin/org/logout/notifications/telegram/data/entities/incoming.kt | 1 | 867 | package org.logout.notifications.telegram.data.entities
import com.fasterxml.jackson.annotation.JsonProperty
import org.logout.notifications.telegram.data.DefaultConstructor
import java.math.BigDecimal
import java.util.*
@DefaultConstructor
data class InfobipIncomingPackage(val results: List<InfobipIncomingMessage>,
val messageCount: Int,
val pendingMessageCount: Int)
@DefaultConstructor
data class InfobipIncomingMessage(val from: String,
@JsonProperty("to") val toKey: String,
val receivedAt: Date,
val message: MessageBody,
val price: Price)
@DefaultConstructor
data class Price(val pricePerMessage: BigDecimal,
val currency: Currency)
| apache-2.0 |
spring-projects/spring-data-examples | cassandra/kotlin/src/main/kotlin/example.springdata.cassandra.kotlin/ApplicationConfiguration.kt | 2 | 952 | /*
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.cassandra.kotlin
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
/**
* @author Mark Paluch
*/
@SpringBootApplication
class ApplicationConfiguration
fun main(args: Array<String>) {
runApplication<ApplicationConfiguration>(*args)
}
| apache-2.0 |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/repository/BaseRepository.kt | 1 | 618 | package com.rolandvitezhu.todocloud.repository
import com.rolandvitezhu.todocloud.app.AppController.Companion.instance
import com.rolandvitezhu.todocloud.database.TodoCloudDatabaseDao
import com.rolandvitezhu.todocloud.network.ApiService
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
open class BaseRepository @Inject constructor() {
@Inject
lateinit var todoCloudDatabaseDao: TodoCloudDatabaseDao
@Inject
lateinit var apiService: ApiService
var nextRowVersion = 0
init {
Objects.requireNonNull(instance)?.appComponent?.inject(this)
}
} | mit |
geeteshk/Hyper | app/src/main/java/io/geeteshk/hyper/extensions/String.kt | 1 | 557 | package io.geeteshk.hyper.extensions
import android.text.Editable
import android.text.Spannable
import android.text.style.ForegroundColorSpan
fun String.replace(vararg pairs: Pair<String, String>) =
pairs.fold(this) { it, (old, new) -> it.replace(old, new, true) }
fun Editable.span(color: Int, range: IntRange) =
setSpan(ForegroundColorSpan(color), range.start, range.endInclusive, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
fun Editable.color(regex: Regex, color: Int) {
regex.findAll(this).forEach {
span(color, it.range)
}
} | apache-2.0 |
Saketme/JRAW | lib/src/main/kotlin/net/dean/jraw/models/SubredditSearchSort.kt | 2 | 547 | package net.dean.jraw.models
/** Sorting used specifically in [net.dean.jraw.pagination.SubredditSearchPaginator] */
enum class SubredditSearchSort : Sorting {
/** Top results will more closely match the query */
RELEVANCE,
/**
* Top results will have the most actions per unit time. An action could be a user submitting a post, submitting a
* comment, or voting, but at the end of the day how reddit determines "activity" is really up to them.
*/
ACTIVITY;
override val requiresTimePeriod: Boolean = false
}
| mit |
abigpotostew/easypolitics | shared/src/main/kotlin/bz/stewart/bracken/shared/data/PublicTitle.kt | 1 | 100 | package bz.stewart.bracken.shared.data
/**
* Created by stew on 5/18/17.
*/
interface PublicTitle | apache-2.0 |
Maccimo/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/tree/dependency/AttachedJarDependency.kt | 4 | 552 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.importing.tree.dependency
import com.intellij.openapi.roots.DependencyScope
class AttachedJarDependency(artifactName: String,
val classes: List<String>,
val sources: List<String>,
val javadocs: List<String>,
scope: DependencyScope) : MavenImportDependency<String>(artifactName, scope) | apache-2.0 |
Maccimo/intellij-community | plugins/kotlin/fir/test/org/jetbrains/kotlin/idea/fir/inspections/AbstractHLLocalInspectionTest.kt | 2 | 1304 | // 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.fir.inspections
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import org.jetbrains.kotlin.idea.fir.highlighter.KotlinHighLevelDiagnosticHighlightingPass
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.AbstractLocalInspectionTest
import org.jetbrains.kotlin.test.utils.IgnoreTests
import java.io.File
abstract class AbstractHLLocalInspectionTest : AbstractLocalInspectionTest() {
override fun isFirPlugin() = true
override val inspectionFileName: String = ".firInspection"
override fun checkForUnexpectedErrors(fileText: String) {}
override fun collectHighlightInfos(): List<HighlightInfo> {
return KotlinHighLevelDiagnosticHighlightingPass.ignoreThisPassInTests { super.collectHighlightInfos() }
}
override fun doTestFor(mainFile: File, inspection: AbstractKotlinInspection, fileText: String) {
IgnoreTests.runTestIfNotDisabledByFileDirective(mainFile.toPath(), IgnoreTests.DIRECTIVES.IGNORE_FIR, "after") {
super.doTestFor(mainFile, inspection, fileText)
}
}
} | apache-2.0 |
Rin-Da/UCSY-News | app/src/main/java/io/github/rin_da/ucsynews/presentation/home/view/NavHeaderView.kt | 1 | 1667 | package io.github.rin_da.ucsynews.presentation.home.view
import android.content.Context
import android.view.Gravity
import android.view.View
import com.pawegio.kandroid.dp
import io.github.rin_da.ucsynews.R
import io.github.rin_da.ucsynews.presentation.base.ui.appCompatImageView
import io.github.rin_da.ucsynews.presentation.base.ui.setDemiBold
import org.jetbrains.anko.*
/**
* Created by user on 12/15/16.
*/
class NavHeaderView : AnkoComponent<Context> {
override fun createView(ui: AnkoContext<Context>): View {
with(ui) {
verticalLayout(theme = R.style.ThemeOverlay_AppCompat_Dark) {
backgroundColor = R.color.colorPrimary
gravity = Gravity.CENTER
lparams(width = matchParent, height = dimen(R.dimen.nav_header_height))
appCompatImageView {
imageResource = R.drawable.ic_sad
}.lparams(width = dimen(R.dimen.home_profile_image_dimens), height = dimen(R.dimen.home_profile_image_dimens)) {
}
textView {
textSize = sp(8).toFloat()
setDemiBold()
gravity = Gravity.CENTER_HORIZONTAL
text = "Sovalnokovia Marcida"
}.lparams(width = dp(200), height = wrapContent) {
gravity = Gravity.CENTER
topMargin = dimen(R.dimen.activity_vertical_margin)
bottomPadding = dimen(R.dimen.activity_vertical_margin)
leftPadding = dimen(R.dimen.activity_horizontal_margin)
}
}
}
return ui.view
}
}
| mit |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/helper/SearchHelperKt.kt | 1 | 7935 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.common.Direction
import com.maddyhome.idea.vim.helper.SearchHelper.findPositionOfFirstCharacter
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
private data class State(val position: Int, val trigger: Char, val inQuote: Boolean?, val lastOpenSingleQuotePos: Int)
// bounds are considered inside corresponding quotes
fun checkInString(chars: CharSequence, currentPos: Int, str: Boolean): Boolean {
val begin = findPositionOfFirstCharacter(chars, currentPos, setOf('\n'), false, Direction.BACKWARDS)?.second ?: 0
val changes = quoteChanges(chars, begin)
// TODO: here we need to keep only the latest element in beforePos (if any) and
// don't need atAndAfterPos to be eagerly collected
var (beforePos, atAndAfterPos) = changes.partition { it.position < currentPos }
var (atPos, afterPos) = atAndAfterPos.partition { it.position == currentPos }
assert(atPos.size <= 1) { "Multiple characters at position $currentPos in string $chars" }
if (atPos.isNotEmpty()) {
val atPosChange = atPos[0]
if (afterPos.isEmpty()) {
// it is situation when cursor is on closing quote, so we must consider that we are inside quotes pair
afterPos = afterPos.toMutableList()
afterPos.add(atPosChange)
} else {
// it is situation when cursor is on opening quote, so we must consider that we are inside quotes pair
beforePos = beforePos.toMutableList()
beforePos.add(atPosChange)
}
}
val lastBeforePos = beforePos.lastOrNull()
// if opening quote was found before pos (inQuote=true), it doesn't mean pos is in string, we need
// to find closing quote to be sure
var posInQuote = lastBeforePos?.inQuote?.let { if (it) null else it }
val lastOpenSingleQuotePosBeforeCurrentPos = lastBeforePos?.lastOpenSingleQuotePos ?: -1
var posInChar = if (lastOpenSingleQuotePosBeforeCurrentPos == -1) false else null
var inQuote: Boolean? = null
for ((_, trigger, inQuoteAfter, lastOpenSingleQuotePosAfter) in afterPos) {
inQuote = inQuoteAfter
if (posInQuote != null && posInChar != null) break
if (posInQuote == null && inQuoteAfter != null) {
// if we found double quote
if (trigger == '"') {
// then previously it has opposite value
posInQuote = !inQuoteAfter
// if we found single quote
} else if (trigger == '\'') {
// then we found closing single quote
posInQuote = inQuoteAfter
}
}
if (posInChar == null && lastOpenSingleQuotePosAfter != lastOpenSingleQuotePosBeforeCurrentPos) {
// if we found double quote and we reset position of last single quote
if (trigger == '"' && lastOpenSingleQuotePosAfter == -1) {
// then it means previously there supposed to be open single quote
posInChar = false
// if we found single quote
} else if (trigger == '\'') {
// if we reset position of last single quote
// it means we found closing single quote
// else it means we found opening single quote
posInChar = lastOpenSingleQuotePosAfter == -1
}
}
}
return if (str) posInQuote != null && posInQuote && (inQuote == null || !inQuote) else posInChar != null && posInChar
}
// yields changes of inQuote and lastOpenSingleQuotePos during while iterating over chars
// rules are that:
// - escaped quotes are skipped
// - single quoted group may enclose only one character, maybe escaped,
// - so distance between opening and closing single quotes cannot be more than 3
// - bounds are considered inside corresponding quotes
private fun quoteChanges(chars: CharSequence, begin: Int) = sequence {
// position of last found unpaired single quote
var lastOpenSingleQuotePos = -1
// whether we are in double quotes
// true - definitely yes
// false - definitely no
// null - maybe yes, in case we found such combination: '"
// in that situation it may be double quote inside single quotes, so we cannot threat it as double quote pair open/close
var inQuote: Boolean? = false
val charsToSearch = setOf('\'', '"', '\n')
var found = findPositionOfFirstCharacter(chars, begin, charsToSearch, false, Direction.FORWARDS)
while (found != null && found.first != '\n') {
val i = found.second
val c = found.first
when (c) {
'"' -> {
// if [maybe] in quote, then we know we found closing quote, so now we surely are not in quote
if (inQuote == null || inQuote) {
// we just found closing double quote
inQuote = false
// reset last found single quote, as it was in string literal
lastOpenSingleQuotePos = -1
// if we previously found unclosed single quote
} else if (lastOpenSingleQuotePos >= 0) {
// ...but we are too far from it
if (i - lastOpenSingleQuotePos > 2) {
// then it definitely was not opening single quote
lastOpenSingleQuotePos = -1
// and we found opening double quote
inQuote = true
} else {
// else we don't know if we inside double or single quotes or not
inQuote = null
}
// we were not in double nor in single quote, so now we are in double quote
} else {
inQuote = true
}
}
'\'' -> {
// if we previously found unclosed single quote
if (lastOpenSingleQuotePos >= 0) {
// ...but we are too far from it
if (i - lastOpenSingleQuotePos > 3) {
// ... forget about it and threat current one as unclosed
lastOpenSingleQuotePos = i
} else {
// else we found closing single quote
lastOpenSingleQuotePos = -1
// and if we didn't know whether we are in double quote or not
if (inQuote == null) {
// then now we are definitely not in
inQuote = false
}
}
} else {
// we found opening single quote
lastOpenSingleQuotePos = i
}
}
}
yield(State(i, c, inQuote, lastOpenSingleQuotePos))
found =
findPositionOfFirstCharacter(chars, i + Direction.FORWARDS.toInt(), charsToSearch, false, Direction.FORWARDS)
}
}
/**
* Check ignorecase and smartcase options to see if a case insensitive search should be performed with the given pattern.
*
* When ignorecase is not set, this will always return false - perform a case sensitive search.
*
* Otherwise, check smartcase. When set, the search will be case insensitive if the pattern contains only lowercase
* characters, and case sensitive (returns false) if the pattern contains any lowercase characters.
*
* The smartcase option can be ignored, e.g. when searching for the whole word under the cursor. This always performs a
* case insensitive search, so `\<Work\>` will match `Work` and `work`. But when choosing the same pattern from search
* history, the smartcase option is applied, and `\<Work\>` will only match `Work`.
*/
fun shouldIgnoreCase(pattern: String, ignoreSmartCaseOption: Boolean): Boolean {
val sc = VimPlugin.getOptionService().isSet(OptionScope.GLOBAL, OptionConstants.smartcaseName) &&
!ignoreSmartCaseOption
return VimPlugin.getOptionService().isSet(OptionScope.GLOBAL, OptionConstants.ignorecaseName) && !(sc && containsUpperCase(pattern))
}
private fun containsUpperCase(pattern: String): Boolean {
for (i in pattern.indices) {
if (Character.isUpperCase(pattern[i]) && (i == 0 || pattern[i - 1] != '\\')) {
return true
}
}
return false
}
| mit |
fcostaa/kotlin-rxjava-android | feature/listing/src/main/kotlin/com/github/felipehjcosta/marvelapp/listing/presentation/CharacterListViewModel.kt | 1 | 709 | package com.github.felipehjcosta.marvelapp.listing.presentation
import com.felipecosta.rxaction.RxCommand
import io.reactivex.Observable
interface CharacterListViewModelInput {
val loadItemsCommand: RxCommand<Any>
val loadMoreItemsCommand: RxCommand<Any>
}
interface CharacterListViewModelOutput {
val items: Observable<List<CharacterItemViewModel>>
val showLoading: Observable<Boolean>
val showLoadItemsError: Observable<Boolean>
val newItems: Observable<List<CharacterItemViewModel>>
val showLoadingMore: Observable<Boolean>
}
abstract class CharacterListViewModel {
abstract val input: CharacterListViewModelInput
abstract val output: CharacterListViewModelOutput
}
| mit |
edwardharks/Aircraft-Recognition | androidcommon/src/main/kotlin/com/edwardharker/aircraftrecognition/ui/TextViewExtensions.kt | 1 | 694 | package com.edwardharker.aircraftrecognition.ui
import android.graphics.drawable.Drawable
import android.os.Build
import android.widget.TextView
fun TextView.setTextAppearanceCompat(textAppearance: Int) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
@Suppress("DEPRECATION")
setTextAppearance(context, textAppearance)
} else {
setTextAppearance(textAppearance)
}
}
var TextView.drawableBottom: Drawable?
get() = compoundDrawables[3]
set(value) {
setCompoundDrawablesRelativeWithIntrinsicBounds(
compoundDrawables[0],
compoundDrawables[1],
compoundDrawables[2],
value
)
}
| gpl-3.0 |
oliveiradev/RxPhoto | lib/src/main/java/com/github/oliveiradev/lib/exceptions/ExternalStorageWriteException.kt | 1 | 139 | package com.github.oliveiradev.lib.exceptions
/**
* Created by Genius on 03.12.2017.
*/
class ExternalStorageWriteException: Exception() | mit |
mdaniel/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/whenExpression/whenAnyEntry.kt | 12 | 233 | fun foo(x: Any): Any = x.hashCode()
fun a() {
val i = 0
<warning descr="SSR">when (foo(i)) {
is Int -> Unit
else -> Unit
}</warning>
<warning descr="SSR">when (i) {
1 -> Unit
}</warning>
} | apache-2.0 |
andrewoma/kommon | src/main/kotlin/com/github/andrewoma/kommon/collection/CircularBuffer.kt | 1 | 4264 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kommon.collection
import java.util.*
internal class CircularBuffer<T>(size: Int) : List<T> {
private var elements: Array<Any?> // TODO ... fix bound of Array
private var start = 0
private var end = 0
private var full = false
private var maxElements = 0
init {
require(size >= 0) { "The size must be greater than 0" }
elements = arrayOfNulls(size)
maxElements = elements.size
}
override val size: Int
get() = when {
end < start -> maxElements - start + end
end == start -> if (full) maxElements else 0
else -> end - start
}
override fun isEmpty() = size == 0
fun add(element: T) {
if (size == maxElements) {
remove()
}
elements[end++] = element
if (end >= maxElements) {
end = 0
}
if (end == start) {
full = true
}
}
fun remove(): T {
if (isEmpty()) throw NoSuchElementException()
val element = elements[start]
elements[start++] = null
if (start >= maxElements) {
start = 0
}
full = false
@Suppress("UNCHECKED_CAST")
return element as T
}
private fun increment(index: Int) = (index + 1).let { if (it >= maxElements) 0 else it }
override fun iterator(): Iterator<T> {
return object : Iterator<T> {
private var index = start
private var lastReturnedIndex = -1
private var isFirst = full
override fun hasNext() = isFirst || (index != end)
override fun next(): T {
if (!hasNext()) {
throw NoSuchElementException()
}
isFirst = false
lastReturnedIndex = index
index = increment(index)
@Suppress("UNCHECKED_CAST")
return elements[lastReturnedIndex] as T
}
}
}
override fun contains(element: T): Boolean {
throw UnsupportedOperationException()
}
override fun containsAll(elements: Collection<T>): Boolean {
throw UnsupportedOperationException()
}
override fun get(index: Int): T {
if (index >= size) throw IndexOutOfBoundsException("")
val pos = (start + index).let { if (it >= maxElements) it - maxElements else it }
@Suppress("UNCHECKED_CAST")
return elements[pos] as T
}
override fun indexOf(element: T): Int {
throw UnsupportedOperationException()
}
override fun lastIndexOf(element: T): Int {
throw UnsupportedOperationException()
}
override fun listIterator(): ListIterator<T> {
throw UnsupportedOperationException()
}
override fun listIterator(index: Int): ListIterator<T> {
throw UnsupportedOperationException()
}
override fun subList(fromIndex: Int, toIndex: Int): List<T> {
throw UnsupportedOperationException()
}
override fun toString(): String {
return this.joinToString(", ", "[", "]")
}
}
| mit |
mdaniel/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/MacDistributionBuilder.kt | 1 | 22513 | // 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.diagnostic.telemetry.createTask
import com.intellij.diagnostic.telemetry.use
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.util.SystemProperties
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData
import org.jetbrains.intellij.build.impl.productInfo.checkInArchive
import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson
import org.jetbrains.intellij.build.io.copyDir
import org.jetbrains.intellij.build.io.copyFile
import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders
import org.jetbrains.intellij.build.io.writeNewFile
import org.jetbrains.intellij.build.tasks.NoDuplicateZipArchiveOutputStream
import org.jetbrains.intellij.build.tasks.dir
import org.jetbrains.intellij.build.tasks.entry
import org.jetbrains.intellij.build.tasks.executableFileUnixMode
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermission
import java.time.LocalDate
import java.util.concurrent.ForkJoinTask
import java.util.function.BiConsumer
import java.util.zip.Deflater
import kotlin.io.path.nameWithoutExtension
class MacDistributionBuilder(override val context: BuildContext,
private val customizer: MacDistributionCustomizer,
private val ideaProperties: Path?) : OsSpecificDistributionBuilder {
private val targetIcnsFileName: String = "${context.productProperties.baseFileName}.icns"
override val targetOs: OsFamily
get() = OsFamily.MACOS
private fun getDocTypes(): String {
val associations = mutableListOf<String>()
if (customizer.associateIpr) {
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>ipr</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${targetIcnsFileName}</string>
<key>CFBundleTypeName</key>
<string>${context.applicationInfo.productName} Project File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
for (fileAssociation in customizer.fileAssociations) {
val iconPath = fileAssociation.iconPath
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>${fileAssociation.extension}</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${if (iconPath.isEmpty()) targetIcnsFileName else File(iconPath).name}</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
return associations.joinToString(separator = "\n ") + customizer.additionalDocTypes
}
override fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) {
doCopyExtraFiles(macDistDir = targetPath, arch = arch, copyDistFiles = true)
}
private fun doCopyExtraFiles(macDistDir: Path, arch: JvmArchitecture?, copyDistFiles: Boolean) {
@Suppress("SpellCheckingInspection")
val platformProperties = mutableListOf(
"\n#---------------------------------------------------------------------",
"# macOS-specific system properties",
"#---------------------------------------------------------------------",
"com.apple.mrj.application.live-resize=false",
"apple.laf.useScreenMenuBar=true",
"jbScreenMenuBar.enabled=true",
"apple.awt.fileDialogForDirectories=true",
"apple.awt.graphics.UseQuartz=true",
"apple.awt.fullscreencapturealldisplays=false"
)
customizer.getCustomIdeaProperties(context.applicationInfo).forEach(BiConsumer { k, v -> platformProperties.add("$k=$v") })
layoutMacApp(ideaProperties!!, platformProperties, getDocTypes(), macDistDir, context)
unpackPty4jNative(context, macDistDir, "darwin")
generateBuildTxt(context, macDistDir.resolve("Resources"))
if (copyDistFiles) {
copyDistFiles(context, macDistDir)
}
customizer.copyAdditionalFiles(context, macDistDir.toString())
if (arch != null) {
customizer.copyAdditionalFiles(context, macDistDir, arch)
}
generateUnixScripts(context, emptyList(), macDistDir.resolve("bin"), OsFamily.MACOS)
}
override fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) {
doCopyExtraFiles(macDistDir = osAndArchSpecificDistPath, arch = arch, copyDistFiles = false)
context.executeStep(spanBuilder("build macOS artifacts").setAttribute("arch", arch.name), BuildOptions.MAC_ARTIFACTS_STEP) {
val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)
val publishSit = context.publishSitArchive
val publishZipOnly = !publishSit && context.options.buildStepsToSkip.contains(BuildOptions.MAC_DMG_STEP)
val binariesToSign = customizer.getBinariesToSign(context, arch)
if (!binariesToSign.isEmpty()) {
context.executeStep(spanBuilder("sign binaries for macOS distribution")
.setAttribute("arch", arch.name), BuildOptions.MAC_SIGN_STEP) {
context.signFiles(binariesToSign.map(osAndArchSpecificDistPath::resolve), mapOf(
"mac_codesign_options" to "runtime",
"mac_codesign_force" to "true",
"mac_codesign_deep" to "true",
))
}
}
val macZip = (if (publishZipOnly) context.paths.artifactDir else context.paths.tempDir)
.resolve("$baseName.mac.${arch.name}.zip")
val macZipWithoutRuntime = macZip.resolveSibling(macZip.nameWithoutExtension + "-no-jdk.zip")
val zipRoot = getMacZipRoot(customizer, context)
val runtimeDist = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.MACOS, arch)
val directories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, runtimeDist)
val extraFiles = context.getDistFiles()
val compressionLevel = if (publishSit || publishZipOnly) Deflater.DEFAULT_COMPRESSION else Deflater.BEST_SPEED
val errorsConsumer = context.messages::warning
if (context.options.buildMacArtifactsWithRuntime) {
buildMacZip(
targetFile = macZip,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule, context = context,
javaExecutablePath = "../jbr/Contents/Home/bin/java"),
directories = directories,
extraFiles = extraFiles,
executableFilePatterns = generateExecutableFilesPatterns(true),
compressionLevel = compressionLevel,
errorsConsumer = errorsConsumer
)
}
if (context.options.buildMacArtifactsWithoutRuntime) {
buildMacZip(
targetFile = macZipWithoutRuntime,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule, context = context, javaExecutablePath = null),
directories = directories - runtimeDist,
extraFiles = extraFiles,
executableFilePatterns = generateExecutableFilesPatterns(false),
compressionLevel = compressionLevel,
errorsConsumer = errorsConsumer
)
}
if (publishZipOnly) {
Span.current().addEvent("skip DMG and SIT artifacts producing")
context.notifyArtifactBuilt(macZip)
if (context.options.buildMacArtifactsWithoutRuntime) {
context.notifyArtifactBuilt(macZipWithoutRuntime)
}
}
else {
buildAndSignDmgFromZip(macZip, macZipWithoutRuntime, arch, context.builtinModule).invoke()
}
}
}
fun buildAndSignDmgFromZip(macZip: Path, macZipWithoutRuntime: Path?, arch: JvmArchitecture, builtinModule: BuiltinModulesFileData?): ForkJoinTask<*> {
return createBuildForArchTask(builtinModule, arch, macZip, macZipWithoutRuntime, customizer, context)
}
private fun layoutMacApp(ideaPropertiesFile: Path,
platformProperties: List<String>,
docTypes: String?,
macDistDir: Path,
context: BuildContext) {
val macCustomizer = customizer
copyDirWithFileFilter(context.paths.communityHomeDir.communityRoot.resolve("bin/mac"), macDistDir.resolve("bin"), customizer.binFilesFilter)
copyDir(context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/Contents"), macDistDir)
val executable = context.productProperties.baseFileName
Files.move(macDistDir.resolve("MacOS/executable"), macDistDir.resolve("MacOS/$executable"))
//noinspection SpellCheckingInspection
val icnsPath = Path.of((if (context.applicationInfo.isEAP) customizer.icnsPathForEAP else null) ?: customizer.icnsPath)
val resourcesDistDir = macDistDir.resolve("Resources")
copyFile(icnsPath, resourcesDistDir.resolve(targetIcnsFileName))
for (fileAssociation in customizer.fileAssociations) {
if (!fileAssociation.iconPath.isEmpty()) {
val source = Path.of(fileAssociation.iconPath)
val dest = resourcesDistDir.resolve(source.fileName)
Files.deleteIfExists(dest)
copyFile(source, dest)
}
}
val fullName = context.applicationInfo.productName
//todo[nik] improve
val minor = context.applicationInfo.minorVersion
val isNotRelease = context.applicationInfo.isEAP && !minor.contains("RC") && !minor.contains("Beta")
val version = if (isNotRelease) "EAP ${context.fullBuildNumber}" else "${context.applicationInfo.majorVersion}.${minor}"
val isEap = if (isNotRelease) "-EAP" else ""
val properties = Files.readAllLines(ideaPropertiesFile)
properties.addAll(platformProperties)
Files.write(macDistDir.resolve("bin/idea.properties"), properties)
val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val classPath = context.bootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val fileVmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties).toMutableList()
val additionalJvmArgs = context.getAdditionalJvmArguments(OsFamily.MACOS).toMutableList()
if (!bootClassPath.isEmpty()) {
//noinspection SpellCheckingInspection
additionalJvmArgs.add("-Xbootclasspath/a:$bootClassPath")
}
val predicate: (String) -> Boolean = { it.startsWith("-D") }
val launcherProperties = additionalJvmArgs.filter(predicate)
val launcherVmOptions = additionalJvmArgs.filterNot(predicate)
fileVmOptions.add("-XX:ErrorFile=\$USER_HOME/java_error_in_${executable}_%p.log")
fileVmOptions.add("-XX:HeapDumpPath=\$USER_HOME/java_error_in_${executable}.hprof")
VmOptionsGenerator.writeVmOptions(macDistDir.resolve("bin/${executable}.vmoptions"), fileVmOptions, "\n")
val urlSchemes = macCustomizer.urlSchemes
val urlSchemesString = if (urlSchemes.isEmpty()) {
""
}
else {
"""
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>Stacktrace</string>
<key>CFBundleURLSchemes</key>
<array>
${urlSchemes.joinToString(separator = "\n") { " <string>$it</string>" }}
</array>
</dict>
</array>
"""
}
val todayYear = LocalDate.now().year.toString()
//noinspection SpellCheckingInspection
substituteTemplatePlaceholders(
inputFile = macDistDir.resolve("Info.plist"),
outputFile = macDistDir.resolve("Info.plist"),
placeholder = "@@",
values = listOf(
Pair("build", context.fullBuildNumber),
Pair("doc_types", docTypes ?: ""),
Pair("executable", executable),
Pair("icns", targetIcnsFileName),
Pair("bundle_name", fullName),
Pair("product_state", isEap),
Pair("bundle_identifier", macCustomizer.bundleIdentifier),
Pair("year", todayYear),
Pair("version", version),
Pair("vm_options", optionsToXml(launcherVmOptions)),
Pair("vm_properties", propertiesToXml(launcherProperties, mapOf("idea.executable" to context.productProperties.baseFileName))),
Pair("class_path", classPath),
Pair("main_class_name", context.productProperties.mainClassName.replace('.', '/')),
Pair("url_schemes", urlSchemesString),
Pair("architectures", "<key>LSArchitecturePriority</key>\n <array>\n" +
macCustomizer.architectures.joinToString(separator = "\n") { " <string>$it</string>\n" } +
" </array>"),
Pair("min_osx", macCustomizer.minOSXVersion),
)
)
val distBinDir = macDistDir.resolve("bin")
Files.createDirectories(distBinDir)
val sourceScriptDir = context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/mac/scripts")
Files.newDirectoryStream(sourceScriptDir).use { stream ->
val inspectCommandName = context.productProperties.inspectCommandName
for (file in stream) {
if (file.toString().endsWith(".sh")) {
var fileName = file.fileName.toString()
if (fileName == "inspect.sh" && inspectCommandName != "inspect") {
fileName = "${inspectCommandName}.sh"
}
val sourceFileLf = Files.createTempFile(context.paths.tempDir, file.fileName.toString(), "")
try {
// Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts
// https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri
Files.writeString(sourceFileLf, Files.readString(file).replace("\r", ""))
val target = distBinDir.resolve(fileName)
substituteTemplatePlaceholders(
sourceFileLf,
target,
"@@",
listOf(
Pair("product_full", fullName),
Pair("script_name", executable),
Pair("inspectCommandName", inspectCommandName),
),
false,
)
}
finally {
Files.delete(sourceFileLf)
}
}
}
}
}
override fun generateExecutableFilesPatterns(includeRuntime: Boolean): List<String> {
val executableFilePatterns = mutableListOf(
"bin/*.sh",
"bin/*.py",
"bin/fsnotifier",
"bin/printenv",
"bin/restarter",
"bin/repair",
"MacOS/*"
)
if (includeRuntime) {
executableFilePatterns += context.bundledRuntime.executableFilesPatterns(OsFamily.MACOS)
}
return executableFilePatterns + customizer.extraExecutables
}
private fun createBuildForArchTask(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path, macZipWithoutRuntime: Path?,
customizer: MacDistributionCustomizer,
context: BuildContext): ForkJoinTask<*> {
return createTask(spanBuilder("build macOS artifacts for specific arch").setAttribute("arch", arch.name)) {
val notarize = SystemProperties.getBooleanProperty("intellij.build.mac.notarize", true)
ForkJoinTask.invokeAll(buildForArch(builtinModule, arch, macZip, macZipWithoutRuntime, notarize, customizer, context))
Files.deleteIfExists(macZip)
}
}
private fun buildForArch(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path, macZipWithoutRuntime: Path?,
notarize: Boolean,
customizer: MacDistributionCustomizer,
context: BuildContext): List<ForkJoinTask<*>> {
val tasks = mutableListOf<ForkJoinTask<*>?>()
val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}"
val archStr = arch.name
if (context.options.buildMacArtifactsWithRuntime) {
tasks.add(createSkippableTask(
spanBuilder("build DMG with Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_jre_$archStr",
context
) {
signAndBuildDmg(builtinModule = builtinModule,
context = context,
customizer = customizer,
macHostProperties = context.proprietaryBuildTools.macHostProperties,
macZip = macZip,
isRuntimeBundled = true,
suffix = suffix,
notarize = notarize)
})
}
if (context.options.buildMacArtifactsWithoutRuntime) {
requireNotNull(macZipWithoutRuntime)
tasks.add(createSkippableTask(
spanBuilder("build DMG without Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_no_jre_$archStr",
context
) {
signAndBuildDmg(builtinModule = builtinModule,
context = context,
customizer = customizer,
macHostProperties = context.proprietaryBuildTools.macHostProperties,
macZip = macZipWithoutRuntime,
isRuntimeBundled = false,
suffix = "-no-jdk$suffix",
notarize = notarize)
})
}
return tasks.filterNotNull()
}
}
private fun optionsToXml(options: List<String>): String {
val buff = StringBuilder()
for (it in options) {
buff.append(" <string>").append(it).append("</string>\n")
}
return buff.toString().trim()
}
private fun propertiesToXml(properties: List<String>, moreProperties: Map<String, String>): String {
val buff = StringBuilder()
for (it in properties) {
val p = it.indexOf('=')
buff.append(" <key>").append(it.substring(2, p)).append("</key>\n")
buff.append(" <string>").append(it.substring(p + 1)).append("</string>\n")
}
moreProperties.forEach { (key, value) ->
buff.append(" <key>").append(key).append("</key>\n")
buff.append(" <string>").append(value).append("</string>\n")
}
return buff.toString().trim()
}
internal fun getMacZipRoot(customizer: MacDistributionCustomizer, context: BuildContext): String =
"${customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)}/Contents"
internal fun generateMacProductJson(builtinModule: BuiltinModulesFileData?, context: BuildContext, javaExecutablePath: String?): String {
val executable = context.productProperties.baseFileName
return generateMultiPlatformProductJson(
relativePathToBin = "../bin",
builtinModules = builtinModule,
launch = listOf(
ProductInfoLaunchData(
os = OsFamily.MACOS.osName,
launcherPath = "../MacOS/${executable}",
javaExecutablePath = javaExecutablePath,
vmOptionsFilePath = "../bin/${executable}.vmoptions",
startupWmClass = null,
)
), context = context
)
}
private fun MacDistributionBuilder.buildMacZip(targetFile: Path,
zipRoot: String,
productJson: String,
directories: List<Path>,
extraFiles: Collection<Map.Entry<Path, String>>,
executableFilePatterns: List<String>,
compressionLevel: Int,
errorsConsumer: (String) -> Unit) {
spanBuilder("build zip archive for macOS")
.setAttribute("file", targetFile.toString())
.setAttribute("zipRoot", zipRoot)
.setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns)
.use {
val fs = targetFile.fileSystem
val patterns = executableFilePatterns.map { fs.getPathMatcher("glob:$it") }
val entryCustomizer: (ZipArchiveEntry, Path, String) -> Unit = { entry, file, relativePath ->
when {
patterns.any { it.matches(Path.of(relativePath)) } -> entry.unixMode = executableFileUnixMode
SystemInfoRt.isUnix && PosixFilePermission.OWNER_EXECUTE in Files.getPosixFilePermissions (file) -> {
errorsConsumer("Executable permissions of $relativePath won't be set in $targetFile. " +
"Please make sure that executable file patterns are updated.")
}
}
}
writeNewFile(targetFile) { targetFileChannel ->
NoDuplicateZipArchiveOutputStream(targetFileChannel).use { zipOutStream ->
zipOutStream.setLevel(compressionLevel)
zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson.encodeToByteArray())
val fileFilter: (Path, String) -> Boolean = { sourceFile, relativePath ->
if (relativePath.endsWith(".txt") && !relativePath.contains('/')) {
zipOutStream.entry("$zipRoot/Resources/${relativePath}", sourceFile)
false
}
else {
true
}
}
for (dir in directories) {
zipOutStream.dir(dir, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
}
for ((file, relativePath) in extraFiles) {
zipOutStream.entry("$zipRoot/${FileUtilRt.toSystemIndependentName(relativePath)}${if (relativePath.isEmpty()) "" else "/"}${file.fileName}", file)
}
}
}
checkInArchive(archiveFile = targetFile, pathInArchive = "$zipRoot/Resources", context = context)
}
}
| apache-2.0 |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/repository/CoverCache.kt | 1 | 3199 | package com.kelsos.mbrc.repository
import android.app.Application
import com.kelsos.mbrc.constants.Protocol
import com.kelsos.mbrc.data.CoverInfo
import com.kelsos.mbrc.data.key
import com.kelsos.mbrc.data.library.Cover
import com.kelsos.mbrc.data.library.key
import com.kelsos.mbrc.di.modules.AppDispatchers
import com.kelsos.mbrc.networking.ApiBase
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.withContext
import okio.ByteString.Companion.decodeBase64
import okio.buffer
import okio.sink
import timber.log.Timber
import java.io.File
import javax.inject.Inject
class CoverCache
@Inject
constructor(
private val albumRepository: AlbumRepository,
private val api: ApiBase,
private val dispatchers: AppDispatchers,
app: Application
) {
private val cache = File(app.cacheDir, "covers")
init {
if (!cache.exists()) {
cache.mkdir()
}
}
suspend fun cache() {
val covers = withContext(dispatchers.db) {
val albumCovers = mutableListOf<CoverInfo>()
val covers = albumRepository.getAllCursor()
.map {
CoverInfo(
artist = it.artist ?: "",
album = it.album ?: "",
hash = it.cover ?: ""
)
}
withContext(dispatchers.io) {
val files = cache.listFiles()?.map { it.nameWithoutExtension } ?: emptyList()
for (cover in covers) {
if (cover.hash.isBlank() || files.contains(cover.key())) {
albumCovers.add(cover)
} else {
albumCovers.add(cover.copy(hash = ""))
}
}
}
albumCovers
}
withContext(dispatchers.io) {
val updated = mutableListOf<CoverInfo>()
api.getAll(Protocol.LibraryCover, covers, Cover::class).onCompletion {
Timber.v("Updated covers for ${updated.size} albums")
withContext(dispatchers.db) {
albumRepository.updateCovers(updated)
}
val storedCovers = albumRepository.getAllCursor().map { it.key() }
val coverFiles = cache.listFiles()
if (coverFiles != null) {
val notInDb = coverFiles.filter { !storedCovers.contains(it.nameWithoutExtension) }
Timber.v("deleting ${notInDb.size} covers no longer in db")
for (file in notInDb) {
runCatching { file.delete() }
}
}
}.collect { (payload, response) ->
if (response.status == 304) {
Timber.v("cover for $payload did not change")
return@collect
}
val cover = response.cover
val hash = response.hash
if (response.status == 200 && !cover.isNullOrEmpty() && !hash.isNullOrEmpty()) {
val result = runCatching {
val file = File(cache, payload.key())
val decodeBase64 = cover.decodeBase64()
if (decodeBase64 != null) {
file.sink().buffer().use { sink -> sink.write(decodeBase64) }
}
updated.add(payload.copy(hash = hash))
}
if (result.isFailure) {
Timber.e(result.exceptionOrNull(), "Could not save cover for $payload")
}
}
}
}
}
}
| gpl-3.0 |
rafaelfiume/Prosciutto-Mob | app/src/prod/kotlin/com/rafaelfiume/prosciutto/adviser/integration/ServerName.kt | 1 | 172 | package com.rafaelfiume.prosciutto.adviser.integration
object ServerName {
fun name(): String {
return "http://app.rafaelfiume.com/salume/supplier/"
}
}
| mit |
micolous/metrodroid | src/commonTest/kotlin/au/id/micolous/metrodroid/test/BERTLVTest.kt | 1 | 3244 | /*
* BERTLVTest.kt
*
* Copyright 2019 Michael Farrell <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.test
import au.id.micolous.metrodroid.card.iso7816.ISO7816TLV
import au.id.micolous.metrodroid.util.ImmutableByteArray
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class BERTLVTest {
@Test
fun testFindDefiniteShort() {
// tag 50 (parent, definite short)
// -> tag 51: "hello world"
val d = ImmutableByteArray.fromHex("500e510b68656c6c6f20776f726c64")
val e = ImmutableByteArray.fromASCII("hello world")
assertEquals(e, ISO7816TLV.findBERTLV(d, "51", false))
}
@Test
fun testFindIndefinite() {
// tag 50 (parent, indefinite)
// -> tag 51: "hello world"
// end-of-contents octets
val d = ImmutableByteArray.fromHex("5080510b68656c6c6f20776f726c640000")
val e = ImmutableByteArray.fromASCII("hello world")
assertEquals(e, ISO7816TLV.findBERTLV(d, "51", false))
}
@Test
fun testFindDefinite1() {
// tag 50 (parent, definite long, 1 byte)
// -> tag 51: "hello world"
val d = ImmutableByteArray.fromHex("50810e510b68656c6c6f20776f726c64")
val e = ImmutableByteArray.fromASCII("hello world")
assertEquals(e, ISO7816TLV.findBERTLV(d, "51", false))
}
@Test
fun testFindDefinite7() {
// tag 50 (parent, definite long, 7 bytes)
// -> tag 51: "hello world"
val d = ImmutableByteArray.fromHex("50870000000000000e510b68656c6c6f20776f726c64")
val e = ImmutableByteArray.fromASCII("hello world")
assertEquals(e, ISO7816TLV.findBERTLV(d, "51", false))
}
@Test
fun testFindDefinite126() {
// tag 50 (parent, definite long, 126 bytes)
// -> tag 51: "hello world"
val d = (ImmutableByteArray.fromHex("50fe") +
ImmutableByteArray.empty(125) +
ImmutableByteArray.fromHex("0e510b68656c6c6f20776f726c64"))
val e = ImmutableByteArray.fromASCII("hello world")
assertEquals(e, ISO7816TLV.findBERTLV(d, "51", false))
}
@Test
fun testFindDefiniteReallyLong() {
// tag 50 (parent, definite long, 0xffffffffffffffff bytes)
// -> tag 51: "hello world"
val d = (ImmutableByteArray.fromHex("5088") +
ImmutableByteArray(8) { 0xff.toByte() } +
ImmutableByteArray.fromHex("0e510b68656c6c6f20776f726c64"))
// Should fail
assertNull(ISO7816TLV.findBERTLV(d, "51", false))
}
}
| gpl-3.0 |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJvmNameHandler.kt | 4 | 3603 | // 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.refactoring.rename
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.rename.PsiElementRenameHandler
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isPlain
import org.jetbrains.kotlin.psi.psiUtil.plainContent
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class RenameJvmNameHandler : PsiElementRenameHandler() {
private fun getStringTemplate(dataContext: DataContext): KtStringTemplateExpression? {
val caret = CommonDataKeys.CARET.getData(dataContext) ?: return null
val ktFile = CommonDataKeys.PSI_FILE.getData(dataContext) as? KtFile ?: return null
return ktFile.findElementAt(caret.offset)?.getNonStrictParentOfType<KtStringTemplateExpression>()
}
override fun isAvailableOnDataContext(dataContext: DataContext): Boolean {
val nameExpression = getStringTemplate(dataContext) ?: return false
if (!nameExpression.isPlain()) return false
val entry = ((nameExpression.parent as? KtValueArgument)?.parent as? KtValueArgumentList)?.parent as? KtAnnotationEntry
?: return false
val annotationType = entry.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, entry.typeReference]
?: return false
return annotationType.constructor.declarationDescriptor?.importableFqName == DescriptorUtils.JVM_NAME
}
private fun wrapDataContext(dataContext: DataContext): DataContext? {
val nameExpression = getStringTemplate(dataContext) ?: return null
val name = nameExpression.plainContent
val entry = nameExpression.getStrictParentOfType<KtAnnotationEntry>() ?: return null
val newElement =
when (val annotationList = PsiTreeUtil.getParentOfType(entry, KtModifierList::class.java, KtFileAnnotationList::class.java)) {
is KtModifierList -> (annotationList.parent as? KtDeclaration)?.toLightMethods()?.firstOrNull { it.name == name }
?: return null
is KtFileAnnotationList -> annotationList.getContainingKtFile().findFacadeClass() ?: return null
else -> return null
}
return DataContext { id ->
if (CommonDataKeys.PSI_ELEMENT.`is`(id)) return@DataContext newElement
dataContext.getData(id)
}
}
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) {
super.invoke(project, editor, file, wrapDataContext(dataContext) ?: return)
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext) {
super.invoke(project, elements, wrapDataContext(dataContext) ?: return)
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findWithStructuralGrouping/kotlinPropertyUsages.0.kt | 7 | 502 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtProperty
// GROUPING_RULES: org.jetbrains.kotlin.idea.findUsages.KotlinDeclarationGroupingRule
// OPTIONS: usages
package server
open class A<T> {
open var <caret>foo: T = TODO()
}
open class B : A<String>() {
override var foo: String
get() {
println("get")
return super<A>.foo
}
set(value: String) {
println("set:" + value)
super<A>.foo = value
}
}
// FIR_COMPARISON | apache-2.0 |
GunoH/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/api/request/GitLabProjectApi.kt | 2 | 2065 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.api.request
import com.intellij.collaboration.api.dto.GraphQLConnectionDTO
import com.intellij.collaboration.api.dto.GraphQLCursorPageInfoDTO
import com.intellij.collaboration.api.page.GraphQLPagesLoader
import org.jetbrains.plugins.gitlab.api.GitLabApi
import org.jetbrains.plugins.gitlab.api.GitLabGQLQueries
import org.jetbrains.plugins.gitlab.api.GitLabProjectCoordinates
import org.jetbrains.plugins.gitlab.api.dto.GitLabMemberDTO
import org.jetbrains.plugins.gitlab.mergerequest.api.dto.GitLabLabelDTO
suspend fun GitLabApi.loadAllProjectLabels(project: GitLabProjectCoordinates): List<GitLabLabelDTO> {
val pagesLoader = GraphQLPagesLoader<GitLabLabelDTO> { pagination ->
val parameters = GraphQLPagesLoader.arguments(pagination) + mapOf(
"fullPath" to project.projectPath.fullPath()
)
val request = gqlQuery(project.serverPath.gqlApiUri, GitLabGQLQueries.getProjectLabels, parameters)
loadGQLResponse(request, LabelConnection::class.java, "project", "labels").body()
}
return pagesLoader.loadAll()
}
suspend fun GitLabApi.getAllProjectMembers(project: GitLabProjectCoordinates): List<GitLabMemberDTO> {
val pagesLoader = GraphQLPagesLoader<GitLabMemberDTO> { pagination ->
val parameters = GraphQLPagesLoader.arguments(pagination) + mapOf(
"fullPath" to project.projectPath.fullPath()
)
val request = gqlQuery(project.serverPath.gqlApiUri, GitLabGQLQueries.getProjectMembers, parameters)
loadGQLResponse(request, ProjectMembersConnection::class.java, "project", "projectMembers").body()
}
return pagesLoader.loadAll()
}
private class LabelConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GitLabLabelDTO>)
: GraphQLConnectionDTO<GitLabLabelDTO>(pageInfo, nodes)
private class ProjectMembersConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GitLabMemberDTO>)
: GraphQLConnectionDTO<GitLabMemberDTO>(pageInfo, nodes) | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/convertToIsArrayOfCall/nullableArrayLhs.kt | 5 | 124 | // "Convert to 'isArrayOf' call" "true"
// WITH_STDLIB
fun test(a: Array<*>?) {
if (a is <caret>Array<String>) {
}
} | apache-2.0 |
GunoH/intellij-community | plugins/remote-control/src/org/jetbrains/ide/OpenSettingsHttpService.kt | 5 | 677 | package org.jetbrains.ide
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.QueryStringDecoder
internal class OpenSettingsService : RestService() {
override fun getServiceName() = "settings"
override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? {
val name = urlDecoder.parameters()["name"]?.firstOrNull()?.trim() ?: return parameterMissedErrorMessage("name")
if (!OpenSettingsJbProtocolService.doOpenSettings(name)) {
return "no configurables found"
}
sendOk(request, context)
return null
}
}
| apache-2.0 |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/segmentedprogressbar/SegmentedProgressBar.kt | 2 | 12270 | /*
MIT License
Copyright (c) 2020 Tiago Ornelas
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.thoughtcrime.securesms.components.segmentedprogressbar
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.viewpager.widget.ViewPager
import org.thoughtcrime.securesms.R
import java.util.concurrent.TimeUnit
/**
* Created by Tiago Ornelas on 18/04/2020.
* Represents a segmented progress bar on which, the progress is set by segments
* @see Segment
* And the progress of each segment is animated based on a set speed
*/
class SegmentedProgressBar : View, ViewPager.OnPageChangeListener, View.OnTouchListener {
companion object {
/**
* It is common now for devices to run at 60FPS
*/
val MILLIS_PER_FRAME = TimeUnit.MILLISECONDS.toMillis(17)
}
private val path = Path()
private val corners = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f)
/**
* Number of total segments to draw
*/
var segmentCount: Int = resources.getInteger(R.integer.segmentedprogressbar_default_segments_count)
set(value) {
field = value
this.initSegments()
}
/**
* Mapping of segment index -> duration in millis. Negative durations
* ARE valid but they'll result in a call to SegmentedProgressBarListener#onRequestSegmentProgressPercentage
* which should return the current % position for the currently playing item. This helps
* to avoid synchronizing the seek bar to playback.
*/
var segmentDurations: Map<Int, Long> = mapOf()
set(value) {
field = value
this.initSegments()
}
var margin: Int = resources.getDimensionPixelSize(R.dimen.segmentedprogressbar_default_segment_margin)
private set
var radius: Int = resources.getDimensionPixelSize(R.dimen.segmentedprogressbar_default_corner_radius)
private set
var segmentStrokeWidth: Int =
resources.getDimensionPixelSize(R.dimen.segmentedprogressbar_default_segment_stroke_width)
private set
var segmentBackgroundColor: Int = Color.WHITE
private set
var segmentSelectedBackgroundColor: Int =
context.getThemeColor(R.attr.colorAccent)
private set
var segmentStrokeColor: Int = Color.BLACK
private set
var segmentSelectedStrokeColor: Int = Color.BLACK
private set
var timePerSegmentMs: Long =
resources.getInteger(R.integer.segmentedprogressbar_default_time_per_segment_ms).toLong()
private set
private var segments = mutableListOf<Segment>()
private val selectedSegment: Segment?
get() = segments.firstOrNull { it.animationState == Segment.AnimationState.ANIMATING }
private val selectedSegmentIndex: Int
get() = segments.indexOf(this.selectedSegment)
// Drawing
val strokeApplicable: Boolean
get() = segmentStrokeWidth * 4 <= measuredHeight
val segmentWidth: Float
get() = (measuredWidth - margin * (segmentCount - 1)).toFloat() / segmentCount
var viewPager: ViewPager? = null
@SuppressLint("ClickableViewAccessibility")
set(value) {
field = value
if (value == null) {
viewPager?.removeOnPageChangeListener(this)
viewPager?.setOnTouchListener(null)
} else {
viewPager?.addOnPageChangeListener(this)
viewPager?.setOnTouchListener(this)
}
}
/**
* Sets callbacks for progress bar state changes
* @see SegmentedProgressBarListener
*/
var listener: SegmentedProgressBarListener? = null
private var lastFrameTimeMillis: Long = 0L
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
val typedArray =
context.theme.obtainStyledAttributes(attrs, R.styleable.SegmentedProgressBar, 0, 0)
segmentCount =
typedArray.getInt(R.styleable.SegmentedProgressBar_totalSegments, segmentCount)
margin =
typedArray.getDimensionPixelSize(
R.styleable.SegmentedProgressBar_segmentMargins,
margin
)
radius =
typedArray.getDimensionPixelSize(
R.styleable.SegmentedProgressBar_segmentCornerRadius,
radius
)
segmentStrokeWidth =
typedArray.getDimensionPixelSize(
R.styleable.SegmentedProgressBar_segmentStrokeWidth,
segmentStrokeWidth
)
segmentBackgroundColor =
typedArray.getColor(
R.styleable.SegmentedProgressBar_segmentBackgroundColor,
segmentBackgroundColor
)
segmentSelectedBackgroundColor =
typedArray.getColor(
R.styleable.SegmentedProgressBar_segmentSelectedBackgroundColor,
segmentSelectedBackgroundColor
)
segmentStrokeColor =
typedArray.getColor(
R.styleable.SegmentedProgressBar_segmentStrokeColor,
segmentStrokeColor
)
segmentSelectedStrokeColor =
typedArray.getColor(
R.styleable.SegmentedProgressBar_segmentSelectedStrokeColor,
segmentSelectedStrokeColor
)
timePerSegmentMs =
typedArray.getInt(
R.styleable.SegmentedProgressBar_timePerSegment,
timePerSegmentMs.toInt()
).toLong()
typedArray.recycle()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
init {
setLayerType(LAYER_TYPE_SOFTWARE, null)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
segments.forEachIndexed { index, segment ->
val drawingComponents = getDrawingComponents(segment, index)
when (index) {
0 -> {
corners.indices.forEach { corners[it] = 0f }
corners[0] = radius.toFloat()
corners[1] = radius.toFloat()
corners[6] = radius.toFloat()
corners[7] = radius.toFloat()
}
segments.lastIndex -> {
corners.indices.forEach { corners[it] = 0f }
corners[2] = radius.toFloat()
corners[3] = radius.toFloat()
corners[4] = radius.toFloat()
corners[5] = radius.toFloat()
}
}
drawingComponents.first.forEachIndexed { drawingIndex, rectangle ->
when (index) {
0, segments.lastIndex -> {
path.reset()
path.addRoundRect(rectangle, corners, Path.Direction.CW)
canvas?.drawPath(path, drawingComponents.second[drawingIndex])
}
else -> canvas?.drawRect(
rectangle,
drawingComponents.second[drawingIndex]
)
}
}
}
onFrame(System.currentTimeMillis())
}
/**
* Start/Resume progress animation
*/
fun start() {
pause()
val segment = selectedSegment
if (segment == null) {
next()
} else {
isPaused = false
invalidate()
}
}
/**
* Pauses the animation process
*/
fun pause() {
isPaused = true
lastFrameTimeMillis = 0L
}
/**
* Resets the whole animation state and selected segments
* !Doesn't restart it!
* To restart, call the start() method
*/
fun reset() {
this.segments.map { it.animationState = Segment.AnimationState.IDLE }
this.invalidate()
}
/**
* Starts animation for the following segment
*/
fun next() {
loadSegment(offset = 1, userAction = true)
}
/**
* Starts animation for the previous segment
*/
fun previous() {
loadSegment(offset = -1, userAction = true)
}
/**
* Restarts animation for the current segment
*/
fun restartSegment() {
loadSegment(offset = 0, userAction = true)
}
/**
* Skips a number of segments
* @param offset number o segments fo skip
*/
fun skip(offset: Int) {
loadSegment(offset = offset, userAction = true)
}
/**
* Sets current segment to the
* @param position index
*/
fun setPosition(position: Int) {
loadSegment(offset = position - this.selectedSegmentIndex, userAction = true)
}
// Private methods
private fun loadSegment(offset: Int, userAction: Boolean) {
val oldSegmentIndex = this.segments.indexOf(this.selectedSegment)
val nextSegmentIndex = oldSegmentIndex + offset
// Index out of bounds, ignore operation
if (userAction && nextSegmentIndex !in 0 until segmentCount) {
if (nextSegmentIndex >= segmentCount) {
this.listener?.onFinished()
} else {
loadSegment(offset = 0, userAction = false)
}
return
}
segments.mapIndexed { index, segment ->
if (offset > 0) {
if (index < nextSegmentIndex) segment.animationState =
Segment.AnimationState.ANIMATED
} else if (offset < 0) {
if (index > nextSegmentIndex - 1) segment.animationState =
Segment.AnimationState.IDLE
} else if (offset == 0) {
if (index == nextSegmentIndex) segment.animationState = Segment.AnimationState.IDLE
}
}
val nextSegment = this.segments.getOrNull(nextSegmentIndex)
// Handle next segment transition/ending
if (nextSegment != null) {
pause()
nextSegment.animationState = Segment.AnimationState.ANIMATING
isPaused = false
invalidate()
this.listener?.onPage(oldSegmentIndex, this.selectedSegmentIndex)
viewPager?.currentItem = this.selectedSegmentIndex
} else {
pause()
this.listener?.onFinished()
}
}
private fun getSegmentProgressPercentage(segment: Segment, timeSinceLastFrameMillis: Long): Float {
return if (segment.animationDurationMillis > 0) {
segment.animationProgressPercentage + timeSinceLastFrameMillis.toFloat() / segment.animationDurationMillis
} else {
listener?.onRequestSegmentProgressPercentage() ?: 0f
}
}
private fun initSegments() {
this.segments.clear()
segments.addAll(
List(segmentCount) {
val duration = segmentDurations[it] ?: timePerSegmentMs
Segment(duration)
}
)
this.invalidate()
reset()
}
private var isPaused = true
private fun onFrame(frameTimeMillis: Long) {
if (isPaused) {
return
}
val lastFrameTimeMillis = this.lastFrameTimeMillis
this.lastFrameTimeMillis = frameTimeMillis
val selectedSegment = this.selectedSegment
if (selectedSegment == null) {
loadSegment(offset = 1, userAction = false)
} else if (lastFrameTimeMillis > 0L) {
val segmentProgressPercentage = getSegmentProgressPercentage(selectedSegment, frameTimeMillis - lastFrameTimeMillis)
selectedSegment.animationProgressPercentage = segmentProgressPercentage
if (selectedSegment.animationProgressPercentage >= 1f) {
loadSegment(offset = 1, userAction = false)
} else {
this.invalidate()
}
} else {
this.invalidate()
}
}
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
override fun onPageSelected(position: Int) {
this.setPosition(position)
}
override fun onTouch(p0: View?, p1: MotionEvent?): Boolean {
when (p1?.action) {
MotionEvent.ACTION_DOWN -> pause()
MotionEvent.ACTION_UP -> start()
}
return false
}
}
| gpl-3.0 |
jk1/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/inferenceResults.kt | 3 | 6532 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.dataFlow.inference
import com.intellij.codeInsight.Nullability
import com.intellij.codeInsight.NullableNotNullManager
import com.intellij.codeInspection.dataFlow.JavaMethodContractUtil
import com.intellij.codeInspection.dataFlow.Mutability
import com.intellij.lang.LighterASTNode
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiMethodImpl
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.siyeh.ig.psiutils.ClassUtils
import java.util.*
/**
* @author peter
*/
data class ExpressionRange internal constructor (internal val startOffset: Int, internal val endOffset: Int) {
companion object {
@JvmStatic
fun create(expr: LighterASTNode, scopeStart: Int): ExpressionRange = ExpressionRange(
expr.startOffset - scopeStart, expr.endOffset - scopeStart)
}
fun restoreExpression(scope: PsiCodeBlock): PsiExpression? {
val scopeStart = scope.textRange.startOffset
return PsiTreeUtil.findElementOfClassAtRange(scope.containingFile, startOffset + scopeStart, endOffset + scopeStart,
PsiExpression::class.java)
}
}
data class PurityInferenceResult(internal val mutatedRefs: List<ExpressionRange>, internal val singleCall: ExpressionRange?) {
fun isPure(method: PsiMethod, body: () -> PsiCodeBlock): Boolean = !mutatesNonLocals(method, body) && callsOnlyPureMethods(body)
private fun mutatesNonLocals(method: PsiMethod, body: () -> PsiCodeBlock): Boolean {
return mutatedRefs.any { range -> !isLocalVarReference(range.restoreExpression(body()), method) }
}
private fun callsOnlyPureMethods(body: () -> PsiCodeBlock): Boolean {
if (singleCall == null) return true
val called = (singleCall.restoreExpression(body()) as PsiCall).resolveMethod()
return called != null && JavaMethodContractUtil.isPure(called)
}
private fun isLocalVarReference(expression: PsiExpression?, scope: PsiMethod): Boolean {
return when (expression) {
is PsiReferenceExpression -> expression.resolve().let { it is PsiLocalVariable || it is PsiParameter }
is PsiArrayAccessExpression -> (expression.arrayExpression as? PsiReferenceExpression)?.resolve().let { target ->
target is PsiLocalVariable && isLocallyCreatedArray(scope, target)
}
else -> false
}
}
private fun isLocallyCreatedArray(scope: PsiMethod, target: PsiLocalVariable): Boolean {
val initializer = target.initializer
if (initializer != null && initializer !is PsiNewExpression) {
return false
}
for (ref in ReferencesSearch.search(target, LocalSearchScope(scope)).findAll()) {
if (ref is PsiReferenceExpression && PsiUtil.isAccessedForWriting(ref)) {
val assign = PsiTreeUtil.getParentOfType(ref, PsiAssignmentExpression::class.java)
if (assign == null || assign.rExpression !is PsiNewExpression) {
return false
}
}
}
return true
}
}
interface MethodReturnInferenceResult {
fun getNullability(method: PsiMethod, body: () -> PsiCodeBlock): Nullability
fun getMutability(method: PsiMethod, body: () -> PsiCodeBlock): Mutability = Mutability.UNKNOWN
@Suppress("EqualsOrHashCode")
data class Predefined(internal val value: Nullability) : MethodReturnInferenceResult {
override fun hashCode(): Int = value.ordinal
override fun getNullability(method: PsiMethod, body: () -> PsiCodeBlock): Nullability = when {
value == Nullability.NULLABLE && InferenceFromSourceUtil.suppressNullable(
method) -> Nullability.UNKNOWN
else -> value
}
}
data class FromDelegate(internal val value: Nullability, internal val delegateCalls: List<ExpressionRange>) : MethodReturnInferenceResult {
override fun getNullability(method: PsiMethod, body: () -> PsiCodeBlock): Nullability {
if (value == Nullability.NULLABLE) {
return if (InferenceFromSourceUtil.suppressNullable(method)) Nullability.UNKNOWN
else Nullability.NULLABLE
}
return when {
delegateCalls.all { range -> isNotNullCall(range, body()) } -> Nullability.NOT_NULL
else -> Nullability.UNKNOWN
}
}
override fun getMutability(method: PsiMethod, body: () -> PsiCodeBlock): Mutability {
if (value == Nullability.NOT_NULL) {
return Mutability.UNKNOWN
}
return delegateCalls.stream().map { range -> getDelegateMutability(range, body()) }.reduce(
Mutability::union).orElse(
Mutability.UNKNOWN)
}
private fun getDelegateMutability(delegate: ExpressionRange, body: PsiCodeBlock): Mutability {
val call = delegate.restoreExpression(body) as PsiMethodCallExpression
val target = call.resolveMethod()
return when {
target == null -> Mutability.UNKNOWN
ClassUtils.isImmutable(target.returnType, false) -> Mutability.UNMODIFIABLE
else -> Mutability.getMutability(target)
}
}
private fun isNotNullCall(delegate: ExpressionRange, body: PsiCodeBlock): Boolean {
val call = delegate.restoreExpression(body) as PsiMethodCallExpression
if (call.type is PsiPrimitiveType) return true
val target = call.resolveMethod()
return target != null && NullableNotNullManager.isNotNull(target)
}
}
}
data class MethodData(
val methodReturn: MethodReturnInferenceResult?,
val purity: PurityInferenceResult?,
val contracts: List<PreContract>,
val notNullParameters: BitSet,
internal val bodyStart: Int,
internal val bodyEnd: Int
) {
fun methodBody(method: PsiMethodImpl): () -> PsiCodeBlock = {
if (method.stub != null)
CachedValuesManager.getCachedValue(method) { CachedValueProvider.Result(getDetachedBody(method), method) }
else
method.body!!
}
private fun getDetachedBody(method: PsiMethod): PsiCodeBlock {
val document = method.containingFile.viewProvider.document ?: return method.body!!
val bodyText = PsiDocumentManager.getInstance(method.project).getLastCommittedText(document).substring(bodyStart, bodyEnd)
return JavaPsiFacade.getElementFactory(method.project).createCodeBlockFromText(bodyText, method)
}
} | apache-2.0 |
jk1/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ElementResolveResult.kt | 4 | 1306 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiSubstitutor
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState
open class ElementResolveResult<out T : PsiElement>(private val element: T) : GroovyResolveResult {
final override fun getElement(): T = element
override fun isValidResult(): Boolean = element.isValid && isStaticsOK && isAccessible && isApplicable
override fun isStaticsOK(): Boolean = true
override fun isAccessible(): Boolean = true
override fun getCurrentFileResolveContext(): PsiElement? = null
override fun getSubstitutor(): PsiSubstitutor = PsiSubstitutor.EMPTY
override fun isApplicable(): Boolean = true
override fun isInvokedOnProperty(): Boolean = false
override fun getSpreadState(): SpreadState? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ElementResolveResult<*>
return element == other.element
}
override fun hashCode(): Int = element.hashCode()
}
| apache-2.0 |
marius-m/wt4 | models/src/main/java/lt/markmerkk/utils/LogFormatters.kt | 1 | 5572 | package lt.markmerkk.utils
import org.joda.time.format.DateTimeFormat
import lt.markmerkk.entities.Log
import org.joda.time.*
import org.joda.time.format.PeriodFormatterBuilder
import org.slf4j.LoggerFactory
object LogFormatters {
private val l = LoggerFactory.getLogger(LogFormatters::class.java)!!
const val TIME_SHORT_FORMAT = "HH:mm"
const val DATE_SHORT_FORMAT = "yyyy-MM-dd"
const val DATE_LONG_FORMAT = "yyyy-MM-dd HH:mm"
const val DATE_VERY_LONG_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS"
val formatTime = DateTimeFormat.forPattern(TIME_SHORT_FORMAT)!!
val formatDate = DateTimeFormat.forPattern(DATE_SHORT_FORMAT)!!
val longFormatDateTime = DateTimeFormat.forPattern(DATE_LONG_FORMAT)!!
val veryLongFormat = DateTimeFormat.forPattern(DATE_VERY_LONG_FORMAT)!!
val defaultDate = LocalDate(1970, 1, 1)
private val periodFormatter = PeriodFormatterBuilder()
.appendDays()
.appendSuffix("d")
.appendHours()
.appendSuffix("h")
.appendMinutes()
.appendSuffix("m")
.appendSeconds()
.appendSuffix("s")
.toFormatter()
private val periodFormatterShort = PeriodFormatterBuilder()
.appendDays()
.appendSuffix("d")
.appendHours()
.appendSuffix("h")
.appendMinutes()
.appendSuffix("m")
.appendSeconds()
.appendSuffix("s")
.toFormatter()
fun humanReadableDuration(duration: Duration): String {
return periodFormatter.print(duration.toPeriod())
}
fun humanReadableDurationShort(duration: Duration): String {
if (duration.standardMinutes <= 0)
return "0m"
val builder = StringBuilder()
val type = PeriodType.forFields(arrayOf(DurationFieldType.hours(), DurationFieldType.minutes()))
val period = Period(duration, type)
if (period.days != 0)
builder.append(period.days).append("d").append(" ")
if (period.hours != 0)
builder.append(period.hours).append("h").append(" ")
if (period.minutes != 0)
builder.append(period.minutes).append("m").append(" ")
if (builder.isNotEmpty() && builder[builder.length - 1] == " "[0])
builder.deleteCharAt(builder.length - 1)
return builder.toString()
}
fun formatLogsBasic(logs: List<Log>): String {
val hasMultipleDates = hasMultipleDates(logs)
return logs
.map { formatLogBasic(log = it, includeDate = hasMultipleDates) }
.joinToString("\n")
}
fun formatLogBasic(log: Log, includeDate: Boolean): String {
val startDate = LogFormatters.formatDate.print(log.time.start)
val formatStart = LogFormatters.formatTime.print(log.time.start)
val formatEnd = LogFormatters.formatTime.print(log.time.end)
val durationAsString = LogFormatters.humanReadableDurationShort(log.time.duration)
return StringBuilder()
.append(if (includeDate) "$startDate " else "")
.append("$formatStart - $formatEnd ($durationAsString)")
.append(" >> ")
.append(if (!log.code.isEmpty()) "'${log.code.code}' " else "")
.append("'${log.comment}'")
.toString()
}
/**
* @return logs are in span through multiple dates
*/
fun hasMultipleDates(logs: List<Log>): Boolean {
val logDates: Set<LocalDate> = logs
.map { it.time.start.toLocalDate() }
.toSet()
return logDates.size > 1
}
fun dtFromRawOrNull(
dateAsString: String,
timeAsString: String
): DateTime? {
return try {
val date = LogFormatters.formatDate.parseLocalDate(dateAsString)
val time = LogFormatters.formatTime.parseLocalTime(timeAsString)
date.toDateTime(time)
} catch (e: IllegalArgumentException) {
l.warn("Error parsing date time as string from ${dateAsString} / ${timeAsString}", e)
null
}
}
fun dateFromRawOrDefault(
dateAsString: String
): LocalDate {
return try {
formatDate.parseLocalDate(dateAsString)
} catch (e: IllegalArgumentException) {
l.warn("Error parsing date as string from ${dateAsString}", e)
defaultDate
}
}
fun timeFromRawOrDefault(
timeAsString: String
): LocalTime {
return try {
formatTime.parseLocalTime(timeAsString)
} catch (e: IllegalArgumentException) {
l.warn("Error parsing time as string from ${timeAsString}", e)
LocalTime.MIDNIGHT
}
}
/**
* Formats time
* If not the same day, will include date
* If next day, it will say tomorrow
*/
fun formatTime(
stringRes: StringRes,
dtCurrent: DateTime,
dtTarget: DateTime,
): String {
return when {
dtCurrent.toLocalDate().isEqual(dtTarget.toLocalDate()) -> formatTime.print(dtTarget)
dtCurrent.plusDays(1).toLocalDate().isEqual(dtTarget.toLocalDate()) -> {
"${stringRes.resTomorrow()} ${formatTime.print(dtTarget)}"
}
else -> longFormatDateTime.print(dtTarget)
}
}
interface StringRes {
fun resTomorrow(): String
}
}
fun Duration.toStringShort(): String {
return LogFormatters.humanReadableDurationShort(this)
} | apache-2.0 |
chiclaim/android-sample | language-kotlin/kotlin-sample/coroutine-in-action/src/main/kotlin/com/chiclaim/coroutine/basic/example-basic-02b.kt | 1 | 447 |
import kotlinx.coroutines.*
//把所有的代码都放到阻塞代码块里
// start main coroutine
fun main() = runBlocking<Unit> {
GlobalScope.launch { // launch new coroutine in background and continue
println("Before Coroutine delay....")
delay(1000L)
println("World!")
}
println("Hello,") // main coroutine continues here immediately
delay(2000L) // delaying for 2 seconds to keep JVM alive
}
| apache-2.0 |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/swift/SwiftSchemeManagementBuilder.kt | 1 | 1099 | package org.roylance.yaclib.core.services.swift
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.utilities.SwiftUtilities
class SwiftSchemeManagementBuilder(
private val projectInformation: YaclibModel.ProjectInformation) : IBuilder<YaclibModel.File> {
override fun build(): YaclibModel.File {
val file = YaclibModel.File.newBuilder()
.setFileExtension(YaclibModel.FileExtension.PLIST_EXT)
.setFileToWrite(InitialTemplate)
.setFileName("xcschememanagement")
.setFullDirectoryLocation("${SwiftUtilities.buildSwiftFullName(
projectInformation.mainDependency)}.xcodeproj/xcshareddata/xcshemes")
.build()
return file
}
private val InitialTemplate = """<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>${SwiftUtilities.buildSwiftFullName(projectInformation.mainDependency)}.xcscheme</key>
<dict></dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict></dict>
</dict>
</plist>
"""
} | mit |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/TimerDetails.kt | 1 | 15549 | /*
* Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments
import android.app.DatePickerDialog.OnDateSetListener
import android.app.Dialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.widget.Button
import android.widget.DatePicker
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.SwitchCompat
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.math.NumberUtils
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.entities.Timer
import org.dvbviewer.controller.ui.base.BaseDialogFragment
import org.dvbviewer.controller.ui.widget.DateField
import org.dvbviewer.controller.utils.DateUtils
import java.util.*
/**
* The Class TimerDetails.
*
* @author RayBa
*/
class TimerDetails : BaseDialogFragment(), OnDateSetListener, OnClickListener, OnLongClickListener {
private var timer: Timer? = null
private var channelField: TextView? = null
private var titleField: TextView? = null
private var activeBox: SwitchCompat? = null
private var dateField: DateField? = null
private var startField: DateField? = null
private var stopField: DateField? = null
private var startTimeSetListener: OnTimeSetListener? = null
private var stopTimeSetListener: OnTimeSetListener? = null
private var cal: Calendar? = null
private var postRecordSpinner: Spinner? = null
private var mOntimeredEditedListener: OnTimerEditedListener? = null
private var monitoringSpinner: Spinner? = null
private var monitoringLabel: TextView? = null
private var preField: AppCompatEditText? = null
private var postField: AppCompatEditText? = null
/* (non-Javadoc)
* @see android.support.v4.app.DialogFragment#onCreate(android.os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
cal = GregorianCalendar.getInstance()
if (savedInstanceState == null) {
bundleToTimer(arguments!!)
} else {
bundleToTimer(savedInstanceState)
}
}
/* (non-Javadoc)
* @see com.actionbarsherlock.app.SherlockDialogFragment#onAttach(android.app.Activity)
*/
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnTimerEditedListener) {
mOntimeredEditedListener = context
}
}
/* (non-Javadoc)
* @see android.support.v4.app.DialogFragment#onActivityCreated(android.os.Bundle)
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (timer != null) {
val create = timer!!.id < 0L
titleField!!.text = timer!!.title
dateField!!.date = timer!!.start
val start = if (create) timer!!.start else DateUtils.addMinutes(timer!!.start, timer!!.pre)
val stop = if (create) timer!!.end else DateUtils.addMinutes(timer!!.end, timer!!.post * -1)
activeBox!!.isChecked = !timer!!.isFlagSet(Timer.FLAG_DISABLED)
start?.let { startField!!.setTime(it) }
stop?.let { stopField!!.setTime(it) }
preField!!.setText(timer!!.pre.toString())
postField!!.setText(timer!!.post.toString())
val invalidindex = timer!!.timerAction >= postRecordSpinner!!.count
postRecordSpinner!!.setSelection(if (invalidindex) 0 else timer!!.timerAction)
if (!TextUtils.isEmpty(timer!!.channelName)) {
channelField!!.text = timer!!.channelName
}
if (StringUtils.isNotBlank(timer!!.pdc)) {
monitoringSpinner!!.setSelection(timer!!.monitorPDC)
} else {
monitoringLabel!!.visibility = View.GONE
monitoringSpinner!!.visibility = View.GONE
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setTitle(if (timer != null && timer!!.id <= 0) R.string.createTimer else R.string.editTimer)
return dialog
}
/* (non-Javadoc)
* @see android.support.v4.app.DialogFragment#onSaveInstanceState(android.os.Bundle)
*/
override fun onSaveInstanceState(arg0: Bundle) {
super.onSaveInstanceState(arg0)
timerToBundle(timer!!, arg0)
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = activity!!.layoutInflater.inflate(R.layout.fragment_timer_details, container, false)
titleField = v.findViewById(R.id.titleField)
dateField = v.findViewById(R.id.dateField)
activeBox = v.findViewById(R.id.activeBox)
startField = v.findViewById(R.id.startField)
preField = v.findViewById(R.id.pre)
postField = v.findViewById(R.id.post)
postRecordSpinner = v.findViewById(R.id.postRecordingSpinner)
monitoringLabel = v.findViewById(R.id.monitoringCaption)
monitoringSpinner = v.findViewById(R.id.monitoringgSpinner)
startTimeSetListener = OnTimeSetListener { view, hourOfDay, minute ->
cal!!.time = startField!!.date
cal!!.set(Calendar.HOUR_OF_DAY, hourOfDay)
cal!!.set(Calendar.MINUTE, minute)
startField!!.setTime(cal!!.time)
}
stopTimeSetListener = OnTimeSetListener { view, hourOfDay, minute ->
cal!!.time = stopField!!.date
cal!!.set(Calendar.HOUR_OF_DAY, hourOfDay)
cal!!.set(Calendar.MINUTE, minute)
stopField!!.setTime(cal!!.time)
}
stopField = v.findViewById(R.id.stopField)
val cancelButton = v.findViewById<Button>(R.id.buttonCancel)
val okButton = v.findViewById<Button>(R.id.buttonOk)
channelField = v.findViewById(R.id.channelField)
dateField!!.setOnClickListener(this)
startField!!.setOnClickListener(this)
stopField!!.setOnClickListener(this)
cancelButton.setOnClickListener(this)
okButton.setOnClickListener(this)
dateField!!.setOnLongClickListener(this)
startField!!.setOnLongClickListener(this)
stopField!!.setOnLongClickListener(this)
return v
}
fun setOnTimerEditedListener(onTimerEditedListener: OnTimerEditedListener) {
this.mOntimeredEditedListener = onTimerEditedListener
}
/* (non-Javadoc)
* @see android.app.DatePickerDialog.OnDateSetListener#onDateSet(android.widget.DatePicker, int, int, int)
*/
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) {
val cal = GregorianCalendar.getInstance()
cal.time = dateField!!.date
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
dateField!!.date = cal.time
}
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
override fun onClick(v: View) {
val f: DateDialogFragment
when (v.id) {
R.id.dateField -> {
f = DateDialogFragment.newInstance(this@TimerDetails, dateField!!.date!!)
f.show(activity!!.supportFragmentManager, "datepicker")
}
R.id.startField -> {
f = DateDialogFragment.newInstance(startTimeSetListener!!, startField!!.date!!)
f.show(activity!!.supportFragmentManager, "startTimePicker")
}
R.id.stopField -> {
f = DateDialogFragment.newInstance(stopTimeSetListener!!, stopField!!.date!!)
f.show(activity!!.supportFragmentManager, "stopTimePicker")
}
R.id.buttonCancel -> {
if (mOntimeredEditedListener != null) {
mOntimeredEditedListener!!.timerEdited(null)
}
dismiss()
}
R.id.buttonOk -> {
calcStartEnd()
timer!!.title = titleField!!.text.toString()
timer!!.timerAction = postRecordSpinner!!.selectedItemPosition
timer!!.monitorPDC = monitoringSpinner!!.selectedItemPosition
timer!!.pre = NumberUtils.toInt(preField!!.text!!.toString())
timer!!.post = NumberUtils.toInt(postField!!.text!!.toString())
if (activeBox!!.isChecked) {
timer!!.unsetFlag(Timer.FLAG_DISABLED)
} else {
timer!!.setFlag(Timer.FLAG_DISABLED)
}
mOntimeredEditedListener?.timerEdited(timer)
if (dialog != null && dialog!!.isShowing) {
dismiss()
}
}
else -> {
}
}
}
private fun calcStartEnd() {
val day = GregorianCalendar.getInstance()
val start = GregorianCalendar.getInstance()
val end = GregorianCalendar.getInstance()
day.time = dateField!!.date
start.time = startField!!.date
start.set(Calendar.DAY_OF_YEAR, day.get(Calendar.DAY_OF_YEAR))
end.time = stopField!!.date
end.set(Calendar.DAY_OF_YEAR, day.get(Calendar.DAY_OF_YEAR))
if (end.before(start)) {
end.add(Calendar.DAY_OF_YEAR, 1)
}
start.set(Calendar.DAY_OF_YEAR, day.get(Calendar.DAY_OF_YEAR))
timer!!.start = start.time
timer!!.end = end.time
}
private fun bundleToTimer(bundle: Bundle) {
timer = Timer()
timer!!.id = bundle.getLong(EXTRA_ID, 0)
timer!!.title = bundle.getString(EXTRA_TITLE)
timer!!.channelName = bundle.getString(EXTRA_CHANNEL_NAME)
timer!!.channelId = bundle.getLong(EXTRA_CHANNEL_ID, 0)
timer!!.start = Date(bundle.getLong(EXTRA_START, System.currentTimeMillis()))
timer!!.end = Date(bundle.getLong(EXTRA_END, System.currentTimeMillis()))
timer!!.timerAction = bundle.getInt(EXTRA_ACTION, 0)
timer!!.pre = bundle.getInt(EXTRA_PRE, 5)
timer!!.post = bundle.getInt(EXTRA_POST, 5)
timer!!.eventId = bundle.getString(EXTRA_EVENT_ID)
timer!!.pdc = bundle.getString(EXTRA_PDC)
timer!!.adjustPAT = bundle.getInt(EXTRA_ADJUST_PAT, -1)
timer!!.allAudio = bundle.getInt(EXTRA_ALL_AUDIO, -1)
timer!!.dvbSubs = bundle.getInt(EXTRA_DVB_SUBS, -1)
timer!!.teletext = bundle.getInt(EXTRA_TELETEXT, -1)
timer!!.eitEPG = bundle.getInt(EXTRA_EIT_EPG, -1)
timer!!.monitorPDC = bundle.getInt(EXTRA_MONITOR_PDC, -1)
timer!!.runningStatusSplit = bundle.getInt(EXTRA_STATUS_SPLIT, -1)
if (!bundle.getBoolean(EXTRA_ACTIVE)) {
timer!!.setFlag(Timer.FLAG_DISABLED)
}
}
/* (non-Javadoc)
* @see android.view.View.OnLongClickListener#onLongClick(android.view.View)
*/
override fun onLongClick(v: View): Boolean {
return true
}
/**
* The listener interface for receiving onTimerEdited events.
* The class that is interested in processing a onTimerEdited
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's `addOnTimerEditedListener` method. When
* the onTimerEdited event occurs, that object's appropriate
* method is invoked.
*
* @author RayBa
`` */
interface OnTimerEditedListener {
/**
* Timer edited.
*
* @param timer the Timer which has been edited
*/
fun timerEdited(timer: Timer?)
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
val parentFragment = targetFragment
if (parentFragment is DialogInterface.OnDismissListener) {
(parentFragment as DialogInterface.OnDismissListener).onDismiss(dialog)
}
}
companion object {
val TIMER_RESULT = 0
val RESULT_CHANGED = 1
val EXTRA_ID = "_id"
val EXTRA_TITLE = "_title"
val EXTRA_CHANNEL_NAME = "_channel_name"
val EXTRA_CHANNEL_ID = "_channel_id"
val EXTRA_START = "_start"
val EXTRA_END = "_end"
val EXTRA_ACTION = "_action"
val EXTRA_ACTIVE = "_active"
val EXTRA_PRE = "_pre"
val EXTRA_POST = "_post"
val EXTRA_EVENT_ID = "_event_id"
val EXTRA_PDC = "_pdc"
val EXTRA_ADJUST_PAT = "AdjustPAT"
val EXTRA_ALL_AUDIO = "AllAudio"
val EXTRA_DVB_SUBS = "DVBSubs"
val EXTRA_TELETEXT = "Teletext"
val EXTRA_EIT_EPG = "EITEPG"
val EXTRA_MONITOR_PDC = "MonitorPDC"
val EXTRA_STATUS_SPLIT = "RunningStatusSplit"
/**
* New instance.
*
* @return the timer details©
*/
fun newInstance(): TimerDetails {
return TimerDetails()
}
fun buildBundle(timer: Timer): Bundle {
val bundle = Bundle()
timerToBundle(timer, bundle)
return bundle
}
private fun timerToBundle(timer: Timer, bundle: Bundle) {
bundle.putLong(EXTRA_ID, timer.id)
bundle.putString(EXTRA_TITLE, timer.title)
bundle.putString(EXTRA_CHANNEL_NAME, timer.channelName)
bundle.putLong(EXTRA_CHANNEL_ID, timer.channelId)
bundle.putLong(EXTRA_START, timer.start!!.time)
bundle.putLong(EXTRA_END, timer.end!!.time)
bundle.putInt(EXTRA_ACTION, timer.timerAction)
bundle.putInt(EXTRA_PRE, timer.pre)
bundle.putInt(EXTRA_POST, timer.post)
bundle.putString(EXTRA_EVENT_ID, timer.eventId)
bundle.putString(EXTRA_PDC, timer.pdc)
bundle.putString(EXTRA_PDC, timer.pdc)
bundle.putInt(EXTRA_ADJUST_PAT, timer.adjustPAT)
bundle.putInt(EXTRA_ALL_AUDIO, timer.allAudio)
bundle.putInt(EXTRA_DVB_SUBS, timer.dvbSubs)
bundle.putInt(EXTRA_TELETEXT, timer.teletext)
bundle.putInt(EXTRA_EIT_EPG, timer.eitEPG)
bundle.putInt(EXTRA_MONITOR_PDC, timer.monitorPDC)
bundle.putInt(EXTRA_STATUS_SPLIT, timer.runningStatusSplit)
bundle.putBoolean(EXTRA_ACTIVE, !timer.isFlagSet(Timer.FLAG_DISABLED))
}
}
}
| apache-2.0 |
ktorio/ktor | ktor-utils/jvm/src/io/ktor/util/AttributesJvm.kt | 1 | 2421 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.util
import java.util.concurrent.*
/**
* Create JVM specific attributes instance.
*/
public actual fun Attributes(concurrent: Boolean): Attributes =
if (concurrent) ConcurrentSafeAttributes() else HashMapAttributes()
private abstract class AttributesJvmBase : Attributes {
protected abstract val map: MutableMap<AttributeKey<*>, Any?>
@Suppress("UNCHECKED_CAST")
public final override fun <T : Any> getOrNull(key: AttributeKey<T>): T? = map[key] as T?
public final override operator fun contains(key: AttributeKey<*>): Boolean = map.containsKey(key)
public final override fun <T : Any> put(key: AttributeKey<T>, value: T) {
map[key] = value
}
public final override fun <T : Any> remove(key: AttributeKey<T>) {
map.remove(key)
}
public final override val allKeys: List<AttributeKey<*>>
get() = map.keys.toList()
}
private class ConcurrentSafeAttributes : AttributesJvmBase() {
override val map: ConcurrentHashMap<AttributeKey<*>, Any?> = ConcurrentHashMap()
/**
* Gets a value of the attribute for the specified [key], or calls supplied [block] to compute its value.
* Note: [block] could be eventually evaluated twice for the same key.
* TODO: To be discussed. Workaround for android < API 24.
*/
override fun <T : Any> computeIfAbsent(key: AttributeKey<T>, block: () -> T): T {
@Suppress("UNCHECKED_CAST")
map[key]?.let { return it as T }
val result = block()
@Suppress("UNCHECKED_CAST")
return (map.putIfAbsent(key, result) ?: result) as T
}
}
private class HashMapAttributes : AttributesJvmBase() {
override val map: MutableMap<AttributeKey<*>, Any?> = HashMap()
/**
* Gets a value of the attribute for the specified [key], or calls supplied [block] to compute its value.
* Note: [block] could be eventually evaluated twice for the same key.
* TODO: To be discussed. Workaround for android < API 24.
*/
override fun <T : Any> computeIfAbsent(key: AttributeKey<T>, block: () -> T): T {
@Suppress("UNCHECKED_CAST")
map[key]?.let { return it as T }
val result = block()
@Suppress("UNCHECKED_CAST")
return (map.put(key, result) ?: result) as T
}
}
| apache-2.0 |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mcp/inspections/StackEmptyInspection.kt | 1 | 5830 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.inspections
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.demonwav.mcdev.platform.mcp.srg.SrgMemberReference
import com.demonwav.mcdev.util.MemberReference
import com.demonwav.mcdev.util.findModule
import com.demonwav.mcdev.util.fullQualifiedName
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiBinaryExpression
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiField
import com.intellij.psi.PsiReferenceExpression
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import org.jetbrains.annotations.Nls
class StackEmptyInspection : BaseInspection() {
companion object {
const val STACK_FQ_NAME = "net.minecraft.item.ItemStack"
val STACK_JVM_NAME = STACK_FQ_NAME.replace('.', '/')
val EMPTY_SRG = SrgMemberReference.parse("$STACK_JVM_NAME/field_190927_a")
val IS_EMPTY_SRG = SrgMemberReference.parse("$STACK_JVM_NAME/func_190926_b")
}
@Nls
override fun getDisplayName() = "ItemStack comparison through ItemStack.EMPTY"
override fun buildErrorString(vararg infos: Any): String {
val compareExpression = infos[0] as PsiExpression
return "\"${compareExpression.text}\" compared with ItemStack.EMPTY"
}
override fun getStaticDescription() =
"Comparing an ItemStack to ItemStack.EMPTY to query stack emptiness can cause unwanted issues." +
"When a stack in an inventory is shrunk, the instance is not replaced with ItemStack.EMPTY, but" +
" the stack should still be considered empty. Instead, isEmpty() should be called."
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
return object : InspectionGadgetsFix() {
override fun getFamilyName() = "Replace with .isEmpty()"
override fun doFix(project: Project, descriptor: ProblemDescriptor) {
val compareExpression = infos[0] as PsiExpression
val binaryExpression = infos[2] as PsiBinaryExpression
val elementFactory = JavaPsiFacade.getElementFactory(project)
val mappedIsEmpty = compareExpression.findModule()?.getMappedMethod(IS_EMPTY_SRG)?.name ?: "isEmpty"
var expressionText = "${compareExpression.text}.$mappedIsEmpty()"
// If we were checking for != ItemStack.EMPTY, use !stack.isEmpty()
if (binaryExpression.operationSign.tokenType == JavaTokenType.NE) {
expressionText = "!$expressionText"
}
val replacedExpression = elementFactory.createExpressionFromText(expressionText, binaryExpression.context)
binaryExpression.replace(replacedExpression)
}
}
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitBinaryExpression(expression: PsiBinaryExpression) {
val operationType = expression.operationSign.tokenType
if (operationType == JavaTokenType.EQEQ || operationType == JavaTokenType.NE) {
val leftExpression = expression.lOperand
val rightExpression = expression.rOperand
// Check if both operands evaluate to an ItemStack
if (isExpressionStack(leftExpression) && isExpressionStack(rightExpression)) {
val leftEmpty = isExpressionEmptyConstant(leftExpression)
val rightEmpty = isExpressionEmptyConstant(rightExpression)
// Check that only one of the references are ItemStack.EMPTY
if (leftEmpty xor rightEmpty) {
// The other operand will be the stack
val compareExpression = if (leftEmpty) rightExpression else leftExpression
val emptyReference = if (leftEmpty) leftExpression else rightExpression
registerError(expression, compareExpression, emptyReference, expression)
}
}
}
}
private fun isExpressionStack(expression: PsiExpression?): Boolean {
return (expression?.type as? PsiClassType)?.resolve()?.fullQualifiedName == STACK_FQ_NAME
}
private fun isExpressionEmptyConstant(expression: PsiExpression?): Boolean {
val reference = expression as? PsiReferenceExpression ?: return false
val field = reference.resolve() as? PsiField ?: return false
val mappedEmpty = field.findModule()?.getMappedField(EMPTY_SRG)?.name ?: "EMPTY"
return field.name == mappedEmpty && field.containingClass?.fullQualifiedName == STACK_FQ_NAME
}
}
}
private fun Module.getMappedMethod(reference: MemberReference): MemberReference? {
val srgManager = MinecraftFacet.getInstance(this, McpModuleType)?.srgManager
return srgManager?.srgMapNow?.mapToMcpMethod(reference)
}
private fun Module.getMappedField(reference: MemberReference): MemberReference? {
val srgManager = MinecraftFacet.getInstance(this, McpModuleType)?.srgManager
return srgManager?.srgMapNow?.mapToMcpField(reference)
}
}
| mit |
neva-dev/javarel-framework | storage/store/src/main/kotlin/com/neva/javarel/storage/store/api/StoreAdmin.kt | 1 | 515 | package com.neva.javarel.storage.store.api
interface StoreAdmin {
/**
* Name of default connection
*/
val connectionDefault: String
/**
* Select default store
*/
fun store(): Store
/**
* Select one of available stores using connection name
*/
fun store(connectionName: String): Store
/**
* Available store connections
*/
val connections: Set<StoreConnection>
/**
* Connected stores
*/
val connectedStores: Set<Store>
} | apache-2.0 |
emoji-gen/Emoji-Android | app/src/main/java/moe/pine/emoji/fragment/generator/SelectFontDialogFragment.kt | 1 | 1999 | package moe.pine.emoji.fragment.generator
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import moe.pine.emoji.activity.GeneratorActivity
import moe.pine.emoji.activity.binding.fontKey
import moe.pine.emoji.activity.binding.fontName
import moe.pine.emoji.lib.emoji.model.Font
/**
* Fragment for font selection dialog
* Created by pine on May 6, 2017.
*/
class SelectFontDialogFragment : DialogFragment() {
companion object {
val FONT_NAMES_KEY = "fontNames"
val FONT_KEYS_KEY = "fontKeys"
fun newInstance(fonts: List<Font>): SelectFontDialogFragment {
return SelectFontDialogFragment().also { fragment ->
val arguments = Bundle()
val fontNames = fonts.map(Font::name).toTypedArray()
val fontKeys = fonts.map(Font::key).toTypedArray()
arguments.putStringArray(FONT_NAMES_KEY, fontNames)
arguments.putStringArray(FONT_KEYS_KEY, fontKeys)
fragment.arguments = arguments
}
}
}
private lateinit var fontNames: Array<String>
private lateinit var fontKeys: Array<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.fontNames = this.arguments!!.getStringArray(FONT_NAMES_KEY)
this.fontKeys = this.arguments!!.getStringArray(FONT_KEYS_KEY)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(this.activity)
.setItems(this.fontNames) { dialog, which ->
dialog.dismiss()
this.updateFont(which)
}
.create()
}
private fun updateFont(position: Int) {
val activity = this.activity as GeneratorActivity
activity.fontName = this.fontNames[position]
activity.fontKey = this.fontKeys[position]
}
} | mit |
stanfy/helium | codegen/objc/objc-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/objectivec/entity/filetree/ObjCSourcePartsContainer.kt | 1 | 940 | package com.stanfy.helium.handler.codegen.objectivec.entity.filetree;
/**
* Created by paultaykalo on 12/16/15.
* Class that can have another source parts
*/
open class ObjCSourcePartsContainer : ObjCSourcePart {
val sourceParts = arrayListOf<ObjCSourcePart>()
/**
* Adds source part to current container
* @param sourcePart source part that need to be rendered as a part of container
*/
fun addSourcePart(sourcePart: ObjCSourcePart) {
sourceParts.add(sourcePart);
}
/**
* Adds string source part to current container
* @param sourcePart source part that need to be rendered as a part of container
*/
fun addSourcePart(sourcePart: String) {
sourceParts.add(ObjCStringSourcePart(sourcePart));
}
override fun asString(): String {
val bld = StringBuilder();
for (part in sourceParts) {
bld.append(part.asString());
bld.append("\n");
}
return bld.toString();
}
}
| apache-2.0 |
mdanielwork/intellij-community | plugins/stats-collector/features/src/com/jetbrains/completion/feature/Transformer.kt | 6 | 822 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.completion.feature
/**
* @author Vitaliy.Bibaev
*/
interface Transformer {
fun featureArray(relevanceMap: Map<String, Any>,
userFactors: Map<String, Any?>): DoubleArray
} | apache-2.0 |
StPatrck/edac | app/src/main/java/com/phapps/elitedangerous/companion/api/edc/dtos/EdcLastStarportDto.kt | 1 | 204 | package com.phapps.elitedangerous.companion.api.edc.dtos
data class EdcLastStarportDto(val id: Long, val name: String, val services: EdcServiceDto,
val faction: String, val minorfaction: String)
| gpl-3.0 |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/user/internal/UserOrganisationUnitLinkStoreImpl.kt | 1 | 5778 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.user.internal
import android.database.Cursor
import java.lang.RuntimeException
import kotlin.Throws
import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.SQLStatementBuilderImpl
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementBinder
import org.hisp.dhis.android.core.arch.db.stores.binders.internal.StatementWrapper
import org.hisp.dhis.android.core.arch.db.stores.internal.LinkStoreImpl
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit
import org.hisp.dhis.android.core.user.UserOrganisationUnitLink
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkTableInfo
internal class UserOrganisationUnitLinkStoreImpl private constructor(
databaseAdapter: DatabaseAdapter,
masterColumn: String,
builder: SQLStatementBuilderImpl,
binder: StatementBinder<UserOrganisationUnitLink>
) : LinkStoreImpl<UserOrganisationUnitLink>(
databaseAdapter,
builder,
masterColumn,
binder,
{ cursor: Cursor -> UserOrganisationUnitLink.create(cursor) }
),
UserOrganisationUnitLinkStore {
@Throws(RuntimeException::class)
override fun queryRootCaptureOrganisationUnitUids(): List<String> {
return selectStringColumnsWhereClause(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
WhereClauseBuilder()
.appendKeyNumberValue(UserOrganisationUnitLinkTableInfo.Columns.ROOT, 1)
.appendKeyStringValue(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
OrganisationUnit.Scope.SCOPE_DATA_CAPTURE
).build()
)
}
override fun queryOrganisationUnitUidsByScope(scope: OrganisationUnit.Scope): List<String> {
return selectStringColumnsWhereClause(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
WhereClauseBuilder()
.appendKeyStringValue(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
scope.name
).build()
)
}
override fun queryAssignedOrganisationUnitUidsByScope(scope: OrganisationUnit.Scope): List<String> {
return selectStringColumnsWhereClause(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT,
WhereClauseBuilder()
.appendKeyNumberValue(UserOrganisationUnitLinkTableInfo.Columns.USER_ASSIGNED, 1)
.appendKeyStringValue(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
scope.name
).build()
)
}
override fun isCaptureScope(organisationUnit: String): Boolean {
val whereClause = WhereClauseBuilder()
.appendKeyStringValue(UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT, organisationUnit)
.appendKeyStringValue(
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
OrganisationUnit.Scope.SCOPE_DATA_CAPTURE
)
.build()
return countWhere(whereClause) == 1
}
companion object {
private val BINDER =
StatementBinder<UserOrganisationUnitLink> { o: UserOrganisationUnitLink, w: StatementWrapper ->
w.bind(1, o.user())
w.bind(2, o.organisationUnit())
w.bind(3, o.organisationUnitScope())
w.bind(4, o.root())
w.bind(5, o.userAssigned())
}
@JvmStatic
fun create(databaseAdapter: DatabaseAdapter): UserOrganisationUnitLinkStore {
val statementBuilder = SQLStatementBuilderImpl(UserOrganisationUnitLinkTableInfo.TABLE_INFO)
return UserOrganisationUnitLinkStoreImpl(
databaseAdapter,
UserOrganisationUnitLinkTableInfo.Columns.ORGANISATION_UNIT_SCOPE,
statementBuilder,
BINDER
)
}
}
}
| bsd-3-clause |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/option/OptionService.kt | 1 | 532 | package org.hisp.dhis.android.core.option
import io.reactivex.Single
interface OptionService {
fun blockingSearchForOptions(
optionSetUid: String,
searchText: String? = null,
optionToHideUids: List<String>? = null,
optionToShowUids: List<String>? = null,
): List<Option>
fun searchForOptions(
optionSetUid: String,
searchText: String? = null,
optionToHideUids: List<String>? = null,
optionToShowUids: List<String>? = null,
): Single<List<Option>>
}
| bsd-3-clause |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/ProgressIconShowcaseAction.kt | 7 | 1115 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ui
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.ColorPicker
import com.intellij.ui.SpinningProgressIcon
import com.intellij.ui.components.dialog
import com.intellij.ui.dsl.builder.panel
/**
* @author Konstantin Bulenkov
*/
internal class ProgressIconShowcaseAction : DumbAwareAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
val icon = SpinningProgressIcon()
val panel = panel {
row {
icon(icon)
link("Change color") {
ColorPicker.showColorPickerPopup(null, icon.getIconColor()) { color, _ -> color?.let { icon.setIconColor(it) } }
}
}
}
val dialog = dialog(templatePresentation.text, panel)
dialog.isModal = false
dialog.setSize(600, 600)
dialog.show()
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/addNewLineAfterAnnotations/preserveComments.kt | 13 | 344 | // "Add new line after annotations" "true"
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class Ann
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class Ann2(val x: String)
fun foo(y: Int) {
var x = 1
@Ann // abc
@Ann2("") /* abc2*/ x<caret> += 2
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/kdoc/KDocLinkMultiModuleResolveTest.kt | 4 | 5804 | // 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.kdoc
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.rt.execution.junit.FileComparisonFailure
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.editor.quickDoc.AbstractQuickDocProviderTest.wrapToFileComparisonFailure
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.resolve.BindingContext.DECLARATION_TO_DESCRIPTOR
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
import java.io.File
@RunWith(JUnit38ClassRunner::class)
class KDocLinkMultiModuleResolveTest : AbstractMultiModuleTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("kdoc/multiModuleResolve")
fun testSimple() {
val code = module("code")
val samples = module("samples", hasTestRoot = true)
samples.addDependency(code)
doInfoTest("code/usage.kt")
}
fun testFqName() {
val code = module("code")
val samples = module("samples", hasTestRoot = true)
samples.addDependency(code)
doInfoTest("code/usage.kt")
doResolveSampleTest("samples")
doResolveSampleTest("samples.SampleGroup")
doResolveSampleTest("samples.megasamples")
doResolveSampleTest("samples.megasamples.MegaSamplesGroup")
doResolveSampleTest("samples.notindir")
doResolveSampleTest("samples.notindir.NotInDirSamples")
doResolveSampleTest("samplez")
doResolveSampleTest("samplez.a")
doResolveSampleTest("samplez.a.b")
doResolveSampleTest("samplez.a.b.c")
doResolveSampleTest("samplez.a.b.c.Samplez")
}
fun testTypeParameters() {
val code = module("code")
val samples = module("samples", hasTestRoot = true)
samples.addDependency(code)
doInfoTest("code/usageSingleTypeParameter.kt")
doInfoTest("code/usageNestedTypeParameters.kt")
}
private fun doResolveSampleTest(link: String) {
configureByFile("${getTestName(true)}/code/usage.kt")
val documentationManager = DocumentationManager.getInstance(myProject)
val targetElement = documentationManager.findTargetElement(myEditor, file)
targetElement as KtElement
val bindingContext = targetElement.analyze()
val descriptor = bindingContext[DECLARATION_TO_DESCRIPTOR, targetElement]!!
val kdoc = descriptor.findKDoc()!!.contentTag as KDocSection
val resolutionFacade = targetElement.getResolutionFacade()
assertNotEmpty(resolveKDocLink(bindingContext, resolutionFacade, descriptor, kdoc.findTagByName("sample")!!, link.split(".")))
}
private fun doInfoTest(path: String) {
val fullPath = "${getTestName(true)}/$path"
val testDataFile = File(testDataPath, fullPath)
configureByFile(fullPath)
val documentationManager = DocumentationManager.getInstance(myProject)
val targetElement = documentationManager.findTargetElement(myEditor, file)
val originalElement = DocumentationManager.getOriginalElement(targetElement)
var info = DocumentationManager.getProviderFromElement(targetElement).generateDoc(targetElement, originalElement)
if (info != null) {
info = StringUtil.convertLineSeparators(info)
}
if (info != null && !info.endsWith("\n")) {
info += "\n"
}
val textData = FileUtil.loadFile(testDataFile, true)
val directives = InTextDirectivesUtils.findLinesWithPrefixesRemoved(textData, false, true, "INFO:")
if (directives.isEmpty()) {
throw FileComparisonFailure(
"'// INFO:' directive was expected",
textData,
textData + "\n\n//INFO: " + info,
testDataFile.absolutePath
)
} else {
val expectedInfo = directives.joinToString("\n", postfix = "\n")
if (expectedInfo.endsWith("...\n")) {
if (!info!!.startsWith(expectedInfo.removeSuffix("...\n"))) {
wrapToFileComparisonFailure(info, testDataFile.absolutePath, textData)
}
} else if (expectedInfo != info) {
wrapToFileComparisonFailure(info!!, testDataFile.absolutePath, textData)
}
}
}
fun testSeeTagFqName() {
module("usage")
module("code")
doResolveTest("usage/usage.kt", KtClass::class.java)
}
fun testMarkdownLinkFqName() {
module("usage")
module("code")
doResolveTest("usage/usage.kt", KtNamedFunction::class.java)
}
fun testSamePackages() {
module("usage")
module("code")
doResolveTest("usage/foo/bar/usage.kt", KtClass::class.java)
}
private fun doResolveTest(path: String, clazz: Class<*>) {
configureByFile("${getTestName(true)}/$path")
val element = file.findReferenceAt(editor.caretModel.offset)
val resolvedElement = element?.resolve()
assertNotNull(resolvedElement)
assertInstanceOf(resolvedElement, clazz)
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/compiler-plugins/parcelize/tests/test/org/jetbrains/kotlin/pacelize/ide/test/AbstractParcelizeQuickFixTest.kt | 7 | 626 | // 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.pacelize.ide.test
import org.jetbrains.kotlin.idea.quickfix.AbstractQuickFixTest
abstract class AbstractParcelizeQuickFixTest : AbstractQuickFixTest() {
override fun setUp() {
super.setUp()
addParcelizeLibraries(module)
}
override fun tearDown() {
try {
removeParcelizeLibraries(module)
} catch (e: Throwable) {
addSuppressedException(e)
} finally {
super.tearDown()
}
}
} | apache-2.0 |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/ui/Clickable.kt | 1 | 326 | package tripleklay.ui
import react.SignalView
/**
* Implemented by [Element]s that can be clicked.
*/
interface Clickable<T : Element<*>> {
/** A signal that is emitted when this element is clicked. */
fun clicked(): SignalView<T>
/** Programmatically triggers a click of this element. */
fun click()
}
| apache-2.0 |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/base/ControlFlow.kt | 1 | 3147 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instruction
import com.github.jonathanxd.kores.KoresPart
import com.github.jonathanxd.kores.base.ControlFlow.Type
/**
* Control the flow of a statement.
*
* @property type Type of the flow control
* @property at Label to control flow (Note: [Type.CONTINUE] goes to Start of label and [Type.BREAK] goes to end of label).
* **Note**: [Type.CONTINUE] to a label is dangerous.
*/
data class ControlFlow(val type: Type, val at: Label?) : KoresPart, Instruction {
override fun builder(): Builder = Builder(this)
class Builder() : com.github.jonathanxd.kores.builder.Builder<ControlFlow, Builder> {
lateinit var type: Type
var at: Label? = null
constructor(defaults: ControlFlow) : this() {
this.type = defaults.type
this.at = defaults.at
}
/**
* See [ControlFlow.type]
*/
fun type(value: Type): Builder {
this.type = value
return this
}
/**
* See [ControlFlow.at]
*/
fun at(value: Label?): Builder {
this.at = value
return this
}
override fun build(): ControlFlow = ControlFlow(this.type, this.at)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: ControlFlow): Builder = Builder(defaults)
}
}
enum class Type {
/**
* Breaks to end of the flow
*/
BREAK,
/**
* Continue at start of the flow
*/
CONTINUE
}
}
| mit |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/old/tests/testData/fileOrElement/class/notUtilityClass.kt | 13 | 137 | internal open class Base {
companion object {
val CONSTANT = 10
}
}
internal class Derived : Base() {
fun foo() {}
} | apache-2.0 |
MasoodFallahpoor/InfoCenter | InfoCenter/src/main/java/com/fallahpoor/infocenter/fragments/CameraFragment.kt | 1 | 11855 | /*
Copyright (C) 2014-2016 Masood Fallahpoor
This file is part of Info Center.
Info Center 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.
Info Center 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 Info Center. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fallahpoor.infocenter.fragments
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.ImageFormat
import android.hardware.Camera
import android.hardware.Camera.CameraInfo
import android.os.AsyncTask
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import com.fallahpoor.infocenter.R
import com.fallahpoor.infocenter.Utils
import com.fallahpoor.infocenter.adapters.CustomArrayAdapter
import com.fallahpoor.infocenter.adapters.HeaderListItem
import com.fallahpoor.infocenter.adapters.ListItem
import com.fallahpoor.infocenter.adapters.OrdinaryListItem
import de.halfbit.pinnedsection.PinnedSectionListView
import kotlinx.android.synthetic.main.fragment_camera.*
import java.util.*
/**
* CameraFragment displays some properties of the camera(s) of the device,
* if any.
*/
// CHECK Is it possible for a device to have front camera but not rear camera?
// TODO Update the code to use the new Camera API introduced in Android Lollipop.
class CameraFragment : Fragment() {
private var utils: Utils? = null
private var getCameraParamsTask: GetCameraParamsTask? = null
private// how many cameras do we have in here?!
val listItems: ArrayList<ListItem>
get() {
val items = ArrayList<ListItem>()
when (Camera.getNumberOfCameras()) {
1 -> items.addAll(getCameraParams(CameraInfo.CAMERA_FACING_BACK))
2 -> {
items.add(HeaderListItem(getString(R.string.cam_item_back_camera)))
items.addAll(getCameraParams(CameraInfo.CAMERA_FACING_BACK))
items.add(HeaderListItem(getString(R.string.cam_item_front_camera)))
items.addAll(getCameraParams(CameraInfo.CAMERA_FACING_FRONT))
}
}
return items
}
private val itemsArray: Array<String>
get() = arrayOf(
getString(R.string.cam_item_camera_quality),
getString(R.string.cam_item_picture_size),
getString(R.string.cam_item_picture_format),
getString(R.string.cam_item_supported_video_sizes),
getString(R.string.cam_item_focal_length),
getString(R.string.cam_item_antibanding),
getString(R.string.cam_item_auto_exposure_lock),
getString(R.string.cam_item_auto_white_balance_lock),
getString(R.string.cam_item_color_effect),
getString(R.string.cam_item_flash),
getString(R.string.cam_item_scene_selection),
getString(R.string.cam_item_zoom),
getString(R.string.cam_item_video_snapshot)
)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_camera, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
utils = Utils(activity!!)
(listView as PinnedSectionListView).setShadowVisible(false)
textView.setText(R.string.cam_no_camera)
if (ActivityCompat.checkSelfPermission(
activity!!,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
populateListView()
} else {
requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_CAMERA)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_CODE_CAMERA) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateListView()
} else {
listView.emptyView = textView
}
}
}
override fun onDestroy() {
super.onDestroy()
if (getCameraParamsTask != null) {
getCameraParamsTask!!.cancel(true)
getCameraParamsTask = null
}
if (progressWheel != null && progressWheel.isSpinning) {
progressWheel.stopSpinning()
}
}
private fun populateListView() {
if (Camera.getNumberOfCameras() > 0) {
getCameraParamsTask = GetCameraParamsTask()
getCameraParamsTask!!.execute()
} else {
listView.emptyView = textView
}
}
private fun getCameraInstance(cameraId: Int): Camera? {
var camera: Camera? = null
try {
camera = Camera.open(cameraId)
} catch (ignored: Exception) {
}
return camera
}
private fun getCameraParams(cameraFacing: Int): ArrayList<ListItem> {
val camParams = ArrayList<ListItem>()
val cameraParams: Camera.Parameters
val camera: Camera? = getCameraInstance(cameraFacing)
val items: Array<String>
val subItems: ArrayList<String>
if (camera != null) {
cameraParams = camera.parameters
releaseCamera(camera)
items = itemsArray
subItems = getParameters(cameraParams)
for (i in items.indices) {
camParams.add(OrdinaryListItem(items[i], subItems[i]))
}
} else { // camera is busy or for some other reason camera isn't available
if (cameraFacing == CameraInfo.CAMERA_FACING_BACK) {
camParams.add(
OrdinaryListItem(
getString(R.string.cam_sub_item_back_camera_info_unavailable), ""
)
)
} else {
camParams.add(
OrdinaryListItem(
getString(R.string.cam_sub_item_front_camera_info_unavailable), ""
)
)
}
}
return camParams
} // end method getCameraParams
private fun getParameters(cameraParams: Camera.Parameters): ArrayList<String> {
val params = ArrayList<String>()
val supported = getString(R.string.supported)
val unsupported = getString(R.string.unsupported)
params.add(getMegaPixels(cameraParams))
params.add(getPictureSize(cameraParams))
params.add(getPictureFormat(cameraParams))
params.add(getSupportedVideoSizes(cameraParams))
params.add(getFocalLength(cameraParams))
params.add(if (cameraParams.antibanding != null) supported else unsupported)
params.add(if (cameraParams.isAutoExposureLockSupported) supported else unsupported)
params.add(if (cameraParams.isAutoWhiteBalanceLockSupported) supported else unsupported)
params.add(if (cameraParams.colorEffect != null) supported else unsupported)
params.add(if (cameraParams.flashMode != null) supported else unsupported)
params.add(if (cameraParams.sceneMode != null) supported else unsupported)
params.add(if (cameraParams.isZoomSupported) supported else unsupported)
params.add(if (cameraParams.isVideoSnapshotSupported) supported else unsupported)
return params
} // end method getParameters
private fun getMegaPixels(cameraParams: Camera.Parameters): String {
val pictureSizes = cameraParams.supportedPictureSizes
var strMegaPixels = getString(R.string.unknown)
val dblMegaPixels: Double
var maxHeight = Integer.MIN_VALUE
var maxWidth = Integer.MIN_VALUE
for (pictureSize in pictureSizes) {
if (pictureSize.width > maxWidth) {
maxWidth = pictureSize.width
}
if (pictureSize.height > maxHeight) {
maxHeight = pictureSize.height
}
}
if (maxWidth != Integer.MIN_VALUE && maxHeight != Integer.MIN_VALUE) {
dblMegaPixels = (maxWidth * maxHeight).toDouble() / 1000000
strMegaPixels = String.format(
utils!!.locale, "%.1f %s",
dblMegaPixels, getString(R.string.cam_sub_item_mp)
)
}
return strMegaPixels
} // end method getMegaPixels
private fun getPictureSize(cameraParams: Camera.Parameters): String {
val width = cameraParams.pictureSize.width
val height = cameraParams.pictureSize.height
return String.format(utils!!.locale, "%d x %d", width, height)
}
private fun getPictureFormat(cameraParams: Camera.Parameters): String {
val intFormat = cameraParams.pictureFormat
val format: String
format = when (intFormat) {
ImageFormat.JPEG -> "JPEG"
ImageFormat.RGB_565 -> "RGB"
else -> getString(R.string.unknown)
}
return format
}
private fun getSupportedVideoSizes(cameraParams: Camera.Parameters): String {
var i = 0
val videoSizes = StringBuilder()
val supportedVideoSizes =
cameraParams.supportedVideoSizes ?: return getString(R.string.unknown)
while (i < supportedVideoSizes.size - 1) {
videoSizes.append(
String.format(
utils!!.locale, "%d x %d, ",
supportedVideoSizes[i].width,
supportedVideoSizes[i].height
)
)
i++
}
videoSizes.append(
String.format(
utils!!.locale, "%d x %d ",
supportedVideoSizes[i].width, supportedVideoSizes[i].height
)
)
return videoSizes.toString()
}
private fun getFocalLength(cameraParams: Camera.Parameters): String {
return try {
String.format(
utils!!.locale, "%.2f %s",
cameraParams.focalLength,
getString(R.string.cam_sub_item_mm)
)
} catch (ex: IllegalFormatException) {
getString(R.string.unknown)
}
}
private fun releaseCamera(camera: Camera?) {
camera?.release()
}
private inner class GetCameraParamsTask : AsyncTask<Void, Void, ArrayList<ListItem>>() {
override fun onPreExecute() {
super.onPreExecute()
progressWheel.visibility = View.VISIBLE
}
override fun doInBackground(vararg params: Void): ArrayList<ListItem> {
return listItems
}
override fun onPostExecute(result: ArrayList<ListItem>) {
super.onPostExecute(result)
listView.adapter = CustomArrayAdapter(activity, result)
getCameraParamsTask = null
progressWheel.visibility = View.INVISIBLE
progressWheel.stopSpinning()
}
}
companion object {
private const val REQUEST_CODE_CAMERA = 1001
}
} | gpl-3.0 |
pine613/RxBindroid | example/src/main/java/moe/pine/rx/bindroid/example/presentation/activity/MainActivity.kt | 1 | 712 | package moe.pine.rx.bindroid.example.presentation.activity
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import moe.pine.rx.bindroid.example.R
import moe.pine.rx.bindroid.example.business.Models
import moe.pine.rx.bindroid.example.business.viewmodel.activity.FragmentTransactionViewModel
/**
* MainActivity
* Created by pine on 2016/03/06.
*/
class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
this.bindViewModel()
}
private fun bindViewModel() {
FragmentTransactionViewModel(Models.viewPath).subscribe(this)
}
}
| apache-2.0 |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/column/ColumnExtra1.kt | 1 | 11579 | package jp.juggler.subwaytooter.column
import android.annotation.SuppressLint
import android.view.View
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.entity.EntityId
import jp.juggler.subwaytooter.api.entity.TimelineItem
import jp.juggler.subwaytooter.api.entity.TootStatus
import jp.juggler.subwaytooter.columnviewholder.ColumnViewHolder
import jp.juggler.subwaytooter.pref.PrefB
import jp.juggler.util.LogCategory
import jp.juggler.util.getAdaptiveRippleDrawable
import jp.juggler.util.notZero
import jp.juggler.util.showToast
import org.jetbrains.anko.backgroundDrawable
private val log = LogCategory("ColumnExtra1")
///////////////////////////////////////////////////
// ViewHolderとの連携
fun Column.canRemoteOnly() = when (type) {
ColumnType.FEDERATE, ColumnType.FEDERATED_AROUND -> true
else -> false
}
fun Column.canReloadWhenRefreshTop(): Boolean = when (type) {
ColumnType.KEYWORD_FILTER,
ColumnType.SEARCH,
ColumnType.SEARCH_MSP,
ColumnType.SEARCH_TS,
ColumnType.SEARCH_NOTESTOCK,
ColumnType.CONVERSATION,
ColumnType.CONVERSATION_WITH_REFERENCE,
ColumnType.LIST_LIST,
ColumnType.TREND_TAG,
ColumnType.FOLLOW_SUGGESTION,
ColumnType.PROFILE_DIRECTORY,
ColumnType.STATUS_HISTORY,
-> true
ColumnType.LIST_MEMBER,
ColumnType.MUTES,
ColumnType.FOLLOW_REQUESTS,
-> isMisskey
else -> false
}
// カラム操作的にリフレッシュを許容するかどうか
fun Column.canRefreshTopBySwipe(): Boolean =
canReloadWhenRefreshTop() ||
when (type) {
ColumnType.CONVERSATION,
ColumnType.CONVERSATION_WITH_REFERENCE,
ColumnType.INSTANCE_INFORMATION,
-> false
else -> true
}
// カラム操作的に下端リフレッシュを許容するかどうか
fun Column.canRefreshBottomBySwipe(): Boolean = when (type) {
ColumnType.LIST_LIST,
ColumnType.CONVERSATION,
ColumnType.CONVERSATION_WITH_REFERENCE,
ColumnType.INSTANCE_INFORMATION,
ColumnType.KEYWORD_FILTER,
ColumnType.SEARCH,
ColumnType.TREND_TAG,
ColumnType.FOLLOW_SUGGESTION,
ColumnType.STATUS_HISTORY,
-> false
ColumnType.FOLLOW_REQUESTS -> isMisskey
ColumnType.LIST_MEMBER -> !isMisskey
else -> true
}
// データ的にリフレッシュを許容するかどうか
fun Column.canRefreshTop(): Boolean = when (pagingType) {
ColumnPagingType.Default -> idRecent != null
else -> false
}
// データ的にリフレッシュを許容するかどうか
fun Column.canRefreshBottom(): Boolean = when (pagingType) {
ColumnPagingType.Default, ColumnPagingType.Cursor -> idOld != null
ColumnPagingType.None -> false
ColumnPagingType.Offset -> true
}
fun Column.getIconId(): Int = type.iconId(accessInfo.acct)
fun Column.getColumnName(long: Boolean) =
type.name2(this, long) ?: type.name1(context)
fun Column.getContentColor() = contentColor.notZero() ?: Column.defaultColorContentText
fun Column.getAcctColor() = acctColor.notZero() ?: Column.defaultColorContentAcct
fun Column.getHeaderPageNumberColor() =
headerFgColor.notZero() ?: Column.defaultColorHeaderPageNumber
fun Column.getHeaderNameColor() = headerFgColor.notZero() ?: Column.defaultColorHeaderName
fun Column.getHeaderBackgroundColor() = headerBgColor.notZero() ?: Column.defaultColorHeaderBg
fun Column.setHeaderBackground(view: View) {
view.backgroundDrawable = getAdaptiveRippleDrawable(
getHeaderBackgroundColor(),
getHeaderNameColor()
)
}
val Column.hasHashtagExtra: Boolean
get() = when {
isMisskey -> false
type == ColumnType.HASHTAG -> true
// ColumnType.HASHTAG_FROM_ACCT は追加のタグを指定しても結果に反映されない
else -> false
}
fun Column.getHeaderDesc(): String {
var cache = cacheHeaderDesc
if (cache != null) return cache
cache = when (type) {
ColumnType.SEARCH -> context.getString(R.string.search_desc_mastodon_api)
ColumnType.SEARCH_MSP -> loadSearchDesc(
R.raw.search_desc_msp_en,
R.raw.search_desc_msp_ja
)
ColumnType.SEARCH_TS -> loadSearchDesc(
R.raw.search_desc_ts_en,
R.raw.search_desc_ts_ja
)
ColumnType.SEARCH_NOTESTOCK -> loadSearchDesc(
R.raw.search_desc_notestock_en,
R.raw.search_desc_notestock_ja
)
else -> ""
}
cacheHeaderDesc = cache
return cache
}
fun Column.hasMultipleViewHolder(): Boolean = listViewHolder.size > 1
fun Column.addColumnViewHolder(cvh: ColumnViewHolder) {
// 現在のリストにあるなら削除する
removeColumnViewHolder(cvh)
// 最後に追加されたものが先頭にくるようにする
// 呼び出しの後に必ず追加されているようにする
listViewHolder.addFirst(cvh)
}
/////////////////////////////////////////////////////////////////
// ActMain の表示開始時に呼ばれる
fun Column.onActivityStart() {
// 破棄されたカラムなら何もしない
if (isDispose.get()) {
log.d("onStart: column was disposed.")
return
}
// 未初期化なら何もしない
if (!bFirstInitialized) {
log.d("onStart: column is not initialized.")
return
}
// 初期ロード中なら何もしない
if (bInitialLoading) {
log.d("onStart: column is in initial loading.")
return
}
// フィルタ一覧のリロードが必要
if (filterReloadRequired) {
filterReloadRequired = false
startLoading()
return
}
// 始端リフレッシュの最中だった
// リフレッシュ終了時に自動でストリーミング開始するはず
if (bRefreshingTop) {
log.d("onStart: bRefreshingTop is true.")
return
}
if (!bRefreshLoading &&
canAutoRefresh() &&
!PrefB.bpDontRefreshOnResume(appState.pref) &&
!dontAutoRefresh
) {
// リフレッシュしてからストリーミング開始
log.d("onStart: start auto refresh.")
startRefresh(bSilent = true, bBottom = false)
} else if (isSearchColumn) {
// 検索カラムはリフレッシュもストリーミングもないが、表示開始のタイミングでリストの再描画を行いたい
fireShowContent(reason = "Column onStart isSearchColumn", reset = true)
} else if (canStreamingState() && canStreamingType()) {
// ギャップつきでストリーミング開始
this.bPutGap = true
fireShowColumnStatus()
}
}
fun Column.cancelLastTask() {
if (lastTask != null) {
lastTask?.cancel()
lastTask = null
//
bInitialLoading = false
bRefreshLoading = false
mInitialLoadingError = context.getString(R.string.cancelled)
}
}
// @Nullable String parseMaxId( TootApiResult result ){
// if( result != null && result.link_older != null ){
// Matcher m = reMaxId.matcher( result.link_older );
// if( m.get() ) return m.group( 1 );
// }
// return null;
// }
fun Column.startLoading() {
cancelLastTask()
initFilter()
Column.showOpenSticker = PrefB.bpOpenSticker(appState.pref)
mRefreshLoadingErrorPopupState = 0
mRefreshLoadingError = ""
mInitialLoadingError = ""
bFirstInitialized = true
bInitialLoading = true
bRefreshLoading = false
idOld = null
idRecent = null
offsetNext = 0
pagingType = ColumnPagingType.Default
duplicateMap.clear()
listData.clear()
fireShowContent(reason = "loading start", reset = true)
@SuppressLint("StaticFieldLeak")
val task = ColumnTask_Loading(this)
this.lastTask = task
task.start()
}
fun Column.startRefresh(
bSilent: Boolean,
bBottom: Boolean,
postedStatusId: EntityId? = null,
refreshAfterToot: Int = -1,
) {
if (lastTask != null) {
if (!bSilent) {
context.showToast(true, R.string.column_is_busy)
val holder = viewHolder
if (holder != null) holder.refreshLayout.isRefreshing = false
}
return
} else if (bBottom && !canRefreshBottom()) {
if (!bSilent) {
context.showToast(true, R.string.end_of_list)
val holder = viewHolder
if (holder != null) holder.refreshLayout.isRefreshing = false
}
return
} else if (!bBottom && !canRefreshTop()) {
val holder = viewHolder
if (holder != null) holder.refreshLayout.isRefreshing = false
startLoading()
return
}
if (bSilent) {
val holder = viewHolder
if (holder != null) {
holder.refreshLayout.isRefreshing = true
}
}
if (!bBottom) {
bRefreshingTop = true
}
bRefreshLoading = true
mRefreshLoadingError = ""
@SuppressLint("StaticFieldLeak")
val task = ColumnTask_Refresh(this, bSilent, bBottom, postedStatusId, refreshAfterToot)
this.lastTask = task
task.start()
fireShowColumnStatus()
}
fun Column.startRefreshForPost(
refreshAfterPost: Int,
postedStatusId: EntityId,
postedReplyId: EntityId?,
) {
when (type) {
ColumnType.HOME,
ColumnType.LOCAL,
ColumnType.FEDERATE,
ColumnType.DIRECT_MESSAGES,
ColumnType.MISSKEY_HYBRID,
-> startRefresh(
bSilent = true,
bBottom = false,
postedStatusId = postedStatusId,
refreshAfterToot = refreshAfterPost
)
ColumnType.PROFILE -> {
if (profileTab == ProfileTab.Status && profileId == accessInfo.loginAccount?.id) {
startRefresh(
bSilent = true,
bBottom = false,
postedStatusId = postedStatusId,
refreshAfterToot = refreshAfterPost
)
}
}
ColumnType.CONVERSATION,
ColumnType.CONVERSATION_WITH_REFERENCE,
-> {
// 会話への返信が行われたなら会話を更新する
try {
if (postedReplyId != null) {
for (item in listData) {
if (item is TootStatus && item.id == postedReplyId) {
startLoading()
break
}
}
}
} catch (_: Throwable) {
}
}
else -> Unit
}
}
fun Column.startGap(gap: TimelineItem?, isHead: Boolean) {
if (gap == null) {
context.showToast(true, "gap is null")
return
}
if (lastTask != null) {
context.showToast(true, R.string.column_is_busy)
return
}
@Suppress("UNNECESSARY_SAFE_CALL")
viewHolder?.refreshLayout?.isRefreshing = true
bRefreshLoading = true
mRefreshLoadingError = ""
@SuppressLint("StaticFieldLeak")
val task = ColumnTask_Gap(this, gap, isHead = isHead)
this.lastTask = task
task.start()
fireShowColumnStatus()
}
| apache-2.0 |
github/codeql | java/ql/test/kotlin/library-tests/call-int-to-char/test.kt | 1 | 137 | fun f(x: Int) = x.toChar()
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.toChar in java.lang.Integer%
| mit |
JoelMarcey/buck | tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/actions/select/KotlinBuckTestActions.kt | 1 | 2960 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.intellij.ideabuck.actions.select
import com.facebook.buck.intellij.ideabuck.icons.BuckIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedFunction
/** Implementation of {@link KotlinBuckTestAction} for class test action. */
class ClassKotlinBuckTestAction(testClass: KtClass, debug: Boolean) :
KotlinBuckTestAction(testClass, debug) {
override fun getTestSelector(): String = testClass.fqName?.asString() ?: ""
override fun getFullTestName(): String = testClass.name ?: ""
override fun getDisplayTestName(): String = getFullTestName()
}
/** Implementation of {@link KotlinBuckTestAction} for function test action. */
class FunctionKotlinBuckTestAction(
private val testFunction: KtNamedFunction,
testClass: KtClass,
debug: Boolean
) : KotlinBuckTestAction(testClass, debug) {
override fun getTestSelector(): String = testClass.fqName?.asString() + "#" + testFunction.name
override fun getFullTestName(): String = testClass.name + "#" + testFunction.name
override fun getDisplayTestName(): String = truncateName(testFunction.name)
}
/** Implementation of {@link AbstractBuckTestAction} that runs a class/method. */
abstract class KotlinBuckTestAction(val testClass: KtClass, private val debug: Boolean) :
AbstractBuckTestAction() {
override fun isDebug(): Boolean {
return debug
}
/** User press the run/debug icon */
override fun actionPerformed(e: AnActionEvent) {
val project = testClass.project
val virtualFile = testClass.containingFile.virtualFile
createTestConfigurationFromContext(getFullTestName(), getTestSelector(), project, virtualFile)
}
/** Update the run/debug gutter icon */
override fun update(e: AnActionEvent) {
val verb =
if (debug) {
e.presentation.icon = BuckIcons.BUCK_DEBUG
"Debug"
} else {
e.presentation.icon = BuckIcons.BUCK_RUN
"Run"
}
e.presentation.text = "$verb '${getDisplayTestName()}' with Buck"
e.presentation.isEnabledAndVisible = true
}
// Utils function to distinguish function test action from class test action
abstract fun getTestSelector(): String
abstract fun getFullTestName(): String
abstract fun getDisplayTestName(): String
}
| apache-2.0 |
antlr/grammars-v4 | kotlin/kotlin-formal/examples/fuzzer/kt14564_2.kt-2053804782.kt_minimized.kt | 1 | 195 | var result = "fail"
object TimeUtil {
fun waitForAssert(z: String): Unit {
waitForEx(action={result})
}
inline fun waitForEx(retryWait: Int = 200, action: (() -> String)): Unit {
(action)!!()
}
} | mit |
auricgoldfinger/Memento-Namedays | memento/src/test/java/com/alexstyl/specialdates/addevent/JavaMessageDisplayer.kt | 3 | 172 | package com.alexstyl.specialdates.addevent
class JavaMessageDisplayer : MessageDisplayer {
override fun showMessage(string: String) {
println(string)
}
}
| mit |
pratamawijaya/example | KotlinLanguage/BasicKotlin/app/src/main/java/com/pratamawijaya/basickotlin/domain/datasource/ForecastDataSource.kt | 1 | 437 | package com.pratamawijaya.basickotlin.domain.datasource
import com.pratamawijaya.basickotlin.domain.model.Forecast
import com.pratamawijaya.basickotlin.domain.model.ForecastList
/**
* Created by : pratama - [email protected]
* Date : 10/24/15
* Project : BasicKotlin
*/
interface ForecastDataSource {
fun requestForecastByZipCode(zipCode: Long, date: Long): ForecastList?
fun requestDayForecast(id: Long): Forecast?
} | apache-2.0 |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/gradle/McpProjectResolverExtension.kt | 1 | 1787 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.gradle
import com.demonwav.mcdev.platform.mcp.gradle.datahandler.McpModelFG2Handler
import com.demonwav.mcdev.platform.mcp.gradle.datahandler.McpModelFG3Handler
import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG2
import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG3
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
class McpProjectResolverExtension : AbstractProjectResolverExtension() {
// Register our custom Gradle tooling API model in IntelliJ's project resolver
override fun getExtraProjectModelClasses(): Set<Class<out Any>> =
setOf(McpModelFG2::class.java, McpModelFG3::class.java)
override fun getToolingExtensionsClasses() = extraProjectModelClasses
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
var data: McpModelData? = null
for (handler in handlers) {
data = handler.build(gradleModule, ideModule.data, resolverCtx)
if (data != null) {
break
}
}
data?.let {
// Register our data in the module
ideModule.createChild(McpModelData.KEY, data)
}
// Process the other resolver extensions
super.populateModuleExtraModels(gradleModule, ideModule)
}
companion object {
private val handlers = listOf(McpModelFG2Handler, McpModelFG3Handler)
}
}
| mit |
vladmm/intellij-community | plugins/settings-repository/src/ReadOnlySourcesManager.kt | 9 | 2018 | /*
* 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.util.SmartList
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.jetbrains.annotations.TestOnly
import java.io.File
class ReadOnlySourcesManager(private val settings: IcsSettings, public val rootDir: File) {
private var _repositories: List<Repository>? = null
val repositories: List<Repository>
get() {
var r = _repositories
if (r == null) {
if (settings.readOnlySources.isEmpty()) {
r = emptyList()
}
else {
r = SmartList<Repository>()
for (source in settings.readOnlySources) {
try {
val path = source.path ?: continue
val dir = File(rootDir, path)
if (dir.exists()) {
r.add(FileRepositoryBuilder().setBare().setGitDir(dir).build())
}
else {
LOG.warn("Skip read-only source ${source.url} because dir doesn't exists")
}
}
catch (e: Exception) {
LOG.error(e)
}
}
}
_repositories = r
}
return r
}
fun setSources(sources: List<ReadonlySource>) {
settings.readOnlySources = sources
_repositories = null
}
@TestOnly fun sourceToDir(source: ReadonlySource) = File(rootDir, source.path!!)
} | apache-2.0 |
google/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter.tests/testSrc/com/intellij/ide/starter/tests/examples/data/GoLandCases.kt | 3 | 563 | package com.intellij.ide.starter.tests.examples.data
import com.intellij.ide.starter.data.TestCaseTemplate
import com.intellij.ide.starter.ide.IdeProductProvider
import com.intellij.ide.starter.project.ProjectInfo
import kotlin.io.path.div
object GoLandCases : TestCaseTemplate(IdeProductProvider.GO) {
val LightEditor = getTemplate()
val Kratos = getTemplate().copy(
projectInfo = ProjectInfo(
testProjectURL = "https://github.com/go-kratos/kratos/archive/refs/heads/main.zip",
testProjectImageRelPath = { it / "kratos-main" }
)
)
} | apache-2.0 |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/customize/transferSettings/TransferSettingsDataProvider.kt | 1 | 2258 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.customize.transferSettings
import com.intellij.ide.customize.transferSettings.models.BaseIdeVersion
import com.intellij.ide.customize.transferSettings.models.FailedIdeVersion
import com.intellij.ide.customize.transferSettings.models.IdeVersion
import com.intellij.ide.customize.transferSettings.providers.TransferSettingsProvider
import com.intellij.openapi.diagnostic.logger
import java.util.*
import java.util.stream.Collectors
class TransferSettingsDataProvider(private val providers: List<TransferSettingsProvider>) {
val baseIdeVersions = mutableListOf<BaseIdeVersion>()
val ideVersions = mutableListOf<IdeVersion>()
val failedIdeVersions = mutableListOf<FailedIdeVersion>()
val orderedIdeVersions get() = ideVersions + failedIdeVersions
constructor(vararg providers: TransferSettingsProvider) : this(providers.toList())
fun refresh(): TransferSettingsDataProvider {
val newBase = TransferSettingsDataProviderSession(providers, baseIdeVersions.map { it.id }).baseIdeVersions
baseIdeVersions.addAll(newBase)
ideVersions.addAll(newBase.filterIsInstance<IdeVersion>())
ideVersions.sortByDescending { it.lastUsed }
failedIdeVersions.addAll(newBase.filterIsInstance<FailedIdeVersion>())
return this
}
}
private class TransferSettingsDataProviderSession(private val providers: List<TransferSettingsProvider>,
private val skipIds: List<String>?) {
private val logger = logger<TransferSettingsDataProviderSession>()
val baseIdeVersions: List<BaseIdeVersion> by lazy { createBaseIdeVersions() }
private fun createBaseIdeVersions() = providers
.parallelStream()
.flatMap { provider ->
if (!provider.isAvailable()) {
logger.info("Provider ${provider.name} is not available")
return@flatMap null
}
try {
provider.getIdeVersions(skipIds ?: emptyList()).stream()
}
catch (t: Throwable) {
logger.warn("Failed to get base ide versions", t)
return@flatMap null
}
}
.filter(Objects::nonNull)
.collect(Collectors.toList())
} | apache-2.0 |
google/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ExtractedDirectoryPackagingElementEntityImpl.kt | 1 | 11040 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.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.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
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 ExtractedDirectoryPackagingElementEntityImpl(val dataSource: ExtractedDirectoryPackagingElementEntityData) : ExtractedDirectoryPackagingElementEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java,
PackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
override val filePath: VirtualFileUrl
get() = dataSource.filePath
override val pathInArchive: String
get() = dataSource.pathInArchive
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ExtractedDirectoryPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<ExtractedDirectoryPackagingElementEntity>(), ExtractedDirectoryPackagingElementEntity.Builder {
constructor() : this(ExtractedDirectoryPackagingElementEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ExtractedDirectoryPackagingElementEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isFilePathInitialized()) {
error("Field FileOrDirectoryPackagingElementEntity#filePath should be initialized")
}
if (!getEntityData().isPathInArchiveInitialized()) {
error("Field ExtractedDirectoryPackagingElementEntity#pathInArchive 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 ExtractedDirectoryPackagingElementEntity
this.entitySource = dataSource.entitySource
this.filePath = dataSource.filePath
this.pathInArchive = dataSource.pathInArchive
if (parents != null) {
this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// 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.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var filePath: VirtualFileUrl
get() = getEntityData().filePath
set(value) {
checkModificationAllowed()
getEntityData().filePath = value
changedProperty.add("filePath")
val _diff = diff
if (_diff != null) index(this, "filePath", value)
}
override var pathInArchive: String
get() = getEntityData().pathInArchive
set(value) {
checkModificationAllowed()
getEntityData().pathInArchive = value
changedProperty.add("pathInArchive")
}
override fun getEntityData(): ExtractedDirectoryPackagingElementEntityData = result
?: super.getEntityData() as ExtractedDirectoryPackagingElementEntityData
override fun getEntityClass(): Class<ExtractedDirectoryPackagingElementEntity> = ExtractedDirectoryPackagingElementEntity::class.java
}
}
class ExtractedDirectoryPackagingElementEntityData : WorkspaceEntityData<ExtractedDirectoryPackagingElementEntity>() {
lateinit var filePath: VirtualFileUrl
lateinit var pathInArchive: String
fun isFilePathInitialized(): Boolean = ::filePath.isInitialized
fun isPathInArchiveInitialized(): Boolean = ::pathInArchive.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ExtractedDirectoryPackagingElementEntity> {
val modifiable = ExtractedDirectoryPackagingElementEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ExtractedDirectoryPackagingElementEntity {
return getCached(snapshot) {
val entity = ExtractedDirectoryPackagingElementEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ExtractedDirectoryPackagingElementEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ExtractedDirectoryPackagingElementEntity(filePath, pathInArchive, entitySource) {
this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ExtractedDirectoryPackagingElementEntityData
if (this.entitySource != other.entitySource) return false
if (this.filePath != other.filePath) return false
if (this.pathInArchive != other.pathInArchive) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ExtractedDirectoryPackagingElementEntityData
if (this.filePath != other.filePath) return false
if (this.pathInArchive != other.pathInArchive) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + filePath.hashCode()
result = 31 * result + pathInArchive.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + filePath.hashCode()
result = 31 * result + pathInArchive.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.filePath?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 |
camunda/camunda-process-test-coverage | extension/engine-platform-7/src/main/kotlin/org/camunda/community/process_test_coverage/engine/platform7/ProcessCoverageInMemProcessEngineConfiguration.kt | 1 | 684 | package org.camunda.community.process_test_coverage.engine.platform7
import org.camunda.community.process_test_coverage.engine.platform7.ProcessCoverageConfigurator.initializeProcessCoverageExtensions
import org.camunda.bpm.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration
/**
* Standalone in memory process engine configuration additionally configuring
* flow node, sequence flow and compensation listeners for process coverage
* testing.
*
* @author z0rbas
*/
class ProcessCoverageInMemProcessEngineConfiguration : StandaloneInMemProcessEngineConfiguration() {
override fun init() {
initializeProcessCoverageExtensions(this)
super.init()
}
} | apache-2.0 |
JetBrains/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/enumValuesSoftDeprecate/toListCall.kt | 1 | 165 | // COMPILER_ARGUMENTS: -XXLanguage:+EnumEntries -opt-in=kotlin.ExperimentalStdlibApi
// WITH_STDLIB
enum class EnumClass
val a = EnumClass.values<caret>().toList()
| apache-2.0 |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringInspection.kt | 1 | 3210 | // 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.inspections.substring
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.evaluatesTo
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.toResolvedCall
import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
abstract class ReplaceSubstringInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
protected abstract fun isApplicableInner(element: KtDotQualifiedExpression): Boolean
protected open val isAlwaysStable: Boolean = false
final override fun isApplicable(element: KtDotQualifiedExpression): Boolean =
if ((isAlwaysStable || element.receiverExpression.isStableSimpleExpression()) && element.isMethodCall("kotlin.text.substring")) {
isApplicableInner(element)
} else
false
override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis()
protected fun isIndexOfCall(expression: KtExpression?, expectedReceiver: KtExpression): Boolean {
return expression is KtDotQualifiedExpression
&& expression.isMethodCall("kotlin.text.indexOf")
&& expression.receiverExpression.evaluatesTo(expectedReceiver)
&& expression.callExpression!!.valueArguments.size == 1
}
private fun KtDotQualifiedExpression.isMethodCall(fqMethodName: String): Boolean {
val resolvedCall = toResolvedCall(BodyResolveMode.PARTIAL) ?: return false
return resolvedCall.resultingDescriptor.fqNameUnsafe.asString() == fqMethodName
}
protected fun KtDotQualifiedExpression.isFirstArgumentZero(): Boolean {
val bindingContext = analyze()
val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return false
val expression = resolvedCall.call.valueArguments[0].getArgumentExpression() as? KtConstantExpression ?: return false
val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) ?: return false
val constantType = bindingContext.getType(expression) ?: return false
return constant.getValue(constantType) == 0
}
protected fun KtDotQualifiedExpression.replaceWith(pattern: String, argument: KtExpression) {
val psiFactory = KtPsiFactory(project)
replace(psiFactory.createExpressionByPattern(pattern, receiverExpression, argument))
}
} | apache-2.0 |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/adapter/InputAdapter.kt | 1 | 2441 | /*
* Generates ResponseAdapters for variables/input
*/
package com.apollographql.apollo3.compiler.codegen.kotlin.adapter
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext
import com.apollographql.apollo3.compiler.codegen.Identifier
import com.apollographql.apollo3.compiler.codegen.Identifier.customScalarAdapters
import com.apollographql.apollo3.compiler.codegen.Identifier.fromJson
import com.apollographql.apollo3.compiler.codegen.Identifier.toJson
import com.apollographql.apollo3.compiler.codegen.Identifier.value
import com.apollographql.apollo3.compiler.codegen.Identifier.writer
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinSymbols
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.NamedType
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.writeToResponseCodeBlock
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
internal fun List<NamedType>.inputAdapterTypeSpec(
context: KotlinContext,
adapterName: String,
adaptedTypeName: TypeName,
): TypeSpec {
return TypeSpec.objectBuilder(adapterName)
.addSuperinterface(KotlinSymbols.Adapter.parameterizedBy(adaptedTypeName))
.addFunction(notImplementedFromResponseFunSpec(adaptedTypeName))
.addFunction(writeToResponseFunSpec(context, adaptedTypeName))
.build()
}
private fun notImplementedFromResponseFunSpec(adaptedTypeName: TypeName) = FunSpec.builder(fromJson)
.addModifiers(KModifier.OVERRIDE)
.addParameter(Identifier.reader, KotlinSymbols.JsonReader)
.addParameter(customScalarAdapters, KotlinSymbols.CustomScalarAdapters)
.returns(adaptedTypeName)
.addCode("throw %T(%S)", ClassName("kotlin", "IllegalStateException"), "Input type used in output position")
.build()
private fun List<NamedType>.writeToResponseFunSpec(
context: KotlinContext,
adaptedTypeName: TypeName,
): FunSpec {
return FunSpec.builder(toJson)
.addModifiers(KModifier.OVERRIDE)
.addParameter(writer, KotlinSymbols.JsonWriter)
.addParameter(customScalarAdapters, KotlinSymbols.CustomScalarAdapters)
.addParameter(value, adaptedTypeName)
.addCode(writeToResponseCodeBlock(context))
.build()
}
| mit |
square/okio | okio/src/nativeMain/kotlin/okio/PosixFileSystem.kt | 1 | 3559 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.get
import okio.Path.Companion.toPath
import okio.internal.toPath
import platform.posix.EEXIST
import platform.posix.closedir
import platform.posix.dirent
import platform.posix.errno
import platform.posix.opendir
import platform.posix.readdir
import platform.posix.set_posix_errno
internal object PosixFileSystem : FileSystem() {
private val SELF_DIRECTORY_ENTRY = ".".toPath()
private val PARENT_DIRECTORY_ENTRY = "..".toPath()
override fun canonicalize(path: Path) = variantCanonicalize(path)
override fun metadataOrNull(path: Path) = variantMetadataOrNull(path)
override fun list(dir: Path): List<Path> = list(dir, throwOnFailure = true)!!
override fun listOrNull(dir: Path): List<Path>? = list(dir, throwOnFailure = false)
private fun list(dir: Path, throwOnFailure: Boolean): List<Path>? {
val opendir = opendir(dir.toString())
?: if (throwOnFailure) throw errnoToIOException(errno) else return null
try {
val result = mutableListOf<Path>()
val buffer = Buffer()
set_posix_errno(0) // If readdir() returns null it's either the end or an error.
while (true) {
val dirent: CPointer<dirent> = readdir(opendir) ?: break
val childPath = buffer.writeNullTerminated(
bytes = dirent[0].d_name
).toPath(normalize = true)
if (childPath == SELF_DIRECTORY_ENTRY || childPath == PARENT_DIRECTORY_ENTRY) {
continue // exclude '.' and '..' from the results.
}
result += dir / childPath
}
if (errno != 0) {
if (throwOnFailure) throw errnoToIOException(errno)
else return null
}
result.sort()
return result
} finally {
closedir(opendir) // Ignore errno from closedir.
}
}
override fun openReadOnly(file: Path) = variantOpenReadOnly(file)
override fun openReadWrite(file: Path, mustCreate: Boolean, mustExist: Boolean): FileHandle {
return variantOpenReadWrite(file, mustCreate = mustCreate, mustExist = mustExist)
}
override fun source(file: Path) = variantSource(file)
override fun sink(file: Path, mustCreate: Boolean) = variantSink(file, mustCreate)
override fun appendingSink(file: Path, mustExist: Boolean) = variantAppendingSink(file, mustExist)
override fun createDirectory(dir: Path, mustCreate: Boolean) {
val result = variantMkdir(dir)
if (result != 0) {
if (errno == EEXIST) {
if (mustCreate) errnoToIOException(errno)
else return
}
throw errnoToIOException(errno)
}
}
override fun atomicMove(
source: Path,
target: Path
) {
variantMove(source, target)
}
override fun delete(path: Path, mustExist: Boolean) {
variantDelete(path, mustExist)
}
override fun createSymlink(source: Path, target: Path) = variantCreateSymlink(source, target)
override fun toString() = "PosixSystemFileSystem"
}
| apache-2.0 |
RanolP/Kubo | Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/client/objects/TelegramClientUser.kt | 1 | 1686 | package io.github.ranolp.kubo.telegram.client.objects
import com.github.badoualy.telegram.tl.api.TLUser
import io.github.ranolp.kubo.general.side.Side
import io.github.ranolp.kubo.telegram.Telegram
import io.github.ranolp.kubo.telegram.general.objects.TelegramUser
class TelegramClientUser(val user: TLUser) : TelegramUser {
override val side: Side = Telegram.CLIENT_SIDE
override val firstName: String
get() = user.firstName
override val lastName: String?
get() = user.lastName
override val username: String?
get() = user.username
override val isSelf: Boolean
get() = user.self
override val languageCode: String
get() = user.langCode
override val isBot: Boolean
get() = user.bot
override val id: Int
get() = user.id
val contact: Boolean
get() = user.contact
val mutualContact: Boolean
get() = user.mutualContact
val deleted: Boolean
get() = user.deleted
val botChatHistory: Boolean
get() = user.botChatHistory
val botNochats: Boolean
get() = user.botNochats
val verified: Boolean
get() = user.verified
val restricted: Boolean
get() = user.restricted
val min: Boolean
get() = user.min
val botInlineGeo: Boolean
get() = user.botInlineGeo
val accessHash: Long
get() = user.accessHash
val phone: String
get() = user.phone
// photo
// status
val botInfoVersion: Int
get() = user.botInfoVersion
val restrictionReason: String
get() = user.restrictionReason
val botInlinePlaceholder: String
get() = user.botInlinePlaceholder
} | mit |
allotria/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/ErrorReportConfigurable.kt | 1 | 2195 | // 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.diagnostic
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.SERVICE_NAME_PREFIX
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.components.*
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.XCollection
@State(name = "ErrorReportConfigurable", storages = [Storage(StoragePathMacros.CACHE_FILE)])
internal class ErrorReportConfigurable : PersistentStateComponent<DeveloperList>, SimpleModificationTracker() {
companion object {
@JvmStatic
val SERVICE_NAME = "$SERVICE_NAME_PREFIX — JetBrains Account"
@JvmStatic
fun getInstance() = service<ErrorReportConfigurable>()
@JvmStatic
fun getCredentials() = PasswordSafe.instance.get(CredentialAttributes(SERVICE_NAME))
}
var developerList = DeveloperList()
set(value) {
field = value
incModificationCount()
}
override fun getState() = developerList
override fun loadState(value: DeveloperList) {
developerList = value
}
}
// 24 hours
private const val UPDATE_INTERVAL = 24L * 60 * 60 * 1000
internal class DeveloperList {
constructor() {
developers = mutableListOf()
timestamp = 0
}
constructor(list: MutableList<Developer>) {
developers = list
timestamp = System.currentTimeMillis()
}
@field:XCollection(style = XCollection.Style.v2)
val developers: List<Developer>
@field:Attribute
var timestamp: Long
private set
fun isUpToDateAt() = timestamp != 0L && (System.currentTimeMillis() - timestamp) < UPDATE_INTERVAL
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DeveloperList
return developers == other.developers || timestamp == other.timestamp
}
override fun hashCode(): Int {
var result = developers.hashCode()
result = 31 * result + timestamp.hashCode()
return result
}
} | apache-2.0 |
maiktheknife/KittyCat | app/src/main/kotlin/net/kivitro/kittycat/presenter/DetailPresenter.kt | 1 | 2873 | package net.kivitro.kittycat.presenter
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.util.Pair
import android.view.View
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import net.kivitro.kittycat.BuildConfig
import net.kivitro.kittycat.R
import net.kivitro.kittycat.model.Cat
import net.kivitro.kittycat.network.TheCatAPI
import net.kivitro.kittycat.view.DetailView
import net.kivitro.kittycat.view.activity.FullScreenImageActivity
import timber.log.Timber
import java.util.concurrent.TimeUnit
/**
* Created by Max on 10.03.2016.
*/
class DetailPresenter : Presenter<DetailView>() {
private var voteDisposable: Disposable? = null
private var favDisposable: Disposable? = null
private var defavDisposable: Disposable? = null
override fun detachView() {
super.detachView()
voteDisposable?.dispose()
favDisposable?.dispose()
defavDisposable?.dispose()
}
fun onVoted(cat: Cat, rating: Int) {
Timber.d("onVoted %s", cat)
voteDisposable = TheCatAPI.API
.vote(cat.id!!, rating)
.timeout(BuildConfig.REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ _ ->
view?.onVoting(rating)
},
{ t ->
Timber.d(t, "onVoted")
view?.onVotingError(t.message ?: "Unknown Error")
}
)
}
fun onFavourited(cat: Cat) {
Timber.d("onFavourited %s", cat)
favDisposable = TheCatAPI.API
.favourite(cat.id!!, TheCatAPI.ACTION_ADD)
.timeout(BuildConfig.REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ _ ->
view?.onFavourited()
},
{ t ->
Timber.d(t, "onFavourited")
view?.onFavouritedError(t.message ?: "Unknown Error")
})
}
fun onDefavourited(cat: Cat) {
Timber.d("onDefavourited %s", cat)
defavDisposable = TheCatAPI.API
.favourite(cat.id!!, TheCatAPI.ACTION_REMOVE)
.timeout(BuildConfig.REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ _ ->
view?.onDefavourited()
},
{ t ->
Timber.d(t, "onDefavourited")
view?.onFavouritedError(t.message ?: "Unknown Error")
})
}
fun onImageClicked(cat: Cat, mutedColor: Int, vibrateColor: Int, vibrateColorDark: Int, v: View) {
Timber.d("onImageClicked %s", cat)
view?.let {
val ac = it.activity
val aoc = ActivityOptionsCompat.makeSceneTransitionAnimation(ac,
Pair(v, ac.getString(R.string.transition_cat_image))
)
ac.startActivity(FullScreenImageActivity.getStarterIntent(ac, cat, mutedColor, vibrateColor, vibrateColorDark), aoc.toBundle())
}
}
} | mit |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHSubmittableTextFieldModel.kt | 2 | 1169 | // 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.pullrequest.comment.ui
import com.intellij.openapi.application.runWriteAction
import com.intellij.util.ui.codereview.timeline.comment.SubmittableTextFieldModelBase
import org.jetbrains.plugins.github.util.completionOnEdt
import org.jetbrains.plugins.github.util.errorOnEdt
import org.jetbrains.plugins.github.util.successOnEdt
import java.util.concurrent.CompletableFuture
open class GHSubmittableTextFieldModel(
initialText: String,
private val submitter: (String) -> CompletableFuture<*>
) : SubmittableTextFieldModelBase(initialText) {
constructor(submitter: (String) -> CompletableFuture<*>) : this("", submitter)
override fun submit() {
if (isBusy) return
isBusy = true
document.setReadOnly(true)
submitter(document.text).successOnEdt {
document.setReadOnly(false)
runWriteAction {
document.setText("")
}
}.errorOnEdt {
document.setReadOnly(false)
error = it
}.completionOnEdt {
isBusy = false
}
}
} | apache-2.0 |
fluidsonic/fluid-json | basic/tests-jvm/JsonWriterTest.kt | 1 | 1469 | package tests.basic
import io.fluidsonic.json.*
import java.io.*
import kotlin.test.*
class JsonWriterTest {
@Test
fun testWithErrorChecking() {
val writer = JsonWriter.build(StringWriter())
expect(writer.isErrored).toBe(false)
expect(writer.withErrorChecking { "test" }).toBe("test")
expect(writer.isErrored).toBe(false)
try {
if (0.toBigDecimal() == 0.toBigDecimal()) writer.withErrorChecking { throw RuntimeException() }
throw AssertionError(".withErrorChecking() should not consume exception")
}
catch (e: Throwable) {
expect(writer.isErrored).toBe(true)
}
try {
writer.withErrorChecking { }
throw AssertionError(".withErrorChecking() throw when errored")
}
catch (e: JsonException) {
expect(writer.isErrored).toBe(true)
}
}
@Test
fun testDefaultWriteDelegations() {
var doubleValue: Double? = null
var longValue: Long? = null
var stringValue: String? = null
val writer = object : DummyJsonWriter() {
override fun writeDouble(value: Double) {
doubleValue = value
}
override fun writeLong(value: Long) {
longValue = value
}
override fun writeString(value: String) {
stringValue = value
}
}
writer.writeByte(1)
expect(longValue).toBe(1L)
writer.writeFloat(2.0f)
expect(doubleValue).toBe(2.0)
writer.writeInt(3)
expect(longValue).toBe(3)
writer.writeMapKey("4")
expect(stringValue).toBe("4")
writer.writeShort(5)
expect(longValue).toBe(5)
}
}
| apache-2.0 |
allotria/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/column/VcsLogColumnProperties.kt | 2 | 1294 | // 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.vcs.log.ui.table.column
import com.intellij.vcs.log.impl.VcsLogUiProperties.VcsLogUiProperty
import com.intellij.vcs.log.ui.table.VcsLogColumnDeprecated
data class VcsLogColumnProperties(
val visibility: TableColumnVisibilityProperty,
val width: TableColumnWidthProperty
) {
companion object {
fun create(column: VcsLogColumn<*>) = VcsLogColumnProperties(
TableColumnVisibilityProperty(column),
TableColumnWidthProperty(column)
)
}
}
class TableColumnVisibilityProperty(val column: VcsLogColumn<*>) : VcsLogUiProperty<Boolean>("Table.${column.id}.ColumnIdVisibility")
class TableColumnWidthProperty(val column: VcsLogColumn<*>) : VcsLogUiProperty<Int>("Table.${column.id}.ColumnIdWidth") {
@Deprecated("Should be removed after some releases. Used only for moving old columns width")
fun moveOldSettings(oldMapping: Map<Int, Int>, newMapping: MutableMap<String, Int>) {
val oldValue = oldMapping.map { (column, width) -> VcsLogColumnDeprecated.getVcsLogColumnEx(column) to width }.toMap()[column]
if (name !in newMapping && oldValue != null) {
newMapping[name] = oldValue
}
}
} | apache-2.0 |
google/Kotlin-FirViewer | src/main/kotlin/io/github/tgeng/firviewer/uiUtils.kt | 1 | 11361 | // Copyright 2021 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 io.github.tgeng.firviewer
import com.google.common.base.CaseFormat
import com.google.common.primitives.Primitives
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.ui.components.JBLabel
import com.intellij.ui.scale.JBUIScale
import org.jetbrains.kotlin.KtPsiSourceElement
import org.jetbrains.kotlin.fir.FirPureAbstractElement
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.render
import org.jetbrains.kotlin.fir.resolve.dfa.cfg.CFGNode
import org.jetbrains.kotlin.util.AttributeArrayOwner
import org.jetbrains.kotlin.analysis.api.tokens.HackToForceAllowRunningAnalyzeOnEDT
import org.jetbrains.kotlin.analysis.api.tokens.hackyAllowRunningOnEdt
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import java.awt.Color
import java.awt.FlowLayout
import java.awt.Font
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
import kotlin.reflect.KCallable
import kotlin.reflect.KFunction
import kotlin.reflect.KProperty
import kotlin.reflect.KVisibility
import kotlin.reflect.full.createType
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.javaGetter
import kotlin.reflect.jvm.javaMethod
fun label(
s: String,
bold: Boolean = false,
italic: Boolean = false,
multiline: Boolean = false,
icon: Icon? = null,
tooltipText: String? = null
) = JBLabel(
if (multiline) ("<html>" + s.replace("\n", "<br/>").replace(" ", " ") + "</html>") else s
).apply {
this.icon = icon
this.toolTipText = toolTipText
font = font.deriveFont((if (bold) Font.BOLD else Font.PLAIN) + if (italic) Font.ITALIC else Font.PLAIN)
}
fun render(e: FirElement) = JBLabel(e.render())
fun type(e: TreeNode<*>): JComponent {
val nameAndType = label(
if (e.name == "" || e.name.startsWith('<')) {
""
} else {
e.name + ": "
} + e.t::class.simpleName,
bold = true
)
val address = label("@" + Integer.toHexString(System.identityHashCode(e.t)))
val nameTypeAndAddress = nameAndType + address
return if (e.t is FirDeclaration) {
nameTypeAndAddress + label(e.t.resolvePhase.toString(), italic = true)
} else {
nameTypeAndAddress
}
}
private val twoPoint = JBUIScale.scale(2)
operator fun JComponent.plus(that: JComponent?): JPanel {
return if (this is JPanel) {
add(that)
this
} else {
JPanel(FlowLayout(FlowLayout.LEFT).apply {
vgap = twoPoint
}).apply {
add(this@plus)
if (that != null) add(that)
isOpaque = false
}
}
}
fun highlightInEditor(obj: Any, project: Project) {
val editorManager = FileEditorManager.getInstance(project) ?: return
val editor: Editor = editorManager.selectedTextEditor ?: return
editor.markupModel.removeAllHighlighters()
val (vf, startOffset, endOffset) = when (obj) {
is FirPureAbstractElement -> obj.source?.let {
val source = it as? KtPsiSourceElement ?: return@let null
FileLocation(source.psi.containingFile.virtualFile, it.startOffset, it.endOffset)
}
is PsiElement -> obj.textRange?.let {
FileLocation(
obj.containingFile.virtualFile,
it.startOffset,
it.endOffset
)
}
is CFGNode<*> -> obj.fir.source?.let {
val source = it as? KtPsiSourceElement ?: return@let null
FileLocation(source.psi.containingFile.virtualFile, it.startOffset, it.endOffset)
}
else -> null
} ?: return
if (vf != FileEditorManager.getInstance(project).selectedFiles.firstOrNull()) return
val textAttributes =
TextAttributes(null, null, Color.GRAY, EffectType.BOXED, Font.PLAIN)
editor.markupModel.addRangeHighlighter(
startOffset,
endOffset,
HighlighterLayer.CARET_ROW,
textAttributes,
HighlighterTargetArea.EXACT_RANGE
)
}
private data class FileLocation(val vf: VirtualFile, val startIndex: Int, val endIndex: Int)
val unitType = Unit::class.createType()
val skipMethodNames = setOf(
"copy",
"toString",
"delete",
"clone",
"getUserDataString",
"hashCode",
"getClass",
"component1",
"component2",
"component3",
"component4",
"component5"
)
val psiElementMethods = PsiElement::class.java.methods.map { it.name }.toSet() - setOf(
"getTextRange",
"getTextRangeInParent",
"getTextLength",
"getText",
"getResolveScope",
"getUseScope",
"getReferences",
)
@OptIn(HackToForceAllowRunningAnalyzeOnEDT::class)
fun Any.traverseObjectProperty(
propFilter: (KCallable<*>) -> Boolean = { true }, methodFilter: (Method) -> Boolean = { true },
fn: (name: String, value: Any?, () -> Any?) -> Unit
) {
try {
this::class.members
.filter { propFilter(it) && it.parameters.size == 1 && it.visibility == KVisibility.PUBLIC && it.returnType != unitType && it.name !in skipMethodNames && (this !is PsiElement || it.name !in psiElementMethods) }
.sortedWith { m1, m2 ->
fun KCallable<*>.declaringClass() = when (this) {
is KFunction<*> -> javaMethod?.declaringClass
is KProperty<*> -> javaGetter?.declaringClass
else -> null
}
val m1Class = m1.declaringClass()
val m2Class = m2.declaringClass()
when {
m1Class == m2Class -> 0
m1Class == null -> 1
m2Class == null -> -1
m1Class.isAssignableFrom(m2Class) -> -1
else -> 1
}
}
.forEach { prop ->
val value = try {
prop.isAccessible = true
hackyAllowRunningOnEdt {
prop.call(this)
}
} catch (e: Throwable) {
return@forEach
}
fn(prop.name, value) {
hackyAllowRunningOnEdt {
prop.call(this)
}
}
}
} catch (e: Throwable) {
// fallback to traverse with Java reflection
this::class.java.methods
.filter { methodFilter(it) && it.name !in skipMethodNames && it.parameterCount == 0 && it.modifiers and Modifier.PUBLIC != 0 && it.returnType.simpleName != "void" && (this !is PsiElement || it.name !in psiElementMethods) }
// methods in super class is at the beginning
.sortedWith { m1, m2 ->
when {
m1.declaringClass == m2.declaringClass -> 0
m1.declaringClass.isAssignableFrom(m2.declaringClass) -> -1
else -> 1
}
}
.distinctBy { it.name }
.forEach { method ->
val value = try {
hackyAllowRunningOnEdt {
method.invoke(this)
}
} catch (e: Throwable) {
return@forEach
}
fn(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, method.name.removePrefix("get")), value) {
hackyAllowRunningOnEdt {
method.invoke(this)
}
}
}
}
}
fun Any.getTypeAndId(): String {
return when {
isData() -> this::class.simpleName
?: this::class.toString()
else -> this::class.simpleName + " @" + Integer.toHexString(System.identityHashCode(this))
}
}
fun Any.getForMapKey(): String {
return when {
isData() -> toString()
else -> this::class.simpleName + " @" + Integer.toHexString(System.identityHashCode(this)) + " | " + toString()
}
}
fun Any.isData(): Boolean = try {
this is Iterable<*> || this is Map<*, *> || this is AttributeArrayOwner<*, *> ||
this is Enum<*> || this::class.java.isPrimitive || Primitives.isWrapperType(this::class.java) ||
this::class.java == String::class.java || this::class.java == Name::class.java ||
this::class.isData || this::class.objectInstance != null
} catch (e: Throwable) {
false
}
//private class CfgGraphViewer(state: TreeUiState, index: Int, graph: ControlFlowGraph) :
// ObjectViewer(state, index) {
//
// private val nodeNameMap = mutableMapOf<CFGNode<*>, String>()
// private val nodeClassCounter = mutableMapOf<String, AtomicInteger>()
// val CFGNode<*>.name:String get() = nodeNameMap.computeIfAbsent(this) { node ->
// val nodeClassName = (node::class.simpleName?:node::class.toString()).removeSuffix("Node")
// nodeClassName + nodeClassCounter.computeIfAbsent(nodeClassName) { AtomicInteger() }.getAndIncrement()
// }
//
// private val graph = SingleGraph("foo").apply {
// graph.nodes.forEach { node ->
// addNode(node.name)
// }
// val edgeCounter = AtomicInteger()
// val edgeNameMap = mutableMapOf<String, EdgeData>()
// graph.nodes.forEach { node ->
// node.followingNodes.forEach { to ->
// val edgeId = edgeCounter.getAndIncrement().toString()
// addEdge(edgeId, node.name, to.name)
// }
// }
// }
//
// data class EdgeData(val from:CFGNode<*>, val to: CFGNode<*>, val edge: Edge?)
//
// val viewer = SwingViewer(this.graph, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD).apply {
// enableAutoLayout()
// }
// override val view: JComponent = viewer.addDefaultView(false) as JComponent
//
// override fun selectAndGetObject(name: String): Any? {
// return null
// }
//}
| apache-2.0 |
dagi12/eryk-android-common | src/main/java/pl/edu/amu/wmi/erykandroidcommon/recycler/EmptyGridDialogFragment.kt | 1 | 769 | package pl.edu.amu.wmi.erykandroidcommon.recycler
import android.app.AlertDialog
import android.app.Dialog
import android.app.DialogFragment
import android.os.Bundle
import pl.edu.amu.wmi.erykandroidcommon.R
class EmptyGridDialogFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
builder
.setTitle(getString(R.string.no_data))
.setNegativeButton(android.R.string.ok) { dialogInterface, _ ->
activity.finish()
dialogInterface.dismiss()
}
return builder.create()
}
companion object {
val instance: EmptyGridDialogFragment get() = EmptyGridDialogFragment()
}
}
| apache-2.0 |
EGF2/android-client | egf2-generator/src/main/kotlin/com/eigengraph/egf2/generator/mappers/IntegerMapper.kt | 1 | 1232 | package com.eigengraph.egf2.generator.mappers
import com.eigengraph.egf2.generator.Field
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.MethodSpec
import java.util.*
import javax.lang.model.element.Modifier
class IntegerMapper(targetPackage: String) : Mapper(targetPackage) {
override fun getField(field: Field, custom_schemas: LinkedHashMap<String, LinkedList<Field>>): FieldSpec {
val fs: FieldSpec.Builder
fs = FieldSpec.builder(Int::class.java, field.name, Modifier.PUBLIC)
return fs.build()
}
override fun deserialize(field: Field, supername: String, deserialize: MethodSpec.Builder, custom_schemas: LinkedHashMap<String, LinkedList<Field>>) {
if (field.required) {
deserialize.addStatement("final int \$L = jsonObject.get(\"\$L\").getAsInt()", field.name, field.name)
deserialize.addStatement("\$L.\$L = \$L", supername, field.name, field.name)
} else {
deserialize.beginControlFlow("if(jsonObject.has(\"\$L\"))", field.name)
deserialize.addStatement("final int \$L = jsonObject.get(\"\$L\").getAsInt()", field.name, field.name)
deserialize.addStatement("\$L.\$L = \$L", supername, field.name, field.name)
deserialize.endControlFlow()
}
deserialize.addCode("\n")
}
} | mit |
leafclick/intellij-community | platform/workspaceModel-core/src/cppModel.kt | 1 | 2094 | package com.intellij.workspace.api
import java.io.File
/**
* The approximation of the existing C++ model:
*
* @see com.jetbrains.cidr.lang.workspace.OCWorkspace
* @see com.jetbrains.cidr.lang.workspace.OCResolveConfiguration
* @see com.jetbrains.cidr.lang.workspace.OCCompilerSettings
*/
interface CppConfiguration {
val name: String
// source roots in C++ world are mostly files, not folders
val sourceRoots: List<CppSourceRoot>
val defaultCompilerSettings: CppCompilerSettings
val languageCompilerSettings: Map<CppLanguage, CppCompilerSettings>
}
enum class CppLanguage { C, CPP, OC, OCPP }
interface CppSourceRoot {
val file: FilePointer
val generated: Boolean
val language: CppLanguage? /* normally the language is determined by file extension, but it can be customized */
val compilerSettings: CppCompilerSettings
val output: String?
}
enum class CppCompilerKind { CLANG, GCC, MSVC }
interface CppCompilerSettings {
val compilerKind: CppCompilerKind?
val compilerExecutable: File?
val compilerWorkingDir: File?
val compilerArguments: List<String>?
/** @see com.jetbrains.cidr.lang.workspace.OCCompilerSettings.getHeadersSearchPaths */
val headerSearchPaths: List<CppHeaderSearchPath>?
/** @see com.jetbrains.cidr.lang.workspace.OCCompilerSettings.getImplicitIncludes*/
val implicitIncludes: List<FilePointer>?
/** @see com.jetbrains.cidr.lang.workspace.OCCompilerSettings.getMappedInclude */
val mappedIncludes: Map<String, FilePointer>?
val preprocessorDefines: String? // or List<String> for better interning
/** @see com.jetbrains.cidr.lang.workspace.OCCompilerSettings.getCompilerFeatures*/
val compilerFeatures: Map<CppCompilerFeature, Any>
/** @see com.jetbrains.cidr.lang.workspace.OCCompilerSettings.getCachingKey */
val cachingKey: String
}
interface CppHeaderSearchPath {
val path: FilePointer
val type: Type
val recursive: Boolean
enum class Type {
HEADERS, FRAMEWORKS
}
}
interface CppCompilerFeature {
/** @see com.jetbrains.cidr.lang.workspace.compiler.OCCompilerFeatures */
} | apache-2.0 |
zdary/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigSpaceInHeaderInspection.kt | 4 | 1520 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.editorconfig.language.codeinsight.quickfixes.EditorConfigRemoveSpacesQuickFix
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigHeader
import org.editorconfig.language.psi.EditorConfigPatternEnumeration
import org.editorconfig.language.psi.EditorConfigVisitor
class EditorConfigSpaceInHeaderInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() {
override fun visitHeader(header: EditorConfigHeader) {
if (PsiTreeUtil.hasErrorElements(header)) return
val spaces = findSuspiciousSpaces(header)
if (spaces.isEmpty()) return
val message = EditorConfigBundle["inspection.space.in.header.message"]
holder.registerProblem(
header,
message,
EditorConfigRemoveSpacesQuickFix(spaces)
)
}
}
companion object {
fun findSuspiciousSpaces(header: EditorConfigHeader) =
PsiTreeUtil.findChildrenOfType(header, PsiWhiteSpace::class.java)
.filter { it.parent !is EditorConfigPatternEnumeration }
}
}
| apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/bridges/kt2702.kt | 5 | 221 | open class A<R> {
open fun foo(r: R): R {return r}
}
open class B : A<String>() {
}
open class C : B() {
override fun foo(r: String): String {
return super.foo(r) + "K"
}
}
fun box() = C().foo("O")
| apache-2.0 |
Pozo/threejs-kotlin | examples/src/main/kotlin/examples/App.kt | 1 | 199 | package examples
import examples.geometry.colors.Colors
import examples.geometry.colors.ColorsDsl
fun main(args: Array<String>) {
val helloWorld = ColorsDsl()
helloWorld.render()
}
| mit |
redundent/kotlin-xml-builder | kotlin-xml-dsl-generator/src/test/resources/code/attributes.kt | 1 | 5157 | @file:Suppress("PropertyName", "ReplaceArrayOfWithLiteral", "LocalVariableName", "FunctionName", "RemoveRedundantBackticks")
package org.redundent.generated
import org.redundent.kotlin.xml.*
open class `Attributes`(nodeName: String) : Node(nodeName) {
var `uri`: kotlin.String? by attributes
var `base64Binary`: kotlin.ByteArray? by attributes
var `boolean`: kotlin.Boolean? by attributes
var `byte`: kotlin.Byte? by attributes
var `date`: java.util.Date? by attributes
var `dateTime`: java.util.Date? by attributes
var `decimal`: java.math.BigDecimal? by attributes
var `double`: kotlin.Double? by attributes
var `duration`: javax.xml.datatype.Duration? by attributes
var `float`: kotlin.Float? by attributes
var `gDay`: java.util.Date? by attributes
var `gMonth`: java.util.Date? by attributes
var `gMonthDay`: java.util.Date? by attributes
var `gYear`: java.util.Date? by attributes
var `gYearMonth`: java.util.Date? by attributes
var `hexBinary`: kotlin.ByteArray? by attributes
var `int`: kotlin.Int? by attributes
var `integer`: kotlin.Int? by attributes
var `long`: kotlin.Long? by attributes
var `negativeInteger`: kotlin.Int? by attributes
var `nonNegativeInteger`: kotlin.Int? by attributes
var `nonPositiveInteger`: kotlin.Int? by attributes
var `positiveInteger`: kotlin.Int? by attributes
var `string`: kotlin.String? by attributes
var `short`: kotlin.Short? by attributes
var `time`: java.util.Date? by attributes
var `token`: kotlin.String? by attributes
var `unsignedByte`: kotlin.Short? by attributes
var `unsignedInt`: kotlin.Long? by attributes
var `unsignedLong`: kotlin.Int? by attributes
var `unsignedShort`: kotlin.Int? by attributes
}
@JvmOverloads
fun `attributes`(`uri`: kotlin.String? = null,
`base64Binary`: kotlin.ByteArray? = null,
`boolean`: kotlin.Boolean? = null,
`byte`: kotlin.Byte? = null,
`date`: java.util.Date? = null,
`dateTime`: java.util.Date? = null,
`decimal`: java.math.BigDecimal? = null,
`double`: kotlin.Double? = null,
`duration`: javax.xml.datatype.Duration? = null,
`float`: kotlin.Float? = null,
`gDay`: java.util.Date? = null,
`gMonth`: java.util.Date? = null,
`gMonthDay`: java.util.Date? = null,
`gYear`: java.util.Date? = null,
`gYearMonth`: java.util.Date? = null,
`hexBinary`: kotlin.ByteArray? = null,
`int`: kotlin.Int? = null,
`integer`: kotlin.Int? = null,
`long`: kotlin.Long? = null,
`negativeInteger`: kotlin.Int? = null,
`nonNegativeInteger`: kotlin.Int? = null,
`nonPositiveInteger`: kotlin.Int? = null,
`positiveInteger`: kotlin.Int? = null,
`string`: kotlin.String? = null,
`short`: kotlin.Short? = null,
`time`: java.util.Date? = null,
`token`: kotlin.String? = null,
`unsignedByte`: kotlin.Short? = null,
`unsignedInt`: kotlin.Long? = null,
`unsignedLong`: kotlin.Int? = null,
`unsignedShort`: kotlin.Int? = null,
__block__: `Attributes`.() -> Unit): `Attributes` {
val `attributes` = `Attributes`("attributes")
`attributes`.apply {
if (`uri` != null) {
this.`uri` = `uri`
}
if (`base64Binary` != null) {
this.`base64Binary` = `base64Binary`
}
if (`boolean` != null) {
this.`boolean` = `boolean`
}
if (`byte` != null) {
this.`byte` = `byte`
}
if (`date` != null) {
this.`date` = `date`
}
if (`dateTime` != null) {
this.`dateTime` = `dateTime`
}
if (`decimal` != null) {
this.`decimal` = `decimal`
}
if (`double` != null) {
this.`double` = `double`
}
if (`duration` != null) {
this.`duration` = `duration`
}
if (`float` != null) {
this.`float` = `float`
}
if (`gDay` != null) {
this.`gDay` = `gDay`
}
if (`gMonth` != null) {
this.`gMonth` = `gMonth`
}
if (`gMonthDay` != null) {
this.`gMonthDay` = `gMonthDay`
}
if (`gYear` != null) {
this.`gYear` = `gYear`
}
if (`gYearMonth` != null) {
this.`gYearMonth` = `gYearMonth`
}
if (`hexBinary` != null) {
this.`hexBinary` = `hexBinary`
}
if (`int` != null) {
this.`int` = `int`
}
if (`integer` != null) {
this.`integer` = `integer`
}
if (`long` != null) {
this.`long` = `long`
}
if (`negativeInteger` != null) {
this.`negativeInteger` = `negativeInteger`
}
if (`nonNegativeInteger` != null) {
this.`nonNegativeInteger` = `nonNegativeInteger`
}
if (`nonPositiveInteger` != null) {
this.`nonPositiveInteger` = `nonPositiveInteger`
}
if (`positiveInteger` != null) {
this.`positiveInteger` = `positiveInteger`
}
if (`string` != null) {
this.`string` = `string`
}
if (`short` != null) {
this.`short` = `short`
}
if (`time` != null) {
this.`time` = `time`
}
if (`token` != null) {
this.`token` = `token`
}
if (`unsignedByte` != null) {
this.`unsignedByte` = `unsignedByte`
}
if (`unsignedInt` != null) {
this.`unsignedInt` = `unsignedInt`
}
if (`unsignedLong` != null) {
this.`unsignedLong` = `unsignedLong`
}
if (`unsignedShort` != null) {
this.`unsignedShort` = `unsignedShort`
}
}
`attributes`.apply(__block__)
return `attributes`
} | apache-2.0 |
redundent/kotlin-xml-builder | kotlin-xml-builder/src/test/kotlin/org/redundent/kotlin/xml/CommentTest.kt | 1 | 918 | package org.redundent.kotlin.xml
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
class CommentTest {
@Test
fun testHashCode() {
val comment = Comment("test")
assertEquals(comment.text.hashCode(), comment.hashCode())
}
@Test
fun `equals null`() {
val comment = Comment("test")
assertFalse(comment.equals(null))
}
@Test
fun `equals different type`() {
val comment = Comment("test")
val other = CDATAElement("test")
assertFalse(comment.equals(other))
}
@Test
fun `equals different text`() {
val comment1 = Comment("comment1")
val comment2 = Comment("comment2")
assertNotEquals(comment1, comment2)
assertNotEquals(comment2, comment1)
}
@Test
fun equals() {
val comment1 = Comment("comment")
val comment2 = Comment("comment")
assertEquals(comment1, comment2)
assertEquals(comment2, comment1)
}
} | apache-2.0 |
Xenoage/Zong | utils-kotlin/utils-kotlin-jvm/test/com/xenoage/utils/Assert.kt | 1 | 308 | package com.xenoage.utils
import kotlin.math.abs
import kotlin.test.assertTrue
/** Asserts that the [expected] value is equal to the [actual] value, with the
* given [delta] tolerance value. */
fun assertEquals(expected: Float, actual: Float, delta: Float) {
assertTrue(abs(expected - actual) <= delta)
} | agpl-3.0 |
exponent/exponent | packages/expo-modules-core/android/src/test/java/expo/modules/benchmarks/NewArchitectureBenchmark.kt | 2 | 2276 | package expo.modules.benchmarks
import com.facebook.react.bridge.Dynamic
import com.facebook.react.bridge.DynamicFromObject
import com.facebook.react.bridge.JavaOnlyArray
import com.facebook.react.bridge.ReadableArray
import expo.modules.adapters.react.NativeModulesProxy
import expo.modules.kotlin.ModulesProvider
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
class NewArchitectureBenchmark {
private val benchmarkRule = BenchmarkRule(iteration = 1000000)
private lateinit var proxy: NativeModulesProxy
class MyModule : Module() {
private fun retNull(): Any? {
return null
}
override fun definition() = ModuleDefinition {
name("MyModule")
function("m1") { -> retNull() }
function("m2") { _: Int, _: Int -> retNull() }
function("m3") { _: IntArray -> retNull() }
function("m4") { _: String -> retNull() }
}
}
@Before
fun before() {
val legacyModuleRegister = expo.modules.core.ModuleRegistry(
emptyList(),
emptyList(),
emptyList(),
emptyList()
)
proxy = NativeModulesProxy(
null, legacyModuleRegister,
object : ModulesProvider {
override fun getModulesList(): List<Class<out Module>> =
listOf(MyModule::class.java)
}
)
}
@Ignore("It's a benchmark")
@Test
fun `call function with simple arguments`() {
val testCases = listOf<Pair<Dynamic, ReadableArray>>(
DynamicFromObject("m1") to JavaOnlyArray(),
DynamicFromObject("m2") to JavaOnlyArray().apply {
pushInt(1)
pushInt(2)
},
DynamicFromObject("m3") to JavaOnlyArray().apply {
pushArray(
JavaOnlyArray().apply {
pushInt(1)
pushInt(2)
pushInt(3)
}
)
},
DynamicFromObject("m4") to JavaOnlyArray().apply {
pushString("expo is awesome")
}
)
val emptyPromise = EmptyRNPromise()
repeat(3) {
benchmarkRule.run(::`call function with simple arguments`.name) {
testCases.forEach { (method, args) ->
proxy.callMethod("MyModule", method, args, emptyPromise)
}
}
}
}
}
| bsd-3-clause |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoTypeDeclarationHandler2.kt | 1 | 2959 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.navigation.actions
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.navigation.CtrlMouseInfo
import com.intellij.codeInsight.navigation.impl.*
import com.intellij.codeInsight.navigation.impl.NavigationActionResult.MultipleTargets
import com.intellij.codeInsight.navigation.impl.NavigationActionResult.SingleTarget
import com.intellij.openapi.actionSystem.ex.ActionUtil.underModalProgress
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.ui.list.createTargetPopup
internal object GotoTypeDeclarationHandler2 : CodeInsightActionHandler {
override fun startInWriteAction(): Boolean = false
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val dumbService = DumbService.getInstance(project)
val result: NavigationActionResult? = try {
underModalProgress(project, CodeInsightBundle.message("progress.title.resolving.reference")) {
dumbService.computeWithAlternativeResolveEnabled<NavigationActionResult?, Throwable> {
handleLookup(project, editor, offset)
?: gotoTypeDeclaration(file, offset)?.result()
}
}
}
catch (e: IndexNotReadyException) {
dumbService.showDumbModeNotification(CodeInsightBundle.message("message.navigation.is.not.available.here.during.index.update"))
return
}
if (result == null) {
return
}
gotoTypeDeclaration(project, editor, result)
}
private fun gotoTypeDeclaration(project: Project, editor: Editor, actionResult: NavigationActionResult) {
when (actionResult) {
is SingleTarget -> {
navigateRequest(project, actionResult.request)
}
is MultipleTargets -> {
val popup = createTargetPopup(
CodeInsightBundle.message("choose.type.popup.title"),
actionResult.targets, LazyTargetWithPresentation::presentation
) { (requestor, _) ->
navigateRequestLazy(project, requestor)
}
popup.showInBestPositionFor(editor)
}
}
}
private fun handleLookup(project: Project, editor: Editor, offset: Int): NavigationActionResult? {
val fromLookup = TargetElementUtil.getTargetElementFromLookup(project) ?: return null
return result(elementTypeTargets(editor, offset, listOf(fromLookup)))
}
@JvmStatic
fun getCtrlMouseInfo(file: PsiFile, offset: Int): CtrlMouseInfo? {
return gotoTypeDeclaration(file, offset)?.ctrlMouseInfo()
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/IndexingFlag.kt | 4 | 1239 | // 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.util.indexing
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.ManagingFS
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry
import org.jetbrains.annotations.ApiStatus
/**
* An object dedicated to manage in memory `isIndexed` file flag.
*/
@ApiStatus.Internal
object IndexingFlag {
@JvmStatic
fun cleanupProcessedFlag() {
val roots = ManagingFS.getInstance().roots
for (root in roots) {
cleanProcessedFlagRecursively(root)
}
}
@JvmStatic
fun cleanProcessedFlagRecursively(file: VirtualFile) {
if (file !is VirtualFileSystemEntry) return
cleanProcessingFlag(file)
if (file.isDirectory()) {
for (child in file.cachedChildren) {
cleanProcessedFlagRecursively(child)
}
}
}
@JvmStatic
fun cleanProcessingFlag(file: VirtualFile) {
if (file is VirtualFileSystemEntry) {
file.isFileIndexed = false
}
}
@JvmStatic
fun setFileIndexed(file: VirtualFile) {
if (file is VirtualFileSystemEntry) {
file.isFileIndexed = true
}
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/fileRanking/multilinePrimaryConstructor.kt | 13 | 192 | //FILE: a/a.kt
class A(
val firstName: String,
val lastName: String,
val age: Int
)
//FILE: b/a.kt
class B(
val firstName: String,
val lastName: String,
val age: Int
) | apache-2.0 |
smmribeiro/intellij-community | platform/statistics/devkit/src/com/intellij/internal/statistic/devkit/groups/OpenEventLogFileActionGroup.kt | 2 | 869 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.devkit.groups
import com.intellij.internal.statistic.devkit.StatisticsDevKitUtil.getLogProvidersInTestMode
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
internal class OpenEventLogFileActionGroup : ActionGroup() {
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
return getLogProvidersInTestMode()
.map { logger ->
val recorder = logger.recorderId
com.intellij.internal.statistic.devkit.actions.OpenEventLogFileAction(recorder)
}
.toTypedArray()
}
override fun isPopup(): Boolean {
return getLogProvidersInTestMode().size > 1
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/topLevel/operators/set/Implicit.kt | 10 | 33 | fun test() {
42[42, ""] = 3
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/editor/optimizeImports/jvm/allUnderImports/Simple.dependency.kt | 13 | 20 | package ppp
class C | apache-2.0 |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportLocationHelper.kt | 12 | 653 | package com.jetbrains.python.codeInsight.imports
import com.intellij.openapi.application.ApplicationManager
import com.intellij.psi.PsiElement
interface ImportLocationHelper {
fun getSearchStartPosition(anchor: PsiElement?, insertParent: PsiElement): PsiElement?
companion object {
@JvmStatic
fun getInstance(): ImportLocationHelper {
return ApplicationManager.getApplication().getService(ImportLocationHelper::class.java)
}
}
}
class PyImportLocationHelper : ImportLocationHelper {
override fun getSearchStartPosition(anchor: PsiElement?, insertParent: PsiElement): PsiElement? {
return insertParent.firstChild
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertToBlockBody/valueIsAnonymousObject4.kt | 9 | 77 | // WITH_STDLIB
interface I
private fun f() = <caret>listOf(object : I { })
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/util/ApplicationUtils.kt | 1 | 4304 | // 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.util.application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.impl.CancellationCheck
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
fun <T> runReadAction(action: () -> T): T {
return ApplicationManager.getApplication().runReadAction<T>(action)
}
fun <T> runWriteAction(action: () -> T): T {
return ApplicationManager.getApplication().runWriteAction<T>(action)
}
/**
* Run under the write action if the supplied element is physical; run normally otherwise.
*
* @param e context element
* @param action action to execute
* @return result of action execution
*/
fun <T> runWriteActionIfPhysical(e: PsiElement, action: () -> T): T {
if (e.isPhysical) {
return ApplicationManager.getApplication().runWriteAction<T>(action)
}
return action()
}
fun <T> runWriteActionInEdt(action: () -> T): T {
return if (isDispatchThread()) {
runWriteAction(action)
} else {
var result: T? = null
ApplicationManager.getApplication().invokeLater {
result = runWriteAction(action)
}
result!!
}
}
fun Project.executeWriteCommand(@NlsContexts.Command name: String, command: () -> Unit) {
CommandProcessor.getInstance().executeCommand(this, { runWriteAction(command) }, name, null)
}
fun <T> Project.executeWriteCommand(@NlsContexts.Command name: String, groupId: Any? = null, command: () -> T): T {
return executeCommand<T>(name, groupId) { runWriteAction(command) }
}
fun <T> Project.executeCommand(@NlsContexts.Command name: String, groupId: Any? = null, command: () -> T): T {
@Suppress("UNCHECKED_CAST") var result: T = null as T
CommandProcessor.getInstance().executeCommand(this, { result = command() }, name, groupId)
@Suppress("USELESS_CAST")
return result as T
}
fun <T> runWithCancellationCheck(block: () -> T): T = CancellationCheck.runWithCancellationCheck(block)
inline fun executeOnPooledThread(crossinline action: () -> Unit) =
ApplicationManager.getApplication().executeOnPooledThread { action() }
inline fun invokeLater(crossinline action: () -> Unit) =
ApplicationManager.getApplication().invokeLater { action() }
inline fun invokeLater(expired: Condition<*>, crossinline action: () -> Unit) =
ApplicationManager.getApplication().invokeLater({ action() }, expired)
inline fun isUnitTestMode(): Boolean = ApplicationManager.getApplication().isUnitTestMode
inline fun isDispatchThread(): Boolean = ApplicationManager.getApplication().isDispatchThread
inline fun isApplicationInternalMode(): Boolean = ApplicationManager.getApplication().isInternal
inline fun <reified T : Any> ComponentManager.getService(): T? = this.getService(T::class.java)
inline fun <reified T : Any> ComponentManager.getServiceSafe(): T =
this.getService(T::class.java) ?: error("Unable to locate service ${T::class.java.name}")
fun <T> executeInBackgroundWithProgress(project: Project? = null, @NlsContexts.ProgressTitle title: String, block: () -> T): T {
assert(!ApplicationManager.getApplication().isWriteAccessAllowed) {
"Rescheduling computation into the background is impossible under the write lock"
}
return ProgressManager.getInstance().runProcessWithProgressSynchronously(
ThrowableComputable { block() }, title, true, project
)
}
fun KotlinExceptionWithAttachments.withPsiAttachment(name: String, element: PsiElement?): KotlinExceptionWithAttachments {
kotlin.runCatching { element?.getElementTextWithContext() }.getOrNull()?.let { withAttachment(name, it) }
return this
} | apache-2.0 |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/template/postfix/templates/GrArgPostfixTemplate.kt | 9 | 1056 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.codeInsight.template.postfix.templates
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.impl.MacroCallNode
import com.intellij.codeInsight.template.macro.SuggestVariableNameMacro
import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.codeInsight.template.postfix.GroovyPostfixTemplateUtils
class GrArgPostfixTemplate(provider: PostfixTemplateProvider) :
GrPostfixTemplateBase("arg", "functionCall(expr)", GroovyPostfixTemplateUtils.getExpressionSelector(), provider) {
override fun getGroovyTemplateString(element: PsiElement): String = "__call__(__expr__)__END__"
override fun setVariables(template: Template, element: PsiElement) {
val name = MacroCallNode(SuggestVariableNameMacro())
template.addVariable("call", name, name, true)
}
} | apache-2.0 |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_Pump_TimeTest.kt | 1 | 1392 | package info.nightscout.androidaps.danars.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import org.joda.time.DateTime
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class DanaRS_Packet_Option_Get_Pump_TimeTest : DanaRSTestBase() {
private val packetInjector = HasAndroidInjector {
AndroidInjector {
if (it is DanaRS_Packet) {
it.aapsLogger = aapsLogger
it.dateUtil = dateUtil
}
if (it is DanaRS_Packet_Option_Get_Pump_Time) {
it.danaPump = danaPump
}
}
}
@Test fun runTest() {
val packet = DanaRS_Packet_Option_Get_Pump_Time(packetInjector)
val array = createArray(8, 0.toByte()) // 6 + 2
putByteToArray(array, 0, 19) // year 2019
putByteToArray(array, 1, 2) // month february
putByteToArray(array, 2, 4) // day 4
putByteToArray(array, 3, 20) // hour 20
putByteToArray(array, 4, 11) // min 11
putByteToArray(array, 5, 35) // second 35
packet.handleMessage(array)
Assert.assertEquals(DateTime(2019, 2, 4, 20, 11, 35).millis, danaPump.getPumpTime())
Assert.assertEquals("OPTION__GET_PUMP_TIME", packet.friendlyName)
}
} | agpl-3.0 |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBTDeviceTest.kt | 1 | 1820 | package info.nightscout.androidaps.plugins.general.automation.triggers
import com.google.common.base.Optional
import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorConnect
import org.json.JSONObject
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class TriggerBTDeviceTest : TriggerTestBase() {
var now = 1514766900000L
var someName = "Headset"
var btJson = "{\"data\":{\"comparator\":\"ON_CONNECT\",\"name\":\"Headset\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.triggers.TriggerBTDevice\"}"
@Test fun shouldRun() {
val t: TriggerBTDevice = TriggerBTDevice(injector)
}
@Test fun toJSON() {
val t: TriggerBTDevice = TriggerBTDevice(injector)
t.btDevice.value = someName
Assert.assertEquals(btJson, t.toJSON())
}
@Test
fun fromJSON() {
val t2 = TriggerDummy(injector).instantiate(JSONObject(btJson)) as TriggerBTDevice
Assert.assertEquals(ComparatorConnect.Compare.ON_CONNECT, t2.comparator.value)
Assert.assertEquals("Headset", t2.btDevice.value)
}
@Test
fun icon() {
Assert.assertEquals(Optional.of(R.drawable.ic_bluetooth_white_48dp), TriggerBTDevice(injector).icon())
}
@Test fun duplicate() {
val t: TriggerBTDevice = TriggerBTDevice(injector).also {
it.comparator.value = ComparatorConnect.Compare.ON_DISCONNECT
it.btDevice.value = someName
}
val t1 = t.duplicate() as TriggerBTDevice
Assert.assertEquals("Headset", t1.btDevice.value)
Assert.assertEquals(ComparatorConnect.Compare.ON_DISCONNECT, t.comparator.value)
}
} | agpl-3.0 |
Flank/flank | test_runner/src/test/kotlin/ftl/cli/firebase/test/android/AndroidDoctorCommandTest.kt | 1 | 2794 | package ftl.cli.firebase.test.android
import com.google.common.truth.Truth.assertThat
import flank.common.normalizeLineEnding
import ftl.cli.firebase.test.INVALID_YML_PATH
import ftl.cli.firebase.test.SUCCESS_VALIDATION_MESSAGE
import ftl.config.FtlConstants
import ftl.presentation.cli.firebase.test.android.AndroidDoctorCommand
import ftl.run.exception.YmlValidationError
import ftl.test.util.FlankTestRunner
import org.junit.Rule
import org.junit.Test
import org.junit.contrib.java.lang.system.SystemOutRule
import org.junit.runner.RunWith
import picocli.CommandLine
@RunWith(FlankTestRunner::class)
class AndroidDoctorCommandTest {
@Rule
@JvmField
val systemOutRule: SystemOutRule = SystemOutRule().enableLog().muteForSuccessfulTests()
@Test
fun androidDoctorCommandPrintsHelp() {
val doctor = AndroidDoctorCommand()
assertThat(doctor.usageHelpRequested).isFalse()
CommandLine(doctor).execute("-h")
val output = systemOutRule.log.normalizeLineEnding()
assertThat(output).startsWith(
"Verifies flank firebase is setup correctly\n" +
"\n" +
"doctor [-fh] [-c=<configPath>]\n" +
"\n" +
"Description:\n" +
"\n" +
"Validates Android Flank YAML.\n" +
"\n" +
"\n" +
"Options:\n" +
" -h, --help Prints this help message\n"
)
assertThat(doctor.usageHelpRequested).isTrue()
}
@Test
fun androidDoctorCommandRuns() {
AndroidDoctorCommand().run()
// When there are no lint errors, output is a newline.
val output = systemOutRule.log.normalizeLineEnding()
assertThat(output).isEqualTo(SUCCESS_VALIDATION_MESSAGE)
}
@Test
fun androidDoctorCommandOptions() {
val cmd = AndroidDoctorCommand()
assertThat(cmd.configPath).isEqualTo(FtlConstants.defaultAndroidConfig)
cmd.configPath = "tmp"
assertThat(cmd.configPath).isEqualTo("tmp")
assertThat(cmd.usageHelpRequested).isFalse()
cmd.usageHelpRequested = true
assertThat(cmd.usageHelpRequested).isTrue()
assertThat(cmd.fix).isFalse()
cmd.fix = true
assertThat(cmd.fix).isTrue()
}
@Test(expected = YmlValidationError::class)
fun `should terminate with exit code 1 when yml validation fails`() {
AndroidDoctorCommand().run {
configPath = INVALID_YML_PATH
run()
}
}
@Test
fun `android doctor should not fail on local-result-dir`() {
AndroidDoctorCommand().apply {
configPath = "./src/test/kotlin/ftl/fixtures/test_app_cases/flank-with_local_result_dir.yml"
}.run()
}
}
| apache-2.0 |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/util/LazyMatrix.kt | 1 | 720 | package de.fabmax.kool.util
import de.fabmax.kool.math.Mat4d
import de.fabmax.kool.math.Mat4f
class LazyMat4d(val update: (Mat4d) -> Unit) {
var isDirty = true
private val mat = Mat4d()
fun clear() {
isDirty = false
mat.setIdentity()
}
fun get(): Mat4d {
if (isDirty) {
update(mat)
isDirty = false
}
return mat
}
}
class LazyMat4f(val update: (Mat4f) -> Unit) {
var isDirty = true
private val mat = Mat4f()
fun clear() {
isDirty = false
mat.setIdentity()
}
fun get(): Mat4f {
if (isDirty) {
update(mat)
isDirty = false
}
return mat
}
} | apache-2.0 |
Pattonville-App-Development-Team/Android-App | app/src/androidTest/java/org/pattonvillecs/pattonvilleapp/service/repository/directory/DirectoryRepositoryTest.kt | 1 | 3445 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* 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 org.pattonvillecs.pattonvilleapp.service.repository.directory
import android.arch.persistence.room.Room
import android.support.test.InstrumentationRegistry
import android.support.test.filters.MediumTest
import android.support.test.runner.AndroidJUnit4
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.contains
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.pattonvillecs.pattonvilleapp.service.model.DataSource
import org.pattonvillecs.pattonvilleapp.service.model.directory.Faculty
import org.pattonvillecs.pattonvilleapp.service.repository.AppDatabase
import org.pattonvillecs.pattonvilleapp.service.repository.awaitValue
/**
* Tests adding and removing faculty from an in-memory database.
*
* @author Mitchell Skaggs
* @since 1.3.0
*/
@Suppress("TestFunctionName")
@RunWith(AndroidJUnit4::class)
@MediumTest
class DirectoryRepositoryTest {
private lateinit var appDatabase: AppDatabase
private lateinit var directoryRepository: DirectoryRepository
@Before
fun createDb() {
val context = InstrumentationRegistry.getTargetContext()
appDatabase = AppDatabase.init(Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)).build()
directoryRepository = DirectoryRepository(appDatabase)
}
@After
fun closeDb() {
appDatabase.close()
}
@Test
fun Given_Faculty_When_UpsertAllCalled_Then_ReturnSameFaculty() {
val faculty = testFaculty()
directoryRepository.upsertAll(listOf(faculty))
val facultyMembers = directoryRepository.getFacultyFromLocations(DataSource.DISTRICT).awaitValue()
assertThat(facultyMembers, contains(faculty))
}
private fun testFaculty(firstName: String = "test_first_name",
lastName: String = "test_last_name",
pcn: String = "test_pcn",
description: String = "test_description",
location: DataSource? = DataSource.DISTRICT,
email: String? = "test_email",
officeNumber1: String? = null,
extension1: String? = null,
officeNumber2: String? = null,
extension2: String? = null,
officeNumber3: String? = null,
extension3: String? = null): Faculty {
return Faculty(firstName, lastName, pcn, description, location, email, officeNumber1, extension1, officeNumber2, extension2, officeNumber3, extension3)
}
} | gpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.