repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
docker-client/docker-compose-v3 | src/main/kotlin/de/gesellix/docker/compose/types/StackNetwork.kt | 1 | 652 | package de.gesellix.docker.compose.types
import com.squareup.moshi.Json
import de.gesellix.docker.compose.adapters.DriverOptsType
import de.gesellix.docker.compose.adapters.ExternalType
import de.gesellix.docker.compose.adapters.LabelsType
data class StackNetwork(
var driver: String? = null,
@Json(name = "driver_opts")
@DriverOptsType
var driverOpts: DriverOpts = DriverOpts(),
var ipam: Ipam? = null,
@ExternalType
var external: External = External(),
var internal: Boolean? = null,
var attachable: Boolean? = false,
@LabelsType
var labels: Labels? = null
)
| mit | e3e10ea4df5b55866657bde6b4a51d17 | 30.047619 | 57 | 0.679448 | 4.100629 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/gist/GistActivity.kt | 1 | 1744 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.gist
import android.content.Context
import android.content.Intent
import android.os.Bundle
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.base.BaseActivity
/**
* Created by giulio on 26/05/2017.
*/
class GistActivity : BaseActivity() {
private val GIST_FRAGMENT_TAG = "GIST_FRAGMENT_TAG"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.gist_activity)
var gistFragment: GistFragment? = supportFragmentManager.findFragmentByTag(GIST_FRAGMENT_TAG) as GistFragment?
if (gistFragment == null) {
gistFragment = GistFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.gist_activity_frame, gistFragment, GIST_FRAGMENT_TAG)
.commit()
}
}
override fun onBackPressed() {
super.onBackPressed()
overridePendingTransition(0,0)
}
companion object {
fun getIntent(context: Context): Intent {
return Intent(context, GistActivity::class.java)
}
}
} | apache-2.0 | 3da418eb965778af757fd4b1e0948e5b | 29.614035 | 118 | 0.683486 | 4.471795 | false | false | false | false |
huy-vuong/streamr | app/src/main/java/com/huyvuong/streamr/ui/component/subcomponent/LicenseCardSubcomponent.kt | 1 | 4590 | package com.huyvuong.streamr.ui.component.subcomponent
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.CardView
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.huyvuong.streamr.R
import com.huyvuong.streamr.extension.anko.view
import com.huyvuong.streamr.model.view.License
import com.huyvuong.streamr.util.getCardHeaderDrawable
import org.jetbrains.anko.AnkoComponent
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.browse
import org.jetbrains.anko.cardview.v7.cardView
import org.jetbrains.anko.dip
import org.jetbrains.anko.imageView
import org.jetbrains.anko.leftPadding
import org.jetbrains.anko.linearLayout
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.padding
import org.jetbrains.anko.sp
import org.jetbrains.anko.textView
import org.jetbrains.anko.topPadding
import org.jetbrains.anko.verticalLayout
import org.jetbrains.anko.wrapContent
import android.support.v7.appcompat.R as AppCompatR
class LicenseCardSubcomponent : AnkoComponent<ViewGroup> {
private lateinit var licenseCardView: CardView
private lateinit var photoHeaderTextView: TextView
private lateinit var licenseNameTextView: TextView
private lateinit var licenseSeparatorView: View
private lateinit var openLicenseUrlVerticalLayout: LinearLayout
override fun createView(ui: AnkoContext<ViewGroup>): CardView = with(ui.owner) {
cardView {
licenseCardView = this
setCardBackgroundColor(ContextCompat.getColor(ui.ctx, R.color.cardBackground))
radius = dip(2).toFloat()
elevation = 2.0F
verticalLayout {
lparams(width = matchParent, height = wrapContent)
linearLayout {
lparams(width = matchParent, height = wrapContent)
leftPadding = dip(16)
topPadding = dip(16)
imageView(getCardHeaderDrawable(context, R.drawable.ic_card_license))
.lparams(width = dip(16), height = dip(16))
photoHeaderTextView = textView("License") {
leftPadding = dip(8)
textSize = sp(3.5F).toFloat()
}.lparams(width = matchParent, height = dip(16)) {
gravity = Gravity.CENTER_VERTICAL
}
}
licenseNameTextView = textView("License Name") {
padding = dip(16)
setTextAppearance(
AppCompatR.style.TextAppearance_AppCompat_Headline)
}.lparams(width = matchParent, height = wrapContent)
licenseSeparatorView = view {
background =
ColorDrawable(
ContextCompat.getColor(ui.ctx, R.color.cardDivider))
}.lparams(width = wrapContent, height = dip(1))
openLicenseUrlVerticalLayout = verticalLayout {
lparams(width = matchParent, height = wrapContent)
padding = dip(16)
isFocusable = true
isClickable = true
val outValue = TypedValue()
context.theme.resolveAttribute(
android.R.attr.selectableItemBackground,
outValue,
true)
foreground = ContextCompat.getDrawable(context, outValue.resourceId)
textView("View License") {
setTextAppearance(
AppCompatR.style.TextAppearance_AppCompat_Widget_Button)
}.lparams(width = matchParent, height = wrapContent)
}
}
}
}
fun bind(context: Context, license: License? = null) {
if (license != null) {
licenseNameTextView.text = license.name
if (license.url.isNotBlank()) {
openLicenseUrlVerticalLayout.setOnClickListener { context.browse(license.url) }
} else {
licenseSeparatorView.visibility = View.GONE
openLicenseUrlVerticalLayout.visibility = View.GONE
}
} else {
licenseCardView.visibility = View.GONE
}
}
} | gpl-3.0 | c8e6506ba6b5113c970486bc6f98cb81 | 39.27193 | 95 | 0.616993 | 5.269805 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/adapters/ContributorAdapter.kt | 1 | 4423 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.adapters
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.squareup.picasso.Picasso
import giuliolodi.gitnav.R
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.row_contributor.view.*
import org.eclipse.egit.github.core.Contributor
/**
* Created by giulio on 20/05/2017.
*/
class ContributorAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var mContributorList: MutableList<Contributor?> = arrayListOf()
private val onClickSubject: PublishSubject<String> = PublishSubject.create()
fun getPositionClicks(): Observable<String> {
return onClickSubject
}
class ContributorHolder(root: View) : RecyclerView.ViewHolder(root) {
fun bind (contributor: Contributor) = with(itemView) {
if (contributor.login != null && !contributor.login.isBlank())
row_contributor_login.text = contributor.login
else if (contributor.name != null && !contributor.name.isBlank())
row_contributor_login.text = contributor.name
else
row_contributor_login.text = context.getString(R.string.anonymous)
row_contributor_contributions.text = "Contributions: " + contributor.contributions.toString()
Picasso.with(context).load(contributor.avatarUrl).resize(100,100).centerCrop().into(row_contributor_image)
}
}
class LoadingHolder(root: View) : RecyclerView.ViewHolder(root)
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
val root: RecyclerView.ViewHolder
if (viewType == 1) {
val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_contributor, parent, false))
root = ContributorHolder(view)
} else {
val view = (LayoutInflater.from(parent?.context).inflate(R.layout.row_loading, parent, false))
root = LoadingHolder(view)
}
return root
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ContributorHolder) {
val user = mContributorList[position]!!
holder.bind(user)
holder.itemView.setOnClickListener { user.login?.let { onClickSubject.onNext(user.login) } }
}
}
override fun getItemViewType(position: Int): Int { return if (mContributorList[position] != null) 1 else 0 }
override fun getItemCount(): Int { return mContributorList.size }
override fun getItemId(position: Int): Long { return position.toLong() }
fun addContributorList(contributorList: List<Contributor>) {
if (mContributorList.isEmpty()) {
mContributorList.addAll(contributorList)
notifyDataSetChanged()
}
else if (!contributorList.isEmpty()) {
val lastItemIndex = if (mContributorList.size > 0) mContributorList.size else 0
mContributorList.addAll(contributorList)
notifyItemRangeInserted(lastItemIndex, mContributorList.size)
}
}
fun addContributor(contributor: Contributor) {
mContributorList.add(contributor)
notifyItemInserted(mContributorList.size - 1)
}
fun addLoading() {
mContributorList.add(null)
notifyItemInserted(mContributorList.size - 1)
}
fun hideLoading() {
if (mContributorList.lastIndexOf(null) != -1) {
val lastNull = mContributorList.lastIndexOf(null)
mContributorList.removeAt(lastNull)
notifyItemRemoved(lastNull)
}
}
fun clear() {
mContributorList.clear()
notifyDataSetChanged()
}
} | apache-2.0 | 6c2cbe840ffd1a595915c90977bfbeae | 36.491525 | 118 | 0.684829 | 4.559794 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/adapter/BranchAdapter.kt | 2 | 1936 | package com.commit451.gitlab.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.commit451.gitlab.R
import com.commit451.gitlab.model.Ref
import com.commit451.gitlab.model.api.Branch
import com.commit451.gitlab.viewHolder.BranchViewHolder
import java.util.*
/**
* Adapts the feeds
*/
class BranchAdapter(private val ref: Ref?, private val listener: Listener) : RecyclerView.Adapter<BranchViewHolder>() {
private val values: ArrayList<Branch> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BranchViewHolder {
val holder = BranchViewHolder.inflate(parent)
holder.itemView.setOnClickListener { v ->
val position = v.getTag(R.id.list_position) as Int
listener.onBranchClicked(getEntry(position))
}
return holder
}
override fun onBindViewHolder(holder: BranchViewHolder, position: Int) {
holder.itemView.setTag(R.id.list_position, position)
val branch = getEntry(position)
var selected = false
if (ref != null) {
if (ref.type == Ref.TYPE_BRANCH && ref.ref == branch.name) {
selected = true
}
}
holder.bind(branch, selected)
}
override fun getItemCount(): Int {
return values.size
}
fun setEntries(entries: Collection<Branch>?) {
values.clear()
if (entries != null) {
values.addAll(entries)
}
notifyDataSetChanged()
}
fun addEntries(entries: Collection<Branch>) {
if (!entries.isEmpty()) {
val start = values.size
this.values.addAll(entries)
notifyItemRangeChanged(start, this.values.size)
}
}
private fun getEntry(position: Int): Branch {
return values[position]
}
interface Listener {
fun onBranchClicked(entry: Branch)
}
}
| apache-2.0 | 16a6ae9b6a647992d8c8074274dda52a | 28.333333 | 119 | 0.642562 | 4.420091 | false | false | false | false |
Heiner1/AndroidAPS | rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.kt | 1 | 2220 | package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.R
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileylinkStatusBinding
class RileyLinkStatusActivity : NoSplashAppCompatActivity() {
private lateinit var binding: RileylinkStatusBinding
private var sectionsPagerAdapter: SectionsPagerAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = RileylinkStatusBinding.inflate(layoutInflater)
setContentView(binding.root)
sectionsPagerAdapter = SectionsPagerAdapter(this)
sectionsPagerAdapter?.addFragment(RileyLinkStatusGeneralFragment::class.java.name, rh.gs(R.string.rileylink_settings_tab1))
sectionsPagerAdapter?.addFragment(RileyLinkStatusHistoryFragment::class.java.name, rh.gs(R.string.rileylink_settings_tab2))
binding.pager.adapter = sectionsPagerAdapter
TabLayoutMediator(binding.tabLayout, binding.pager) { tab, position ->
tab.text = sectionsPagerAdapter?.getPageTitle(position)
}.attach()
}
class SectionsPagerAdapter(private val activity: AppCompatActivity) : FragmentStateAdapter(activity) {
private val fragmentList: MutableList<String> = ArrayList()
private val fragmentTitle: MutableList<String> = ArrayList()
override fun getItemCount(): Int = fragmentList.size
override fun createFragment(position: Int): Fragment =
activity.supportFragmentManager.fragmentFactory.instantiate(ClassLoader.getSystemClassLoader(), fragmentList[position])
fun getPageTitle(position: Int): CharSequence = fragmentTitle[position]
fun addFragment(fragment: String, title: String) {
fragmentList.add(fragment)
fragmentTitle.add(title)
}
}
} | agpl-3.0 | 33cf9fbda075b578f6433f425df46d97 | 45.270833 | 131 | 0.768468 | 5.199063 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt | 1 | 1461 | package info.nightscout.androidaps.queue.commands
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.queue.Callback
import javax.inject.Inject
class CommandTempBasalPercent(
injector: HasAndroidInjector,
private val percent: Int,
private val durationInMinutes: Int,
private val enforceNew: Boolean,
private val profile: Profile,
private val tbrType: PumpSync.TemporaryBasalType,
callback: Callback?
) : Command(injector, CommandType.TEMPBASAL, callback) {
@Inject lateinit var activePlugin: ActivePlugin
override fun execute() {
val r =
if (percent == 100)
activePlugin.activePump.cancelTempBasal(enforceNew)
else
activePlugin.activePump.setTempBasalPercent(percent, durationInMinutes, profile, enforceNew, tbrType)
aapsLogger.debug(LTag.PUMPQUEUE, "Result percent: $percent durationInMinutes: $durationInMinutes success: ${r.success} enacted: ${r.enacted}")
callback?.result(r)?.run()
}
override fun status(): String = rh.gs(R.string.temp_basal_percent, percent, durationInMinutes)
override fun log(): String = "TEMP BASAL $percent% $durationInMinutes min"
} | agpl-3.0 | 0e83900c268e20af8b9b3ab92177a60c | 38.513514 | 150 | 0.748802 | 4.77451 | false | false | false | false |
square/wire | wire-library/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/MutableOnWriteList.kt | 1 | 1760 | /*
* Copyright 2015 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 com.squareup.wire.internal
import kotlin.jvm.JvmName
/** A wrapper around an empty/immutable list which only switches to mutable on first mutation. */
internal class MutableOnWriteList<T>(
private val immutableList: List<T>
) : AbstractMutableList<T>(), RandomAccess, Serializable {
internal var mutableList: List<T> = immutableList
override fun get(index: Int): T = mutableList[index]
override val size: Int
@get:JvmName("size") get() = mutableList.size
override fun set(index: Int, element: T): T {
if (mutableList === immutableList) {
mutableList = ArrayList(immutableList)
}
return (mutableList as ArrayList).set(index, element)
}
override fun add(index: Int, element: T) {
if (mutableList === immutableList) {
mutableList = ArrayList(immutableList)
}
(mutableList as ArrayList).add(index, element)
}
override fun removeAt(index: Int): T {
if (mutableList === immutableList) {
mutableList = ArrayList(immutableList)
}
return (mutableList as ArrayList).removeAt(index)
}
@Throws(ObjectStreamException::class)
private fun writeReplace(): Any = ArrayList(mutableList)
}
| apache-2.0 | aa8b53f37b510f32d19425df69427cf5 | 31.592593 | 97 | 0.717045 | 4.210526 | false | false | false | false |
rinp/javaQuiz | src/main/kotlin/xxx/jq/form/CategoryForm.kt | 1 | 505 | package xxx.jq.form
import xxx.jq.entity.Category
import java.io.Serializable
/**
* @author rinp
* @since 2015/12/14
*/
data class CategoryForm(
val id: Long?,
val version: Long = -1,
@field:org.hibernate.validator.constraints.NotBlank(message = "カテゴリ名は必ず入力してください。")
val name: String = "",
val isDelete: Boolean = false
) : Serializable {
fun toCategory(): Category = Category(id = id, name = name, version = version)
} | mit | 5e4d9c92c30c433400cc29bf3b3eecb2 | 21.47619 | 90 | 0.645435 | 3.340426 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/design-compose/src/main/kotlin/app/ss/design/compose/theme/Theme.kt | 1 | 3236 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* 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 app.ss.design.compose.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import app.ss.design.compose.extensions.isS
val DarkColorScheme = darkColorScheme(
primary = Color.White,
secondary = SsColor.BaseBlue,
background = Color.Black,
surface = Color.Black,
onBackground = Color.White,
onSurface = Color.White,
error = SsColor.BaseRed
)
val LightColorScheme = lightColorScheme(
primary = SsColor.BaseBlue,
secondary = SsColor.BaseBlue,
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.White,
onBackground = SsColor.BaseGrey3,
onSurface = SsColor.BaseGrey3,
error = SsColor.BaseRed
)
@Composable
fun SsTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
windowWidthSizeClass: WindowWidthSizeClass? = WindowWidthSizeClass.Compact,
content: @Composable () -> Unit
) {
val colorScheme = when {
isS() -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val dimensions = when (windowWidthSizeClass) {
WindowWidthSizeClass.Medium -> sw600Dimensions
else -> smallDimensions
}
ProvideDimens(dimensions = dimensions) {
MaterialTheme(
colorScheme = colorScheme,
typography = SsTypography,
content = content
)
}
}
object SsTheme {
val dimens: Dimensions
@Composable
get() = LocalAppDimens.current
}
| mit | 906c0a784c140ffee61b6bf969a89eaa | 34.173913 | 96 | 0.735785 | 4.662824 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/uievent/impl/DefaultUIEventProcessor.kt | 1 | 6086 | package org.hexworks.zircon.internal.uievent.impl
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentHashMapOf
import kotlinx.collections.immutable.persistentListOf
import org.hexworks.cobalt.core.api.behavior.DisposeState
import org.hexworks.cobalt.core.api.behavior.NotDisposed
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.cobalt.events.api.Subscription
import org.hexworks.cobalt.logging.api.LoggerFactory
import org.hexworks.zircon.api.uievent.ComponentEvent
import org.hexworks.zircon.api.uievent.ComponentEventSource
import org.hexworks.zircon.api.uievent.ComponentEventType
import org.hexworks.zircon.api.uievent.KeyboardEvent
import org.hexworks.zircon.api.uievent.KeyboardEventType
import org.hexworks.zircon.api.uievent.MouseEvent
import org.hexworks.zircon.api.uievent.MouseEventType
import org.hexworks.zircon.api.uievent.Pass
import org.hexworks.zircon.api.uievent.PreventDefault
import org.hexworks.zircon.api.uievent.Processed
import org.hexworks.zircon.api.uievent.StopPropagation
import org.hexworks.zircon.api.uievent.UIEvent
import org.hexworks.zircon.api.uievent.UIEventPhase
import org.hexworks.zircon.api.uievent.UIEventResponse
import org.hexworks.zircon.api.uievent.UIEventSource
import org.hexworks.zircon.api.uievent.UIEventType
import org.hexworks.zircon.internal.uievent.UIEventProcessor
class DefaultUIEventProcessor : UIEventProcessor, UIEventSource, ComponentEventSource {
private val logger = LoggerFactory.getLogger(this::class)
private var listeners = persistentHashMapOf<UIEventType, PersistentList<InputEventSubscription>>()
override val closedValue: Property<Boolean> = false.toProperty()
override fun close() {
closedValue.value = true
listeners.flatMap { it.value }.forEach {
it.dispose()
}
listeners = listeners.clear()
}
override fun process(event: UIEvent, phase: UIEventPhase): UIEventResponse {
checkClosed()
return listeners[event.type]?.let { list ->
var finalResult: UIEventResponse = Pass
list.forEach {
when (val result = it.listener.invoke(event, phase)) {
Processed,
PreventDefault -> if (result.hasPrecedenceOver(finalResult)) {
finalResult = result
}
StopPropagation -> {
finalResult = result
return@forEach
}
Pass -> {
logger.debug("Result of invoking listener was 'Pass'. Result is ignored.")
}
}
}
finalResult
} ?: Pass
}
override fun handleMouseEvents(
eventType: MouseEventType,
handler: (event: MouseEvent, phase: UIEventPhase) -> UIEventResponse
): Subscription {
checkClosed()
return buildSubscription(eventType) { event, phase ->
handler(event as MouseEvent, phase)
}
}
override fun processMouseEvents(
eventType: MouseEventType,
handler: (event: MouseEvent, phase: UIEventPhase) -> Unit
): Subscription {
checkClosed()
return buildSubscription(eventType) { event, phase ->
handler(event as MouseEvent, phase)
Processed
}
}
override fun handleKeyboardEvents(
eventType: KeyboardEventType,
handler: (event: KeyboardEvent, phase: UIEventPhase) -> UIEventResponse
): Subscription {
checkClosed()
return buildSubscription(eventType) { event, phase ->
handler(event as KeyboardEvent, phase)
}
}
override fun processKeyboardEvents(
eventType: KeyboardEventType,
handler: (event: KeyboardEvent, phase: UIEventPhase) -> Unit
): Subscription {
checkClosed()
return buildSubscription(eventType) { event, phase ->
handler(event as KeyboardEvent, phase)
Processed
}
}
override fun handleComponentEvents(
eventType: ComponentEventType,
handler: (event: ComponentEvent) -> UIEventResponse
): Subscription {
checkClosed()
return buildSubscription(eventType) { event, phase ->
if (phase == UIEventPhase.TARGET) {
handler(event as ComponentEvent)
} else Pass
}
}
override fun processComponentEvents(
eventType: ComponentEventType,
handler: (event: ComponentEvent) -> Unit
): Subscription {
checkClosed()
return buildSubscription(eventType) { event, phase ->
if (phase == UIEventPhase.TARGET) {
handler(event as ComponentEvent)
}
Processed
}
}
private fun buildSubscription(
eventType: UIEventType,
listener: (UIEvent, UIEventPhase) -> UIEventResponse
): Subscription {
val subscription = InputEventSubscription(
eventType = eventType,
listener = listener
)
val subscriptions = listeners.getOrElse(eventType) { persistentListOf() }
listeners = listeners.put(eventType, subscriptions.add(subscription))
return subscription
}
private fun checkClosed() {
if (closed) throw IllegalStateException("This UIEventProcessor is closed.")
}
inner class InputEventSubscription(
private val eventType: UIEventType,
val listener: (UIEvent, UIEventPhase) -> UIEventResponse
) : Subscription {
override var disposeState: DisposeState = NotDisposed
override fun dispose(disposeState: DisposeState) {
val subscription = this
listeners[eventType]?.let { subscriptions ->
listeners = listeners.put(eventType, subscriptions.remove(subscription))
}
this.disposeState = disposeState
}
}
}
| apache-2.0 | f5887c0f086f443a55fac7a32ff5bb59 | 35.662651 | 102 | 0.660532 | 5.118587 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/NDArray.kt | 1 | 9560 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.simplemath.ndarray
import com.kotlinnlp.simplednn.core.functionalities.randomgenerators.RandomGenerator
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.sparse.SparseNDArray
import java.io.Serializable
/**
*
*/
interface NDArray<SelfType : NDArray<SelfType>> : Serializable {
/**
*
*/
val factory: NDArrayFactory<SelfType>
/**
*
*/
val isVector: Boolean
/**
* Whether the array is a bi-dimensional matrix
*/
val isMatrix: Boolean get() = !this.isVector
/**
*
*/
val isOneHotEncoder: Boolean
/**
*
*/
val rows: Int
/**
*
*/
val columns: Int
/**
*
*/
val length: Int
/**
*
*/
val lastIndex: Int
/**
*
*/
val shape: Shape
/**
* Transpose
*/
val t: SelfType
/**
*
*/
operator fun get(i: Int): Number
/**
*
*/
operator fun get(i: Int, j: Int): Number
/**
*
*/
operator fun set(i: Int, value: Number)
/**
*
*/
operator fun set(i: Int, j: Int, value: Number)
/**
* Get the i-th row
*
* @param i the index of the row to be returned
*
* @return the selected row as a new NDArray
*/
fun getRow(i: Int): SelfType
/**
* @return all the rows as a new NDArrays
*/
fun getRows(): List<SelfType> = (0 until this.rows).map { this.getRow(it) }
/**
* Get the i-th column
*
* @param i the index of the column to be returned
*
* @return the selected column as a new NDArray
*/
fun getColumn(i: Int): SelfType
/**
* @return all the columns as a new NDArrays
*/
fun getColumns(): List<SelfType> = (0 until this.columns).map { this.getColumn(it) }
/**
* Get a one-dimensional NDArray sub-vector of a vertical vector.
*
* @param a the start index of the range (inclusive)
* @param b the end index of the range (exclusive)
*
* @return the sub-array
*/
fun getRange(a: Int, b: Int): SelfType
/**
*
*/
fun zeros(): SelfType
/**
*
*/
fun zerosLike(): SelfType
/**
*
*/
fun copy(): SelfType
/**
*
*/
fun assignValues(n: Double): SelfType
/**
*
*/
fun assignValues(a: NDArray<*>): SelfType
/**
*
*/
fun assignValues(a: NDArray<*>, mask: NDArrayMask): SelfType
/**
*
*/
fun sum(): Double
/**
*
*/
fun sum(n: Double): SelfType
/**
*
*/
fun sum(a: SelfType): SelfType
/**
*
*/
fun sumByRows(a: NDArray<*>): DenseNDArray
/**
*
*/
fun sumByColumns(a: NDArray<*>): DenseNDArray
/**
*
*/
fun assignSum(n: Double): SelfType
/**
*
*/
fun assignSum(a: NDArray<*>): SelfType
/**
*
*/
fun assignSum(a: SelfType, n: Double): SelfType
/**
*
*/
fun assignSum(a: SelfType, b: SelfType): SelfType
/**
*
*/
fun sub(n: Double): SelfType
/**
*
*/
fun sub(a: NDArray<*>): SelfType
/**
* In-place subtraction by number
*/
fun assignSub(n: Double): SelfType
/**
*
*/
fun assignSub(a: NDArray<*>): SelfType
/**
*
*/
fun reverseSub(n: Double): SelfType
/**
*
*/
fun dot(a: NDArray<*>): DenseNDArray
/**
*
*/
fun assignDot(a: SelfType, b: SelfType): SelfType
/**
*
*/
fun assignDot(a: DenseNDArray, b: NDArray<*>): SelfType {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
/**
*
*/
fun prod(n: Double): SelfType
/**
*
*/
fun prod(a: NDArray<*>): SelfType
/**
*
*/
fun prod(n: Double, mask: NDArrayMask): SparseNDArray
/**
*
*/
fun assignProd(n: Double): SelfType
/**
*
*/
fun assignProd(n: Double, mask: NDArrayMask): SelfType
/**
*
*/
fun assignProd(a: NDArray<*>): SelfType
/**
*
*/
fun assignProd(a: SelfType, n: Double): SelfType
/**
*
*/
fun assignProd(a: SelfType, b: SelfType): SelfType
/**
*
*/
fun div(n: Double): SelfType
/**
*
*/
fun div(a: NDArray<*>): SelfType
/**
*
*/
fun div(a: SparseNDArray): SparseNDArray
/**
*
*/
fun assignDiv(n: Double): SelfType
/**
*
*/
fun assignDiv(a: SelfType): SelfType
/**
*
*/
fun abs(): SelfType
/**
*
*/
fun avg(): Double
/**
*
*/
fun max(): Double
/**
*
*/
fun min(): Double
/**
* Sign function
*
* @return a new NDArray containing the results of the function sign() applied element-wise
*/
fun sign(): SelfType
/**
*
*/
fun sqrt(): SelfType
/**
*
*/
fun assignSqrt(): SelfType
/**
* Square root of this [NDArray] masked by [mask]
*
* @param mask the mask to apply
*
* @return a [SparseNDArray]
*/
fun sqrt(mask: NDArrayMask): SparseNDArray
/**
* Power.
*
* @param power the exponent
*
* @return a new [NDArray] containing the values of this to the power of [power]
*/
fun pow(power: Double): SelfType
/**
* In-place power.
*
* @param power the exponent
*
* @return this [NDArray] to the power of [power]
*/
fun assignPow(power: Double): SelfType
/**
* Natural exponential.
*
* @return a new [NDArray] containing the results of the natural exponential function applied to this
*/
fun exp(): SelfType
/**
* In-place natural exponential.
*
* @return this [NDArray] with the natural exponential function applied to its values
*/
fun assignExp(): SelfType
/**
* Logarithm with base 10.
*
* @return a new [NDArray] containing the element-wise logarithm with base 10 of this array
*/
fun log10(): SelfType
/**
* In-place logarithm with base 10.
*
* @return this [NDArray] after having applied the logarithm with base 10 to its values
*/
fun assignLog10(): SelfType
/**
* Natural logarithm.
*
* @return a new [NDArray] containing the element-wise natural logarithm of this array
*/
fun ln(): SelfType
/**
* In-place natural logarithm.
*
* @return this [NDArray] after having applied the natural logarithm to its values
*/
fun assignLn(): SelfType
/**
* The norm (L1 distance) of this NDArray.
*
* @return the norm
*/
fun norm(): Double
/**
* Normalize an array with the L1 distance.
*
* @return a new [NDArray] normalized with the L1 distance
*/
fun normalize(): SelfType {
val norm: Double = this.norm()
@Suppress("UNCHECKED_CAST")
return if (norm != 0.0) this.div(norm) else this as SelfType
}
/**
* The Euclidean norm of this NDArray.
*
* @return the euclidean norm
*/
fun norm2(): Double
/**
* Normalize an array with the Euclidean norm.
*
* @return a new [NDArray] normalized with the Euclidean norm
*/
fun normalize2(): SelfType {
val norm2: Double = this.norm2()
@Suppress("UNCHECKED_CAST")
return if (norm2 != 0.0) this.div(norm2) else this as SelfType
}
/**
* Get the index of the highest value eventually skipping the element at the given [exceptIndex] when it is >= 0.
*
* @param exceptIndex the index to exclude
*
* @return the index of the maximum value (-1 if empty)
**/
fun argMaxIndex(exceptIndex: Int = -1): Int
/**
* Get the index of the highest value skipping all the elements at the indices in given set.
*
* @param exceptIndices the set of indices to exclude
*
* @return the index of the maximum value (-1 if empty)
**/
fun argMaxIndex(exceptIndices: Set<Int>): Int
/**
* Round values to Int
*
* @param threshold a value is rounded to the next Int if is >= [threshold], to the previous otherwise
*
* @return a new NDArray with the values of the current one rounded to Int
*/
fun roundInt(threshold: Double = 0.5): SelfType
/**
* Round values to Int in-place
*
* @param threshold a value is rounded to the next Int if is >= [threshold], to the previous otherwise
*
* @return this NDArray
*/
fun assignRoundInt(threshold: Double = 0.5): SelfType
/**
*
*/
fun randomize(randomGenerator: RandomGenerator): SelfType
/**
*
*/
fun concatH(a: SelfType): SelfType
/**
*
*/
fun concatV(a: SelfType): SelfType
/**
* Split this NDArray into more NDArrays.
*
* If the number of arguments is one, split this NDArray into multiple NDArray each with length [splittingLength].
* If there are multiple arguments, split this NDArray according to the length of each [splittingLength] element.
*
* @param splittingLength the length(s) for sub-array division
*
* @return a list containing the split values
*/
fun splitV(vararg splittingLength: Int): List<SelfType>
/**
*
*/
fun equals(a: SelfType, tolerance: Double = 1.0e-04): Boolean
/**
*
*/
fun equals(a: Any, tolerance: Double = 1.0e-04): Boolean {
@Suppress("UNCHECKED_CAST")
return a::class.isInstance(this) && this.equals(a as SelfType, tolerance)
}
/**
*
*/
override fun toString(): String
/**
*
*/
override fun equals(other: Any?): Boolean
/**
*
*/
override fun hashCode(): Int
}
| mpl-2.0 | b76d615d2f3c7c72867a64f0e83ef4ee | 16.477148 | 116 | 0.588075 | 3.671275 | false | false | false | false |
75py/Aplin | app/src/main/java/com/nagopy/android/aplin/data/repository/PackageRepositoryImpl.kt | 1 | 6347 | package com.nagopy.android.aplin.data.repository
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build
import android.print.PrintManager
import logcat.LogPriority
import logcat.logcat
import kotlin.reflect.full.declaredMemberFunctions
import kotlin.reflect.full.staticProperties
class PackageRepositoryImpl(
private val packageManager: PackageManager,
) : PackageRepository {
companion object {
private val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
PackageManager.GET_SIGNING_CERTIFICATES
} else {
@Suppress("DEPRECATION")
PackageManager.GET_SIGNATURES
}
}
override suspend fun loadAll(): List<PackageInfo> {
// https://cs.android.com/android/platform/superproject/+/master:frameworks/base/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java;drc=8cb6c27e8e2f171a0d9f9c4580092ebc4ce562fa
val hiddenModules = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
packageManager.getInstalledModules(0)
.map { it.packageName }
.toHashSet()
} else {
emptySet()
}
logcat(LogPriority.VERBOSE) { "loadAll() hiddenmodules = $hiddenModules" }
val retrieveFlags = PackageManager.MATCH_DISABLED_COMPONENTS or
PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS
val apps = packageManager.getInstalledApplications(retrieveFlags)
.filterNot { hiddenModules.contains(it.packageName) }
.map {
logcat(LogPriority.VERBOSE) { "loadAll() ${it.packageName}" }
packageManager.getPackageInfo(it.packageName, flags)
}
return apps
}
override suspend fun loadHomePackageNames(): Set<String> {
val intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
val pkgs = packageManager.queryIntentActivities(intent, 0)
.map { it.activityInfo.packageName }
logcat(LogPriority.VERBOSE) { "loadHomePackageNames = $pkgs" }
return pkgs.toHashSet()
}
override suspend fun loadCurrentDefaultHomePackageName(): String? {
val res = packageManager.resolveActivity(
Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME),
PackageManager.MATCH_DEFAULT_ONLY,
)
logcat(LogPriority.VERBOSE) { "loadCurrentDefaultHome = ${res?.activityInfo?.applicationInfo?.packageName}" }
return res?.activityInfo?.applicationInfo?.packageName
}
override fun loadLabel(applicationInfo: ApplicationInfo): String {
return applicationInfo.loadLabel(packageManager).toString()
}
override fun loadIcon(applicationInfo: ApplicationInfo): Drawable {
return applicationInfo.loadIcon(packageManager)
}
override val systemPackage: PackageInfo? by lazy {
try {
packageManager.getPackageInfo("android", flags)
} catch (t: Throwable) {
logcat(LogPriority.VERBOSE) { "mSystemPackageInfo: $t" }
null
}
}
override val permissionControllerPackageName: String? by lazy {
if (Build.VERSION_CODES.N <= Build.VERSION.SDK_INT) {
try {
val v = PackageManager::class.declaredMemberFunctions.firstOrNull {
it.name == "getPermissionControllerPackageName"
}?.call(packageManager) as? String
logcat(LogPriority.VERBOSE) { "permissionControllerPackageName = $v" }
return@lazy v
} catch (t: Throwable) {
logcat(LogPriority.VERBOSE) { "permissionControllerPackageName: $t" }
}
}
return@lazy null
}
override val servicesSystemSharedLibraryPackageName: String? by lazy {
if (Build.VERSION_CODES.N <= Build.VERSION.SDK_INT) {
try {
val v = PackageManager::class.declaredMemberFunctions.firstOrNull {
it.name == "getServicesSystemSharedLibraryPackageName"
}?.call(packageManager) as? String
logcat(LogPriority.VERBOSE) { "servicesSystemSharedLibraryPackageName = $v" }
return@lazy v
} catch (t: Throwable) {
logcat(LogPriority.VERBOSE) { "servicesSystemSharedLibraryPackageName: $t" }
}
}
return@lazy null
}
override val sharedSystemSharedLibraryPackageName: String? by lazy {
if (Build.VERSION_CODES.N <= Build.VERSION.SDK_INT) {
try {
val v = PackageManager::class.declaredMemberFunctions.firstOrNull {
it.name == "getSharedSystemSharedLibraryPackageName"
}?.call(packageManager) as? String
logcat(LogPriority.VERBOSE) { "sharedSystemSharedLibraryPackageName = $v" }
return@lazy v
} catch (t: Throwable) {
logcat(LogPriority.VERBOSE) { "sharedSystemSharedLibraryPackageName: $t" }
}
}
return@lazy null
}
override val printSpoolerPackageName: String? by lazy {
try {
val v = PrintManager::class.staticProperties.firstOrNull {
it.name == "PRINT_SPOOLER_PACKAGE_NAME"
}?.call() as? String
logcat(LogPriority.VERBOSE) { "PRINT_SPOOLER_PACKAGE_NAME = $v" }
return@lazy v ?: "com.android.printspooler"
} catch (t: Throwable) {
logcat(LogPriority.VERBOSE) { "PRINT_SPOOLER_PACKAGE_NAME: $t" }
return@lazy "com.android.printspooler"
}
}
override val deviceProvisioningPackage: String? by lazy {
try {
val r = Resources.getSystem()
val id = r.getIdentifier("config_deviceProvisioningPackage", "string", "android")
val v = r.getString(id)
logcat(LogPriority.VERBOSE) { "deviceProvisioningPackage = $v" }
return@lazy v
} catch (t: Throwable) {
logcat(LogPriority.VERBOSE) { "deviceProvisioningPackage: $t" }
return@lazy null
}
}
}
| apache-2.0 | e86e3fe0583b47154902bae52c87a1c4 | 39.685897 | 218 | 0.636521 | 4.72247 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MoveToSealedMatchingPackageFix.kt | 1 | 9734 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.PackageWrapper
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveHandler
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.isSealed
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.cases.*
import org.jetbrains.kotlin.idea.refactoring.move.getTargetPackageFqName
import org.jetbrains.kotlin.idea.refactoring.move.guessNewFileName
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsHandler
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsHandlerActions
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinAwareMoveFilesOrDirectoriesModel
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinNestedClassesToUpperLevelModel
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinTopLevelDeclarationsModel
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperInterfaces
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor
class MoveToSealedMatchingPackageFix(element: KtTypeReference) : KotlinQuickFixAction<KtTypeReference>(element) {
private val moveHandler =
if (isUnitTestMode()) {
MoveKotlinDeclarationsHandler(MoveKotlinDeclarationsHandlerTestActions())
} else {
MoveKotlinDeclarationsHandler(false)
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeReference = element ?: return
// 'element' references sealed class/interface in extension list
val classToMove = typeReference.parentOfType<KtClass>() ?: return
val defaultTargetDir = typeReference.resolveToDir() ?: return
val parentContext = SimpleDataContext.getProjectContext(project)
val context = SimpleDataContext.getSimpleContext(LangDataKeys.TARGET_PSI_ELEMENT.name, defaultTargetDir, parentContext)
moveHandler.tryToMove(classToMove, project, context, null, editor)
}
private fun KtTypeReference.resolveToDir(): PsiDirectory? {
val ktUserType = typeElement as? KtUserType ?: return null
val ktNameReferenceExpression = ktUserType.referenceExpression as? KtNameReferenceExpression ?: return null
val declDescriptor = ktNameReferenceExpression.resolveMainReferenceToDescriptors().singleOrNull() ?: return null
return declDescriptor.containingDeclaration?.findPsi()?.containingFile?.containingDirectory
}
override fun startInWriteAction(): Boolean {
return false
}
override fun getText(): String {
val typeReference = element ?: return ""
val referencedName = (typeReference.typeElement as? KtUserType)?.referenceExpression?.getReferencedName() ?: return ""
val classToMove = typeReference.parentOfType<KtClass>() ?: return ""
return KotlinBundle.message("fix.move.to.sealed.text", classToMove.nameAsSafeName.asString(), referencedName)
}
override fun getFamilyName(): String {
return KotlinBundle.message("fix.move.to.sealed.family")
}
companion object : KotlinSingleIntentionActionFactory() {
private fun ClassDescriptor.isBinarySealed(): Boolean = isSealed() && this is DeserializedClassDescriptor
override fun createAction(diagnostic: Diagnostic): MoveToSealedMatchingPackageFix? {
val typeReference = diagnostic.psiElement as? KtTypeReference ?: return null
// We cannot suggest moving this class to the binary of his parent
val classDescriptor = typeReference.parentOfType<KtClass>()?.resolveToDescriptorIfAny() ?: return null
if (classDescriptor.getSuperInterfaces().any { it.isBinarySealed() }) return null
if (classDescriptor.getSuperClassNotAny()?.isBinarySealed() == true) return null
return MoveToSealedMatchingPackageFix(typeReference)
}
}
}
private class MoveKotlinDeclarationsHandlerTestActions : MoveKotlinDeclarationsHandlerActions {
override fun invokeMoveKotlinTopLevelDeclarationsRefactoring(
project: Project,
elementsToMove: Set<KtNamedDeclaration>,
targetPackageName: String,
targetDirectory: PsiDirectory?,
targetFile: KtFile?,
freezeTargets: Boolean,
moveToPackage: Boolean,
moveCallback: MoveCallback?
) {
val sourceFiles = getSourceFiles(elementsToMove)
val targetFilePath =
targetFile?.virtualFile?.path ?: (sourceFiles[0].virtualFile.parent.path + "/" + guessNewFileName(elementsToMove))
val model = MoveKotlinTopLevelDeclarationsModel(
project = project,
elementsToMove = elementsToMove.toList(),
targetPackage = targetPackageName,
selectedPsiDirectory = targetDirectory,
fileNameInPackage = "Derived.kt",
targetFilePath = targetFilePath,
isMoveToPackage = true,
isSearchReferences = false,
isSearchInComments = false,
isSearchInNonJavaFiles = false,
isDeleteEmptyFiles = false,
applyMPPDeclarations = false,
moveCallback = null
)
model.computeModelResult(throwOnConflicts = true).processor.run()
}
private fun getSourceFiles(elementsToMove: Collection<KtNamedDeclaration>): List<KtFile> {
return elementsToMove.map { obj: KtPureElement -> obj.containingKtFile }
.distinct()
}
override fun invokeKotlinSelectNestedClassChooser(nestedClass: KtClassOrObject, targetContainer: PsiElement?) =
doWithMoveKotlinNestedClassesToUpperLevelModel(nestedClass, targetContainer)
private fun doWithMoveKotlinNestedClassesToUpperLevelModel(nestedClass: KtClassOrObject, targetContainer: PsiElement?) {
val outerClass = nestedClass.containingClassOrObject ?: throw FailedToRunCaseException()
val newTarget = targetContainer
?: outerClass.containingClassOrObject
?: outerClass.containingFile.let { it.containingDirectory ?: it }
val packageName = getTargetPackageFqName(newTarget)?.asString() ?: ""
val model = object : MoveKotlinNestedClassesToUpperLevelModel(
project = nestedClass.project,
innerClass = nestedClass,
target = newTarget,
parameter = "",
className = nestedClass.name ?: "",
passOuterClass = false,
searchInComments = false,
isSearchInNonJavaFiles = false,
packageName = packageName,
isOpenInEditor = false
) {
override fun chooseSourceRoot(
newPackage: PackageWrapper,
contentSourceRoots: List<VirtualFile>,
initialDir: PsiDirectory?
) = contentSourceRoots.firstOrNull()
}
model.computeModelResult(throwOnConflicts = true).processor.run()
}
override fun invokeKotlinAwareMoveFilesOrDirectoriesRefactoring(
project: Project,
initialDirectory: PsiDirectory?,
elements: List<PsiFileSystemItem>,
moveCallback: MoveCallback?
) {
val targetPath =
initialDirectory?.virtualFile?.path
?: elements.firstOrNull()?.containingFile?.virtualFile?.path
?: throw NotImplementedError()
val model = KotlinAwareMoveFilesOrDirectoriesModel(
project = project,
elementsToMove = elements,
targetDirectoryName = randomDirectoryPathMutator(targetPath),
updatePackageDirective = randomBoolean(),
searchReferences = randomBoolean(),
moveCallback = null
)
project.executeCommand(MoveHandler.getRefactoringName()) {
model.computeModelResult().processor.run()
}
}
override fun showErrorHint(project: Project, editor: Editor?, message: String, title: String, helpId: String?) =
throw NotImplementedError()
override fun invokeMoveKotlinNestedClassesRefactoring(
project: Project,
elementsToMove: List<KtClassOrObject>,
originalClass: KtClassOrObject,
targetClass: KtClassOrObject,
moveCallback: MoveCallback?
) = throw NotImplementedError()
} | apache-2.0 | 81e4962d6f47c236ae5458798c560117 | 44.919811 | 158 | 0.731868 | 5.66919 | false | false | false | false |
mdaniel/intellij-community | python/src/com/jetbrains/python/debugger/PySetNextStatementAction.kt | 2 | 3339 | // 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.jetbrains.python.debugger
import com.intellij.codeInsight.hint.HintManager
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pair
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.impl.DebuggerSupport
import com.intellij.xdebugger.impl.XDebuggerUtilImpl
import com.intellij.xdebugger.impl.actions.XDebuggerActionBase
import com.intellij.xdebugger.impl.actions.XDebuggerSuspendedActionHandler
import com.jetbrains.python.debugger.pydev.PyDebugCallback
class PySetNextStatementAction : XDebuggerActionBase(true) {
private val setNextStatementActionHandler: XDebuggerSuspendedActionHandler
init {
setNextStatementActionHandler = object : XDebuggerSuspendedActionHandler() {
override fun perform(session: XDebugSession, dataContext: DataContext) {
val debugProcess = session.debugProcess as? PyDebugProcess ?: return
val position = XDebuggerUtilImpl.getCaretPosition(session.project, dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(dataContext) ?: FileEditorManager.getInstance(session.project).selectedTextEditor
val suspendContext = debugProcess.session.suspendContext
ApplicationManager.getApplication().executeOnPooledThread(Runnable {
debugProcess.startSetNextStatement(suspendContext, position, object : PyDebugCallback<Pair<Boolean, String>> {
override fun ok(response: Pair<Boolean, String>) {
if (!response.first && editor != null) {
ApplicationManager.getApplication().invokeLater(Runnable {
if (!editor.isDisposed) {
editor.caretModel.moveToOffset(position.offset)
HintManager.getInstance().showErrorHint(editor, response.second) // NON-NLS
}
}, ModalityState.defaultModalityState())
}
}
override fun error(e: PyDebuggerException) {
LOG.error(e)
}
})
})
}
override fun isEnabled(project: Project, event: AnActionEvent): Boolean {
return super.isEnabled(project, event) && PyDebugSupportUtils.isCurrentPythonDebugProcess(event)
}
}
}
override fun getHandler(debuggerSupport: DebuggerSupport): XDebuggerSuspendedActionHandler = setNextStatementActionHandler
override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun isHidden(event: AnActionEvent): Boolean {
val project = event.getData(CommonDataKeys.PROJECT)
return project == null || !PyDebugSupportUtils.isCurrentPythonDebugProcess(event)
}
companion object {
private val LOG = Logger.getInstance(PySetNextStatementAction::class.java)
}
}
| apache-2.0 | b166ada9de3390ccb789b39082b67ced | 46.7 | 158 | 0.75292 | 5.200935 | false | false | false | false |
micolous/metrodroid | src/iOSMain/kotlin/au/id/micolous/metrodroid/time/Timestamp.kt | 1 | 5826 | /*
* Timestamp.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.time
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.util.TripObfuscator
import platform.Foundation.*
import kotlin.native.concurrent.SharedImmutable
fun date2Timestamp(date: NSDate): TimestampFull {
val t = (date.timeIntervalSince1970 * 1000).toLong()
val tz = NSTimeZone.defaultTimeZone.name
return TimestampFull(timeInMillis = t, tz = MetroTimeZone(tz))
}
internal actual fun makeNow(): TimestampFull = date2Timestamp(NSDate())
/** Reference to UTC timezone. */
@SharedImmutable
private val UTC : NSTimeZone = NSTimeZone.timeZoneForSecondsFromGMT(0)
// Currently empty but there are few time zones that may need mapping in
// the future like e.g. America/Buenos_Aires
@SharedImmutable
private val tzOverrides = mapOf<String,String>()
private fun metroTz2NS(tz: MetroTimeZone): NSTimeZone {
if (tz == MetroTimeZone.LOCAL)
return NSTimeZone.defaultTimeZone
if (tz == MetroTimeZone.UTC || tz == MetroTimeZone.UNKNOWN)
return UTC
val tzMapped = tzOverrides[tz.olson] ?: tz.olson
val nstz = NSTimeZone.timeZoneWithName(tzName = tzMapped)
if (nstz != null) {
return nstz
}
Log.e("metroTz2NS", "Unable to find timezone ${tz.olson}. Using UTC as fallback but it's likely to result in wrong timestamps")
return UTC
}
internal actual fun epochDayHourMinToMillis(tz: MetroTimeZone, daysSinceEpoch: Int, hour: Int, min: Int): Long {
val dateComponents = NSDateComponents()
val ymd = getYMD(daysSinceEpoch)
val nstz = metroTz2NS(tz)
dateComponents.day = ymd.day.toLong()
dateComponents.month = ymd.month.oneBasedIndex.toLong()
dateComponents.year = ymd.year.toLong()
dateComponents.hour = hour.toLong()
dateComponents.minute = min.toLong()
dateComponents.second = 0.toLong()
dateComponents.nanosecond = 0.toLong()
dateComponents.timeZone = nstz
val gregorianCalendar = NSCalendar(calendarIdentifier = NSCalendarIdentifierGregorian)
gregorianCalendar.timeZone = nstz
val date = gregorianCalendar.dateFromComponents(dateComponents)
return (date!!.timeIntervalSince1970 * 1000).toLong()
}
internal actual fun getDaysFromMillis(millis: Long, tz: MetroTimeZone): DHM {
val nstz = metroTz2NS(tz)
val cal = NSCalendar(calendarIdentifier = NSCalendarIdentifierGregorian)
cal.timeZone = nstz
val d = NSDate.dateWithTimeIntervalSince1970(millis / 1000.0)
val comp = cal.componentsInTimeZone(nstz, fromDate = d)
return DHM(days = YMD(
year = comp.year.toInt(),
month = comp.month.toInt() - 1,
day = comp.day.toInt()).daysSinceEpoch,
hour = comp.hour.toInt(),
min = comp.minute.toInt())
}
actual object TimestampFormatter {
// Equivalent of java Calendar to avoid restructuring the code
data class Calendar(val time: NSDate, val tz: NSTimeZone)
fun makeCalendar(ts: TimestampFull): Calendar = makeRawCalendar(ts.adjust())
private fun makeRawCalendar(ts: TimestampFull): Calendar = Calendar (
time = NSDate.dateWithTimeIntervalSince1970(ts.timeInMillis / 1000.0),
tz = metroTz2NS(ts.tz))
actual fun longDateFormat(ts: Timestamp) = FormattedString(longDateFormat(makeDateCalendar(ts)))
private fun makeDateCalendar(ts: Timestamp): Calendar =
when (ts) {
is TimestampFull -> makeCalendar(ts)
is Daystamp -> {
val adjusted = TripObfuscator.maybeObfuscateTS(ts.adjust())
Calendar (
time = NSDate.dateWithTimeIntervalSince1970(adjusted.daysSinceEpoch * 86400.0),
tz = UTC)
}
}
actual fun dateTimeFormat(ts: TimestampFull) = FormattedString(dateTimeFormat(makeCalendar(ts)))
fun dateFormat(ts: Timestamp) = FormattedString(dateFormat(makeDateCalendar(ts)))
actual fun timeFormat(ts: TimestampFull) = FormattedString(timeFormat(makeDateCalendar(ts)))
private fun formatCalendar(dateStyle: NSDateFormatterStyle,
timeStyle: NSDateFormatterStyle, c: Calendar): String {
val dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
dateFormatter.timeZone = c.tz
return dateFormatter.stringFromDate(c.time)
}
private fun longDateFormat(date: Calendar?): String {
return formatCalendar(NSDateFormatterMediumStyle, NSDateFormatterNoStyle,
date ?: return "")
}
private fun dateFormat(date: Calendar?): String {
return formatCalendar(NSDateFormatterShortStyle, NSDateFormatterNoStyle,
date ?: return "")
}
private fun timeFormat(date: Calendar?): String {
return formatCalendar(NSDateFormatterNoStyle, NSDateFormatterShortStyle,
date ?: return "")
}
private fun dateTimeFormat(date: Calendar?): String {
return formatCalendar(NSDateFormatterShortStyle, NSDateFormatterShortStyle,
date ?: return "")
}
}
| gpl-3.0 | 0f344fa4c185ecd872471f2d8b0a3a84 | 38.632653 | 131 | 0.705973 | 4.17934 | false | false | false | false |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/schedule/ScheduleService.kt | 1 | 4075 | package net.squanchy.schedule
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import io.reactivex.functions.Function3
import net.squanchy.schedule.domain.view.Event
import net.squanchy.schedule.domain.view.Schedule
import net.squanchy.schedule.domain.view.SchedulePage
import net.squanchy.schedule.domain.view.Track
import net.squanchy.schedule.tracksfilter.TracksFilter
import net.squanchy.service.firebase.FirestoreDbService
import net.squanchy.service.firebase.model.schedule.FirestoreEvent
import net.squanchy.service.firebase.model.schedule.FirestoreFavorite
import net.squanchy.service.firebase.model.schedule.FirestoreSchedulePage
import net.squanchy.service.firebase.toEvent
import net.squanchy.service.repository.AuthService
import net.squanchy.support.checksum.Checksum
import net.squanchy.support.time.toLocalDate
import org.threeten.bp.ZoneId
interface ScheduleService {
fun schedule(): Observable<Schedule>
}
class FirestoreScheduleService(
private val authService: AuthService,
private val dbService: FirestoreDbService,
private val tracksFilter: TracksFilter,
private val checksum: Checksum
) : ScheduleService {
override fun schedule(): Observable<Schedule> {
val filteredDbSchedulePages = dbService.scheduleView()
.filterByTracks(tracksFilter.selectedTracks)
val domainSchedulePages = Observable.combineLatest(
filteredDbSchedulePages,
dbService.timezone(),
authService.ifUserSignedInThenObservableFrom(dbService::favorites),
toSortedDomainSchedulePages()
)
return Observable.combineLatest(domainSchedulePages, dbService.timezone(), BiFunction(::Schedule))
}
private fun Observable<List<FirestoreSchedulePage>>.filterByTracks(selectedTracks: Observable<Set<Track>>) =
Observable.combineLatest(
this,
selectedTracks,
BiFunction { pages: List<FirestoreSchedulePage>, tracks: Set<Track> ->
pages.filterPagesEvents { it.hasTrackOrNoTrack(tracks) }
}
)
private fun List<FirestoreSchedulePage>.filterPagesEvents(predicate: (FirestoreEvent) -> Boolean) =
map { it.filterPageEvents(predicate) }
private fun FirestoreSchedulePage.filterPageEvents(predicate: (FirestoreEvent) -> Boolean): FirestoreSchedulePage {
val filteredEvents = events.filter(predicate)
return FirestoreSchedulePage().apply {
events = filteredEvents
day = [email protected]
}
}
private fun FirestoreEvent.hasTrackOrNoTrack(allowedTracks: Set<Track>) =
track?.let { eventTrack -> allowedTracks.any { it.id == eventTrack.id } } ?: true
private fun toSortedDomainSchedulePages() =
Function3<List<FirestoreSchedulePage>, ZoneId, List<FirestoreFavorite>, List<SchedulePage>> { pages, timeZone, favorites ->
pages.toSortedDomainSchedulePages(checksum, timeZone, favorites)
}
private fun List<FirestoreSchedulePage>.toSortedDomainSchedulePages(
checksum: Checksum,
timeZone: ZoneId,
favorites: List<FirestoreFavorite>
) =
map { page -> page.toSortedDomainSchedulePage(checksum, timeZone, favorites) }
.sortedBy(SchedulePage::date)
private fun FirestoreSchedulePage.toSortedDomainSchedulePage(
checksum: Checksum,
timeZone: ZoneId,
favorites: List<FirestoreFavorite>
): SchedulePage = SchedulePage(
day.id,
day.date.toLocalDate(timeZone),
events.map { it.toEvent(checksum, timeZone, favorites) }
.sortedByStartTimeAndRoom()
)
private fun FirestoreEvent.toEvent(checksum: Checksum, timeZone: ZoneId, favorites: List<FirestoreFavorite>) =
this.toEvent(checksum, timeZone, favorites.any { favorite -> favorite.id == this.id })
private fun List<Event>.sortedByStartTimeAndRoom() =
sortedWith(compareBy(
Event::startTime,
{ it.place.orNull()?.position ?: -1 }
))
}
| apache-2.0 | c085ad420a47a4db63089affdce7f25b | 38.95098 | 131 | 0.721718 | 4.625426 | false | false | false | false |
anitaa1990/DeviceInfo-Sample | deviceinfo/src/main/java/com/an/deviceinfo/device/model/Battery.kt | 1 | 1767 | package com.an.deviceinfo.device.model
import android.content.Context
import com.an.deviceinfo.device.DeviceInfo
import org.json.JSONObject
class Battery(context: Context) {
var batteryPercent: Int = 0
var isPhoneCharging: Boolean = false
var batteryHealth: String? = null
var batteryTechnology: String? = null
var batteryTemperature: Float = 0.toFloat()
var batteryVoltage: Int = 0
var chargingSource: String? = null
var isBatteryPresent: Boolean = false
init {
val deviceInfo = DeviceInfo(context)
this.batteryPercent = deviceInfo.batteryPercent
this.isPhoneCharging = deviceInfo.isPhoneCharging
this.batteryHealth = deviceInfo.batteryHealth
this.batteryTechnology = deviceInfo.batteryTechnology
this.batteryTemperature = deviceInfo.batteryTemperature
this.batteryVoltage = deviceInfo.batteryVoltage
this.chargingSource = deviceInfo.chargingSource
this.isBatteryPresent = deviceInfo.isBatteryPresent
}
fun toJSON(): JSONObject? {
try {
val jsonObject = JSONObject()
jsonObject.put("batteryPercent", batteryPercent)
jsonObject.put("isPhoneCharging", isPhoneCharging)
jsonObject.put("batteryHealth", batteryHealth)
jsonObject.put("batteryTechnology", batteryTechnology)
jsonObject.put("batteryTemperature", batteryTemperature.toDouble())
jsonObject.put("batteryVoltage", batteryVoltage)
jsonObject.put("chargingSource", chargingSource)
jsonObject.put("isBatteryPresent", isBatteryPresent)
return jsonObject
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
}
| apache-2.0 | ccf610c5d218dd7beec07285fdd5d00a | 33.647059 | 79 | 0.684776 | 4.935754 | false | false | false | false |
thaapasa/jalkametri-android | app/src/main/java/fi/tuska/jalkametri/MainActivity.kt | 1 | 16905 | package fi.tuska.jalkametri
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.ContextMenu
import android.view.ContextMenu.ContextMenuInfo
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.Transformation
import android.widget.AdapterView.AdapterContextMenuInfo
import android.widget.AdapterView.OnItemClickListener
import android.widget.GridView
import android.widget.TextView
import fi.tuska.jalkametri.Common.ACTIVITY_CODE_ADD_FAVOURITE
import fi.tuska.jalkametri.Common.ACTIVITY_CODE_MODIFY_FAVOURITE
import fi.tuska.jalkametri.Common.ACTIVITY_CODE_SELECT_DRINK
import fi.tuska.jalkametri.Common.DEFAULT_ICON_RES
import fi.tuska.jalkametri.Common.DEVELOPER_FUNCTIONALITY_ENABLED
import fi.tuska.jalkametri.Common.KEY_ORIGINAL
import fi.tuska.jalkametri.Common.KEY_RESULT
import fi.tuska.jalkametri.activity.GUIActivity
import fi.tuska.jalkametri.activity.JalkametriDBActivity
import fi.tuska.jalkametri.activity.fragment.CurrentStatusFragment
import fi.tuska.jalkametri.dao.DrinkStatus
import fi.tuska.jalkametri.dao.DrinkStatus.DrivingState.DrivingMaybe
import fi.tuska.jalkametri.dao.DrinkStatus.DrivingState.DrivingNo
import fi.tuska.jalkametri.dao.DrinkStatus.DrivingState.DrivingOK
import fi.tuska.jalkametri.dao.Favourites
import fi.tuska.jalkametri.dao.History
import fi.tuska.jalkametri.dao.HistoryHelper
import fi.tuska.jalkametri.data.DrinkEvent
import fi.tuska.jalkametri.data.DrinkSelection
import fi.tuska.jalkametri.data.DrinkStatusCalc
import fi.tuska.jalkametri.db.FavouritesDB
import fi.tuska.jalkametri.db.HistoryDB
import fi.tuska.jalkametri.gui.DrinkDetailsDialog
import fi.tuska.jalkametri.gui.NamedIconAdapter
import fi.tuska.jalkametri.task.AlcoholLevelMeter
import fi.tuska.jalkametri.util.AssertionUtils
import fi.tuska.jalkametri.util.DialogUtil
import fi.tuska.jalkametri.util.LocalizationUtil
import fi.tuska.jalkametri.util.LogUtil
import fi.tuska.jalkametri.util.StringUtil
import org.joda.time.Instant
/**
* Main activity class: shows status information and links to other activities.
*
* @author Tuukka Haapasalo
*/
open class MainActivity : JalkametriDBActivity(R.string.app_name, R.string.help_main), GUIActivity {
private var viewModel: ViewModel? = null
fun toastAlcoholStatus(v: View) {
viewModel?.let {
DrinkActivities.makeDrinkToast(this, it.currentStatus.level, false)
}
}
fun showAddDrink(v: View) {
CommonActivities.showAddDrink(this)
}
fun showDrivingStatus(v: View): Unit {
viewModel?.showDrivingStatus(v)
}
override fun onCreate(savedInstanceState: Bundle?) {
LogUtil.i(TAG, "Creating jAlkaMetri application")
LogUtil.d(TAG, "Assertions are %s", if (AssertionUtils.isAssertionsEnabled) "on" else "off")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModel(this).apply {
updateFavourites()
}
}
override fun onStart() {
super.onStart()
updateUI()
if (!prefs.isDisclaimerRead) {
CommonActivities.showDisclaimer(this)
}
// Force widget update, in case widget updating thread is dead
JalkametriWidget.triggerRecalculate(this, db)
}
override fun updateUI() {
viewModel?.updateUI()
}
override fun onSearchRequested(): Boolean {
if (DEVELOPER_FUNCTIONALITY_ENABLED) {
LogUtil.i(TAG, "Showing development menu")
viewModel?.let { openContextMenu(it.developmentView) }
return true
} else {
return super.onSearchRequested()
}
}
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo) {
val viewId = v.id
when (viewId) {
R.id.favourites -> {
// Show the favourites menu
LogUtil.d(TAG, "Showing favourites menu")
val inflater = menuInflater
inflater.inflate(R.menu.favourite_actions, menu)
}
R.id.development_view ->
// Show the development menu
if (DEVELOPER_FUNCTIONALITY_ENABLED) {
LogUtil.d(TAG, "Showing development menu")
val inflater = menuInflater
inflater.inflate(R.menu.menu_developer, menu)
}
else -> super.onCreateContextMenu(menu, v, menuInfo)
}
}
override fun onContextItemSelected(item: MenuItem): Boolean {
val info = item.menuInfo as AdapterContextMenuInfo
when (item.itemId) {
R.id.action_modify -> {
// Modify the selected favorite
viewModel?.favouritesAdapter?.getItem(info.position)?.let { fav ->
LogUtil.d(TAG, "Modifying %s", fav)
DrinkActivities.startModifyDrinkEvent(this, fav, true, true, false, ACTIVITY_CODE_MODIFY_FAVOURITE)
}
return true
}
R.id.action_show_info -> viewModel?.showInfoForSelected(info.position)
R.id.action_delete -> {
// Delete the selected favorite
viewModel?.apply {
favouritesAdapter?.getItem(info.position)?.let { fav ->
LogUtil.d(TAG, "Deleting %s", fav)
favourites.deleteFavourite(fav.index)
updateFavourites()
}
}
return true
}
R.id.action_drink -> {
// Drink the selected favorite
viewModel?.favouritesAdapter?.getItem(info.position)?.let { fav ->
LogUtil.d(TAG, "Drinking %s", fav)
DrinkActivities.startSelectDrinkDetails(this, fav, ACTIVITY_CODE_SELECT_DRINK)
}
return true
}
}
return super.onContextItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
val extras = data?.extras
when (requestCode) {
ACTIVITY_CODE_SELECT_DRINK -> {
run {
val sel = DrinkActivities.getDrinkSelectionFromResult(data)
viewModel?.consumeDrink(sel)
}
return
}
ACTIVITY_CODE_ADD_FAVOURITE -> {
run {
val sel = extras!!.get(KEY_RESULT) as DrinkSelection
viewModel?.apply {
favourites?.createFavourite(sel)
updateFavourites()
LogUtil.d(TAG, "Added %s to favourites", sel)
}
}
return
}
ACTIVITY_CODE_MODIFY_FAVOURITE -> {
run {
val modifications = extras!!.get(KEY_RESULT) as DrinkSelection
val originalID = extras.getLong(KEY_ORIGINAL)
viewModel?.apply {
val event = favourites.getFavourite(originalID)
event.drink = modifications.drink
event.size = modifications.size
favourites.updateFavourite(originalID, event)
updateFavourites()
}
}
return
}
Common.ACTIVITY_CODE_SHOW_PREFERENCES -> {
run {
LogUtil.i(TAG, "Updating locale to %s", prefs.locale)
LocalizationUtil.setLocale(prefs.locale, baseContext)
}
return
}
}
}
}
/*
* Options menu handling --------------------------------------------------
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
val inflater = menuInflater
inflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (super.onOptionsItemSelected(item))
return true
when (item.itemId) {
R.id.action_add_favourite -> {
// Add a favourite
DrinkActivities.startSelectDrink(this, ACTIVITY_CODE_ADD_FAVOURITE)
return true
}
R.id.action_legal -> {
// Show legal disclaimer
CommonActivities.showDisclaimer(this)
return true
}
R.id.action_about -> {
// Show an about screen
CommonActivities.showAbout(this)
return true
}
R.id.action_show_preferences -> {
showPreferences(null)
return true
}
}
return super.onOptionsItemSelected(item)
}
private class ViewModel(val activity: MainActivity) {
val timeUtil = activity.timeUtil
val db = activity.db
val history: History = HistoryDB(db, activity)
val meter: AlcoholLevelMeter = AlcoholLevelMeter(history, activity)
val favourites: Favourites = FavouritesDB(activity.db, activity)
val addFavouritesPrompt = activity.findViewById(R.id.add_favourites_prompt) as TextView
val currentStatus = activity.fragmentManager.findFragmentById(R.id.current_status) as CurrentStatusFragment
val gaugeAnimation = AlcoholLevelAnimation()
val favouritesList: GridView = activity.findViewById(R.id.favourites) as GridView
val developmentView: View = activity.findViewById(R.id.development_view)
var favouritesAdapter: NamedIconAdapter<DrinkEvent>? = null
init {
currentStatus.setAlcoholLevel(0.6, DrivingMaybe)
activity.registerForContextMenu(developmentView)
favouritesList.onItemClickListener = OnItemClickListener { _, _, position, _ ->
favouritesAdapter?.getItem(position)?.let { favorite ->
val sel = DrinkSelection(favorite.drink, favorite.size, Instant.now())
consumeDrink(sel)
}
}
activity.registerForContextMenu(favouritesList)
}
fun updateFavourites() {
val favs = favourites.favourites
LogUtil.d(TAG, "Showing %d favourites", favs.size)
favouritesAdapter = NamedIconAdapter(activity, favs, DEFAULT_ICON_RES)
favouritesList.adapter = favouritesAdapter
JalkametriWidget.triggerRecalculate(activity, db)
LogUtil.d(TAG, "Recalculated widget")
// If favourites list is empty, show the prompt; otherwise, hide it.
addFavouritesPrompt.visibility = if (favs.isEmpty()) View.VISIBLE else View.GONE
}
fun updateUI() {
val status = meter.drinkStatus
val drivingState = status.getDrivingState(activity.prefs)
currentStatus.setAlcoholLevel(status.alcoholLevel, drivingState)
updateDrinkDateText()
currentStatus.updateSobriety(status)
updatePortionsText(status)
}
private fun updatePortionsText(status: DrinkStatus) {
val shownDay = timeUtil.getCurrentDrinkingDate(activity.prefs)
val todayPortions = HistoryHelper.countDayPortions(history, shownDay, activity)
val weekPortions = HistoryHelper.countWeekPortions(history, shownDay, activity)
val totalPortions = history.countTotalPortions()
currentStatus.showPortions(String.format(PORTIONS_FORMAT, todayPortions, weekPortions, totalPortions))
}
private fun updateDrinkDateText() {
val today = timeUtil.getCurrentDrinkingDate(activity.prefs)
currentStatus.showDrinkDate(StringUtil.uppercaseFirstLetter(timeUtil.dateFormatWDay.print(today)))
}
fun showInfoForSelected(position: Int) {
favouritesAdapter?.getItem(position)?.let {
LogUtil.d(TAG, "Showing %s", it)
activity.showCustomDialog(DrinkDetailsDialog.createDialog(it, false))
}
}
fun showDrivingStatus(v: View) {
val res = activity.resources
val status = meter.drinkStatus
when (status.getDrivingState(activity.prefs)) {
DrivingOK -> DialogUtil.showMessage(activity, R.string.drive_status_ok, R.string.title_drive_status)
DrivingMaybe -> {
val messagePat = res.getString(R.string.drive_status_maybe)
val toSober = status.hoursToSober
val soberTime = getTimeAfterHours(toSober)
val toSoberTime = getHoursMsg(toSober)
val message = String.format(messagePat, toSoberTime, soberTime)
DialogUtil.showMessage(activity, message, R.string.title_drive_status)
}
DrivingNo -> {
val messagePat = res.getString(R.string.drive_status_no)
val toDrive = status.getHoursToAlcoholLevel(activity.prefs.drivingAlcoholLimit)
val toSober = status.hoursToSober
val toDriveTime = getHoursMsg(toDrive)
val toSoberTime = getHoursMsg(toSober)
val driveTime = getTimeAfterHours(toDrive)
val soberTime = getTimeAfterHours(toSober)
val message = String.format(messagePat, toDriveTime, driveTime, toSoberTime, soberTime)
DialogUtil.showMessage(activity, message, R.string.title_drive_status)
}
null -> {
}
}
}
fun getTimeAfterHours(afterHours: Double): String {
return timeUtil.timeFormat.print(timeUtil.getTimeAfterHours(afterHours))
}
fun getHoursMsg(hours: Double): String {
val res = activity.resources
if (hours >= 1) {
val fullHours = hours.toInt()
return String.format(res.getString(R.string.hourmin_pat), fullHours, ((hours - fullHours) * 60).toInt())
} else {
return String.format(res.getString(R.string.min_pat), (hours * 60).toInt())
}
}
fun consumeDrink(selection: DrinkSelection?) {
// Get original alcohol level
val orgLevel = currentStatus.level
val orgState = currentStatus.drivingState
// Add drink
history.createDrink(selection)
JalkametriWidget.triggerRecalculate(activity, db)
// Make toast
DrinkActivities.makeDrinkToast(activity, orgLevel, true)
updateUI()
val newLevel = currentStatus.level
// Fall back to old values
currentStatus.setAlcoholLevel(orgLevel, orgState)
// Start animation
gaugeAnimation.showAnimation(orgLevel, newLevel, 0.8)
}
private inner class AlcoholLevelAnimation : Animation() {
private var startAlcoholLevel = 0.0
private var endAlcoholLevel = 0.0
fun showAnimation(oldLevel: Double, newLevel: Double, duration: Double) {
startAlcoholLevel = oldLevel
endAlcoholLevel = newLevel
LogUtil.i(TAG, "Starting animation")
setDuration((duration * 1000L).toLong())
startTime = AnimationUtils.currentAnimationTimeMillis()
repeatCount = 0
currentStatus.startAnimation(this)
}
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
super.applyTransformation(interpolatedTime, t)
val showLevel = (endAlcoholLevel - startAlcoholLevel) * interpolatedTime + startAlcoholLevel
val showState = DrinkStatusCalc.getDrivingState(activity.prefs, showLevel)
LogUtil.d(TAG, "Animating at time %.2f: level %.2f", interpolatedTime, showLevel)
currentStatus.setAlcoholLevel(showLevel, showState)
}
}
}
companion object {
private val TAG = "MainActivity"
private val PORTIONS_FORMAT = "%.1f / %.1f / %.1f"
}
}
| mit | 19ce3e38628d2a9cd737f4eac3510cba | 38.497664 | 120 | 0.603135 | 4.568919 | false | false | false | false |
JavaEden/Orchid-Core | OrchidCore/src/main/kotlin/com/eden/orchid/api/resources/resource/ThumbnailResource.kt | 2 | 4483 | package com.eden.orchid.api.resources.resource
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.theme.assets.AssetPage
import com.eden.orchid.api.resources.thumbnails.Renameable
import com.eden.orchid.api.resources.thumbnails.Resizable
import com.eden.orchid.api.resources.thumbnails.Rotateable
import com.eden.orchid.api.resources.thumbnails.Scalable
import com.eden.orchid.api.theme.permalinks.PermalinkStrategy
import com.eden.orchid.utilities.convertOutputStream
import net.coobird.thumbnailator.Thumbnails
import net.coobird.thumbnailator.geometry.Positions
import org.apache.commons.io.FilenameUtils
import javax.imageio.ImageIO
class ThumbnailResource(
resource: OrchidResource
) : ResourceTransformation(resource),
Rotateable,
Scalable,
Resizable,
Renameable {
override fun rotate(page: AssetPage, angle: Double) {
page.reference.fileName = page.reference.originalFileName + "_rotate-${angle}"
contentStreamTransformations.add { input ->
convertOutputStream(page.context) { safeOs ->
Thumbnails
.of(input)
.rotate(angle)
.scale(1.0)
.outputFormat(reference.outputExtension)
.toOutputStream(safeOs)
}
}
}
override fun scale(page: AssetPage, factor: Double) {
page.reference.fileName = page.reference.originalFileName + "_scale-${factor}"
contentStreamTransformations.add { input ->
convertOutputStream(page.context) { safeOs ->
Thumbnails
.of(input)
.scale(factor)
.outputFormat(reference.outputExtension)
.toOutputStream(safeOs)
}
}
}
override fun resize(page: AssetPage, width: Int, height: Int, mode: Resizable.Mode) {
page.reference.fileName = page.reference.originalFileName + "_${width}x${height}_${mode.name}"
contentStreamTransformations.add { input ->
convertOutputStream(page.context) { safeOs ->
val thumbnailBuilder = Thumbnails.of(input)
when (mode) {
Resizable.Mode.exact -> thumbnailBuilder.forceSize(width, height)
Resizable.Mode.fit -> thumbnailBuilder.size(width, height)
Resizable.Mode.bl -> thumbnailBuilder.size(width, height).crop(Positions.BOTTOM_LEFT)
Resizable.Mode.bc -> thumbnailBuilder.size(width, height).crop(Positions.BOTTOM_CENTER)
Resizable.Mode.br -> thumbnailBuilder.size(width, height).crop(Positions.BOTTOM_RIGHT)
Resizable.Mode.cl -> thumbnailBuilder.size(width, height).crop(Positions.CENTER_LEFT)
Resizable.Mode.c -> thumbnailBuilder.size(width, height).crop(Positions.CENTER)
Resizable.Mode.cr -> thumbnailBuilder.size(width, height).crop(Positions.CENTER_RIGHT)
Resizable.Mode.tl -> thumbnailBuilder.size(width, height).crop(Positions.TOP_LEFT)
Resizable.Mode.tc -> thumbnailBuilder.size(width, height).crop(Positions.TOP_CENTER)
Resizable.Mode.tr -> thumbnailBuilder.size(width, height).crop(Positions.TOP_RIGHT)
}
thumbnailBuilder.outputFormat(reference.outputExtension)
thumbnailBuilder.toOutputStream(safeOs)
}
}
}
override fun rename(
page: AssetPage,
permalinkStrategy: PermalinkStrategy,
permalink: String,
usePrettyUrl: Boolean
) {
val originalExtension = page.reference.outputExtension
val newExtension = FilenameUtils.getExtension(permalink)
permalinkStrategy.applyPermalink(page, permalink, usePrettyUrl)
if (newExtension.isNotBlank() && newExtension != originalExtension) {
contentStreamTransformations.add { input ->
if (ImageIO.getWriterFormatNames().any { it == newExtension }) {
convertOutputStream(page.context) { safeOs ->
Thumbnails
.of(input)
.scale(1.0)
.outputFormat(newExtension)
.toOutputStream(safeOs)
}
} else {
input
}
}
}
}
}
| mit | 51b4e53023d7746e5d2e5a6b9456a8c0 | 42.524272 | 107 | 0.613875 | 4.759023 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/navbar/actions/DefaultNavBarItemDataRule.kt | 2 | 2471 | // 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.navbar.actions
import com.intellij.ide.impl.dataRules.GetDataRule
import com.intellij.ide.navbar.NavBarItem
import com.intellij.ide.navbar.NavBarItemProvider
import com.intellij.ide.navbar.impl.*
import com.intellij.openapi.actionSystem.CommonDataKeys.*
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.MODULE
import com.intellij.openapi.module.ModuleType
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiUtilCore
internal class DefaultNavBarItemDataRule : GetDataRule {
override fun getData(dataProvider: DataProvider): NavBarItem? {
val ctx = DataContext { dataId -> dataProvider.getData(dataId) }
// leaf element -- either from old EP impls or default one
// owner -- EP extension provided the leaf (if any)
val (leaf, owner) = fromOldExtensions { ext -> ext.getLeafElement(ctx)?.let { it to ext } }
?: fromDataContext(ctx)?.let { Pair(it, null) }
?: return null
if (leaf.isValid) {
return PsiNavBarItem(leaf, owner)
}
else {
// Narrow down the root element to the first interesting one
MODULE.getData(ctx)
?.takeUnless { ModuleType.isInternal(it) }
?.let { return ModuleNavBarItem(it) }
val projectItem = PROJECT.getData(ctx)
?.let(::ProjectNavBarItem)
?: return null
val childItem = NavBarItemProvider.EP_NAME
.extensionList.asSequence()
.flatMap { ext -> ext.iterateChildren(projectItem) }
.firstOrNull()
?: return projectItem
val grandChildItem = NavBarItemProvider.EP_NAME
.extensionList.asSequence()
.flatMap { ext -> ext.iterateChildren(childItem) }
.firstOrNull()
?: return childItem
return grandChildItem
}
}
private fun fromDataContext(ctx: DataContext): PsiElement? {
val element = PSI_FILE.getData(ctx)
?: PsiUtilCore.findFileSystemItem(PROJECT.getData(ctx), VIRTUAL_FILE.getData(ctx))
return adjustWithAllExtensions(element)
}
}
| apache-2.0 | 40b92871202d50a7ea48a4a721375bfc | 38.222222 | 120 | 0.649535 | 4.706667 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/data/timer/TimerViewModel.kt | 1 | 1487 | package org.dvbviewer.controller.data.timer
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.dvbviewer.controller.data.api.ApiResponse
import org.dvbviewer.controller.data.entities.Timer
class TimerViewModel internal constructor(private val mRepository: TimerRepository) : ViewModel() {
private val data: MutableLiveData<ApiResponse<List<Timer>>> = MutableLiveData()
fun getTimerList(force: Boolean = false): MutableLiveData<ApiResponse<List<Timer>>> {
if (data.value == null || force) {
fetchTimerList()
}
return data
}
private fun fetchTimerList() {
viewModelScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT) {
var apiResponse: ApiResponse<List<Timer>> = ApiResponse.error(null, null)
async(Dispatchers.Default) {
apiResponse = try {
ApiResponse.success(mRepository.getTimer())
} catch (e: Exception) {
Log.e(TAG, "Error getting timer list", e)
ApiResponse.error(e, null)
}
}.await()
data.value = apiResponse
}
}
companion object {
private const val TAG = "TimerViewModel"
}
} | apache-2.0 | d9f5150dd4a75af84dd69926f9787a3d | 30 | 99 | 0.666443 | 4.87541 | false | false | false | false |
ktorio/ktor | ktor-shared/ktor-events/common/src/io/ktor/events/Events.kt | 1 | 2844 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.events
import io.ktor.util.*
import io.ktor.util.collections.*
import kotlinx.coroutines.*
import kotlinx.coroutines.internal.*
@OptIn(InternalAPI::class)
public class Events {
@OptIn(InternalCoroutinesApi::class)
private val handlers = CopyOnWriteHashMap<EventDefinition<*>, LockFreeLinkedListHead>()
/**
* Subscribe [handler] to an event specified by [definition]
*/
public fun <T> subscribe(definition: EventDefinition<T>, handler: EventHandler<T>): DisposableHandle {
val registration = HandlerRegistration(handler)
@OptIn(InternalCoroutinesApi::class)
handlers.computeIfAbsent(definition) { LockFreeLinkedListHead() }.addLast(registration)
return registration
}
/**
* Unsubscribe [handler] from an event specified by [definition]
*/
public fun <T> unsubscribe(definition: EventDefinition<T>, handler: EventHandler<T>) {
@OptIn(InternalCoroutinesApi::class)
handlers[definition]?.forEach<HandlerRegistration> {
if (it.handler == handler) it.remove()
}
}
/**
* Raises the event specified by [definition] with the [value] and calls all handlers.
*
* Handlers are called in order of subscriptions.
* If some handler throws an exception, all remaining handlers will still run. The exception will eventually be re-thrown.
*/
public fun <T> raise(definition: EventDefinition<T>, value: T) {
var exception: Throwable? = null
handlers[definition]?.forEach<HandlerRegistration> { registration ->
try {
@Suppress("UNCHECKED_CAST")
(registration.handler as EventHandler<T>)(value)
} catch (e: Throwable) {
exception?.addSuppressed(e) ?: run { exception = e }
}
}
exception?.let { throw it }
}
@OptIn(InternalCoroutinesApi::class)
private class HandlerRegistration(val handler: EventHandler<*>) : LockFreeLinkedListNode(), DisposableHandle {
override fun dispose() {
remove()
}
}
}
/**
* Specifies signature for the event handler
*/
public typealias EventHandler<T> = (T) -> Unit
// TODO: make two things: definition that is kept private to subsystem, and declaration which is public.
// Invoke only by definition, subscribe by declaration
/**
* Definition of an event.
* Event is used as a key so both [hashCode] and [equals] need to be implemented properly.
* Inheriting of this class is an experimental feature.
* Instantiate directly if inheritance not necessary.
*
* @param T specifies what is a type of a value passed to the event
*/
public open class EventDefinition<T>
| apache-2.0 | edc18bb0ca18a170028676dac28833bd | 34.55 | 126 | 0.675105 | 4.62439 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/SourceController.kt | 1 | 9341 | package eu.kanade.tachiyomi.ui.browse.source
import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.ControllerChangeType
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dev.chrisbanes.insetter.applyInsetter
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.IFlexible
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.databinding.SourceMainControllerBinding
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.ui.base.controller.SearchableNucleusController
import eu.kanade.tachiyomi.ui.base.controller.requestPermissionsSafe
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.browse.BrowseController
import eu.kanade.tachiyomi.ui.browse.source.browse.BrowseSourceController
import eu.kanade.tachiyomi.ui.browse.source.globalsearch.GlobalSearchController
import eu.kanade.tachiyomi.ui.browse.source.latest.LatestUpdatesController
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.util.preference.minusAssign
import eu.kanade.tachiyomi.util.preference.plusAssign
import eu.kanade.tachiyomi.util.view.onAnimationsFinished
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
/**
* This controller shows and manages the different catalogues enabled by the user.
* This controller should only handle UI actions, IO actions should be done by [SourcePresenter]
* [SourceAdapter.OnSourceClickListener] call function data on browse item click.
* [SourceAdapter.OnLatestClickListener] call function data on latest item click
*/
class SourceController :
SearchableNucleusController<SourceMainControllerBinding, SourcePresenter>(),
FlexibleAdapter.OnItemClickListener,
FlexibleAdapter.OnItemLongClickListener,
SourceAdapter.OnSourceClickListener {
private val preferences: PreferencesHelper = Injekt.get()
/**
* Adapter containing sources.
*/
private var adapter: SourceAdapter? = null
init {
setHasOptionsMenu(true)
}
override fun getTitle(): String? {
return applicationContext?.getString(R.string.label_sources)
}
override fun createPresenter(): SourcePresenter {
return SourcePresenter()
}
override fun createBinding(inflater: LayoutInflater) = SourceMainControllerBinding.inflate(inflater)
override fun onViewCreated(view: View) {
super.onViewCreated(view)
binding.recycler.applyInsetter {
type(navigationBars = true) {
padding()
}
}
adapter = SourceAdapter(this)
// Create recycler and set adapter.
binding.recycler.layoutManager = LinearLayoutManager(view.context)
binding.recycler.adapter = adapter
binding.recycler.onAnimationsFinished {
(activity as? MainActivity)?.ready = true
}
adapter?.fastScroller = binding.fastScroller
requestPermissionsSafe(arrayOf(WRITE_EXTERNAL_STORAGE), 301)
// Update list on extension changes (e.g. new installation)
(parentController as BrowseController).extensionListUpdateRelay
.skip(1) // Skip first update when ExtensionController created
.subscribeUntilDestroy {
presenter.updateSources()
}
}
override fun onDestroyView(view: View) {
adapter = null
super.onDestroyView(view)
}
override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) {
super.onChangeStarted(handler, type)
if (type.isPush) {
presenter.updateSources()
}
}
override fun onItemClick(view: View, position: Int): Boolean {
onItemClick(position)
return false
}
private fun onItemClick(position: Int) {
val item = adapter?.getItem(position) as? SourceItem ?: return
val source = item.source
openSource(source, BrowseSourceController(source))
}
override fun onItemLongClick(position: Int) {
val activity = activity ?: return
val item = adapter?.getItem(position) as? SourceItem ?: return
val isPinned = item.header?.code?.equals(SourcePresenter.PINNED_KEY) ?: false
val items = mutableListOf(
Pair(
activity.getString(if (isPinned) R.string.action_unpin else R.string.action_pin),
{ toggleSourcePin(item.source) }
)
)
if (item.source !is LocalSource) {
items.add(
Pair(
activity.getString(R.string.action_disable),
{ disableSource(item.source) }
)
)
}
SourceOptionsDialog(item.source.toString(), items).showDialog(router)
}
private fun disableSource(source: Source) {
preferences.disabledSources() += source.id.toString()
presenter.updateSources()
}
private fun toggleSourcePin(source: Source) {
val isPinned = source.id.toString() in preferences.pinnedSources().get()
if (isPinned) {
preferences.pinnedSources() -= source.id.toString()
} else {
preferences.pinnedSources() += source.id.toString()
}
presenter.updateSources()
}
/**
* Called when browse is clicked in [SourceAdapter]
*/
override fun onBrowseClick(position: Int) {
onItemClick(position)
}
/**
* Called when latest is clicked in [SourceAdapter]
*/
override fun onLatestClick(position: Int) {
val item = adapter?.getItem(position) as? SourceItem ?: return
openSource(item.source, LatestUpdatesController(item.source))
}
/**
* Called when pin icon is clicked in [SourceAdapter]
*/
override fun onPinClick(position: Int) {
val item = adapter?.getItem(position) as? SourceItem ?: return
toggleSourcePin(item.source)
}
/**
* Opens a catalogue with the given controller.
*/
private fun openSource(source: CatalogueSource, controller: BrowseSourceController) {
if (!preferences.incognitoMode().get()) {
preferences.lastUsedSource().set(source.id)
}
parentController!!.router.pushController(controller.withFadeTransaction())
}
/**
* Called when an option menu item has been selected by the user.
*
* @param item The selected item.
* @return True if this event has been consumed, false if it has not.
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// Initialize option to open catalogue settings.
R.id.action_settings -> {
parentController!!.router.pushController(
SourceFilterController()
.withFadeTransaction()
)
}
}
return super.onOptionsItemSelected(item)
}
/**
* Called to update adapter containing sources.
*/
fun setSources(sources: List<IFlexible<*>>) {
adapter?.updateDataSet(sources)
}
/**
* Called to set the last used catalogue at the top of the view.
*/
fun setLastUsedSource(item: SourceItem?) {
adapter?.removeAllScrollableHeaders()
if (item != null) {
adapter?.addScrollableHeader(item)
adapter?.addScrollableHeader(LangItem(SourcePresenter.LAST_USED_KEY))
}
}
class SourceOptionsDialog(bundle: Bundle? = null) : DialogController(bundle) {
private lateinit var source: String
private lateinit var items: List<Pair<String, () -> Unit>>
constructor(source: String, items: List<Pair<String, () -> Unit>>) : this() {
this.source = source
this.items = items
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
return MaterialAlertDialogBuilder(activity!!)
.setTitle(source)
.setItems(items.map { it.first }.toTypedArray()) { dialog, which ->
items[which].second()
dialog.dismiss()
}
.create()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
createOptionsMenu(
menu,
inflater,
R.menu.browse_sources,
R.id.action_search,
R.string.action_global_search_hint,
false // GlobalSearch handles the searching here
)
}
override fun onSearchViewQueryTextSubmit(query: String?) {
parentController!!.router.pushController(
GlobalSearchController(query).withFadeTransaction()
)
}
}
| apache-2.0 | 49c4f7a6601fa485474f4c1652055d33 | 33.341912 | 104 | 0.668879 | 4.852468 | false | false | false | false |
emanuelpalm/palm-compute | core/src/main/java/se/ltu/emapal/compute/util/Result.kt | 1 | 3400 | package se.ltu.emapal.compute.util
/**
* Data type used for error handling.
*
* In places where it is expected that functions fail frequently, it may be inappropriate to use
* regular exceptions, as these are easy to ignore and are expensive in terms of performance. The
* [Result] type is constructed either as a success, wrapping an arbitrary value, or a failure,
* wrapping an arbitrary error, and can later be destructed using a when expression.
*/
sealed class Result<T, E : Throwable> {
/** A successful result. */
class Success<T, E : Throwable>(val value: T) : Result<T, E>() {
override fun <U> apply(f: (T) -> Result<U, E>) = f(value)
override fun <F : Throwable> applyError(f: (E) -> Result<T, F>) = Result.Success<T, F>(value)
override fun <U> map(f: (T) -> U) = Result.Success<U, E>(f(value))
override fun <F : Throwable> mapError(f: (E) -> F) = Result.Success<T, F>(value)
override fun unwrap() = value
override fun ifValue(f: (T) -> Unit) = f(value)
override fun ifError(f: (E) -> Unit) = Unit
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other?.javaClass != javaClass) {
return false
}
other as Success<*, *>
return value == other.value
}
override fun hashCode() = value?.hashCode() ?: 0
override fun toString() = "Result.Success(value=$value)"
}
/** A failed result. */
class Failure<T, E : Throwable>(val error: E) : Result<T, E>() {
override fun <U> apply(f: (T) -> Result<U, E>) = Result.Failure<U, E>(error)
override fun <F : Throwable> applyError(f: (E) -> Result<T, F>) = f(error)
override fun <U> map(f: (T) -> U) = Result.Failure<U, E>(error)
override fun <F : Throwable> mapError(f: (E) -> F) = Result.Failure<T, F>(f(error))
override fun unwrap() = throw error
override fun ifValue(f: (T) -> Unit) = Unit
override fun ifError(f: (E) -> Unit) = f(error)
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other?.javaClass != javaClass) {
return false
}
other as Failure<*, *>
return error == other.error
}
override fun hashCode() = error.hashCode()
override fun toString() = "Result.Failure(error=$error)"
}
/** Applies function [f] to value, if a value is available. */
abstract fun <U> apply(f: (T) -> Result<U, E>): Result<U, E>
/** Applies function [f] to error, if an error is available. */
abstract fun <F : Throwable> applyError(f: (E) -> Result<T, F>): Result<T, F>
/** Maps function [f] to value, if a value is available. */
abstract fun <U> map(f: (T) -> U): Result<U, E>
/** Maps function [f] to error, if an error is available. */
abstract fun <F : Throwable> mapError(f: (E) -> F): Result<T, F>
/** Unwraps result, causing either its value to be returned, or error to be thrown. */
abstract fun unwrap(): T
/** Executes provided function only if value is available. */
abstract fun ifValue(f: (T) -> Unit)
/** Executes provided function only if error is available. */
abstract fun ifError(f: (E) -> Unit)
} | mit | 9dbdc630e1a057e8ac152a6afe561066 | 40.47561 | 101 | 0.575294 | 3.719912 | false | false | false | false |
adrianswiatek/numbers-teacher | NumbersTeacher/app/src/main/java/pl/aswiatek/numbersteacher/businesslogic/AnswerState.kt | 1 | 928 | package pl.aswiatek.numbersteacher.businesslogic
import android.os.Bundle
import pl.aswiatek.numbersteacher.listener.StateChangedListener
data class AnswerState(private val stateChangedListener: StateChangedListener) {
var question: Int = 0
get() = field
set(value) {
field = value
stateChangedListener.onQuestionChanged()
}
var answer: Int = 0
get() = field
set(value) {
field = value
stateChangedListener.onAnswerChanged()
}
fun getFormattedQuestion(radix: Int) = question.toString(radix).toUpperCase()
fun getFormattedAnswer(radix: Int) = answer.toString(radix).toUpperCase()
fun putTo(bundle: Bundle) {
bundle.putInt(QUESTION, question)
bundle.putInt(ANSWER, answer)
}
companion object {
private val QUESTION = "QUESTION"
private val ANSWER = "ANSWER"
}
}
| mit | e7e25cfd0a6c4f125c98799d0736d290 | 25.514286 | 81 | 0.648707 | 4.54902 | false | false | false | false |
pureal-code/pureal-os | tests.traits/src/net/pureal/tests/traits/Transform2Specs.kt | 1 | 2420 | package net.pureal.tests.traits
import org.jetbrains.spek.api.*
import net.pureal.traits.*
class Transform2Specs : Spek() {init {
given("an identity transform") {
val t = Transforms2.identity
on("applying it on a vector") {
val applied = t(vector(1.4, -11))
it("should be unchanged") {
shouldEqual(vector(1.4, -11), applied)
}
}
}
given("a translation") {
val t = Transforms2.translation(vector(2, -3))
on("applying it on a vector") {
val applied = t(vector(1, 3))
it("should be translated accordingly") {
shouldEqual(vector(3, 0), applied)
}
}
}
given("a rotation") {
val t = Transforms2.rotation(Math.PI / 2)
on("applying it on a vector") {
val x = t(vector(1, 3))
it("should be rotated accordingly") {
shouldEqualWithError(vector(-3, 1), x)
}
}
}
given("a scale") {
val t = Transforms2.scale(-2)
on("applying it on a vector") {
val applied = t(vector(1, 3))
it("should be scaled accordingly") {
shouldEqual(vector(-2, -6), applied)
}
}
}
given("a reflection") {
val t = Transforms2.reflection(axisAngle = 10 * Math.PI)
on("applying it on a vector") {
val applied = t(vector(1, 3))
it("should be reflected accordingly") {
shouldEqualWithError(vector(1, -3), applied)
}
}
}
given("an arbitrary affine transformation") {
val t = transform(matrix(-4, 3, 5, 0, 4, -0.5, 1, 0, 6))
on("getting the string representation") {
val x = t.toString()
it("should be correct") {
shouldEqual("transform(matrix(-4.0, 3.0, 5.0, 0.0, 4.0, -0.5, 1.0, 0.0, 6.0))", x)
}
}
}
given("a translation of (3,3) before a rotation of pi/2") {
val t = Transforms2.translation(vector(3, 3)) before Transforms2.rotation(Math.PI / 2)
on("applying it on (1,0)") {
val x = t(vector(1, 0))
it("should be (-3,4)") {
shouldEqual(vector(-3, 4), x)
}
}
}
}
} | bsd-3-clause | 677db0ce20d8de911fd408121494502e | 24.615385 | 98 | 0.47438 | 3.941368 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/SideOnlyUtil.kt | 1 | 6065 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.forge.ForgeModuleType
import com.demonwav.mcdev.platform.forge.util.ForgeConstants
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.util.Pair
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import java.util.Arrays
import java.util.LinkedList
object SideOnlyUtil {
fun beginningCheck(element: PsiElement): Boolean {
// We need the module to get the MinecraftModule
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return false
// Check that the MinecraftModule
// 1. Exists
// 2. Is a ForgeModuleType
val facet = MinecraftFacet.getInstance(module)
return facet != null && facet.isOfType(ForgeModuleType)
}
private fun normalize(text: String): String {
if (text.startsWith(ForgeConstants.SIDE_ANNOTATION)) {
// We chop off the "net.minecraftforge.fml.relauncher." part here
return text.substring(text.lastIndexOf(".") - 4)
}
return text
}
fun checkMethod(method: PsiMethod): Side {
val methodAnnotation = method.modifierList.findAnnotation(ForgeConstants.SIDE_ONLY_ANNOTATION) ?: // It's not annotated, which would be invalid if the element was annotated
// (which, if we've gotten this far, is true)
return Side.NONE
// Check the value of the annotation
val methodValue = methodAnnotation.findAttributeValue("value") ?: // The annotation has no value yet, IntelliJ will give it's own error because a value is required
return Side.INVALID
// Return the value of the annotation
return getFromName(methodValue.text)
}
fun checkElementInMethod(element: PsiElement): Side {
var changingElement = element
// Maybe there is a better way of doing this, I don't know, but crawl up the PsiElement stack in search of the
// method this element is in. If it's not in a method it won't find one and the PsiMethod will be null
var method: PsiMethod? = null
while (method == null && changingElement.parent != null) {
val parent = changingElement.parent
if (parent is PsiMethod) {
method = parent
} else {
changingElement = parent
}
if (parent is PsiClass) {
break
}
}
// No method was found
if (method == null) {
return Side.INVALID
}
return checkMethod(method)
}
fun checkClassHierarchy(psiClass: PsiClass): List<Pair<Side, PsiClass>> {
val classList = LinkedList<PsiClass>()
classList.add(psiClass)
var parent: PsiElement = psiClass
while (parent.parent != null) {
parent = parent.parent
if (parent is PsiClass) {
classList.add(parent)
}
}
// We want to use an array list so indexing into the list is not expensive
return classList.map { checkClass(it) }
}
fun getSideForClass(psiClass: PsiClass): Side {
return getFirstSide(checkClassHierarchy(psiClass))
}
private fun checkClass(psiClass: PsiClass): Pair<Side, PsiClass> {
val side = psiClass.getUserData(Side.KEY)
if (side != null) {
return Pair(side, psiClass)
}
val modifierList = psiClass.modifierList ?: return Pair(Side.NONE, psiClass)
// Check for the annotation, if it's not there then we return none, but this is
// usually irrelevant for classes
val annotation = modifierList.findAnnotation(ForgeConstants.SIDE_ONLY_ANNOTATION)
if (annotation == null) {
if (psiClass.supers.isEmpty()) {
return Pair(Side.NONE, psiClass)
}
// check the classes this class extends
return psiClass.supers.asSequence()
.filter {
// Prevent stack-overflow on cyclic dependencies
psiClass != it
}
.map { checkClassHierarchy(it) }
.firstOrNull { it.isNotEmpty() }?.let { Pair(it[0].getFirst(), psiClass) } ?: Pair(Side.NONE, psiClass)
}
// Check the value on the annotation. If it's not there, IntelliJ will throw
// it's own error
val value = annotation.findAttributeValue("value") ?: return Pair(Side.INVALID, psiClass)
return Pair(getFromName(value.text), psiClass)
}
fun checkField(field: PsiField): Side {
// We check if this field has the @SideOnly annotation we are looking for
// If it doesn't, we aren't worried about it
val modifierList = field.modifierList ?: return Side.NONE
val annotation = modifierList.findAnnotation(ForgeConstants.SIDE_ONLY_ANNOTATION) ?: return Side.NONE
// The value may not necessarily be set, but that will give an error by default as "value" is a
// required value for @SideOnly
val value = annotation.findAttributeValue("value") ?: return Side.INVALID
// Finally, get the value of the SideOnly
return SideOnlyUtil.getFromName(value.text)
}
private fun getFromName(name: String): Side {
return when (normalize(name)) {
"Side.SERVER" -> Side.SERVER
"Side.CLIENT" -> Side.CLIENT
else -> Side.INVALID
}
}
fun getFirstSide(list: List<Pair<Side, PsiClass>>): Side {
return list.firstOrNull { it.first !== Side.NONE }?.first ?: Side.NONE
}
fun <T : Any?> getSubArray(infos: Array<T>): Array<T> {
return Arrays.copyOfRange(infos, 1, infos.size - 1)
}
}
| mit | 2bc24e730f87a3c586231d44c40e1087 | 34.887574 | 180 | 0.629843 | 4.672573 | false | false | false | false |
dahlstrom-g/intellij-community | tools/intellij.ide.starter/src/com/intellij/ide/starter/ide/IdeArchiveExtractor.kt | 2 | 4047 | package com.intellij.ide.starter.ide
import com.intellij.ide.starter.di.di
import com.intellij.ide.starter.exec.ExecOutputRedirect
import com.intellij.ide.starter.exec.exec
import com.intellij.ide.starter.path.GlobalPaths
import com.intellij.ide.starter.utils.FileSystem
import com.intellij.ide.starter.utils.HttpClient
import com.intellij.ide.starter.utils.catchAll
import com.intellij.ide.starter.utils.logOutput
import org.kodein.di.direct
import org.kodein.di.instance
import java.io.File
import java.nio.file.Path
import kotlin.io.path.createDirectories
import kotlin.io.path.div
import kotlin.io.path.nameWithoutExtension
import kotlin.time.Duration.Companion.minutes
object IdeArchiveExtractor {
fun unpackIdeIfNeeded(ideInstallerFile: File, unpackDir: File) {
if (unpackDir.isDirectory && unpackDir.listFiles()?.isNotEmpty() == true) {
logOutput("Build directory $unpackDir already exists for the binary $ideInstallerFile")
return
}
logOutput("Extracting application into $unpackDir")
when {
ideInstallerFile.extension == "dmg" -> unpackDmg(ideInstallerFile, unpackDir.toPath())
ideInstallerFile.extension == "exe" -> unpackWin(ideInstallerFile, unpackDir)
ideInstallerFile.extension == "zip" -> FileSystem.unpack(ideInstallerFile.toPath(), unpackDir.toPath())
ideInstallerFile.name.endsWith(".tar.gz") -> FileSystem.unpackTarGz(ideInstallerFile, unpackDir)
else -> error("Unsupported build file: $ideInstallerFile")
}
}
private fun unpackDmg(dmgFile: File, target: Path): Path {
target.toFile().deleteRecursively()
target.createDirectories()
val mountDir = File(dmgFile.path + "-mount${System.currentTimeMillis()}")
try {
exec(presentablePurpose = "hdiutil",
workDir = target,
timeout = 10.minutes,
stderrRedirect = ExecOutputRedirect.ToStdOut("hdiutil"),
stdoutRedirect = ExecOutputRedirect.ToStdOut("hdiutil"),
args = listOf("hdiutil", "attach", "-readonly", "-noautoopen", "-noautofsck", "-nobrowse", "-mountpoint", "$mountDir",
"$dmgFile"))
}
catch (t: Throwable) {
dmgFile.delete()
throw Error("Failed to mount $dmgFile. ${t.message}.", t)
}
try {
val appDir = mountDir.listFiles()?.singleOrNull { it.name.endsWith(".app") }
?: error("Failed to find the only one .app folder in $dmgFile")
val targetAppDir = target / appDir.name
exec(
presentablePurpose = "copy-dmg",
workDir = target,
timeout = 10.minutes,
stderrRedirect = ExecOutputRedirect.ToStdOut("cp"),
args = listOf("cp", "-R", "$appDir", "$targetAppDir"))
return targetAppDir
}
finally {
catchAll {
exec(
presentablePurpose = "hdiutil",
workDir = target,
timeout = 10.minutes,
stdoutRedirect = ExecOutputRedirect.ToStdOut("hdiutil"),
stderrRedirect = ExecOutputRedirect.ToStdOut("hdiutil"),
args = listOf("hdiutil", "detach", "-force", "$mountDir"))
}
}
}
private fun unpackWin(exeFile: File, targetDir: File) {
targetDir.deleteRecursively()
//we use 7-Zip to unpack NSIS binaries, same way as in Toolbox App
val sevenZipUrl = "https://repo.labs.intellij.net/thirdparty/7z-cmdline-15.06.zip"
val sevenZipCacheDir = di.direct.instance<GlobalPaths>().getCacheDirectoryFor("7zip")
val sevenZipFile = sevenZipCacheDir / sevenZipUrl.split("/").last()
val sevenZipTool = sevenZipCacheDir / sevenZipFile.fileName.nameWithoutExtension
HttpClient.downloadIfMissing(sevenZipUrl, sevenZipFile)
FileSystem.unpackIfMissing(sevenZipFile, sevenZipTool)
val severZipToolExe = sevenZipTool.resolve("7z.exe")
targetDir.mkdirs()
exec(
presentablePurpose = "unpack-zip",
workDir = targetDir.toPath(),
timeout = 10.minutes,
args = listOf(severZipToolExe.toAbsolutePath().toString(), "x", "-y", "-o$targetDir", exeFile.path)
)
}
} | apache-2.0 | 982919a59c40b7a274a09c118202a14b | 36.831776 | 129 | 0.686187 | 4.142272 | false | false | false | false |
jasvilladarez/Kotlin_Practice | Notes/app/src/main/kotlin/com/jv/practice/notes/presentation/views/fragments/NoteListFragment.kt | 1 | 2752 | /*
* Copyright 2016 Jasmine Villadarez
*
* 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.jv.practice.notes.presentation.views.fragments
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jv.practice.notes.R
import com.jv.practice.notes.domain.model.response.Note
import com.jv.practice.notes.presentation.internal.di.components.NoteListComponent
import com.jv.practice.notes.presentation.presenters.NoteListPresenter
import com.jv.practice.notes.presentation.views.NoteListView
import com.jv.practice.notes.presentation.views.adapters.NoteListAdapter
import kotlinx.android.synthetic.main.fragment_note_list.*
import javax.inject.Inject
class NoteListFragment() : BaseFragment(), NoteListView {
@Inject
lateinit var noteListPresenter: NoteListPresenter
private lateinit var noteListAdapter: NoteListAdapter
companion object Factory {
fun newInstance(): NoteListFragment {
var fragment = NoteListFragment()
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var v = inflater.inflate(R.layout.fragment_note_list, container, false)
return v
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews(view)
}
private fun initViews(view: View) {
noteListRecyclerView.setHasFixedSize(true)
noteListRecyclerView.layoutManager = LinearLayoutManager(view.context)
noteListAdapter = NoteListAdapter()
noteListRecyclerView.adapter = noteListAdapter
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
getComponent(NoteListComponent::class.java).inject(this)
noteListPresenter.view = this
noteListPresenter.getNotes()
}
override fun renderNotes(notes: List<Note>) {
noteListAdapter.notes = notes
}
override fun showLoadingView() {
}
override fun hideLoadingView() {
}
} | apache-2.0 | 0c673c433625409672f9c200479bacf1 | 32.573171 | 116 | 0.742369 | 4.656514 | false | false | false | false |
cdietze/klay | src/main/kotlin/klay/core/GL20.kt | 1 | 44154 | package klay.core
import klay.core.buffers.*
/**
* Interface and values for OpenGL ES 2.0, based on the official JOGL GL2ES2 interface.
*/
abstract class GL20 protected constructor(val bufs: GL20.Buffers, val checkErrors: Boolean) {
/**
* A helper class for bridging between Java arrays and buffers when implementing [GL20].
*/
abstract class Buffers {
var intBuffer = createIntBuffer(32)
var floatBuffer = createFloatBuffer(32)
var shortBuffer = createShortBuffer(32)
var byteBuffer = createByteBuffer(256)
fun setByteBuffer(source: ByteArray, offset: Int, length: Int) {
resizeByteBuffer(length - offset)
byteBuffer.put(source, offset, length)
byteBuffer.rewind()
}
fun setShortBuffer(source: ShortArray, offset: Int, length: Int) {
resizeShortBuffer(length - offset)
shortBuffer.put(source, offset, length)
shortBuffer.rewind()
}
fun setIntBuffer(source: IntArray, offset: Int, length: Int) {
resizeIntBuffer(length - offset)
intBuffer.put(source, offset, length)
intBuffer.rewind()
}
fun setFloatBuffer(source: FloatArray, offset: Int, length: Int) {
resizeFloatBuffer(length - offset)
floatBuffer.put(source, offset, length)
floatBuffer.rewind()
}
fun setShortBuffer(n: Short) {
shortBuffer.position(0)
shortBuffer.put(n)
shortBuffer.rewind()
}
fun setIntBuffer(n: Int) {
intBuffer.position(0)
intBuffer.put(n)
intBuffer.rewind()
}
fun setFloatBuffer(n: Float) {
floatBuffer.position(0)
floatBuffer.put(n)
floatBuffer.rewind()
}
fun resizeByteBuffer(length: Int) {
val cap = byteBuffer.capacity()
if (cap < length)
byteBuffer = createByteBuffer(newCap(cap, length))
else
byteBuffer.position(0)
byteBuffer.limit(length)
}
fun resizeShortBuffer(length: Int) {
val cap = shortBuffer.capacity()
if (cap < length)
shortBuffer = createShortBuffer(newCap(cap, length))
else
shortBuffer.position(0)
shortBuffer.limit(length)
}
fun resizeIntBuffer(length: Int) {
val cap = intBuffer.capacity()
if (cap < length)
intBuffer = createIntBuffer(newCap(cap, length))
else
intBuffer.position(0)
intBuffer.limit(length)
}
fun resizeFloatBuffer(length: Int) {
val cap = floatBuffer.capacity()
if (cap < length)
floatBuffer = createFloatBuffer(newCap(cap, length))
else
floatBuffer.position(0)
floatBuffer.limit(length)
}
fun createShortBuffer(size: Int): ShortBuffer {
return createByteBuffer(size * 2).asShortBuffer()
}
fun createIntBuffer(size: Int): IntBuffer {
return createByteBuffer(size * 4).asIntBuffer()
}
fun createFloatBuffer(size: Int): FloatBuffer {
return createByteBuffer(size * 4).asFloatBuffer()
}
private fun newCap(cap: Int, length: Int): Int {
var newLength = cap shl 1
while (newLength < length) {
newLength = newLength shl 1
}
return newLength
}
abstract fun createByteBuffer(size: Int): ByteBuffer
abstract fun arrayCopy(src: IntArray, srcPos: Int, dest: IntArray, destPos: Int, length: Int)
abstract fun arrayCopy(src: FloatArray, srcPos: Int, dest: FloatArray, destPos: Int, length: Int)
}
/**
* Checks for any GL error codes and logs them (if [.checkErrors] is true).
* @return true if any errors were reported.
*/
fun checkError(op: String): Boolean {
var reported = 0
if (checkErrors) {
while (true) {
val error = glGetError()
if (error == GL_NO_ERROR) break
reported += 1
println(op + ": glError " + error)
}
}
return reported > 0
}
fun glDeleteBuffer(id: Int) {
bufs.setIntBuffer(id)
glDeleteBuffers(1, bufs.intBuffer)
}
fun glDeleteBuffers(n: Int, buffers: IntArray, offset: Int) {
bufs.setIntBuffer(buffers, offset, n)
glDeleteBuffers(n, bufs.intBuffer)
}
fun glDeleteFramebuffer(id: Int) {
bufs.setIntBuffer(id)
glDeleteFramebuffers(1, bufs.intBuffer)
}
fun glDeleteFramebuffers(n: Int, framebuffers: IntArray, offset: Int) {
bufs.setIntBuffer(framebuffers, offset, n)
glDeleteFramebuffers(n, bufs.intBuffer)
}
fun glDeleteRenderbuffer(id: Int) {
bufs.setIntBuffer(id)
glDeleteRenderbuffers(1, bufs.intBuffer)
}
fun glDeleteRenderbuffers(n: Int, renderbuffers: IntArray, offset: Int) {
bufs.setIntBuffer(renderbuffers, offset, n)
glDeleteRenderbuffers(n, bufs.intBuffer)
}
fun glDeleteTexture(id: Int) {
bufs.setIntBuffer(id)
glDeleteTextures(1, bufs.intBuffer)
}
fun glDeleteTextures(n: Int, textures: IntArray, offset: Int) {
bufs.setIntBuffer(textures, offset, n)
glDeleteTextures(n, bufs.intBuffer)
}
fun glGenBuffer(): Int {
bufs.resizeIntBuffer(1)
glGenBuffers(1, bufs.intBuffer)
return bufs.intBuffer.get(0)
}
fun glGenBuffers(n: Int, buffers: IntArray, offset: Int) {
bufs.resizeIntBuffer(n)
glGenBuffers(n, bufs.intBuffer)
bufs.intBuffer.get(buffers, offset, n)
}
fun glGenFramebuffer(): Int {
bufs.resizeIntBuffer(1)
glGenFramebuffers(1, bufs.intBuffer)
return bufs.intBuffer.get(0)
}
fun glGenFramebuffers(n: Int, framebuffers: IntArray, offset: Int) {
bufs.resizeIntBuffer(n)
glGenFramebuffers(n, bufs.intBuffer)
bufs.intBuffer.get(framebuffers, offset, n)
}
fun glGenRenderbuffer(): Int {
bufs.resizeIntBuffer(1)
glGenRenderbuffers(1, bufs.intBuffer)
return bufs.intBuffer.get(0)
}
fun glGenRenderbuffers(n: Int, renderbuffers: IntArray, offset: Int) {
bufs.resizeIntBuffer(n)
glGenRenderbuffers(n, bufs.intBuffer)
bufs.intBuffer.get(renderbuffers, offset, n)
}
fun glGenTexture(): Int {
bufs.resizeIntBuffer(1)
glGenTextures(1, bufs.intBuffer)
return bufs.intBuffer.get(0)
}
fun glGenTextures(n: Int, textures: IntArray, offset: Int) {
bufs.resizeIntBuffer(n)
glGenTextures(n, bufs.intBuffer)
bufs.intBuffer.get(textures, offset, n)
}
fun glGetAttachedShaders(program: Int, maxcount: Int, count: IntArray, countOffset: Int, shaders: IntArray, shadersOffset: Int) {
val countLength = count.size - countOffset
bufs.resizeIntBuffer(countLength)
val shadersLength = shaders.size - shadersOffset
val intBuffer2 = bufs.createIntBuffer(shadersLength)
glGetAttachedShaders(program, maxcount, bufs.intBuffer, intBuffer2)
bufs.intBuffer.get(count, countOffset, countLength)
intBuffer2.get(shaders, shadersOffset, shadersLength)
}
fun glGetBooleanv(pname: Int, params: ByteArray, offset: Int) {
val length = params.size - offset
bufs.resizeByteBuffer(length)
glGetBooleanv(pname, bufs.byteBuffer)
bufs.byteBuffer.get(params, offset, length)
}
fun glGetBufferParameteriv(target: Int, pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetBufferParameteriv(target, pname, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glGetFloatv(pname: Int, params: FloatArray, offset: Int) {
val length = params.size - offset
bufs.resizeFloatBuffer(length)
glGetFloatv(pname, bufs.floatBuffer)
bufs.floatBuffer.get(params, offset, length)
}
fun glGetFramebufferAttachmentParameteriv(target: Int, attachment: Int, pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetFramebufferAttachmentParameteriv(target, attachment, pname, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glGetIntegerv(pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetIntegerv(pname, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glGetProgramBinary(program: Int, bufsize: Int, length: IntArray, lengthOffset: Int, binaryformat: IntArray, binaryformatOffset: Int, binary: ByteBuffer) {
val lengthLength = bufsize - lengthOffset
bufs.resizeIntBuffer(lengthLength)
val binaryformatLength = bufsize - binaryformatOffset
val intBuffer2 = bufs.createIntBuffer(binaryformatLength)
glGetProgramBinary(program, bufsize, bufs.intBuffer, intBuffer2, binary)
// Return length, binaryformat
bufs.intBuffer.get(length, lengthOffset, lengthLength)
intBuffer2.get(binaryformat, binaryformatOffset, binaryformatLength)
}
fun glGetProgramInfoLog(program: Int, bufsize: Int, length: IntArray, lengthOffset: Int, infolog: ByteArray, infologOffset: Int) {
val intLength = length.size - lengthOffset
bufs.resizeIntBuffer(intLength)
val byteLength = bufsize - infologOffset
bufs.resizeByteBuffer(byteLength)
glGetProgramInfoLog(program, bufsize, bufs.intBuffer, bufs.byteBuffer)
// length is the length of the infoLog string being returned
bufs.intBuffer.get(length, lengthOffset, intLength)
// infoLog is the char array of the infoLog
bufs.byteBuffer.get(infolog, byteLength, infologOffset)
}
fun glGetProgramiv(program: Int, pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetProgramiv(program, pname, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glGetRenderbufferParameteriv(target: Int, pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetRenderbufferParameteriv(target, pname, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glGetShaderInfoLog(shader: Int, bufsize: Int, length: IntArray, lengthOffset: Int, infolog: ByteArray, infologOffset: Int) {
val intLength = length.size - lengthOffset
bufs.resizeIntBuffer(intLength)
val byteLength = bufsize - infologOffset
bufs.resizeByteBuffer(byteLength)
glGetShaderInfoLog(shader, bufsize, bufs.intBuffer, bufs.byteBuffer)
// length is the length of the infoLog string being returned
bufs.intBuffer.get(length, lengthOffset, intLength)
// infoLog is the char array of the infoLog
bufs.byteBuffer.get(infolog, byteLength, infologOffset)
}
fun glGetShaderiv(shader: Int, pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetShaderiv(shader, pname, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glGetTexParameterfv(target: Int, pname: Int, params: FloatArray, offset: Int) {
val length = params.size - offset
bufs.resizeFloatBuffer(length)
glGetTexParameterfv(target, pname, bufs.floatBuffer)
bufs.floatBuffer.get(params, offset, length)
}
fun glGetTexParameteriv(target: Int, pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetTexParameteriv(target, pname, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glGetUniformfv(program: Int, location: Int, params: FloatArray, offset: Int) {
val length = params.size - offset
bufs.resizeFloatBuffer(length)
glGetUniformfv(program, location, bufs.floatBuffer)
bufs.floatBuffer.get(params, offset, length)
}
fun glGetUniformiv(program: Int, location: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetUniformiv(program, location, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glGetVertexAttribfv(index: Int, pname: Int, params: FloatArray, offset: Int) {
val length = params.size - offset
bufs.resizeFloatBuffer(length)
glGetVertexAttribfv(index, pname, bufs.floatBuffer)
bufs.floatBuffer.get(params, offset, length)
}
fun glGetVertexAttribiv(index: Int, pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.resizeIntBuffer(length)
glGetVertexAttribiv(index, pname, bufs.intBuffer)
bufs.intBuffer.get(params, offset, length)
}
fun glTexParameterfv(target: Int, pname: Int, params: FloatArray, offset: Int) {
val length = params.size - offset
bufs.setFloatBuffer(params, offset, length)
glTexParameterfv(target, pname, bufs.floatBuffer)
}
fun glTexParameteriv(target: Int, pname: Int, params: IntArray, offset: Int) {
val length = params.size - offset
bufs.setIntBuffer(params, offset, length)
glTexParameteriv(target, pname, bufs.intBuffer)
}
fun glUniform1fv(location: Int, count: Int, value: FloatArray, offset: Int) {
bufs.setFloatBuffer(value, offset, count)
glUniform1fv(location, count, bufs.floatBuffer)
}
fun glUniform1iv(location: Int, count: Int, value: IntArray, offset: Int) {
bufs.setIntBuffer(value, offset, count)
glUniform1iv(location, count, bufs.intBuffer)
}
fun glUniform2fv(location: Int, count: Int, value: FloatArray, offset: Int) {
bufs.setFloatBuffer(value, 2 * offset, 2 * count)
glUniform2fv(location, count, bufs.floatBuffer)
}
fun glUniform2iv(location: Int, count: Int, value: IntArray, offset: Int) {
bufs.setIntBuffer(value, 2 * offset, 2 * count)
glUniform2iv(location, count, bufs.intBuffer)
}
fun glUniform3fv(location: Int, count: Int, value: FloatArray, offset: Int) {
bufs.setFloatBuffer(value, 3 * offset, 3 * count)
glUniform3fv(location, count, bufs.floatBuffer)
}
fun glUniform3iv(location: Int, count: Int, value: IntArray, offset: Int) {
bufs.setIntBuffer(value, 3 * offset, 3 * count)
glUniform3iv(location, count, bufs.intBuffer)
}
fun glUniform4fv(location: Int, count: Int, value: FloatArray, offset: Int) {
bufs.setFloatBuffer(value, 4 * offset, 4 * count)
glUniform4fv(location, count, bufs.floatBuffer)
}
fun glUniform4iv(location: Int, count: Int, value: IntArray, offset: Int) {
bufs.setIntBuffer(value, 4 * offset, 4 * count)
glUniform4iv(location, count, bufs.intBuffer)
}
fun glUniformMatrix2fv(location: Int, count: Int, transpose: Boolean,
value: FloatArray, offset: Int) {
bufs.setFloatBuffer(value, 2 * 2 * offset, 2 * 2 * count)
glUniformMatrix2fv(location, count, transpose, bufs.floatBuffer)
}
fun glUniformMatrix3fv(location: Int, count: Int, transpose: Boolean,
value: FloatArray, offset: Int) {
bufs.setFloatBuffer(value, 2 * 2 * offset, 3 * 3 * count)
glUniformMatrix3fv(location, count, transpose, bufs.floatBuffer)
}
fun glUniformMatrix4fv(location: Int, count: Int, transpose: Boolean,
value: FloatArray, offset: Int) {
bufs.setFloatBuffer(value, 4 * 4 * offset, 4 * 4 * count)
glUniformMatrix4fv(location, count, transpose, bufs.floatBuffer)
}
fun glVertexAttrib1fv(index: Int, values: FloatArray, offset: Int) {
glVertexAttrib1f(index, values[index + offset])
}
fun glVertexAttrib2fv(index: Int, values: FloatArray, offset: Int) {
glVertexAttrib2f(index, values[index + offset], values[index + 1 + offset])
}
fun glVertexAttrib3fv(index: Int, values: FloatArray, offset: Int) {
glVertexAttrib3f(index, values[index + offset], values[index + 1 + offset], values[index + 2 + offset])
}
fun glVertexAttrib4fv(index: Int, values: FloatArray, offset: Int) {
glVertexAttrib4f(index, values[index + offset], values[index + 1 + offset], values[index + 2 + offset], values[index + 3 + offset])
}
abstract val platformGLExtensions: String
abstract val swapInterval: Int
abstract fun glActiveTexture(texture: Int)
abstract fun glAttachShader(program: Int, shader: Int)
abstract fun glBindAttribLocation(program: Int, index: Int, name: String)
abstract fun glBindBuffer(target: Int, buffer: Int)
abstract fun glBindFramebuffer(target: Int, framebuffer: Int)
abstract fun glBindRenderbuffer(target: Int, renderbuffer: Int)
abstract fun glBindTexture(target: Int, texture: Int)
abstract fun glBlendColor(red: Float, green: Float, blue: Float, alpha: Float)
abstract fun glBlendEquation(mode: Int)
abstract fun glBlendEquationSeparate(modeRGB: Int, modeAlpha: Int)
abstract fun glBlendFunc(sfactor: Int, dfactor: Int)
abstract fun glBlendFuncSeparate(srcRGB: Int, dstRGB: Int, srcAlpha: Int, dstAlpha: Int)
abstract fun glBufferData(target: Int, size: Int, data: Buffer, usage: Int)
abstract fun glBufferSubData(target: Int, offset: Int, size: Int, data: Buffer)
abstract fun glCheckFramebufferStatus(target: Int): Int
abstract fun glClear(mask: Int)
abstract fun glClearColor(red: Float, green: Float, blue: Float, alpha: Float)
abstract fun glClearDepth(depth: Double)
abstract fun glClearDepthf(depth: Float)
abstract fun glClearStencil(s: Int)
abstract fun glColorMask(red: Boolean, green: Boolean, blue: Boolean, alpha: Boolean)
abstract fun glCompileShader(shader: Int)
abstract fun glCompressedTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, imageSize: Int, data: Buffer)
abstract fun glCompressedTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, imageSize: Int, data: Int)
abstract fun glCompressedTexImage3D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, depth: Int, border: Int, imageSize: Int, data: ByteBuffer)
abstract fun glCompressedTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, imageSize: Int, data: Int)
abstract fun glCompressedTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, imageSize: Int, data: Buffer)
abstract fun glCompressedTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, imageSize: Int, data: Int)
abstract fun glCompressedTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, imageSize: Int, data: ByteBuffer)
abstract fun glCompressedTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, imageSize: Int, data: Int)
abstract fun glCopyTexImage2D(target: Int, level: Int, internalformat: Int, x: Int, y: Int, width: Int, height: Int, border: Int)
abstract fun glCopyTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, x: Int, y: Int, width: Int, height: Int)
abstract fun glCopyTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, x: Int, y: Int, width: Int, height: Int)
abstract fun glCreateProgram(): Int
abstract fun glCreateShader(type: Int): Int
abstract fun glCullFace(mode: Int)
abstract fun glDeleteBuffers(n: Int, buffers: IntBuffer)
abstract fun glDeleteFramebuffers(n: Int, framebuffers: IntBuffer)
abstract fun glDeleteProgram(program: Int)
abstract fun glDeleteRenderbuffers(n: Int, renderbuffers: IntBuffer)
abstract fun glDeleteShader(shader: Int)
abstract fun glDeleteTextures(n: Int, textures: IntBuffer)
abstract fun glDepthFunc(func: Int)
abstract fun glDepthMask(flag: Boolean)
abstract fun glDepthRange(zNear: Double, zFar: Double)
abstract fun glDepthRangef(zNear: Float, zFar: Float)
abstract fun glDetachShader(program: Int, shader: Int)
abstract fun glDisable(cap: Int)
abstract fun glDisableVertexAttribArray(index: Int)
abstract fun glDrawArrays(mode: Int, first: Int, count: Int)
abstract fun glDrawElements(mode: Int, count: Int, type: Int, indices: Buffer)
abstract fun glDrawElements(mode: Int, count: Int, type: Int, indices: Int)
abstract fun glEnable(cap: Int)
abstract fun glEnableVertexAttribArray(index: Int)
abstract fun glFinish()
abstract fun glFlush()
abstract fun glFramebufferRenderbuffer(target: Int, attachment: Int, renderbuffertarget: Int, renderbuffer: Int)
abstract fun glFramebufferTexture2D(target: Int, attachment: Int, textarget: Int, texture: Int, level: Int)
abstract fun glFramebufferTexture3D(target: Int, attachment: Int, textarget: Int, texture: Int, level: Int, zoffset: Int)
abstract fun glFrontFace(mode: Int)
abstract fun glGenBuffers(n: Int, buffers: IntBuffer)
abstract fun glGenerateMipmap(target: Int)
abstract fun glGenFramebuffers(n: Int, framebuffers: IntBuffer)
abstract fun glGenRenderbuffers(n: Int, renderbuffers: IntBuffer)
abstract fun glGenTextures(n: Int, textures: IntBuffer)
abstract fun glGetActiveAttrib(program: Int, index: Int, bufsize: Int, length: IntArray, lengthOffset: Int, size: IntArray, sizeOffset: Int, type: IntArray, typeOffset: Int, name: ByteArray, nameOffset: Int)
abstract fun glGetActiveAttrib(program: Int, index: Int, bufsize: Int, length: IntBuffer, size: IntBuffer, type: IntBuffer, name: ByteBuffer)
abstract fun glGetActiveUniform(program: Int, index: Int, bufsize: Int, length: IntArray, lengthOffset: Int, size: IntArray, sizeOffset: Int, type: IntArray, typeOffset: Int, name: ByteArray, nameOffset: Int)
abstract fun glGetActiveUniform(program: Int, index: Int, bufsize: Int, length: IntBuffer, size: IntBuffer, type: IntBuffer, name: ByteBuffer)
abstract fun glGetAttachedShaders(program: Int, maxcount: Int, count: IntBuffer, shaders: IntBuffer)
abstract fun glGetAttribLocation(program: Int, name: String): Int
abstract fun glGetBoolean(pname: Int): Boolean
abstract fun glGetBooleanv(pname: Int, params: ByteBuffer)
abstract fun glGetBoundBuffer(target: Int): Int
abstract fun glGetBufferParameteriv(target: Int, pname: Int, params: IntBuffer)
abstract fun glGetError(): Int
abstract fun glGetFloat(pname: Int): Float
abstract fun glGetFloatv(pname: Int, params: FloatBuffer)
abstract fun glGetFramebufferAttachmentParameteriv(target: Int, attachment: Int, pname: Int, params: IntBuffer)
abstract fun glGetInteger(pname: Int): Int
abstract fun glGetIntegerv(pname: Int, params: IntBuffer)
abstract fun glGetProgramBinary(program: Int, bufSize: Int, length: IntBuffer, binaryFormat: IntBuffer, binary: ByteBuffer)
abstract fun glGetProgramInfoLog(program: Int, bufsize: Int, length: IntBuffer, infolog: ByteBuffer)
abstract fun glGetProgramInfoLog(program: Int): String
abstract fun glGetProgramiv(program: Int, pname: Int, params: IntBuffer)
abstract fun glGetRenderbufferParameteriv(target: Int, pname: Int, params: IntBuffer)
abstract fun glGetShaderInfoLog(shader: Int, bufsize: Int, length: IntBuffer, infolog: ByteBuffer)
abstract fun glGetShaderInfoLog(shader: Int): String
abstract fun glGetShaderiv(shader: Int, pname: Int, params: IntBuffer)
abstract fun glGetShaderPrecisionFormat(shadertype: Int, precisiontype: Int, range: IntArray, rangeOffset: Int, precision: IntArray, precisionOffset: Int)
abstract fun glGetShaderPrecisionFormat(shadertype: Int, precisiontype: Int, range: IntBuffer, precision: IntBuffer)
abstract fun glGetShaderSource(shader: Int, bufsize: Int, length: IntArray, lengthOffset: Int, source: ByteArray, sourceOffset: Int)
abstract fun glGetShaderSource(shader: Int, bufsize: Int, length: IntBuffer, source: ByteBuffer)
abstract fun glGetString(name: Int): String
abstract fun glGetTexParameterfv(target: Int, pname: Int, params: FloatBuffer)
abstract fun glGetTexParameteriv(target: Int, pname: Int, params: IntBuffer)
abstract fun glGetUniformfv(program: Int, location: Int, params: FloatBuffer)
abstract fun glGetUniformiv(program: Int, location: Int, params: IntBuffer)
abstract fun glGetUniformLocation(program: Int, name: String): Int
abstract fun glGetVertexAttribfv(index: Int, pname: Int, params: FloatBuffer)
abstract fun glGetVertexAttribiv(index: Int, pname: Int, params: IntBuffer)
abstract fun glHint(target: Int, mode: Int)
abstract fun glIsBuffer(buffer: Int): Boolean
abstract fun glIsEnabled(cap: Int): Boolean
abstract fun glIsFramebuffer(framebuffer: Int): Boolean
abstract fun glIsProgram(program: Int): Boolean
abstract fun glIsRenderbuffer(renderbuffer: Int): Boolean
abstract fun glIsShader(shader: Int): Boolean
abstract fun glIsTexture(texture: Int): Boolean
abstract fun glIsVBOArrayEnabled(): Boolean
abstract fun glIsVBOElementEnabled(): Boolean
abstract fun glLineWidth(width: Float)
abstract fun glLinkProgram(program: Int)
abstract fun glMapBuffer(target: Int, access: Int): ByteBuffer
abstract fun glPixelStorei(pname: Int, param: Int)
abstract fun glPolygonOffset(factor: Float, units: Float)
abstract fun glProgramBinary(program: Int, binaryFormat: Int, binary: ByteBuffer, length: Int)
abstract fun glReadPixels(x: Int, y: Int, width: Int, height: Int, format: Int, type: Int, pixels: Buffer)
abstract fun glReadPixels(x: Int, y: Int, width: Int, height: Int, format: Int, type: Int, pixelsBufferOffset: Int)
abstract fun glReleaseShaderCompiler()
abstract fun glRenderbufferStorage(target: Int, internalformat: Int, width: Int, height: Int)
abstract fun glSampleCoverage(value: Float, invert: Boolean)
abstract fun glScissor(x: Int, y: Int, width: Int, height: Int)
abstract fun glShaderBinary(n: Int, shaders: IntArray, offset: Int, binaryformat: Int, binary: Buffer, length: Int)
abstract fun glShaderBinary(n: Int, shaders: IntBuffer, binaryformat: Int, binary: Buffer, length: Int)
abstract fun glShaderSource(shader: Int, count: Int, strings: Array<String>, length: IntArray, lengthOffset: Int)
abstract fun glShaderSource(shader: Int, count: Int, strings: Array<String>, length: IntBuffer)
abstract fun glShaderSource(shader: Int, string: String)
abstract fun glStencilFunc(func: Int, ref: Int, mask: Int)
abstract fun glStencilFuncSeparate(face: Int, func: Int, ref: Int, mask: Int)
abstract fun glStencilMask(mask: Int)
abstract fun glStencilMaskSeparate(face: Int, mask: Int)
abstract fun glStencilOp(fail: Int, zfail: Int, zpass: Int)
abstract fun glStencilOpSeparate(face: Int, fail: Int, zfail: Int, zpass: Int)
abstract fun glTexImage2D(target: Int, level: Int, internalformat: Int, width: Int, height: Int, border: Int, format: Int, type: Int, pixels: Buffer?)
abstract fun glTexImage2D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, border: Int, format: Int, type: Int, pixels: Int)
abstract fun glTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, format: Int, type: Int, pixels: Buffer)
abstract fun glTexImage3D(target: Int, level: Int, internalFormat: Int, width: Int, height: Int, depth: Int, border: Int, format: Int, type: Int, pixels: Int)
abstract fun glTexParameterf(target: Int, pname: Int, param: Float)
abstract fun glTexParameterfv(target: Int, pname: Int, params: FloatBuffer)
abstract fun glTexParameteri(target: Int, pname: Int, param: Int)
abstract fun glTexParameteriv(target: Int, pname: Int, params: IntBuffer)
abstract fun glTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, type: Int, pixels: Buffer)
abstract fun glTexSubImage2D(target: Int, level: Int, xoffset: Int, yoffset: Int, width: Int, height: Int, format: Int, type: Int, pixels: Int)
abstract fun glTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, type: Int, pixels: ByteBuffer)
abstract fun glTexSubImage3D(target: Int, level: Int, xoffset: Int, yoffset: Int, zoffset: Int, width: Int, height: Int, depth: Int, format: Int, type: Int, pixels: Int)
abstract fun glUniform1f(location: Int, x: Float)
abstract fun glUniform1fv(location: Int, count: Int, buffer: FloatBuffer)
abstract fun glUniform1i(location: Int, x: Int)
abstract fun glUniform1iv(location: Int, count: Int, value: IntBuffer)
abstract fun glUniform2f(location: Int, x: Float, y: Float)
abstract fun glUniform2fv(location: Int, count: Int, value: FloatBuffer)
abstract fun glUniform2i(location: Int, x: Int, y: Int)
abstract fun glUniform2iv(location: Int, count: Int, value: IntBuffer)
abstract fun glUniform3f(location: Int, x: Float, y: Float, z: Float)
abstract fun glUniform3fv(location: Int, count: Int, value: FloatBuffer)
abstract fun glUniform3i(location: Int, x: Int, y: Int, z: Int)
abstract fun glUniform3iv(location: Int, count: Int, value: IntBuffer)
abstract fun glUniform4f(location: Int, x: Float, y: Float, z: Float, w: Float)
abstract fun glUniform4fv(location: Int, count: Int, value: FloatBuffer)
abstract fun glUniform4i(location: Int, x: Int, y: Int, z: Int, w: Int)
abstract fun glUniform4iv(location: Int, count: Int, value: IntBuffer)
abstract fun glUniformMatrix2fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer)
abstract fun glUniformMatrix3fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer)
abstract fun glUniformMatrix4fv(location: Int, count: Int, transpose: Boolean, value: FloatBuffer)
abstract fun glUnmapBuffer(target: Int): Boolean
abstract fun glUseProgram(program: Int)
abstract fun glValidateProgram(program: Int)
abstract fun glVertexAttrib1f(index: Int, x: Float)
abstract fun glVertexAttrib1fv(index: Int, values: FloatBuffer)
abstract fun glVertexAttrib2f(index: Int, x: Float, y: Float)
abstract fun glVertexAttrib2fv(index: Int, values: FloatBuffer)
abstract fun glVertexAttrib3f(index: Int, x: Float, y: Float, z: Float)
abstract fun glVertexAttrib3fv(index: Int, values: FloatBuffer)
abstract fun glVertexAttrib4f(index: Int, x: Float, y: Float, z: Float, w: Float)
abstract fun glVertexAttrib4fv(index: Int, values: FloatBuffer)
abstract fun glVertexAttribPointer(index: Int, size: Int, type: Int, normalized: Boolean, stride: Int, ptr: Buffer)
abstract fun glVertexAttribPointer(index: Int, size: Int, type: Int, normalized: Boolean, stride: Int, ptr: Int)
abstract fun glViewport(x: Int, y: Int, width: Int, height: Int)
abstract fun hasGLSL(): Boolean
abstract fun isExtensionAvailable(extension: String): Boolean
abstract fun isFunctionAvailable(function: String): Boolean
companion object {
val GL_ACTIVE_TEXTURE = 0x84E0
val GL_DEPTH_BUFFER_BIT = 0x00000100
val GL_STENCIL_BUFFER_BIT = 0x00000400
val GL_COLOR_BUFFER_BIT = 0x00004000
val GL_FALSE = 0
val GL_TRUE = 1
val GL_POINTS = 0x0000
val GL_LINES = 0x0001
val GL_LINE_LOOP = 0x0002
val GL_LINE_STRIP = 0x0003
val GL_TRIANGLES = 0x0004
val GL_TRIANGLE_STRIP = 0x0005
val GL_TRIANGLE_FAN = 0x0006
val GL_ZERO = 0
val GL_ONE = 1
val GL_SRC_COLOR = 0x0300
val GL_ONE_MINUS_SRC_COLOR = 0x0301
val GL_SRC_ALPHA = 0x0302
val GL_ONE_MINUS_SRC_ALPHA = 0x0303
val GL_DST_ALPHA = 0x0304
val GL_ONE_MINUS_DST_ALPHA = 0x0305
val GL_DST_COLOR = 0x0306
val GL_ONE_MINUS_DST_COLOR = 0x0307
val GL_SRC_ALPHA_SATURATE = 0x0308
val GL_FUNC_ADD = 0x8006
val GL_BLEND_EQUATION = 0x8009
val GL_BLEND_EQUATION_RGB = 0x8009 /* == BLEND_EQUATION */
val GL_BLEND_EQUATION_ALPHA = 0x883D
val GL_FUNC_SUBTRACT = 0x800A
val GL_FUNC_REVERSE_SUBTRACT = 0x800B
val GL_BLEND_DST_RGB = 0x80C8
val GL_BLEND_SRC_RGB = 0x80C9
val GL_BLEND_DST_ALPHA = 0x80CA
val GL_BLEND_SRC_ALPHA = 0x80CB
val GL_CONSTANT_COLOR = 0x8001
val GL_ONE_MINUS_CONSTANT_COLOR = 0x8002
val GL_CONSTANT_ALPHA = 0x8003
val GL_ONE_MINUS_CONSTANT_ALPHA = 0x8004
val GL_BLEND_COLOR = 0x8005
val GL_ARRAY_BUFFER = 0x8892
val GL_ELEMENT_ARRAY_BUFFER = 0x8893
val GL_ARRAY_BUFFER_BINDING = 0x8894
val GL_ELEMENT_ARRAY_BUFFER_BINDING = 0x8895
val GL_STREAM_DRAW = 0x88E0
val GL_STATIC_DRAW = 0x88E4
val GL_DYNAMIC_DRAW = 0x88E8
val GL_BUFFER_SIZE = 0x8764
val GL_BUFFER_USAGE = 0x8765
val GL_CURRENT_VERTEX_ATTRIB = 0x8626
val GL_FRONT = 0x0404
val GL_BACK = 0x0405
val GL_FRONT_AND_BACK = 0x0408
val GL_TEXTURE_2D = 0x0DE1
val GL_CULL_FACE = 0x0B44
val GL_BLEND = 0x0BE2
val GL_DITHER = 0x0BD0
val GL_STENCIL_TEST = 0x0B90
val GL_DEPTH_TEST = 0x0B71
val GL_SCISSOR_TEST = 0x0C11
val GL_POLYGON_OFFSET_FILL = 0x8037
val GL_SAMPLE_ALPHA_TO_COVERAGE = 0x809E
val GL_SAMPLE_COVERAGE = 0x80A0
val GL_NO_ERROR = 0
val GL_INVALID_ENUM = 0x0500
val GL_INVALID_VALUE = 0x0501
val GL_INVALID_OPERATION = 0x0502
val GL_OUT_OF_MEMORY = 0x0505
val GL_CW = 0x0900
val GL_CCW = 0x0901
val GL_LINE_WIDTH = 0x0B21
val GL_ALIASED_POINT_SIZE_RANGE = 0x846D
val GL_ALIASED_LINE_WIDTH_RANGE = 0x846E
val GL_CULL_FACE_MODE = 0x0B45
val GL_FRONT_FACE = 0x0B46
val GL_DEPTH_RANGE = 0x0B70
val GL_DEPTH_WRITEMASK = 0x0B72
val GL_DEPTH_CLEAR_VALUE = 0x0B73
val GL_DEPTH_FUNC = 0x0B74
val GL_STENCIL_CLEAR_VALUE = 0x0B91
val GL_STENCIL_FUNC = 0x0B92
val GL_STENCIL_FAIL = 0x0B94
val GL_STENCIL_PASS_DEPTH_FAIL = 0x0B95
val GL_STENCIL_PASS_DEPTH_PASS = 0x0B96
val GL_STENCIL_REF = 0x0B97
val GL_STENCIL_VALUE_MASK = 0x0B93
val GL_STENCIL_WRITEMASK = 0x0B98
val GL_STENCIL_BACK_FUNC = 0x8800
val GL_STENCIL_BACK_FAIL = 0x8801
val GL_STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802
val GL_STENCIL_BACK_PASS_DEPTH_PASS = 0x8803
val GL_STENCIL_BACK_REF = 0x8CA3
val GL_STENCIL_BACK_VALUE_MASK = 0x8CA4
val GL_STENCIL_BACK_WRITEMASK = 0x8CA5
val GL_VIEWPORT = 0x0BA2
val GL_SCISSOR_BOX = 0x0C10
val GL_COLOR_CLEAR_VALUE = 0x0C22
val GL_COLOR_WRITEMASK = 0x0C23
val GL_UNPACK_ALIGNMENT = 0x0CF5
val GL_PACK_ALIGNMENT = 0x0D05
val GL_MAX_TEXTURE_SIZE = 0x0D33
val GL_MAX_VIEWPORT_DIMS = 0x0D3A
val GL_SUBPIXEL_BITS = 0x0D50
val GL_RED_BITS = 0x0D52
val GL_GREEN_BITS = 0x0D53
val GL_BLUE_BITS = 0x0D54
val GL_ALPHA_BITS = 0x0D55
val GL_DEPTH_BITS = 0x0D56
val GL_STENCIL_BITS = 0x0D57
val GL_POLYGON_OFFSET_UNITS = 0x2A00
val GL_POLYGON_OFFSET_FACTOR = 0x8038
val GL_TEXTURE_BINDING_2D = 0x8069
val GL_SAMPLE_BUFFERS = 0x80A8
val GL_SAMPLES = 0x80A9
val GL_SAMPLE_COVERAGE_VALUE = 0x80AA
val GL_SAMPLE_COVERAGE_INVERT = 0x80AB
val GL_NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2
val GL_COMPRESSED_TEXTURE_FORMATS = 0x86A3
val GL_DONT_CARE = 0x1100
val GL_FASTEST = 0x1101
val GL_NICEST = 0x1102
val GL_GENERATE_MIPMAP_HINT = 0x8192
val GL_BYTE = 0x1400
val GL_UNSIGNED_BYTE = 0x1401
val GL_SHORT = 0x1402
val GL_UNSIGNED_SHORT = 0x1403
val GL_INT = 0x1404
val GL_UNSIGNED_INT = 0x1405
val GL_FLOAT = 0x1406
val GL_FIXED = 0x140C
val GL_DEPTH_COMPONENT = 0x1902
val GL_ALPHA = 0x1906
val GL_RGB = 0x1907
val GL_RGBA = 0x1908
val GL_BGRA = 0x80E1
val GL_LUMINANCE = 0x1909
val GL_LUMINANCE_ALPHA = 0x190A
val GL_UNSIGNED_SHORT_4_4_4_4 = 0x8033
val GL_UNSIGNED_SHORT_5_5_5_1 = 0x8034
val GL_UNSIGNED_SHORT_5_6_5 = 0x8363
val GL_UNSIGNED_INT_8_8_8_8 = 0x8035
val GL_UNSIGNED_INT_8_8_8_8_REV = 0x8367
val GL_FRAGMENT_SHADER = 0x8B30
val GL_VERTEX_SHADER = 0x8B31
val GL_MAX_VERTEX_ATTRIBS = 0x8869
val GL_MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB
val GL_MAX_VARYING_VECTORS = 0x8DFC
val GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D
val GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C
val GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872
val GL_MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD
val GL_SHADER_TYPE = 0x8B4F
val GL_DELETE_STATUS = 0x8B80
val GL_LINK_STATUS = 0x8B82
val GL_VALIDATE_STATUS = 0x8B83
val GL_ATTACHED_SHADERS = 0x8B85
val GL_ACTIVE_UNIFORMS = 0x8B86
val GL_ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87
val GL_ACTIVE_ATTRIBUTES = 0x8B89
val GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A
val GL_SHADING_LANGUAGE_VERSION = 0x8B8C
val GL_CURRENT_PROGRAM = 0x8B8D
val GL_NEVER = 0x0200
val GL_LESS = 0x0201
val GL_EQUAL = 0x0202
val GL_LEQUAL = 0x0203
val GL_GREATER = 0x0204
val GL_NOTEQUAL = 0x0205
val GL_GEQUAL = 0x0206
val GL_ALWAYS = 0x0207
val GL_KEEP = 0x1E00
val GL_REPLACE = 0x1E01
val GL_INCR = 0x1E02
val GL_DECR = 0x1E03
val GL_INVERT = 0x150A
val GL_INCR_WRAP = 0x8507
val GL_DECR_WRAP = 0x8508
val GL_VENDOR = 0x1F00
val GL_RENDERER = 0x1F01
val GL_VERSION = 0x1F02
val GL_EXTENSIONS = 0x1F03
val GL_NEAREST = 0x2600
val GL_LINEAR = 0x2601
val GL_NEAREST_MIPMAP_NEAREST = 0x2700
val GL_LINEAR_MIPMAP_NEAREST = 0x2701
val GL_NEAREST_MIPMAP_LINEAR = 0x2702
val GL_LINEAR_MIPMAP_LINEAR = 0x2703
val GL_TEXTURE_MAG_FILTER = 0x2800
val GL_TEXTURE_MIN_FILTER = 0x2801
val GL_TEXTURE_WRAP_S = 0x2802
val GL_TEXTURE_WRAP_T = 0x2803
val GL_TEXTURE = 0x1702
val GL_TEXTURE_CUBE_MAP = 0x8513
val GL_TEXTURE_BINDING_CUBE_MAP = 0x8514
val GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515
val GL_TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516
val GL_TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517
val GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518
val GL_TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519
val GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A
val GL_MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C
val GL_TEXTURE0 = 0x84C0
val GL_TEXTURE1 = 0x84C1
val GL_TEXTURE2 = 0x84C2
val GL_TEXTURE3 = 0x84C3
val GL_TEXTURE4 = 0x84C4
val GL_TEXTURE5 = 0x84C5
val GL_TEXTURE6 = 0x84C6
val GL_TEXTURE7 = 0x84C7
val GL_TEXTURE8 = 0x84C8
val GL_TEXTURE9 = 0x84C9
val GL_TEXTURE10 = 0x84CA
val GL_TEXTURE11 = 0x84CB
val GL_TEXTURE12 = 0x84CC
val GL_TEXTURE13 = 0x84CD
val GL_TEXTURE14 = 0x84CE
val GL_TEXTURE15 = 0x84CF
val GL_TEXTURE16 = 0x84D0
val GL_TEXTURE17 = 0x84D1
val GL_TEXTURE18 = 0x84D2
val GL_TEXTURE19 = 0x84D3
val GL_TEXTURE20 = 0x84D4
val GL_TEXTURE21 = 0x84D5
val GL_TEXTURE22 = 0x84D6
val GL_TEXTURE23 = 0x84D7
val GL_TEXTURE24 = 0x84D8
val GL_TEXTURE25 = 0x84D9
val GL_TEXTURE26 = 0x84DA
val GL_TEXTURE27 = 0x84DB
val GL_TEXTURE28 = 0x84DC
val GL_TEXTURE29 = 0x84DD
val GL_TEXTURE30 = 0x84DE
val GL_TEXTURE31 = 0x84DF
val GL_REPEAT = 0x2901
val GL_CLAMP_TO_EDGE = 0x812F
val GL_MIRRORED_REPEAT = 0x8370
val GL_FLOAT_VEC2 = 0x8B50
val GL_FLOAT_VEC3 = 0x8B51
val GL_FLOAT_VEC4 = 0x8B52
val GL_INT_VEC2 = 0x8B53
val GL_INT_VEC3 = 0x8B54
val GL_INT_VEC4 = 0x8B55
val GL_BOOL = 0x8B56
val GL_BOOL_VEC2 = 0x8B57
val GL_BOOL_VEC3 = 0x8B58
val GL_BOOL_VEC4 = 0x8B59
val GL_FLOAT_MAT2 = 0x8B5A
val GL_FLOAT_MAT3 = 0x8B5B
val GL_FLOAT_MAT4 = 0x8B5C
val GL_SAMPLER_2D = 0x8B5E
val GL_SAMPLER_CUBE = 0x8B60
val GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622
val GL_VERTEX_ATTRIB_ARRAY_SIZE = 0x8623
val GL_VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624
val GL_VERTEX_ATTRIB_ARRAY_TYPE = 0x8625
val GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A
val GL_VERTEX_ATTRIB_ARRAY_POINTER = 0x8645
val GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F
val GL_IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A
val GL_IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B
val GL_COMPILE_STATUS = 0x8B81
val GL_INFO_LOG_LENGTH = 0x8B84
val GL_SHADER_SOURCE_LENGTH = 0x8B88
val GL_SHADER_COMPILER = 0x8DFA
val GL_SHADER_BINARY_FORMATS = 0x8DF8
val GL_NUM_SHADER_BINARY_FORMATS = 0x8DF9
val GL_LOW_FLOAT = 0x8DF0
val GL_MEDIUM_FLOAT = 0x8DF1
val GL_HIGH_FLOAT = 0x8DF2
val GL_LOW_INT = 0x8DF3
val GL_MEDIUM_INT = 0x8DF4
val GL_HIGH_INT = 0x8DF5
val GL_FRAMEBUFFER = 0x8D40
val GL_RENDERBUFFER = 0x8D41
val GL_RGBA4 = 0x8056
val GL_RGB5_A1 = 0x8057
val GL_RGB565 = 0x8D62
val GL_DEPTH_COMPONENT16 = 0x81A5
val GL_STENCIL_INDEX = 0x1901
val GL_STENCIL_INDEX8 = 0x8D48
val GL_RENDERBUFFER_WIDTH = 0x8D42
val GL_RENDERBUFFER_HEIGHT = 0x8D43
val GL_RENDERBUFFER_INTERNAL_FORMAT = 0x8D44
val GL_RENDERBUFFER_RED_SIZE = 0x8D50
val GL_RENDERBUFFER_GREEN_SIZE = 0x8D51
val GL_RENDERBUFFER_BLUE_SIZE = 0x8D52
val GL_RENDERBUFFER_ALPHA_SIZE = 0x8D53
val GL_RENDERBUFFER_DEPTH_SIZE = 0x8D54
val GL_RENDERBUFFER_STENCIL_SIZE = 0x8D55
val GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0
val GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1
val GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2
val GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3
val GL_COLOR_ATTACHMENT0 = 0x8CE0
val GL_DEPTH_ATTACHMENT = 0x8D00
val GL_STENCIL_ATTACHMENT = 0x8D20
val GL_NONE = 0
val GL_FRAMEBUFFER_COMPLETE = 0x8CD5
val GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6
val GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7
val GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9
val GL_FRAMEBUFFER_UNSUPPORTED = 0x8CDD
val GL_FRAMEBUFFER_BINDING = 0x8CA6
val GL_RENDERBUFFER_BINDING = 0x8CA7
val GL_MAX_RENDERBUFFER_SIZE = 0x84E8
val GL_INVALID_FRAMEBUFFER_OPERATION = 0x0506
}
}
| apache-2.0 | 1a2d3c5f8b274404f27627f33dc99cf3 | 44.519588 | 212 | 0.667935 | 3.760027 | false | false | false | false |
Seancheey/Ark-Sonah | src/com/seancheey/gui/RobotEditInterface.kt | 1 | 2982 | package com.seancheey.gui
import com.seancheey.game.Config
import com.seancheey.game.battlefield.EmptyBattlefield
import com.seancheey.game.model.ComponentModel
import com.seancheey.game.model.ComponentNode
import com.seancheey.game.model.RobotModel
/**
* Created by Seancheey on 13/06/2017.
* GitHub: https://github.com/Seancheey
*/
interface RobotEditInterface {
companion object {
private fun symmetricComponent(component: ComponentNode): ComponentNode? {
val symX = Config.botGridNum - component.gridX - component.model.gridWidth
if (symX != component.gridX) {
return ComponentNode.create(component.model, Config.botGridNum - component.gridX - component.model.gridWidth, component.gridY, EmptyBattlefield())
} else {
return null
}
}
}
var editingRobot: RobotModel
var editRobotModelStack: ArrayList<RobotModel>
var symmetricBuild: Boolean
fun addComponentAt(x: Int, y: Int, model: ComponentModel) {
addComponent(ComponentNode.create(model, x, y, EmptyBattlefield()))
}
fun addComponent(component: ComponentNode) {
val symComponent = symmetricComponent(component)
if (symmetricBuild && symComponent != null) {
editingRobot = RobotModel(editingRobot.name, editingRobot.components + component + symComponent)
} else {
editingRobot = RobotModel(editingRobot.name, editingRobot.components + component)
}
updateRobotModel()
}
fun removeComponent(component: ComponentNode) {
val symComp = symmetricComponent(component)
editingRobot = RobotModel(editingRobot.name, editingRobot.components.filterNot { it == component || (symmetricBuild && it == symComp) })
updateRobotModel()
}
fun clearComponents() {
editingRobot = RobotModel(editingRobot.name, listOf())
updateRobotModel()
}
fun resetRobotModel(model: RobotModel) {
editingRobot = RobotModel(model.name, model.components)
updateRobotModel()
// flush editing stack
editRobotModelStack.clear()
}
fun moveAllComponents(dx: Int, dy: Int) {
val newComps = editingRobot.components.map { ComponentNode.create(it.model, it.gridX + dx, it.gridY + dy, EmptyBattlefield()) }
editingRobot = RobotModel(editingRobot.name, newComps)
updateRobotModel()
}
fun undoRobotModel() {
if (editRobotModelStack.size > 0) {
editingRobot = editRobotModelStack.last()
// editingRobot assignment add one change, so remove twice
editRobotModelStack.remove(editRobotModelStack.last())
editRobotModelStack.remove(editRobotModelStack.last())
updateRobotModel()
}
}
fun setRobotModelName(name: String) {
editingRobot = RobotModel(name, editingRobot.components)
updateRobotModel()
}
fun updateRobotModel()
} | mit | 44e2f61419057ed9af208586dae69242 | 34.511905 | 162 | 0.674715 | 4.353285 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/platform/UsersTypeServiceImpl.kt | 1 | 1350 | package top.zbeboy.isy.service.platform
import org.jooq.DSLContext
import org.jooq.Result
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import top.zbeboy.isy.domain.tables.daos.UsersTypeDao
import top.zbeboy.isy.domain.tables.records.UsersTypeRecord
import javax.annotation.Resource
import top.zbeboy.isy.domain.tables.UsersType.USERS_TYPE
/**
* Created by zbeboy 2017-11-16 .
**/
@Service("usersTypeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class UsersTypeServiceImpl @Autowired constructor(dslContext: DSLContext) : UsersTypeService {
private val create: DSLContext = dslContext
@Resource
open lateinit var usersTypeDao: UsersTypeDao
@Resource
open lateinit var usersService: UsersService
override fun findAll(): Result<UsersTypeRecord> {
return create.selectFrom<UsersTypeRecord>(USERS_TYPE).fetch()
}
override fun isCurrentUsersTypeName(usersTypeName: String): Boolean {
val users = usersService.getUserFromSession()
val usersType = usersTypeDao.fetchOneByUsersTypeId(users!!.usersTypeId).usersTypeName
return usersTypeName == usersType
}
} | mit | 0d043d27ab8dd0a57aaee7c57bc4f528 | 34.552632 | 99 | 0.78963 | 4.440789 | false | false | false | false |
airbnb/epoxy | epoxy-sample/src/main/java/com/airbnb/epoxy/sample/models/TestModel6.kt | 1 | 522 | package com.airbnb.epoxy.sample.models
import android.view.View
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModel
import com.airbnb.epoxy.EpoxyModelClass
import com.airbnb.epoxy.sample.R
@EpoxyModelClass(layout = R.layout.model_color)
abstract class TestModel6 : EpoxyModel<View>() {
@EpoxyAttribute
var num: Int = 0
@EpoxyAttribute
var num2: Int = 0
@EpoxyAttribute
var num3: Int = 0
@EpoxyAttribute
var num4: Int = 0
@EpoxyAttribute
var num5: Int = 0
}
| apache-2.0 | 91459142aad600eed8a523870c9cbee1 | 22.727273 | 48 | 0.726054 | 3.755396 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/RESTFUL_USER.kt | 2 | 1906 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
object RESTFUL_USER : Response(){
override val url = "http://localhost:8080/restful/user"
override val str = """{
"userName": "sven",
"roles": ["iniRealm:admin_role"],
"links": [{
"rel": "self",
"href": "http://localhost:8080/restful/user",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/user\""
}, {
"rel": "up",
"href": "http://localhost:8080/restful/",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/homepage\""
}, {
"rel": "urn:org.apache.causeway.restfulobjects:rels/logout",
"href": "http://localhost:8080/restful/user/logout",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/homepage\""
}],
"extensions": {}
}"""
}
| apache-2.0 | c904d90b54e3dcd89531823c4a24b840 | 40.434783 | 92 | 0.637985 | 4.046709 | false | false | false | false |
google/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt | 5 | 28106 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.core
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.builtins.isFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.extensions.DeclarationAttributeAltererExtension
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.addRemoveModifier.MODIFIERS_ORDER
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentsInParentheses
import org.jetbrains.kotlin.resolve.calls.util.isFakeElement
import org.jetbrains.kotlin.resolve.checkers.ExplicitApiDeclarationChecker
import org.jetbrains.kotlin.resolve.checkers.explicitApiEnabled
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.SamConversionOracle
import org.jetbrains.kotlin.resolve.sam.SamConversionResolver
import org.jetbrains.kotlin.resolve.sam.getFunctionTypeForPossibleSamType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun KtLambdaArgument.moveInsideParentheses(bindingContext: BindingContext): KtCallExpression {
val ktExpression = this.getArgumentExpression()
?: throw KotlinExceptionWithAttachments("no argument expression for $this")
.withPsiAttachment("lambdaExpression", this)
return moveInsideParenthesesAndReplaceWith(ktExpression, bindingContext)
}
fun KtLambdaArgument.moveInsideParenthesesAndReplaceWith(
replacement: KtExpression,
bindingContext: BindingContext
): KtCallExpression = moveInsideParenthesesAndReplaceWith(replacement, getLambdaArgumentName(bindingContext))
fun KtLambdaArgument.getLambdaArgumentName(bindingContext: BindingContext): Name? {
val callExpression = parent as KtCallExpression
val resolvedCall = callExpression.getResolvedCall(bindingContext)
return (resolvedCall?.getArgumentMapping(this) as? ArgumentMatch)?.valueParameter?.name
}
fun KtLambdaArgument.moveInsideParenthesesAndReplaceWith(
replacement: KtExpression,
functionLiteralArgumentName: Name?,
withNameCheck: Boolean = true,
): KtCallExpression {
val oldCallExpression = parent as KtCallExpression
val newCallExpression = oldCallExpression.copy() as KtCallExpression
val psiFactory = KtPsiFactory(project)
val argument =
if (withNameCheck && shouldLambdaParameterBeNamed(newCallExpression.getValueArgumentsInParentheses(), oldCallExpression)) {
psiFactory.createArgument(replacement, functionLiteralArgumentName)
} else {
psiFactory.createArgument(replacement)
}
val functionLiteralArgument = newCallExpression.lambdaArguments.firstOrNull()!!
val valueArgumentList = newCallExpression.valueArgumentList ?: psiFactory.createCallArguments("()")
valueArgumentList.addArgument(argument)
(functionLiteralArgument.prevSibling as? PsiWhiteSpace)?.delete()
if (newCallExpression.valueArgumentList != null) {
functionLiteralArgument.delete()
} else {
functionLiteralArgument.replace(valueArgumentList)
}
return oldCallExpression.replace(newCallExpression) as KtCallExpression
}
fun KtLambdaExpression.moveFunctionLiteralOutsideParenthesesIfPossible() {
val valueArgument = parentOfType<KtValueArgument>()?.takeIf {
KtPsiUtil.deparenthesize(it.getArgumentExpression()) == this
} ?: return
val valueArgumentList = valueArgument.parent as? KtValueArgumentList ?: return
val call = valueArgumentList.parent as? KtCallExpression ?: return
if (call.canMoveLambdaOutsideParentheses()) {
call.moveFunctionLiteralOutsideParentheses()
}
}
private fun shouldLambdaParameterBeNamed(args: List<ValueArgument>, callExpr: KtCallExpression): Boolean {
if (args.any { it.isNamed() }) return true
val callee = (callExpr.calleeExpression?.mainReference?.resolve() as? KtFunction) ?: return false
return if (callee.valueParameters.any { it.isVarArg }) true else callee.valueParameters.size - 1 > args.size
}
fun KtCallExpression.getLastLambdaExpression(): KtLambdaExpression? {
if (lambdaArguments.isNotEmpty()) return null
return valueArguments.lastOrNull()?.getArgumentExpression()?.unpackFunctionLiteral()
}
@OptIn(FrontendInternals::class)
fun KtCallExpression.canMoveLambdaOutsideParentheses(): Boolean {
if (getStrictParentOfType<KtDelegatedSuperTypeEntry>() != null) return false
val lastLambdaExpression = getLastLambdaExpression() ?: return false
if (lastLambdaExpression.parentLabeledExpression()?.parentLabeledExpression() != null) return false
val callee = calleeExpression
if (callee is KtNameReferenceExpression) {
val resolutionFacade = getResolutionFacade()
val samConversionTransformer = resolutionFacade.frontendService<SamConversionResolver>()
val samConversionOracle = resolutionFacade.frontendService<SamConversionOracle>()
val languageVersionSettings = resolutionFacade.languageVersionSettings
val newInferenceEnabled = languageVersionSettings.supportsFeature(LanguageFeature.NewInference)
val bindingContext = safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
if (bindingContext.diagnostics.forElement(lastLambdaExpression).none { it.severity == Severity.ERROR }) {
val resolvedCall = getResolvedCall(bindingContext)
if (resolvedCall != null) {
val parameter = resolvedCall.getParameterForArgument(valueArguments.last()) ?: return false
val functionDescriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false
if (parameter != functionDescriptor.valueParameters.lastOrNull()) return false
return parameter.type.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)
}
}
val targets = bindingContext[BindingContext.REFERENCE_TARGET, callee]?.let { listOf(it) }
?: bindingContext[BindingContext.AMBIGUOUS_REFERENCE_TARGET, callee]
?: listOf()
val candidates = targets.filterIsInstance<FunctionDescriptor>()
val lambdaArgumentCount = valueArguments.count { it.getArgumentExpression()?.unpackFunctionLiteral() != null }
val referenceArgumentCount = valueArguments.count { it.getArgumentExpression() is KtCallableReferenceExpression }
// if there are functions among candidates but none of them have last function parameter then not show the intention
val areAllCandidatesWithoutLastFunctionParameter = candidates.none {
it.allowsMoveOfLastParameterOutsideParentheses(
lambdaArgumentCount + referenceArgumentCount,
samConversionTransformer,
samConversionOracle,
newInferenceEnabled
)
}
if (candidates.isNotEmpty() && areAllCandidatesWithoutLastFunctionParameter) return false
}
return true
}
private fun KtExpression.parentLabeledExpression(): KtLabeledExpression? {
return getStrictParentOfType<KtLabeledExpression>()?.takeIf { it.baseExpression == this }
}
private fun KotlinType.allowsMoveOutsideParentheses(
samConversionTransformer: SamConversionResolver,
samConversionOracle: SamConversionOracle,
newInferenceEnabled: Boolean
): Boolean {
// Fast-path
if (isFunctionOrSuspendFunctionType || isTypeParameter()) return true
// Also check if it can be SAM-converted
// Note that it is not necessary in OI, where we provide synthetic candidate descriptors with already
// converted types, but in NI it is performed by conversions, so we check it explicitly
// Also note that 'newInferenceEnabled' is essentially a micro-optimization, as there are no
// harm in just calling 'samConversionTransformer' on all candidates.
return newInferenceEnabled && samConversionTransformer.getFunctionTypeForPossibleSamType(this.unwrap(), samConversionOracle) != null
}
private fun FunctionDescriptor.allowsMoveOfLastParameterOutsideParentheses(
lambdaAndCallableReferencesInOriginalCallCount: Int,
samConversionTransformer: SamConversionResolver,
samConversionOracle: SamConversionOracle,
newInferenceEnabled: Boolean
): Boolean {
val params = valueParameters
val lastParamType = params.lastOrNull()?.type ?: return false
if (!lastParamType.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)) return false
val movableParametersOfCandidateCount = params.count {
it.type.allowsMoveOutsideParentheses(samConversionTransformer, samConversionOracle, newInferenceEnabled)
}
return movableParametersOfCandidateCount == lambdaAndCallableReferencesInOriginalCallCount
}
fun KtCallExpression.moveFunctionLiteralOutsideParentheses() {
assert(lambdaArguments.isEmpty())
val argumentList = valueArgumentList!!
val argument = argumentList.arguments.last()
val expression = argument.getArgumentExpression()!!
assert(expression.unpackFunctionLiteral() != null)
fun isWhiteSpaceOrComment(e: PsiElement) = e is PsiWhiteSpace || e is PsiComment
val prevComma = argument.siblings(forward = false, withItself = false).firstOrNull { it.elementType == KtTokens.COMMA }
val prevComments = (prevComma ?: argumentList.leftParenthesis)
?.siblings(forward = true, withItself = false)
?.takeWhile(::isWhiteSpaceOrComment)?.toList().orEmpty()
val nextComments = argumentList.rightParenthesis
?.siblings(forward = false, withItself = false)
?.takeWhile(::isWhiteSpaceOrComment)?.toList()?.reversed().orEmpty()
val psiFactory = KtPsiFactory(project)
val dummyCall = psiFactory.createExpression("foo() {}") as KtCallExpression
val functionLiteralArgument = dummyCall.lambdaArguments.single()
functionLiteralArgument.getArgumentExpression()?.replace(expression)
if (prevComments.any { it is PsiComment }) {
if (prevComments.firstOrNull() !is PsiWhiteSpace) this.add(psiFactory.createWhiteSpace())
prevComments.forEach { this.add(it) }
prevComments.forEach { if (it is PsiComment) it.delete() }
}
this.add(functionLiteralArgument)
if (nextComments.any { it is PsiComment }) {
nextComments.forEach { this.add(it) }
nextComments.forEach { if (it is PsiComment) it.delete() }
}
/* we should not remove empty parenthesis when callee is a call too - it won't parse */
if (argumentList.arguments.size == 1 && calleeExpression !is KtCallExpression) {
argumentList.delete()
} else {
argumentList.removeArgument(argument)
}
}
fun KtBlockExpression.appendElement(element: KtElement, addNewLine: Boolean = false): KtElement {
val rBrace = rBrace
val newLine = KtPsiFactory(this).createNewLine()
val anchor = if (rBrace == null) {
val lastChild = lastChild
lastChild as? PsiWhiteSpace ?: addAfter(newLine, lastChild)!!
} else {
rBrace.prevSibling!!
}
val addedElement = addAfter(element, anchor)!! as KtElement
if (addNewLine) {
addAfter(newLine, addedElement)
}
return addedElement
}
//TODO: git rid of this method
fun PsiElement.deleteElementAndCleanParent() {
val parent = parent
deleteElementWithDelimiters(this)
deleteChildlessElement(parent, this::class.java)
}
// Delete element if it doesn't contain children of a given type
private fun <T : PsiElement> deleteChildlessElement(element: PsiElement, childClass: Class<T>) {
if (PsiTreeUtil.getChildrenOfType(element, childClass) == null) {
element.delete()
}
}
// Delete given element and all the elements separating it from the neighboring elements of the same class
private fun deleteElementWithDelimiters(element: PsiElement) {
val paramBefore = PsiTreeUtil.getPrevSiblingOfType(element, element.javaClass)
val from: PsiElement
val to: PsiElement
if (paramBefore != null) {
from = paramBefore.nextSibling
to = element
} else {
val paramAfter = PsiTreeUtil.getNextSiblingOfType(element, element.javaClass)
from = element
to = if (paramAfter != null) paramAfter.prevSibling else element
}
val parent = element.parent
parent.deleteChildRange(from, to)
}
fun PsiElement.deleteSingle() {
CodeEditUtil.removeChild(parent?.node ?: return, node ?: return)
}
fun KtClass.getOrCreateCompanionObject(): KtObjectDeclaration {
companionObjects.firstOrNull()?.let { return it }
return appendDeclaration(KtPsiFactory(this).createCompanionObject())
}
inline fun <reified T : KtDeclaration> KtClass.appendDeclaration(declaration: T): T {
val body = getOrCreateBody()
val anchor = PsiTreeUtil.skipSiblingsBackward(body.rBrace ?: body.lastChild!!, PsiWhiteSpace::class.java)
val newDeclaration =
if (anchor?.nextSibling is PsiErrorElement)
body.addBefore(declaration, anchor)
else
body.addAfter(declaration, anchor)
return newDeclaration as T
}
fun KtDeclaration.toDescriptor(): DeclarationDescriptor? {
if (this is KtScriptInitializer) {
return null
}
return resolveToDescriptorIfAny()
}
fun KtModifierListOwner.setVisibility(visibilityModifier: KtModifierKeywordToken, addImplicitVisibilityModifier: Boolean = false) {
if (this is KtDeclaration && !addImplicitVisibilityModifier) {
val defaultVisibilityKeyword = implicitVisibility()
if (visibilityModifier == defaultVisibilityKeyword) {
// Fake elements do not have ModuleInfo and languageVersionSettings because they can't be analysed
// Effectively, this leads to J2K not respecting explicit api mode, but this case seems to be rare anyway.
val explicitVisibilityRequired = !this.isFakeElement &&
this.languageVersionSettings.explicitApiEnabled &&
this.resolveToDescriptorIfAny()?.let { !ExplicitApiDeclarationChecker.explicitVisibilityIsNotRequired(it) } == true
if (!explicitVisibilityRequired) {
this.visibilityModifierType()?.let { removeModifier(it) }
return
}
}
}
addModifier(visibilityModifier)
}
fun KtDeclaration.implicitVisibility(): KtModifierKeywordToken? {
return when {
this is KtPropertyAccessor && isSetter && property.hasModifier(KtTokens.OVERRIDE_KEYWORD) -> {
property.resolveToDescriptorIfAny()
?.safeAs<PropertyDescriptor>()
?.overriddenDescriptors?.forEach {
val visibility = it.setter?.visibility?.toKeywordToken()
if (visibility != null) return visibility
}
KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
this is KtConstructor<*> -> {
// constructors cannot be declared in objects
val klass = getContainingClassOrObject() as? KtClass ?: return KtTokens.DEFAULT_VISIBILITY_KEYWORD
when {
klass.isEnum() -> KtTokens.PRIVATE_KEYWORD
klass.isSealed() ->
if (klass.languageVersionSettings.supportsFeature(LanguageFeature.SealedInterfaces)) KtTokens.PROTECTED_KEYWORD
else KtTokens.PRIVATE_KEYWORD
else -> KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
}
hasModifier(KtTokens.OVERRIDE_KEYWORD) -> {
resolveToDescriptorIfAny()?.safeAs<CallableMemberDescriptor>()
?.overriddenDescriptors
?.let { OverridingUtil.findMaxVisibility(it) }
?.toKeywordToken()
}
else -> KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
}
fun KtModifierListOwner.canBePrivate(): Boolean {
if (modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true) return false
if (this.isAnnotationClassPrimaryConstructor()) return false
if (this is KtProperty && this.hasJvmFieldAnnotation()) return false
if (this is KtDeclaration) {
if (hasActualModifier() || isExpectDeclaration()) return false
val containingClassOrObject = containingClassOrObject as? KtClass ?: return true
if (containingClassOrObject.isAnnotation()) return false
if (containingClassOrObject.isInterface() && !hasBody()) return false
}
return true
}
fun KtModifierListOwner.canBePublic(): Boolean = !isSealedClassConstructor()
fun KtModifierListOwner.canBeProtected(): Boolean {
return when (val parent = if (this is KtPropertyAccessor) this.property.parent else this.parent) {
is KtClassBody -> {
val parentClass = parent.parent as? KtClass
parentClass != null && !parentClass.isInterface() && !this.isFinalClassConstructor()
}
is KtParameterList -> parent.parent is KtPrimaryConstructor
is KtClass -> !this.isAnnotationClassPrimaryConstructor() && !this.isFinalClassConstructor()
else -> false
}
}
fun KtModifierListOwner.canBeInternal(): Boolean {
if (containingClass()?.isInterface() == true) {
val objectDeclaration = getStrictParentOfType<KtObjectDeclaration>() ?: return false
if (objectDeclaration.isCompanion() && hasJvmFieldAnnotation()) return false
}
return !isAnnotationClassPrimaryConstructor() && !isSealedClassConstructor()
}
private fun KtModifierListOwner.isAnnotationClassPrimaryConstructor(): Boolean =
this is KtPrimaryConstructor && (this.parent as? KtClass)?.hasModifier(KtTokens.ANNOTATION_KEYWORD) ?: false
private fun KtModifierListOwner.isFinalClassConstructor(): Boolean {
if (this !is KtConstructor<*>) return false
val ktClass = getContainingClassOrObject().safeAs<KtClass>() ?: return false
return ktClass.toDescriptor().safeAs<ClassDescriptor>()?.isFinalOrEnum ?: return false
}
private fun KtModifierListOwner.isSealedClassConstructor(): Boolean {
if (this !is KtConstructor<*>) return false
val ktClass = getContainingClassOrObject().safeAs<KtClass>() ?: return false
return ktClass.isSealed()
}
fun KtClass.isInheritable(): Boolean {
return when (getModalityFromDescriptor()) {
KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD, KtTokens.SEALED_KEYWORD -> true
else -> false
}
}
val KtParameter.isOverridable: Boolean
get() = hasValOrVar() && !isEffectivelyFinal
val KtProperty.isOverridable: Boolean
get() = !isTopLevel && !isEffectivelyFinal
private val KtDeclaration.isEffectivelyFinal: Boolean
get() = hasModifier(KtTokens.FINAL_KEYWORD) ||
!(hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD) || hasModifier(KtTokens.OVERRIDE_KEYWORD)) ||
containingClassOrObject?.isEffectivelyFinal == true
private val KtClassOrObject.isEffectivelyFinal: Boolean
get() = this is KtObjectDeclaration ||
this is KtClass && isEffectivelyFinal
private val KtClass.isEffectivelyFinal: Boolean
get() = hasModifier(KtTokens.FINAL_KEYWORD) ||
isData() ||
!(isSealed() || hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD))
fun KtDeclaration.isOverridable(): Boolean {
val parent = parent
if (!(parent is KtClassBody || parent is KtParameterList)) return false
val klass = if (parent.parent is KtPrimaryConstructor)
parent.parent.parent as? KtClass
else
parent.parent as? KtClass
if (klass == null || (!klass.isInheritable() && !klass.isEnum())) return false
if (this.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
// 'private' is incompatible with 'open'
return false
}
return when (getModalityFromDescriptor()) {
KtTokens.ABSTRACT_KEYWORD, KtTokens.OPEN_KEYWORD -> true
else -> false
}
}
fun KtDeclaration.getModalityFromDescriptor(descriptor: DeclarationDescriptor? = resolveToDescriptorIfAny()): KtModifierKeywordToken? {
if (descriptor is MemberDescriptor) {
return mapModality(descriptor.modality)
}
return null
}
fun KtDeclaration.implicitModality(): KtModifierKeywordToken {
var predictedModality = predictImplicitModality()
val bindingContext = safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] ?: return predictedModality
val containingDescriptor = descriptor.containingDeclaration ?: return predictedModality
val extensions = DeclarationAttributeAltererExtension.getInstances(this.project)
for (extension in extensions) {
val newModality = extension.refineDeclarationModality(
this,
descriptor as? ClassDescriptor,
containingDescriptor,
mapModalityToken(predictedModality),
isImplicitModality = true
)
if (newModality != null) {
predictedModality = mapModality(newModality)
}
}
return predictedModality
}
fun mapModality(accurateModality: Modality): KtModifierKeywordToken = when (accurateModality) {
Modality.FINAL -> KtTokens.FINAL_KEYWORD
Modality.SEALED -> KtTokens.SEALED_KEYWORD
Modality.OPEN -> KtTokens.OPEN_KEYWORD
Modality.ABSTRACT -> KtTokens.ABSTRACT_KEYWORD
}
private fun mapModalityToken(modalityToken: IElementType): Modality = when (modalityToken) {
KtTokens.FINAL_KEYWORD -> Modality.FINAL
KtTokens.SEALED_KEYWORD -> Modality.SEALED
KtTokens.OPEN_KEYWORD -> Modality.OPEN
KtTokens.ABSTRACT_KEYWORD -> Modality.ABSTRACT
else -> error("Unexpected modality keyword $modalityToken")
}
private fun KtDeclaration.predictImplicitModality(): KtModifierKeywordToken {
if (this is KtClassOrObject) {
if (this is KtClass && this.isInterface()) return KtTokens.ABSTRACT_KEYWORD
return KtTokens.FINAL_KEYWORD
}
val klass = containingClassOrObject ?: return KtTokens.FINAL_KEYWORD
if (hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
if (klass.hasModifier(KtTokens.ABSTRACT_KEYWORD) ||
klass.hasModifier(KtTokens.OPEN_KEYWORD) ||
klass.hasModifier(KtTokens.SEALED_KEYWORD)
) {
return KtTokens.OPEN_KEYWORD
}
}
if (klass is KtClass && klass.isInterface() && !hasModifier(KtTokens.PRIVATE_KEYWORD)) {
return if (hasBody()) KtTokens.OPEN_KEYWORD else KtTokens.ABSTRACT_KEYWORD
}
return KtTokens.FINAL_KEYWORD
}
fun KtSecondaryConstructor.getOrCreateBody(): KtBlockExpression {
bodyExpression?.let { return it }
val delegationCall = getDelegationCall()
val anchor = if (delegationCall.isImplicit) valueParameterList else delegationCall
val newBody = KtPsiFactory(this).createEmptyBody()
return addAfter(newBody, anchor) as KtBlockExpression
}
fun KtParameter.dropDefaultValue() {
val from = equalsToken ?: return
val to = defaultValue ?: from
deleteChildRange(from, to)
}
fun KtTypeParameterListOwner.addTypeParameter(typeParameter: KtTypeParameter): KtTypeParameter? {
typeParameterList?.let { return it.addParameter(typeParameter) }
val list = KtPsiFactory(this).createTypeParameterList("<X>")
list.parameters[0].replace(typeParameter)
val leftAnchor = when (this) {
is KtClass -> nameIdentifier
is KtNamedFunction -> funKeyword
is KtProperty -> valOrVarKeyword
is KtTypeAlias -> nameIdentifier
else -> null
} ?: return null
return (addAfter(list, leftAnchor) as KtTypeParameterList).parameters.first()
}
fun KtNamedFunction.getOrCreateValueParameterList(): KtParameterList {
valueParameterList?.let { return it }
val parameterList = KtPsiFactory(this).createParameterList("()")
val anchor = nameIdentifier ?: funKeyword!!
return addAfter(parameterList, anchor) as KtParameterList
}
fun KtCallableDeclaration.setType(type: KotlinType, shortenReferences: Boolean = true) {
if (type.isError) return
setType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type), shortenReferences)
}
fun KtCallableDeclaration.setType(typeString: String, shortenReferences: Boolean = true) {
val typeReference = KtPsiFactory(project).createType(typeString)
setTypeReference(typeReference)
if (shortenReferences) {
ShortenReferences.DEFAULT.process(getTypeReference()!!)
}
}
fun KtCallableDeclaration.setReceiverType(type: KotlinType) {
if (type.isError) return
val typeReference = KtPsiFactory(project).createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type))
setReceiverTypeReference(typeReference)
ShortenReferences.DEFAULT.process(receiverTypeReference!!)
}
fun KtParameter.setDefaultValue(newDefaultValue: KtExpression): PsiElement {
defaultValue?.let { return it.replaced(newDefaultValue) }
val psiFactory = KtPsiFactory(this)
val eq = equalsToken ?: add(psiFactory.createEQ())
return addAfter(newDefaultValue, eq) as KtExpression
}
fun KtModifierList.appendModifier(modifier: KtModifierKeywordToken) {
add(KtPsiFactory(this).createModifier(modifier))
}
fun KtModifierList.normalize(): KtModifierList {
val psiFactory = KtPsiFactory(this)
return psiFactory.createEmptyModifierList().also { newList ->
val modifiers = SmartList<PsiElement>()
allChildren.forEach {
val elementType = it.node.elementType
when {
it is KtAnnotation || it is KtAnnotationEntry -> newList.add(it)
elementType is KtModifierKeywordToken -> {
if (elementType == KtTokens.DEFAULT_VISIBILITY_KEYWORD) return@forEach
if (elementType == KtTokens.FINALLY_KEYWORD && !hasModifier(KtTokens.OVERRIDE_KEYWORD)) return@forEach
modifiers.add(it)
}
}
}
modifiers.sortBy { MODIFIERS_ORDER.indexOf(it.node.elementType) }
modifiers.forEach { newList.add(it) }
}
} | apache-2.0 | 180dd9b9748f3b5219c3e2325e691ae8 | 41.977064 | 136 | 0.738383 | 5.300019 | false | false | false | false |
youdonghai/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/psiUtil.kt | 1 | 2375 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.util
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.mCOLON
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
/**
* @param owner modifier list owner
*
* @return
* * `true` when owner has explicit type or it's not required for owner to have explicit type
* * `false` when doesn't have explicit type and it's required to have a type or modifier
* * `defaultValue` for the other owners
*
*/
fun modifierListMayBeEmpty(owner: PsiElement?): Boolean = when (owner) {
is GrParameter -> owner.parent.let {
when (it) {
is GrForInClause -> it.declaredVariable != owner || it.delimiter.node.elementType != mCOLON
is GrTraditionalForClause -> it.declaredVariable != owner
else -> true
}
}
is GrMethod -> owner.isConstructor || owner.returnTypeElementGroovy != null && !owner.hasTypeParameters()
is GrVariable -> owner.typeElementGroovy != null
is GrVariableDeclaration -> owner.typeElementGroovy != null
else -> true
}
fun GrModifierList.hasOtherModifiers(modifierElementType: IElementType): Boolean {
return modifiers.any { it.node.elementType != modifierElementType }
}
| apache-2.0 | 2f513f00d3609c224fcede1fc78cd378 | 42.981481 | 107 | 0.770105 | 4.094828 | false | false | false | false |
vanniktech/RxBinding | rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/widget/RxProgressBar.kt | 1 | 1998 | @file:Suppress("NOTHING_TO_INLINE")
package com.jakewharton.rxbinding2.widget
import android.support.annotation.CheckResult
import android.widget.ProgressBar
import io.reactivex.functions.Consumer
import kotlin.Int
import kotlin.Suppress
/**
* An action which increments the progress value of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun ProgressBar.incrementProgressBy(): Consumer<in Int> = RxProgressBar.incrementProgressBy(this)
/**
* An action which increments the secondary progress value of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun ProgressBar.incrementSecondaryProgressBy(): Consumer<in Int> = RxProgressBar.incrementSecondaryProgressBy(this)
/**
* An action which sets whether `view` is indeterminate.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun ProgressBar.indeterminate(): Consumer<in Boolean> = RxProgressBar.indeterminate(this)
/**
* An action which sets the max value of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun ProgressBar.max(): Consumer<in Int> = RxProgressBar.max(this)
/**
* An action which sets the progress value of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun ProgressBar.progress(): Consumer<in Int> = RxProgressBar.progress(this)
/**
* An action which sets the secondary progress value of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
@CheckResult
inline fun ProgressBar.secondaryProgress(): Consumer<in Int> = RxProgressBar.secondaryProgress(this)
| apache-2.0 | b196313dea5eea16b851eed004c7a31b | 30.714286 | 122 | 0.759259 | 4.315335 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2016/Day17.kt | 1 | 1415 | package com.nibado.projects.advent.y2016
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.Direction
import com.nibado.projects.advent.Hash
import com.nibado.projects.advent.Point
object Day17 : Day {
private val dirMap = mapOf("D" to Direction.SOUTH, "U" to Direction.NORTH, "R" to Direction.EAST, "L" to Direction.WEST)
private val input = "hhhxzeay"
private val solution : Pair<String, String> by lazy { solve() }
override fun part1() = solution.first
override fun part2() = solution.second.length.toString()
private fun solve() : Pair<String, String> {
val solutions = mutableListOf<String>()
search("", Point(0, 0), solutions)
return solutions.minByOrNull { it.length }!! to solutions.maxByOrNull { it.length }!!
}
private fun search(path: String, current: Point, solutions: MutableList<String>) {
if(current == Point(3, 3)) {
solutions += path
return
}
val md5 = Hash.md5(input + path)
val next = directions(md5)
.map { it.first to current.plus(it.second) }
.filter { it.second.inBound(3,3) }
next.forEach {
search(path + it.first, it.second, solutions)
}
}
private fun directions(md5: String) = listOf("U", "D", "L", "R").filterIndexed { i, _ -> md5[i] in 'b' .. 'f'}.map { it to dirMap[it]!! }
} | mit | 1ac35470915732512ac8f2e9f616831a | 33.536585 | 141 | 0.620495 | 3.675325 | false | false | false | false |
allotria/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/RefsTable.kt | 1 | 21308 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.util.containers.HashSetInterner
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId.ConnectionType
import com.intellij.workspaceModel.storage.impl.containers.*
import java.util.function.IntFunction
/**
* [isChildNullable] property is ignored for [ConnectionType.ONE_TO_ABSTRACT_MANY] and [ConnectionType.ONE_TO_MANY]
*/
internal class ConnectionId private constructor(
val parentClass: Int,
val childClass: Int,
val connectionType: ConnectionType,
val isParentNullable: Boolean,
val isChildNullable: Boolean
) {
enum class ConnectionType {
ONE_TO_ONE,
ONE_TO_MANY,
ONE_TO_ABSTRACT_MANY,
ABSTRACT_ONE_TO_ONE
}
/**
* This function returns true if this connection allows removing children of parent.
*
* E.g. child is nullable for parent entity, so the child can be safely removed.
*/
fun canRemoveChild(): Boolean {
return connectionType == ConnectionType.ONE_TO_ABSTRACT_MANY || connectionType == ConnectionType.ONE_TO_MANY || isChildNullable
}
/**
* This function returns true if this connection allows removing parent of child.
*
* E.g. parent is optional (nullable) for child entity, so the parent can be safely removed.
*/
fun canRemoveParent(): Boolean = isParentNullable
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ConnectionId
if (parentClass != other.parentClass) return false
if (childClass != other.childClass) return false
if (connectionType != other.connectionType) return false
if (isParentNullable != other.isParentNullable) return false
if (isChildNullable != other.isChildNullable) return false
return true
}
override fun hashCode(): Int {
var result = parentClass.hashCode()
result = 31 * result + childClass.hashCode()
result = 31 * result + connectionType.hashCode()
result = 31 * result + isParentNullable.hashCode()
result = 31 * result + isChildNullable.hashCode()
return result
}
override fun toString(): String {
return "Connection(parent=${ClassToIntConverter.getClassOrDie(
parentClass).simpleName} " +
"child=${ClassToIntConverter.getClassOrDie(
childClass).simpleName} $connectionType)"
}
fun debugStr(): String = """
ConnectionId info:
- Parent class: ${this.parentClass.findEntityClass<WorkspaceEntity>()}
- Child class: ${this.childClass.findEntityClass<WorkspaceEntity>()}
- Connection type: $connectionType
- Parent of child is nullable: $isParentNullable
- Child of parent is nullable: $isChildNullable
""".trimIndent()
companion object {
/** This function should be [@Synchronized] because interner is not thread-save */
@Synchronized
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> create(
parentClass: Class<Parent>,
childClass: Class<Child>,
connectionType: ConnectionType,
isParentNullable: Boolean,
isChildNullable: Boolean
): ConnectionId {
val connectionId = ConnectionId(parentClass.toClassId(), childClass.toClassId(), connectionType, isParentNullable, isChildNullable)
return interner.intern(connectionId)
}
private val interner = HashSetInterner<ConnectionId>()
}
}
/**
* [oneToManyContainer]: [ImmutableNonNegativeIntIntBiMap] - key - child, value - parent
*/
internal class RefsTable internal constructor(
override val oneToManyContainer: Map<ConnectionId, ImmutableNonNegativeIntIntBiMap>,
override val oneToOneContainer: Map<ConnectionId, ImmutableIntIntUniqueBiMap>,
override val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<EntityId, EntityId>>,
override val abstractOneToOneContainer: Map<ConnectionId, BiMap<EntityId, EntityId>>
) : AbstractRefsTable() {
constructor() : this(HashMap(), HashMap(), HashMap(), HashMap())
}
internal class MutableRefsTable(
override val oneToManyContainer: MutableMap<ConnectionId, NonNegativeIntIntBiMap>,
override val oneToOneContainer: MutableMap<ConnectionId, IntIntUniqueBiMap>,
override val oneToAbstractManyContainer: MutableMap<ConnectionId, LinkedBidirectionalMap<EntityId, EntityId>>,
override val abstractOneToOneContainer: MutableMap<ConnectionId, BiMap<EntityId, EntityId>>
) : AbstractRefsTable() {
private val oneToAbstractManyCopiedToModify: MutableSet<ConnectionId> = HashSet()
private val abstractOneToOneCopiedToModify: MutableSet<ConnectionId> = HashSet()
private fun getOneToManyMutableMap(connectionId: ConnectionId): MutableNonNegativeIntIntBiMap {
val bimap = oneToManyContainer[connectionId] ?: run {
val empty = MutableNonNegativeIntIntBiMap()
oneToManyContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableNonNegativeIntIntBiMap -> bimap
is ImmutableNonNegativeIntIntBiMap -> {
val copy = bimap.toMutable()
oneToManyContainer[connectionId] = copy
copy
}
}
}
private fun getOneToAbstractManyMutableMap(connectionId: ConnectionId): LinkedBidirectionalMap<EntityId, EntityId> {
if (connectionId !in oneToAbstractManyContainer) {
oneToAbstractManyContainer[connectionId] = LinkedBidirectionalMap()
}
return if (connectionId in oneToAbstractManyCopiedToModify) {
oneToAbstractManyContainer[connectionId]!!
}
else {
val copy = LinkedBidirectionalMap<EntityId, EntityId>()
val original = oneToAbstractManyContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
oneToAbstractManyContainer[connectionId] = copy
oneToAbstractManyCopiedToModify.add(connectionId)
copy
}
}
private fun getAbstractOneToOneMutableMap(connectionId: ConnectionId): BiMap<EntityId, EntityId> {
if (connectionId !in abstractOneToOneContainer) {
abstractOneToOneContainer[connectionId] = HashBiMap.create()
}
return if (connectionId in abstractOneToOneCopiedToModify) {
abstractOneToOneContainer[connectionId]!!
}
else {
val copy = HashBiMap.create<EntityId, EntityId>()
val original = abstractOneToOneContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
abstractOneToOneContainer[connectionId] = copy
abstractOneToOneCopiedToModify.add(connectionId)
copy
}
}
private fun getOneToOneMutableMap(connectionId: ConnectionId): MutableIntIntUniqueBiMap {
val bimap = oneToOneContainer[connectionId] ?: run {
val empty = MutableIntIntUniqueBiMap()
oneToOneContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableIntIntUniqueBiMap -> bimap
is ImmutableIntIntUniqueBiMap -> {
val copy = bimap.toMutable()
oneToOneContainer[connectionId] = copy
copy
}
}
}
fun removeRefsByParent(connectionId: ConnectionId, parentId: EntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).removeValue(parentId.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).removeValue(parentId.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).removeValue(parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}.let { }
}
fun removeOneToOneRefByParent(connectionId: ConnectionId, parentId: Int) {
getOneToOneMutableMap(connectionId).removeValue(parentId)
}
fun removeOneToOneRefByChild(connectionId: ConnectionId, childId: Int) {
getOneToOneMutableMap(connectionId).removeKey(childId)
}
fun removeOneToManyRefsByChild(connectionId: ConnectionId, childId: Int) {
getOneToManyMutableMap(connectionId).removeKey(childId)
}
fun removeParentToChildRef(connectionId: ConnectionId, parentId: EntityId, childId: EntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).remove(childId.arrayId, parentId.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).remove(childId.arrayId, parentId.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).remove(childId, parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).remove(childId, parentId)
}.let { }
}
internal fun updateChildrenOfParent(connectionId: ConnectionId, parentId: EntityId, childrenIds: Collection<EntityId>) {
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId.arrayId)
val children = childrenIds.map { it.arrayId }.toIntArray()
copiedMap.putAll(children, parentId.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.putForce(childrenIds.single().arrayId, parentId.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
childrenIds.forEach { copiedMap[it] = parentId }
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
childrenIds.forEach { copiedMap[it] = parentId }
}
}.let { }
}
fun <Child : WorkspaceEntityBase> updateOneToManyChildrenOfParent(connectionId: ConnectionId, parentId: Int, childrenEntities: Sequence<Child>) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
val children = childrenEntities.map { it.id.arrayId }.toList().toIntArray()
copiedMap.putAll(children, parentId)
}
fun <Child : WorkspaceEntityBase> updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parentId: EntityId,
childrenEntities: Sequence<Child>) {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
childrenEntities.forEach { copiedMap[it.id] = parentId }
}
fun <Parent : WorkspaceEntityBase, OriginParent : Parent> updateOneToAbstractOneParentOfChild(connectionId: ConnectionId, childId: EntityId,
parentEntity: OriginParent) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentEntity.id
}
fun <Child : WorkspaceEntityBase> updateOneToOneChildOfParent(connectionId: ConnectionId, parentId: Int, childEntity: Child) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeValue(parentId)
copiedMap.put(childEntity.id.arrayId, parentId)
}
fun <Parent : WorkspaceEntityBase> updateOneToOneParentOfChild(connectionId: ConnectionId, childId: Int, parentEntity: Parent) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.put(childId, parentEntity.id.arrayId)
}
internal fun updateParentOfChild(connectionId: ConnectionId, childId: EntityId, parentId: EntityId) {
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId.arrayId)
copiedMap.putAll(intArrayOf(childId.arrayId), parentId.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId.arrayId)
copiedMap.putForce(childId.arrayId, parentId.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentId
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentId
}
}.let { }
}
fun <Parent : WorkspaceEntityBase> updateOneToManyParentOfChild(connectionId: ConnectionId, childId: Int, parent: Parent) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putAll(intArrayOf(childId), parent.id.arrayId)
}
fun toImmutable(): RefsTable = RefsTable(
oneToManyContainer.mapValues { it.value.toImmutable() },
oneToOneContainer.mapValues { it.value.toImmutable() },
oneToAbstractManyContainer.mapValues {
it.value.let { value ->
val map = LinkedBidirectionalMap<EntityId, EntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
},
abstractOneToOneContainer.mapValues {
it.value.let { value ->
val map = HashBiMap.create<EntityId, EntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
}
)
companion object {
fun from(other: RefsTable): MutableRefsTable = MutableRefsTable(
HashMap(other.oneToManyContainer), HashMap(other.oneToOneContainer),
HashMap(other.oneToAbstractManyContainer),
HashMap(other.abstractOneToOneContainer))
}
}
internal sealed class AbstractRefsTable {
internal abstract val oneToManyContainer: Map<ConnectionId, NonNegativeIntIntBiMap>
internal abstract val oneToOneContainer: Map<ConnectionId, IntIntUniqueBiMap>
internal abstract val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<EntityId, EntityId>>
internal abstract val abstractOneToOneContainer: Map<ConnectionId, BiMap<EntityId, EntityId>>
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> findConnectionId(parentClass: Class<Parent>, childClass: Class<Child>): ConnectionId? {
val parentClassId = parentClass.toClassId()
val childClassId = childClass.toClassId()
return (oneToManyContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToOneContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToAbstractManyContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
}
?: abstractOneToOneContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
})
}
fun getParentRefsOfChild(childId: EntityId): Map<ConnectionId, EntityId> {
val childArrayId = childId.arrayId
val childClassId = childId.clazz
val childClass = childId.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, EntityId>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToMany) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, EntityId(value, connectionId.parentClass))
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, EntityId(value, connectionId.parentClass))
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getChildrenRefsOfParentBy(parentId: EntityId): Map<ConnectionId, Set<EntityId>> {
val parentArrayId = parentId.arrayId
val parentClassId = parentId.clazz
val parentClass = parentId.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, Set<EntityId>>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToMany) {
val keys = bimap.getKeys(parentArrayId)
if (!keys.isEmpty()) {
val children = keys.map { EntityId(it, connectionId.childClass) }.toSet()
val existingValue = res.putIfAbsent(connectionId, children)
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, setOf(EntityId(key, connectionId.childClass)))
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
val keys = bimap.getKeysByValue(parentId) ?: continue
if (keys.isNotEmpty()) {
val existingValue = res.putIfAbsent(connectionId, keys.toSet())
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, setOf(key))
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getOneToManyChildren(connectionId: ConnectionId, parentId: Int): NonNegativeIntIntMultiMap.IntSequence? {
return oneToManyContainer[connectionId]?.getKeys(parentId)
}
fun getOneToAbstractManyChildren(connectionId: ConnectionId, parentId: EntityId): List<EntityId>? {
val map = oneToAbstractManyContainer[connectionId]
return map?.getKeysByValue(parentId)
}
fun getAbstractOneToOneChildren(connectionId: ConnectionId, parentId: EntityId): EntityId? {
val map = abstractOneToOneContainer[connectionId]
return map?.inverse()?.get(parentId)
}
fun getOneToAbstractOneParent(connectionId: ConnectionId, childId: EntityId): EntityId? {
return abstractOneToOneContainer[connectionId]?.get(childId)
}
fun <Child : WorkspaceEntity> getOneToOneChild(connectionId: ConnectionId, parentId: Int, transformer: IntFunction<Child?>): Child? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsValue(parentId)) return null
return transformer.apply(bimap.getKey(parentId))
}
fun <Parent : WorkspaceEntity> getOneToOneParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
fun <Parent : WorkspaceEntity> getOneToManyParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToManyContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
}
| apache-2.0 | 4b911b2a900055f0a75ffb3ab49d6bb7 | 41.959677 | 147 | 0.724798 | 5.259936 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/predefined/HtlELPredefined.kt | 1 | 3457 | package com.aemtools.completion.htl.predefined
/**
* @author Dmytro Troynikov
*/
object HtlELPredefined {
/**
* List of values applicable as `context` option values.
*
* `${@ context='<caret>'}`
*/
val CONTEXT_VALUES = listOf(
pc("text", """
Default for content inside elements.
Encodes all HTML special characters.
"""),
pc("html", """
Filters HTML to meet the AntiSamy policy rules, removing what doesn't match the rules.
"""),
pc("attribute", """
Default for attribute values
Encodes all HTML special characters.
"""),
pc("uri", """
To display links and paths Default for _href_ nad _src_ attribute values
Validates URI for writing as an _href_ or _src_ attribute value, outputs nothing if validation fails.
"""),
pc("number", """
To display numbers
Validates URI for containing an integer, outputs zero if validation fails.
"""),
pc("attributeName", """
Default for _data-sly-attribute_ when setting attribute names
Validates the attribute name, outputs nothing if validation fails.
"""),
pc("elementName", """
Default for _data-sly-element_
Validates the element name, outputs nothing if validation fails.
"""),
pc("scriptToken", """
For JS identifiers, literal numbers, or literal strings
Validates the JavaScript token, outputs nothing if validation fails.
"""),
pc("scriptString", """
Within JS strings
Encodes characters that would break out of the string.
"""),
pc("scriptComment", """
Withing JS comments
Validates the JavaScript comment, outputs nothing if validation fails.
"""),
pc("styleToken", """
For CSS identifiers, numbers, dimensions, strings, hex colours or functions
Validates the CSS token, outputs nothing if validation fails.
"""),
pc("styleString", """
Within CSS strings
Encodes characters that would break out of the string.
"""),
pc("styleComment", """
Within CSS comments
Validates the CSS comment, outputs nothing if validation fails.
"""),
pc("unsafe", """
Disables escaping and XSS protection completely.
""")
)
/**
* List of completion variants for list helper variables.
*/
val LIST_AND_REPEAT_HELPER_OBJECT = listOf(
pc("index", "int", "zero-based counter (0..length-1)"),
pc("count", "int", "one-based counter (1..length)"),
pc("first", "boolean", "<b>true</b> for the first element being iterated"),
pc("middle", "boolean", "<b>true</b> if element being iterated is neither the first nor the last"),
pc("last", "boolean", "<b>true</b> for the last element being iterated"),
pc("odd", "boolean", "<b>true</b> if index is odd"),
pc("even", "boolean", "<b>true</b> if index is even")
)
}
private fun pc(completionText: String,
type: String? = null,
documentation: String? = null) =
PredefinedCompletion(completionText, type, documentation)
| gpl-3.0 | d9936b3f31c93db7ba598cb259468344 | 38.284091 | 117 | 0.55713 | 5.046715 | false | false | false | false |
android/wear-os-samples | WearSpeakerSample/wear/src/main/java/com/example/android/wearable/speaker/SpeakerApp.kt | 1 | 5553 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.speaker
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.dialog.Alert
import androidx.wear.compose.material.dialog.Confirmation
import kotlinx.coroutines.launch
/**
* The logic for the speaker sample.
*
* The stateful logic is kept by a [MainState].
*/
@Composable
fun SpeakerApp() {
MaterialTheme {
lateinit var requestPermissionLauncher: ManagedActivityResultLauncher<String, Boolean>
val context = LocalContext.current
val activity = context.findActivity()
val scope = rememberCoroutineScope()
val mainState = remember(activity) {
MainState(
activity = activity,
requestPermission = {
requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
}
)
}
requestPermissionLauncher = rememberLauncherForActivityResult(RequestPermission()) {
// We ignore the direct result here, since we're going to check anyway.
scope.launch {
mainState.permissionResultReturned()
}
}
val lifecycleOwner = LocalLifecycleOwner.current
// Notify the state holder whenever we become stopped to reset the state
DisposableEffect(mainState, scope, lifecycleOwner) {
val lifecycleObserver = object : DefaultLifecycleObserver {
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
scope.launch { mainState.onStopped() }
}
}
lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycleOwner.lifecycle.removeObserver(lifecycleObserver)
}
}
SpeakerScreen(
playbackState = mainState.playbackState,
isPermissionDenied = mainState.isPermissionDenied,
recordingProgress = mainState.recordingProgress,
onMicClicked = {
scope.launch {
mainState.onMicClicked()
}
},
onPlayClicked = {
scope.launch {
mainState.onPlayClicked()
}
},
onMusicClicked = {
scope.launch {
mainState.onMusicClicked()
}
}
)
if (mainState.showPermissionRationale) {
Alert(
title = {
Text(text = stringResource(id = R.string.rationale_for_microphone_permission))
},
positiveButton = {
Button(
onClick = {
requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
mainState.showPermissionRationale = false
}
) {
Text(text = stringResource(id = R.string.ok))
}
},
negativeButton = {
Button(
onClick = {
mainState.showPermissionRationale = false
}
) {
Text(text = stringResource(id = R.string.cancel))
}
}
)
}
if (mainState.showSpeakerNotSupported) {
Confirmation(
onTimeout = { mainState.showSpeakerNotSupported = false }
) {
Text(text = stringResource(id = R.string.no_speaker_supported))
}
}
}
}
/**
* Find the closest Activity in a given Context.
*/
private tailrec fun Context.findActivity(): Activity =
when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> throw IllegalStateException(
"findActivity should be called in the context of an Activity"
)
}
| apache-2.0 | 1a54a28bc232a9a5bfa5152b0d897b1d | 34.369427 | 98 | 0.610121 | 5.519881 | false | false | false | false |
fluidsonic/fluid-json | annotation-processor/sources-jvm/AnnotationProcessor.kt | 1 | 1532 | package io.fluidsonic.json.annotationprocessor
import com.google.auto.service.*
import java.io.*
import javax.annotation.processing.*
import javax.lang.model.*
import javax.lang.model.element.*
import javax.tools.*
@AutoService(Processor::class)
public class AnnotationProcessor : AbstractProcessor(), ErrorLogger, TypeResolver {
private val collectionPhase = CollectionPhase(
errorLogger = this,
typeResolver = this
)
override fun getSupportedAnnotationTypes(): Set<String> =
collectionPhase.annotationClasses.mapTo(mutableSetOf()) { it.java.canonicalName }
override fun getSupportedSourceVersion(): SourceVersion =
SourceVersion.latestSupported()
override fun logError(message: String) {
processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, message)
}
override fun process(annotations: Set<TypeElement>, roundEnvironment: RoundEnvironment): Boolean {
collectionPhase.collect(roundEnvironment = roundEnvironment)
if (roundEnvironment.processingOver()) {
val processingResult = ProcessingPhase(
collectionResult = collectionPhase.finish(),
errorLogger = this
).process()
GenerationPhase(
outputDirectory = File(processingEnv.options[Options.generatedKotlinFilePath]!!),
processingResult = processingResult
).generate()
}
return true
}
override fun resolveType(qualifiedName: String): TypeElement? =
processingEnv.elementUtils.getTypeElement(qualifiedName)
private object Options {
const val generatedKotlinFilePath = "kapt.kotlin.generated"
}
}
| apache-2.0 | 5531c454ec4f62af97baf1b9d34fe7a1 | 24.533333 | 99 | 0.778068 | 4.44058 | false | false | false | false |
moko256/twicalico | app/src/main/java/com/github/moko256/twitlatte/BaseTweetListFragment.kt | 1 | 9338 | /*
* Copyright 2015-2019 The twitlatte 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.moko256.twitlatte
import android.app.Application
import android.content.Context
import android.graphics.Point
import android.graphics.Rect
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.github.moko256.twitlatte.entity.Client
import com.github.moko256.twitlatte.entity.EventType
import com.github.moko256.twitlatte.text.TwitterStringUtils
import com.github.moko256.twitlatte.view.dpToPx
import com.github.moko256.twitlatte.viewmodel.ListViewModel
import com.github.moko256.twitlatte.widget.convertObservableConsumer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
/**
* Created by moko256 on 2016/03/27.
*
* @author moko256
*/
abstract class BaseTweetListFragment : BaseListFragment() {
private lateinit var disposable: CompositeDisposable
lateinit var listViewModel: ListViewModel
protected abstract val listRepository: ListViewModel.ListRepository
override fun onActivityCreated(savedInstanceState: Bundle?) {
val activity = requireActivity()
val value = TypedValue()
val context = requireContext()
val toastTopPosition = if (context.theme.resolveAttribute(R.attr.actionBarSize, value, true)) {
TypedValue.complexToDimensionPixelOffset(value.data, resources.displayMetrics)
} else {
0
}
val client = activity.getClient()!!
listViewModel = ViewModelProviders.of(
this,
ListViewModelFactory(client, arguments
?: Bundle.EMPTY, activity.application, listRepository)
).get(ListViewModel::class.java)
val dp4 = dpToPx(4)
recyclerView.clipToPadding = false
recyclerView.setPadding(dp4, 0, dp4, 0)
recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top = dp4 * 2 - view.paddingTop
} else {
outRect.top = dp4 - view.paddingTop
}
outRect.bottom = dp4 - view.paddingBottom
outRect.left = dp4 - view.paddingLeft
outRect.right = dp4 - view.paddingRight
}
})
if (activity is GetRecyclerViewPool) {
recyclerView.setRecycledViewPool((activity as GetRecyclerViewPool).tweetListViewPool)
}
val adapter = StatusesAdapter(
client,
listViewModel.statusActionModel,
preferenceRepository,
context,
listViewModel.listModel.getIdsList(),
Glide.with(this)
).also {
it.setOnLoadMoreClick { position -> listViewModel.listModel.loadOnGap(position) }
}
recyclerView.adapter = adapter
if (!isInitializedList) {
adapter.notifyDataSetChanged()
}
val seeingPosition = listViewModel.listModel.getSeeingPosition()
val layoutManager = recyclerView.layoutManager!!
if (seeingPosition > 0 && !(activity is HasNotifiableAppBar && savedInstanceState == null)) {
layoutManager.scrollToPosition(seeingPosition)
}
val adapterObservableBinder = convertObservableConsumer(
recyclerView,
adapter,
layoutManager
)
disposable = CompositeDisposable(
listViewModel
.listModel
.getListEventObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
if (it.type == EventType.ADD_TOP && it.size > 0) {
Toast.makeText(context, R.string.new_posts, Toast.LENGTH_SHORT).apply {
setGravity(
Gravity.TOP or Gravity.CENTER,
0,
toastTopPosition
)
}.show()
}
},
listViewModel
.listModel
.getListEventObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
adapterObservableBinder.invoke(it)
if (isRefreshing) {
isRefreshing = false
}
},
listViewModel
.listModel
.getErrorEventObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
notifyErrorBySnackBar(it).show()
if (isRefreshing) {
isRefreshing = false
}
},
listViewModel.statusActionModel.getStatusObservable().subscribe {
adapter.notifyItemChanged(listViewModel.listModel.getIdsList().indexOf(it))
},
listViewModel.statusActionModel.getDidActionObservable().subscribe {
notifyBySnackBar(
TwitterStringUtils.getDidActionStringRes(
client.accessToken.clientType,
it
)
).show()
},
listViewModel.statusActionModel.getErrorObservable().subscribe {
it.printStackTrace()
notifyErrorBySnackBar(it).show()
}
)
super.onActivityCreated(savedInstanceState)
}
override fun onDestroyView() {
disposable.dispose()
listViewModel.listModel.removeOldCache(firstVisibleItemPosition())
recyclerView.swapAdapter(null, true)
super.onDestroyView()
}
override fun onStop() {
super.onStop()
val position = firstVisibleItemPosition()
if (position >= 0) {
listViewModel.listModel.updateSeeingPosition(position)
}
}
override fun onInitializeList() {
isRefreshing = true
listViewModel.listModel.refreshFirst()
}
override fun onUpdateList() {
listViewModel.listModel.refreshOnTop()
}
override fun onLoadMoreList() {
listViewModel.listModel.loadOnBottom()
}
override fun isInitializedList(): Boolean {
return listViewModel.listModel.getIdsList().isNotEmpty()
}
override fun initializeRecyclerViewLayoutManager(): RecyclerView.LayoutManager {
val wm = requireActivity().getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val size = Point()
display.getSize(size)
//Calculated as:
// Picture area: (16 : 9) + Other content: (16 : 3)
// ((size.x * 12) / (size.y * 16)) + 1
val count = (3 * size.x / size.y / 4) + 1
return if (count == 1) {
LinearLayoutManager(context).apply {
recycleChildrenOnDetach = true
}
} else {
StaggeredGridLayoutManager(
count,
StaggeredGridLayoutManager.VERTICAL
)
}
}
private class ListViewModelFactory(
private val client: Client,
private val bundle: Bundle,
private val application: Application,
private val repo: ListViewModel.ListRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return ListViewModel(application, client, bundle, repo) as T
}
}
internal interface GetRecyclerViewPool {
val tweetListViewPool: RecyclerView.RecycledViewPool
}
} | apache-2.0 | 7f415e04b6ecc8ba641b58058eb600c4 | 34.645038 | 117 | 0.587706 | 5.71481 | false | false | false | false |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/ranges/Progressions.kt | 2 | 6139 | /*
* Copyright 2010-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 kotlin.ranges
import kotlin.internal.getProgressionLastElement
/**
* A progression of values of type `Char`.
*/
public open class CharProgression
internal constructor
(
start: Char,
endInclusive: Char,
step: Int
) : Iterable<Char> {
init {
if (step == 0) throw kotlin.IllegalArgumentException("Step must be non-zero")
}
/**
* The first element in the progression.
*/
public val first: Char = start
/**
* The last element in the progression.
*/
public val last: Char = getProgressionLastElement(start.toInt(), endInclusive.toInt(), step).toChar()
/**
* The step of the progression.
*/
public val step: Int = step
override fun iterator(): CharIterator = CharProgressionIterator(first, last, step)
/** Checks if the progression is empty. */
public open fun isEmpty(): Boolean = if (step > 0) first > last else first < last
override fun equals(other: Any?): Boolean =
other is CharProgression && (isEmpty() && other.isEmpty() ||
first == other.first && last == other.last && step == other.step)
override fun hashCode(): Int =
if (isEmpty()) -1 else (31 * (31 * first.toInt() + last.toInt()) + step)
override fun toString(): String = if (step > 0) "$first..$last step $step" else "$first downTo $last step ${-step}"
companion object {
/**
* Creates CharProgression within the specified bounds of a closed range.
* The progression starts with the [rangeStart] value and goes toward the [rangeEnd] value not excluding it, with the specified [step].
* In order to go backwards the [step] must be negative.
*/
public fun fromClosedRange(rangeStart: Char, rangeEnd: Char, step: Int): CharProgression = CharProgression(rangeStart, rangeEnd, step)
}
}
/**
* A progression of values of type `Int`.
*/
public open class IntProgression
internal constructor
(
start: Int,
endInclusive: Int,
step: Int
) : Iterable<Int> {
init {
if (step == 0) throw kotlin.IllegalArgumentException("Step must be non-zero")
}
/**
* The first element in the progression.
*/
public val first: Int = start
/**
* The last element in the progression.
*/
public val last: Int = getProgressionLastElement(start.toInt(), endInclusive.toInt(), step).toInt()
/**
* The step of the progression.
*/
public val step: Int = step
override fun iterator(): IntIterator = IntProgressionIterator(first, last, step)
/** Checks if the progression is empty. */
public open fun isEmpty(): Boolean = if (step > 0) first > last else first < last
override fun equals(other: Any?): Boolean =
other is IntProgression && (isEmpty() && other.isEmpty() ||
first == other.first && last == other.last && step == other.step)
override fun hashCode(): Int =
if (isEmpty()) -1 else (31 * (31 * first + last) + step)
override fun toString(): String = if (step > 0) "$first..$last step $step" else "$first downTo $last step ${-step}"
companion object {
/**
* Creates IntProgression within the specified bounds of a closed range.
* The progression starts with the [rangeStart] value and goes toward the [rangeEnd] value not excluding it, with the specified [step].
* In order to go backwards the [step] must be negative.
*/
public fun fromClosedRange(rangeStart: Int, rangeEnd: Int, step: Int): IntProgression = IntProgression(rangeStart, rangeEnd, step)
}
}
/**
* A progression of values of type `Long`.
*/
public open class LongProgression
internal constructor
(
start: Long,
endInclusive: Long,
step: Long
) : Iterable<Long> {
init {
if (step == 0L) throw kotlin.IllegalArgumentException("Step must be non-zero")
}
/**
* The first element in the progression.
*/
public val first: Long = start
/**
* The last element in the progression.
*/
public val last: Long = getProgressionLastElement(start.toLong(), endInclusive.toLong(), step).toLong()
/**
* The step of the progression.
*/
public val step: Long = step
override fun iterator(): LongIterator = LongProgressionIterator(first, last, step)
/** Checks if the progression is empty. */
public open fun isEmpty(): Boolean = if (step > 0) first > last else first < last
override fun equals(other: Any?): Boolean =
other is LongProgression && (isEmpty() && other.isEmpty() ||
first == other.first && last == other.last && step == other.step)
override fun hashCode(): Int =
if (isEmpty()) -1 else (31 * (31 * (first xor (first ushr 32)) + (last xor (last ushr 32))) + (step xor (step ushr 32))).toInt()
override fun toString(): String = if (step > 0) "$first..$last step $step" else "$first downTo $last step ${-step}"
companion object {
/**
* Creates LongProgression within the specified bounds of a closed range.
* The progression starts with the [rangeStart] value and goes toward the [rangeEnd] value not excluding it, with the specified [step].
* In order to go backwards the [step] must be negative.
*/
public fun fromClosedRange(rangeStart: Long, rangeEnd: Long, step: Long): LongProgression = LongProgression(rangeStart, rangeEnd, step)
}
} | apache-2.0 | 24158a1f8f8c9b70b1bd925082715601 | 32.922652 | 143 | 0.636097 | 4.38187 | false | false | false | false |
PeterVollmer/feel-at-home-android-client | Feel@Home/Feel@Home/src/main/java/club/frickel/feelathome/Effect.kt | 1 | 1274 | package club.frickel.feelathome
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import java.io.Serializable
@JsonIgnoreProperties(ignoreUnknown = true)
class Effect : Serializable {
/**
* @return
*/
/**
* @param description
*/
@JsonProperty("Description")
@get:JsonProperty("Description")
@set:JsonProperty("Description")
var description: String = ""
/**
* @return
*/
/**
* @param name
*/
@JsonProperty("Name")
@get:JsonProperty("Name")
@set:JsonProperty("Name")
var name: String = ""
/**
* @return
*/
/**
* @param config
*/
@JsonProperty("Config")
@get:JsonProperty("Config")
@set:JsonProperty("Config")
var config: Map<String, Any> = emptyMap()
/**
*/
constructor() {
}
/**
* @param name
* *
* @param description
* *
* @param config
*/
constructor(name: String, description: String, config: Map<String, Any>) {
this.name = name
this.description = description
this.config = config
}
/**
* @return
*/
override fun toString(): String {
return this.name
}
} | gpl-2.0 | b9ed8149e2c29bff494e0cf369d1c0b5 | 18.029851 | 78 | 0.565934 | 4.275168 | false | true | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sensors/modules/BaseSensorModule.kt | 2 | 2726 | package abi43_0_0.expo.modules.sensors.modules
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener2
import android.os.Bundle
import android.util.Log
import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi43_0_0.expo.modules.interfaces.sensors.SensorServiceSubscriptionInterface
import abi43_0_0.expo.modules.core.ExportedModule
import abi43_0_0.expo.modules.core.ModuleRegistry
import abi43_0_0.expo.modules.core.interfaces.LifecycleEventListener
import abi43_0_0.expo.modules.core.interfaces.services.EventEmitter
import abi43_0_0.expo.modules.core.interfaces.services.UIManager
abstract class BaseSensorModule internal constructor(context: Context?) : ExportedModule(context), SensorEventListener2, LifecycleEventListener {
lateinit var moduleRegistry: ModuleRegistry
private set
private val sensorKernelServiceSubscription: SensorServiceSubscriptionInterface by lazy {
getSensorService().createSubscriptionForListener(this)
}
private var mIsObserving = false
protected abstract val eventName: String
protected abstract fun getSensorService(): SensorServiceInterface
protected abstract fun eventToMap(sensorEvent: SensorEvent): Bundle
override fun onCreate(moduleRegistry: ModuleRegistry) {
this.moduleRegistry = moduleRegistry
// Unregister from old UIManager
moduleRegistry.getModule(UIManager::class.java)?.unregisterLifecycleEventListener(this)
// Register to new UIManager
moduleRegistry.getModule(UIManager::class.java)?.registerLifecycleEventListener(this)
}
override fun onSensorChanged(sensorEvent: SensorEvent) {
val eventEmitter = moduleRegistry.getModule(EventEmitter::class.java)
eventEmitter?.emit(eventName, eventToMap(sensorEvent))
?: Log.e("E_SENSOR_MODULE", "Could not emit $eventName event, no event emitter present.")
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) = Unit
override fun onFlushCompleted(sensor: Sensor) = Unit
fun setUpdateInterval(updateInterval: Int) {
sensorKernelServiceSubscription.updateInterval = updateInterval.toLong()
}
fun startObserving() {
mIsObserving = true
sensorKernelServiceSubscription.start()
}
fun stopObserving() {
if (mIsObserving) {
mIsObserving = false
sensorKernelServiceSubscription.stop()
}
}
override fun onHostResume() {
if (mIsObserving) {
sensorKernelServiceSubscription.start()
}
}
override fun onHostPause() {
if (mIsObserving) {
sensorKernelServiceSubscription.stop()
}
}
override fun onHostDestroy() {
sensorKernelServiceSubscription.release()
}
}
| bsd-3-clause | b5b49b16af12b029df42f4bde1ff2d64 | 33.075 | 145 | 0.783933 | 4.833333 | false | false | false | false |
AndroidX/androidx | wear/watchface/watchface-complications-data/src/main/java/androidx/wear/watchface/utility/TraceEvent.kt | 3 | 3003 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface.utility
import android.os.Build
import android.os.Trace
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.io.Closeable
/**
* Wrapper around [Trace.beginSection] and [Trace.endSection] which helps reduce boilerplate by
* taking advantage of RAII like [Closeable] in a try block.
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class TraceEvent(traceName: String) : Closeable {
init {
Trace.beginSection(traceName)
}
public override fun close() {
Trace.endSection()
}
}
/**
* Wrapper around [Trace.beginAsyncSection] which helps reduce boilerplate by taking advantage of
* RAII like [Trace.endAsyncSection] in a try block, and by dealing with API version support.
*
* @hide
**/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class AsyncTraceEvent(private val traceName: String) : Closeable {
internal companion object {
private val lock = Any()
private var nextTraceId = 0
internal fun getTraceId() = synchronized(lock) { nextTraceId++ }
}
@RequiresApi(Build.VERSION_CODES.Q)
private object Api29Impl {
@JvmStatic
@DoNotInline
fun callBeginAsyncSection(traceName: String, traceId: Int) {
Trace.beginAsyncSection(traceName, traceId)
}
@JvmStatic
@DoNotInline
fun callEndAsyncSection(traceName: String, traceId: Int) {
Trace.endAsyncSection(traceName, traceId)
}
}
private val traceId = getTraceId()
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Api29Impl.callBeginAsyncSection(traceName, traceId)
}
}
public override fun close() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Api29Impl.callEndAsyncSection(traceName, traceId)
}
}
}
/**
* Wrapper around [CoroutineScope.launch] with an async trace event.
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public fun CoroutineScope.launchWithTracing(
traceEventName: String,
block: suspend CoroutineScope.() -> Unit
): Job = launch {
TraceEvent(traceEventName).use {
block.invoke(this)
}
}
| apache-2.0 | 6202126ca7142236470a519716e26e2f | 28.15534 | 97 | 0.7003 | 4.2 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/gesturehandler/PinchGestureHandler.kt | 2 | 2697 | package versioned.host.exp.exponent.modules.api.components.gesturehandler
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.ScaleGestureDetector.OnScaleGestureListener
import android.view.ViewConfiguration
import kotlin.math.abs
class PinchGestureHandler : GestureHandler<PinchGestureHandler>() {
var scale = 0.0
private set
var velocity = 0.0
private set
val focalPointX: Float
get() = scaleGestureDetector?.focusX ?: Float.NaN
val focalPointY: Float
get() = scaleGestureDetector?.focusY ?: Float.NaN
private var scaleGestureDetector: ScaleGestureDetector? = null
private var startingSpan = 0f
private var spanSlop = 0f
private val gestureListener: OnScaleGestureListener = object : OnScaleGestureListener {
override fun onScale(detector: ScaleGestureDetector): Boolean {
val prevScaleFactor: Double = scale
scale *= detector.scaleFactor.toDouble()
val delta = detector.timeDelta
if (delta > 0) {
velocity = (scale - prevScaleFactor) / delta
}
if (abs(startingSpan - detector.currentSpan) >= spanSlop &&
state == STATE_BEGAN
) {
activate()
}
return true
}
init {
setShouldCancelWhenOutside(false)
}
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
startingSpan = detector.currentSpan
return true
}
override fun onScaleEnd(detector: ScaleGestureDetector) {
// ScaleGestureDetector thinks that when fingers are 27mm away that's a sufficiently good
// reason to trigger this method giving us no other choice but to ignore it completely.
}
}
override fun onHandle(event: MotionEvent) {
if (state == STATE_UNDETERMINED) {
val context = view!!.context
velocity = 0.0
scale = 1.0
scaleGestureDetector = ScaleGestureDetector(context, gestureListener)
val configuration = ViewConfiguration.get(context)
spanSlop = configuration.scaledTouchSlop.toFloat()
begin()
}
scaleGestureDetector?.onTouchEvent(event)
var activePointers = event.pointerCount
if (event.actionMasked == MotionEvent.ACTION_POINTER_UP) {
activePointers -= 1
}
if (state == STATE_ACTIVE && activePointers < 2) {
end()
} else if (event.actionMasked == MotionEvent.ACTION_UP) {
fail()
}
}
override fun activate(force: Boolean) {
// reset scale if the handler has not yet activated
if (state != STATE_ACTIVE) {
velocity = 0.0
scale = 1.0
}
super.activate(force)
}
override fun onReset() {
scaleGestureDetector = null
velocity = 0.0
scale = 1.0
}
}
| bsd-3-clause | 1bb1ea02e954fb00c9cc6f183c6597b3 | 29.303371 | 95 | 0.688172 | 4.548061 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/fileActions/export/MarkdownPdfExportProvider.kt | 1 | 2657 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.fileActions.export
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.cef.misc.CefPdfPrintSettings
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.MarkdownNotifier
import org.intellij.plugins.markdown.fileActions.MarkdownFileActionFormat
import org.intellij.plugins.markdown.fileActions.utils.MarkdownFileEditorUtils
import org.intellij.plugins.markdown.fileActions.utils.MarkdownImportExportUtils
import org.intellij.plugins.markdown.fileActions.utils.MarkdownImportExportUtils.notifyAndRefreshIfExportSuccess
import org.intellij.plugins.markdown.ui.preview.MarkdownPreviewFileEditor
import org.intellij.plugins.markdown.ui.preview.jcef.MarkdownJCEFHtmlPanel
import java.io.File
import java.util.function.BiConsumer
internal class MarkdownPdfExportProvider : MarkdownExportProvider {
override val formatDescription: MarkdownFileActionFormat
get() = format
override fun exportFile(project: Project, mdFile: VirtualFile, outputFile: String) {
val preview = MarkdownFileEditorUtils.findMarkdownPreviewEditor(project, mdFile, true) ?: return
val htmlPanel = preview.getUserData(MarkdownPreviewFileEditor.PREVIEW_BROWSER) ?: return
if (htmlPanel is MarkdownJCEFHtmlPanel) {
htmlPanel.savePdf(outputFile, project) { path, ok ->
if (ok) {
notifyAndRefreshIfExportSuccess(File(path), project)
}
else {
MarkdownNotifier.showErrorNotification(
project,
MarkdownBundle.message("markdown.export.failure.msg", File(path).name)
)
}
}
}
}
override fun validate(project: Project, file: VirtualFile): String? {
val preview = MarkdownFileEditorUtils.findMarkdownPreviewEditor(project, file, true)
if (preview == null || !MarkdownImportExportUtils.isJCEFPanelOpen(preview)) {
return MarkdownBundle.message("markdown.export.validation.failure.msg", formatDescription.formatName)
}
return null
}
private fun MarkdownJCEFHtmlPanel.savePdf(path: String, project: Project, resultCallback: BiConsumer<String, Boolean>) {
cefBrowser.printToPDF(path, CefPdfPrintSettings()) { _, ok ->
val dirToExport = File(path).parent
MarkdownImportExportUtils.refreshProjectDirectory(project, dirToExport)
resultCallback.accept(path, ok)
}
}
companion object {
@JvmStatic
val format = MarkdownFileActionFormat("PDF", "pdf")
}
}
| apache-2.0 | 8d5766af04a638adadfefd3b5c73735d | 41.854839 | 140 | 0.768912 | 4.511036 | false | false | false | false |
GlobalTechnology/android-gto-support | gto-support-api-okhttp3/src/test/kotlin/org/ccci/gto/android/common/api/okhttp3/interceptor/SessionInterceptorTest.kt | 1 | 4924 | package org.ccci.gto.android.common.api.okhttp3.interceptor
import android.content.Context
import android.content.SharedPreferences
import java.io.IOException
import java.util.concurrent.Callable
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import org.ccci.gto.android.common.api.Session
import org.ccci.gto.android.common.api.okhttp3.EstablishSessionApiException
import org.ccci.gto.android.common.api.okhttp3.InvalidSessionApiException
import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.RETURNS_DEEP_STUBS
import org.mockito.kotlin.any
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.doThrow
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.spy
import org.mockito.kotlin.stub
import org.mockito.kotlin.verify
class SessionInterceptorTest {
private lateinit var response: Response
private lateinit var chain: Interceptor.Chain
private lateinit var context: Context
private lateinit var sessionInterceptor: MockSessionInterceptor
private val validSession = spy(MockSession("valid"))
private val invalidSession = spy(MockSession(null))
@Before
fun setup() {
response = mock()
chain = mock {
on { request() } doReturn Request.Builder().url("https://example.com").build()
on { proceed(any()) } doReturn response
}
context = mock(defaultAnswer = RETURNS_DEEP_STUBS)
sessionInterceptor = MockSessionInterceptor(context)
}
@Test
fun `Existing session is valid`() {
sessionInterceptor.stub {
on { loadSession(any()) } doReturn validSession
}
sessionInterceptor.intercept(chain)
verify(sessionInterceptor.establishSession, never()).call()
verify(sessionInterceptor.attachSession).invoke(any(), any())
verify(validSession, never()).save(any())
}
@Test
fun `Existing session is invalid - establishSession() returns valid session`() {
sessionInterceptor.stub {
on { loadSession(any()) } doReturn invalidSession
on { establishSession() } doReturn validSession
}
sessionInterceptor.intercept(chain)
verify(sessionInterceptor.establishSession).call()
verify(sessionInterceptor.attachSession).invoke(any(), eq(validSession))
verify(validSession).save(any())
verify(invalidSession, never()).save(any())
}
@Test
fun `Existing session is invalid - establishSession() returns null`() {
sessionInterceptor.stub {
on { loadSession(any()) } doReturn invalidSession
on { establishSession() } doReturn null
}
assertThrows(InvalidSessionApiException::class.java) {
sessionInterceptor.intercept(chain)
}
verify(sessionInterceptor.establishSession).call()
verify(sessionInterceptor.attachSession, never()).invoke(any(), any())
verify(invalidSession, never()).save(any())
}
@Test
fun `Existing session is invalid - establishSession() throws IOException`() {
sessionInterceptor.stub {
on { loadSession(any()) } doReturn invalidSession
on { establishSession() } doThrow IOException::class
}
assertThrows(EstablishSessionApiException::class.java) {
sessionInterceptor.intercept(chain)
}
verify(sessionInterceptor.establishSession).call()
verify(sessionInterceptor.attachSession, never()).invoke(any(), any())
verify(invalidSession, never()).save(any())
}
@Test
fun `Existing session is null - establishSession() returns valid session`() {
sessionInterceptor.stub {
on { loadSession(any()) } doReturn null
on { establishSession() } doReturn validSession
}
sessionInterceptor.intercept(chain)
verify(sessionInterceptor.establishSession).call()
verify(sessionInterceptor.attachSession).invoke(any(), eq(validSession))
verify(validSession).save(any())
}
private class MockSession(id: String?) : Session(id)
private class MockSessionInterceptor(context: Context) : SessionInterceptor<MockSession>(context) {
val loadSession = mock<(SharedPreferences) -> MockSession?>()
val establishSession = mock<Callable<MockSession?>>()
val attachSession = mock<(Request, MockSession) -> Request> {
on { invoke(any(), any()) } doAnswer { it.getArgument(0) }
}
override fun loadSession(prefs: SharedPreferences) = loadSession.invoke(prefs)
public override fun establishSession() = establishSession.call()
override fun attachSession(request: Request, session: MockSession) = attachSession.invoke(request, session)
}
}
| mit | f8b9141e5216cbaec454c155f6e90a6e | 37.170543 | 115 | 0.692933 | 4.662879 | false | true | false | false |
alibaba/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/inspection/AliPmdInspectionInvoker.kt | 1 | 6737 | /*
* Copyright 1999-2017 Alibaba Group.
*
* 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.alibaba.p3c.idea.inspection
import com.alibaba.p3c.idea.component.AliProjectComponent
import com.alibaba.p3c.idea.config.P3cConfig
import com.alibaba.p3c.idea.pmd.AliPmdProcessor
import com.alibaba.p3c.idea.util.DocumentUtils.calculateLineStart
import com.alibaba.p3c.idea.util.DocumentUtils.calculateRealOffset
import com.alibaba.p3c.idea.util.ProblemsUtils
import com.alibaba.p3c.pmd.lang.java.rule.comment.RemoveCommentedCodeRule
import com.beust.jcommander.internal.Lists
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import net.sourceforge.pmd.Rule
import net.sourceforge.pmd.RuleViolation
import java.util.concurrent.TimeUnit
/**
* @author caikang
* @date 2016/12/13
*/
class AliPmdInspectionInvoker(
private val psiFile: PsiFile,
private val manager: InspectionManager,
private val rule: Rule
) {
private val logger = Logger.getInstance(javaClass)
private var violations: List<RuleViolation> = emptyList()
fun doInvoke(isOnTheFly: Boolean) {
Thread.currentThread().contextClassLoader = javaClass.classLoader
val processor = AliPmdProcessor(rule)
val start = System.currentTimeMillis()
val aliProjectComponent = manager.project.getComponent(AliProjectComponent::class.java)
val fileContext = aliProjectComponent.getFileContext(psiFile.virtualFile)
val ruleViolations = fileContext?.ruleViolations
violations = if (isOnTheFly || ruleViolations == null) {
processor.processFile(psiFile, isOnTheFly)
} else {
ruleViolations[rule.name] ?: emptyList()
}
logger.debug(
"elapsed ${System.currentTimeMillis() - start}ms to" +
" to apply rule ${rule.name} for file ${psiFile.virtualFile.canonicalPath}"
)
}
fun getRuleProblems(isOnTheFly: Boolean): Array<ProblemDescriptor>? {
if (violations.isEmpty()) {
return null
}
val problemDescriptors = Lists.newArrayList<ProblemDescriptor>(violations.size)
for (rv in violations) {
val virtualFile = LocalFileSystem.getInstance().findFileByPath(rv.filename) ?: continue
val psiFile = PsiManager.getInstance(manager.project).findFile(virtualFile) ?: continue
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: continue
val offsets = if (rv.rule.name == RemoveCommentedCodeRule::class.java.simpleName) {
Offsets(
calculateLineStart(document, rv.beginLine),
calculateLineStart(document, rv.endLine + 1) - 1
)
} else {
Offsets(
calculateRealOffset(document, rv.beginLine, rv.beginColumn),
calculateRealOffset(document, rv.endLine, rv.endColumn)
)
}
val errorMessage = if (isOnTheFly) {
rv.description
} else {
"${rv.description} (line ${rv.beginLine})"
}
val problemDescriptor = ProblemsUtils.createProblemDescriptorForPmdRule(
psiFile, manager,
isOnTheFly, rv.rule.name, errorMessage, offsets.start, offsets.end, rv.beginLine
) ?: continue
problemDescriptors.add(problemDescriptor)
}
return problemDescriptors.toTypedArray()
}
companion object {
private lateinit var invokers: Cache<FileRule, AliPmdInspectionInvoker>
val smartFoxConfig = ServiceManager.getService(P3cConfig::class.java)!!
init {
reInitInvokers(smartFoxConfig.ruleCacheTime)
}
fun invokeInspection(
psiFile: PsiFile?, manager: InspectionManager, rule: Rule,
isOnTheFly: Boolean
): Array<ProblemDescriptor>? {
if (psiFile == null) {
return null
}
val virtualFile = psiFile.virtualFile ?: return null
if (!smartFoxConfig.ruleCacheEnable) {
val invoker = AliPmdInspectionInvoker(psiFile, manager, rule)
invoker.doInvoke(isOnTheFly)
return invoker.getRuleProblems(isOnTheFly)
}
var invoker = invokers.getIfPresent(FileRule(virtualFile.canonicalPath!!, rule.name))
if (invoker == null) {
synchronized(virtualFile) {
invoker = invokers.getIfPresent(virtualFile.canonicalPath!!)
if (invoker == null) {
invoker = AliPmdInspectionInvoker(psiFile, manager, rule)
invoker!!.doInvoke(isOnTheFly)
invokers.put(FileRule(virtualFile.canonicalPath!!, rule.name), invoker!!)
}
}
}
return invoker!!.getRuleProblems(isOnTheFly)
}
private fun doInvokeIfPresent(filePath: String, rule: String, isOnTheFly: Boolean) {
invokers.getIfPresent(FileRule(filePath, rule))?.doInvoke(isOnTheFly)
}
fun refreshFileViolationsCache(file: VirtualFile) {
AliLocalInspectionToolProvider.ruleNames.forEach {
doInvokeIfPresent(file.canonicalPath!!, it, false)
}
}
fun reInitInvokers(expireTime: Long) {
invokers = CacheBuilder.newBuilder().maximumSize(500).expireAfterWrite(
expireTime,
TimeUnit.MILLISECONDS
).build<FileRule, AliPmdInspectionInvoker>()!!
}
}
}
data class FileRule(val filePath: String, val ruleName: String)
data class Offsets(val start: Int, val end: Int)
| apache-2.0 | 6a3b3d051795af74cc46d1375ba966cb | 40.58642 | 99 | 0.659938 | 4.798433 | false | false | false | false |
bertilxi/DC-Android | app/src/main/java/utnfrsf/dondecurso/fragment/QueryFragment.kt | 1 | 10906 | package utnfrsf.dondecurso.fragment
import android.app.DatePickerDialog
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.Spinner
import android.widget.TextView
import com.google.gson.internal.LinkedTreeMap
import io.paperdb.Paper
import utnfrsf.dondecurso.R
import utnfrsf.dondecurso.activity.ReservasActivity
import utnfrsf.dondecurso.common.*
import utnfrsf.dondecurso.domain.Carrera
import utnfrsf.dondecurso.domain.Comision
import utnfrsf.dondecurso.domain.Materia
import utnfrsf.dondecurso.domain.Nivel
import utnfrsf.dondecurso.service.Api
import utnfrsf.dondecurso.view.MyArrayAdapter
import utnfrsf.dondecurso.view.MySpinner
import java.text.SimpleDateFormat
import java.util.*
class QueryFragment : Fragment() {
private var rootView: View? = null
private var api = Api.service
private var materias: ArrayList<Materia> = ArrayList()
private var carreras: ArrayList<Carrera> = ArrayList()
private var niveles: ArrayList<Nivel> = ArrayList()
private var comisiones: ArrayList<Comision> = ArrayList()
private var filteredMaterias: ArrayList<Materia> = ArrayList()
private var carrera: Carrera? = null
private var nivel: Nivel? = null
private var materia: Materia? = null
private var comision: Comision? = null
private var adapterCarrera: MyArrayAdapter<Carrera>? = null
private var adapterNivel: MyArrayAdapter<Nivel>? = null
private var adapterMateria: MyArrayAdapter<Materia>? = null
private var adapterComision: MyArrayAdapter<Comision>? = null
private var textViewErrorCarrera: TextView? = null
private var fab: FloatingActionButton? = null
private var spinnerMateria: MySpinner? = null
private var spinnerCarrera: Spinner? = null
private var spinnerNivel: Spinner? = null
private var spinnerComision: Spinner? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater!!.inflate(R.layout.fragment_query, container, false)
initView()
requestLoads()
val myFormat = "dd MMMM yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
val myCalendar = Calendar.getInstance()
textViewErrorCarrera = rootView!!.findView(R.id.textViewErrorCarrera)
val textViewFecha = rootView!!.findView<TextView>(R.id.textViewFecha)
textViewFecha.setOnClickListener({
val date = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
myCalendar.set(Calendar.YEAR, year)
myCalendar.set(Calendar.MONTH, monthOfYear)
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
textViewFecha.text = sdf.format(myCalendar.time)
}
DatePickerDialog(context, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show()
})
textViewFecha.text = sdf.format(myCalendar.time)
fab = rootView!!.findView<FloatingActionButton>(R.id.fab)
fab!!.setOnClickListener({
if (!validar()) {
return@setOnClickListener
}
val fecha = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(myCalendar.time)
async {
Paper.book().write("fecha", fecha)
Paper.book().write("carrera", carrera)
Paper.book().write("nivel", nivel)
Paper.book().write("materia", materia)
Paper.book().write("comision", comision)
onUI {
activity.launchActivity(ReservasActivity())
}
}
})
return rootView
}
private fun requestLoads() {
api.loadSubjects().enqueue({ _, response ->
materias.clear()
val mMaterias = response?.body() as LinkedTreeMap<String, Any>
materias.addAll(Util.fromJson(mMaterias))
processSubjectsLoad()
}, { _, _ ->
if (isAdded) {
Snackbar.make(rootView!!, getString(utnfrsf.dondecurso.R.string.error_conexion), Snackbar.LENGTH_INDEFINITE)
.setAction(getString(utnfrsf.dondecurso.R.string.reintentar), { requestLoads() })
.show()
}
})
}
private fun validar(): Boolean {
val valido = carrera?.id != 0
if (!valido) {
mostrarErrorCarrera()
fab?.isEnabled = false
}
return valido
}
private fun mostrarErrorCarrera() {
textViewErrorCarrera!!.error = getString(utnfrsf.dondecurso.R.string.debe_seleccionar_una_carrera)
textViewErrorCarrera!!.visibility = View.VISIBLE
Snackbar.make(rootView!!, getString(utnfrsf.dondecurso.R.string.debe_seleccionar_una_carrera), Snackbar.LENGTH_LONG).show()
}
fun processSubjectsLoad() {
filteredMaterias.clear()
if (carrera?.id != 0 && nivel?.id != 0) {
materias.asSequence()
.filter { it.idCarrera == carrera?.id && it.nivel == nivel?.id }
.forEach { filteredMaterias.add(it) }
} else if (carrera?.id != 0 && nivel?.id == 0) {
materias.asSequence()
.filter { it.idCarrera == carrera?.id }
.forEach { filteredMaterias.add(it) }
}
if (filteredMaterias.size != 1) {
filteredMaterias.add(0, Materia(0, "Todas"))
}
adapterMateria?.notifyDataSetChanged()
if (filteredMaterias.contains(materia)) {
spinnerMateria?.setSelection(adapterMateria?.getPosition(materia)!!)
} else {
spinnerMateria?.setSelection(0)
}
}
fun initView() {
async {
carreras.add(Carrera(0, "Seleccione una carrera"))
carreras.add(Carrera(1, "Ingeniería en Sistemas"))
carreras.add(Carrera(2, "Ingeniería Industrial"))
carreras.add(Carrera(5, "Ingeniería Eléctrica"))
carreras.add(Carrera(6, "Ingeniería Mecánica"))
carreras.add(Carrera(7, "Ingeniería Civil"))
carreras.add(Carrera(8, "Tecnicatura Superior en Mecatrónica"))
carreras.add(Carrera(9, "Institucional"))
carreras.add(Carrera(10, "Extensión Universitaria"))
niveles.add(Nivel(0, "Todos"))
niveles.add(Nivel(1, "Nivel 1"))
niveles.add(Nivel(2, "Nivel 2"))
niveles.add(Nivel(3, "Nivel 3"))
niveles.add(Nivel(4, "Nivel 4"))
niveles.add(Nivel(5, "Nivel 5"))
niveles.add(Nivel(6, "Nivel 6"))
niveles.add(Nivel(7, "No Corresponde"))
carrera = Paper.book().read("carrera", Carrera(0, "Seleccione una carrera"))
nivel = Paper.book().read("nivel", Nivel(0, "Todos"))
materia = Paper.book().read("materia", Materia(0, "Todas"))
comision = Paper.book().read("comision", Comision(0, "Todas"))
onUI {
spinnerMateria = rootView!!.findView(R.id.spinner_materia)
spinnerCarrera = rootView!!.findView(R.id.spinnerCarrera)
spinnerNivel = rootView!!.findView(R.id.spinner_nivel)
spinnerComision = rootView!!.findView(R.id.spinner_comision)
adapterCarrera = MyArrayAdapter(rootView!!.context, R.layout.spinner_item_dark, carreras, false)
adapterNivel = MyArrayAdapter(rootView!!.context, R.layout.spinner_item_dark, niveles, true)
adapterComision = MyArrayAdapter(rootView!!.context, R.layout.spinner_item_dark, comisiones, true)
adapterMateria = MyArrayAdapter(rootView!!.context, R.layout.spinner_item_dark, filteredMaterias, true)
spinnerMateria!!.adapter = adapterMateria
spinnerCarrera!!.adapter = adapterCarrera
spinnerNivel!!.adapter = adapterNivel
spinnerComision!!.adapter = adapterComision
spinnerCarrera!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
carrera = carreras[position]
processSubjectsLoad()
fab?.isEnabled = true
textViewErrorCarrera!!.visibility = View.GONE
}
}
spinnerMateria!!.setOnItemSelectedEvenIfUnchangedListener(object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
materia = filteredMaterias[position]
comisiones.clear()
comisiones.addAll(materia!!.comisiones!!)
if (comisiones.size != 1) {
comisiones.add(0, Comision(0, "Todas"))
}
adapterComision!!.notifyDataSetChanged()
spinnerComision!!.setSelection(adapterComision?.getPosition(comision)!!)
}
})
spinnerNivel!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
nivel = niveles[position]
processSubjectsLoad()
}
}
spinnerComision!!.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
comision = comisiones[position]
}
}
spinnerCarrera!!.setSelection(adapterCarrera?.getPosition(carrera)!!)
spinnerNivel!!.setSelection(adapterNivel?.getPosition(nivel)!!)
materias.add(materia!!)
processSubjectsLoad()
spinnerMateria!!.setSelection(adapterMateria?.getPosition(materia)!!)
}
}
}
}
| mit | a98e9f833d5163e04761dfb42b3703b8 | 41.400778 | 152 | 0.61026 | 4.186323 | false | false | false | false |
siosio/intellij-community | plugins/grazie/markdown/src/main/kotlin/com/intellij/grazie/ide/language/markdown/MarkdownTextExtractor.kt | 1 | 1324 | package com.intellij.grazie.ide.language.markdown
import com.intellij.grazie.ide.language.markdown.MarkdownPsiUtils.isMarkdownCodeType
import com.intellij.grazie.ide.language.markdown.MarkdownPsiUtils.isMarkdownLinkType
import com.intellij.grazie.text.TextContent
import com.intellij.grazie.text.TextContentBuilder
import com.intellij.grazie.text.TextExtractor
import com.intellij.psi.PsiElement
import com.intellij.psi.util.elementType
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
class MarkdownTextExtractor : TextExtractor() {
public override fun buildTextContent(root: PsiElement, allowedDomains: Set<TextContent.TextDomain>): TextContent? {
if (allowedDomains.contains(TextContent.TextDomain.PLAIN_TEXT) &&
(MarkdownPsiUtils.isHeaderContent(root) || MarkdownPsiUtils.isParagraph(root))) {
return TextContentBuilder.FromPsi
.withUnknown { e ->
e.node.isMarkdownCodeType() ||
e.firstChild == null && e.parent.node.isMarkdownLinkType() && !isLinkText(e)
}
.build(root, TextContent.TextDomain.PLAIN_TEXT)
}
return null
}
private fun isLinkText(e: PsiElement) =
e.elementType == MarkdownTokenTypes.TEXT && e.parent.elementType == MarkdownElementTypes.LINK_TEXT
} | apache-2.0 | 5b9d56f2557914a244e85d55cd678df2 | 44.689655 | 117 | 0.77719 | 4.257235 | false | false | false | false |
travisspencer/kotlin-spark-demo | src/main/kotlin/com/nordicapis/kotlin_spark_sample/Application.kt | 1 | 2053 | /*
Copyright (C) 2015 Nordic APIs AB
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.
Application.kt - The main class and functions used to expose an API application using Spark
*/
package com.nordicapis.kotlin_spark_sample
import org.picocontainer.DefaultPicoContainer
import org.picocontainer.MutablePicoContainer
import spark.servlet.SparkApplication
import kotlin.reflect.KClass
import kotlin.reflect.jvm.java
public class Application(
var composer: Composable = Noncomposer(),
var appContainer: MutablePicoContainer = DefaultPicoContainer(),
var routes: () -> List<Application.RouteData<Controllable>>) : SparkApplication
{
private var router = Router()
init
{
composer.composeApplication(appContainer)
}
override fun init() { }
fun host()
{
var routes = routes.invoke()
for (routeData in routes)
{
val (path, controllerClass, template) = routeData
router.routeTo(path, appContainer, controllerClass, composer, template)
}
}
data class RouteData<out T : Controllable>(val path: String, val controllerClass: Class<out T>, val template: String? = null)
}
fun api(composer: Composable, routes: () -> List<Application.RouteData<Controllable>>)
{
Application(composer = composer, routes = routes).host()
}
fun <T : Controllable> path(path: String, to: KClass<T>, renderWith: String? = null) : Application.RouteData<T>
{
return Application.RouteData(path, to.java, renderWith)
}
fun <T> route(vararg values: T): List<T> = listOf(*values)
| apache-2.0 | 2d2610cdac64093f69e3cd9fe26acc0e | 30.584615 | 129 | 0.724793 | 4.181263 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.kt | 1 | 3474 | // 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.
@file:JvmName("PluginsAdvertiser")
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginNode
import com.intellij.ide.plugins.RepositoryHelper
import com.intellij.ide.plugins.advertiser.PluginData
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationGroupManager
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.PlatformUtils.isIdeaUltimate
import org.jetbrains.annotations.ApiStatus
import java.io.IOException
private const val IGNORE_ULTIMATE_EDITION = "ignoreUltimateEdition"
@get:JvmName("getLog")
val LOG = Logger.getInstance("#PluginsAdvertiser")
private val propertiesComponent
get() = PropertiesComponent.getInstance()
var isIgnoreIdeSuggestion: Boolean
get() = propertiesComponent.isTrueValue(IGNORE_ULTIMATE_EDITION)
set(value) = propertiesComponent.setValue(IGNORE_ULTIMATE_EDITION, value)
@JvmField
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
@Deprecated("Use `notificationGroup` property")
val NOTIFICATION_GROUP = notificationGroup
val notificationGroup: NotificationGroup
get() = NotificationGroupManager.getInstance().getNotificationGroup("Plugins Suggestion")
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use `installAndEnable(Project, Set, Boolean, Runnable)`")
fun installAndEnablePlugins(
pluginIds: Set<String>,
onSuccess: Runnable,
) {
installAndEnable(
LinkedHashSet(pluginIds.map { PluginId.getId(it) }),
onSuccess,
)
}
@Deprecated("Use `installAndEnable(Project, Set, Boolean, Runnable)`")
fun installAndEnable(
pluginIds: Set<PluginId>,
onSuccess: Runnable,
) = installAndEnable(null, pluginIds, true, onSuccess)
fun installAndEnable(
project: Project?,
pluginIds: Set<PluginId>,
showDialog: Boolean = false,
onSuccess: Runnable,
) = ProgressManager.getInstance().run(InstallAndEnableTask(project, pluginIds, showDialog, onSuccess))
internal fun getBundledPluginToInstall(plugins: Collection<PluginData>): List<String> {
return if (isIdeaUltimate()) {
emptyList()
}
else {
val descriptorsById = PluginManagerCore.buildPluginIdMap()
plugins
.filter { it.isBundled }
.filterNot { descriptorsById.containsKey(it.pluginId) }
.map { it.pluginName }
}
}
/**
* Loads list of plugins, compatible with a current build, from all configured repositories
*/
@JvmOverloads
internal fun loadPluginsFromCustomRepositories(indicator: ProgressIndicator? = null): List<PluginNode> {
return RepositoryHelper
.getPluginHosts()
.filterNot {
it == null
&& ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()
}.flatMap {
try {
RepositoryHelper.loadPlugins(it, null, indicator)
}
catch (e: IOException) {
LOG.info("Couldn't load plugins from $it: $e")
LOG.debug(e)
emptyList<PluginNode>()
}
}.distinctBy { it.pluginId }
}
| apache-2.0 | 3dc6fc558863af7bd992ec8f6d29ce13 | 33.39604 | 158 | 0.773748 | 4.55308 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyPrimaryConstructorIntention.kt | 4 | 1704 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.psiUtil.containingClass
@Suppress("DEPRECATION")
class RemoveEmptyPrimaryConstructorInspection : IntentionBasedInspection<KtPrimaryConstructor>(
RemoveEmptyPrimaryConstructorIntention::class
), CleanupLocalInspectionTool {
override fun problemHighlightType(element: KtPrimaryConstructor): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL
}
class RemoveEmptyPrimaryConstructorIntention : SelfTargetingOffsetIndependentIntention<KtPrimaryConstructor>(
KtPrimaryConstructor::class.java,
KotlinBundle.lazyMessage("remove.empty.primary.constructor")
) {
override fun applyTo(element: KtPrimaryConstructor, editor: Editor?) = element.delete()
override fun isApplicableTo(element: KtPrimaryConstructor) = when {
element.valueParameters.isNotEmpty() -> false
element.annotations.isNotEmpty() -> false
element.modifierList?.text?.isBlank() == false -> false
element.containingClass()?.secondaryConstructors?.isNotEmpty() == true -> false
element.isExpectDeclaration() -> false
else -> true
}
}
| apache-2.0 | f319c8cad10dbd21c66ab9f221451375 | 46.333333 | 158 | 0.801643 | 5.392405 | false | false | false | false |
ekoshkin/teamcity-azure-active-directory | azure-active-directory-server/src/main/kotlin/org/jetbrains/teamcity/aad/AADAccessTokenManagerImpl.kt | 1 | 3612 | /*
* Copyright 2000-2021 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.teamcity.aad
import jetbrains.buildServer.serverSide.ServerSettings
import jetbrains.buildServer.serverSide.TeamCityProperties
import jetbrains.buildServer.serverSide.crypt.EncryptionManager
import jetbrains.buildServer.serverSide.auth.impl.TokenGenerator
import org.apache.log4j.Logger
import org.jose4j.jwa.AlgorithmConstraints
import org.jose4j.jwk.RsaJwkGenerator
import org.jose4j.jws.AlgorithmIdentifiers
import org.jose4j.jws.JsonWebSignature
import org.jose4j.jwt.JwtClaims
import org.jose4j.jwt.consumer.JwtConsumerBuilder
import org.jose4j.jwt.consumer.InvalidJwtException
class AADAccessTokenManagerImpl(
private val serverSettings : ServerSettings,
private val encryptionManager: EncryptionManager)
: AADAccessTokenFactory, AADAccessTokenValidator {
private val tokenGenerator = TokenGenerator()
private val key = RsaJwkGenerator.generateJwk(RSA_KEY_LENGTH)
private val algorithmConstraints = AlgorithmConstraints(
AlgorithmConstraints.ConstraintType.WHITELIST, ALGORITHM_IDENTIFIER)
override fun create(): String {
val claims = createClaims()
val jws = JsonWebSignature()
jws.payload = claims.toJson()
jws.key = key.privateKey
jws.algorithmHeaderValue = ALGORITHM_IDENTIFIER
return jws.compactSerialization
}
override fun validate(token: String): Boolean {
val jwtConsumer = JwtConsumerBuilder()
.setRequireExpirationTime()
.setVerificationKey(key.getKey())
.setJwsAlgorithmConstraints(algorithmConstraints)
.build();
try {
val jwtClaims = jwtConsumer.processToClaims(token)
if (jwtClaims.issuer != serverSettings.serverUUID) {
LOG.warn("Incorrect issuer: ${jwtClaims.issuer}")
return false
}
} catch (e: InvalidJwtException) {
if (e.hasExpired()) {
LOG.info("JWT token has expired", e)
} else {
LOG.warn("Exception occurred during JWT token processing", e)
}
return false
}
return true
}
private fun createClaims(): JwtClaims {
var claims = JwtClaims()
claims.issuer = serverSettings.serverUUID
claims.setExpirationTimeMinutesInTheFuture(TeamCityProperties.getFloat(AADConstants.TTL_IN_MINUTES_PROPERTY, DEFAULT_TTL_IN_MINUTES))
claims.setIssuedAtToNow()
claims.setClaim(SALT_CLAIM, tokenGenerator.generateString(SALT_LENGTH))
return claims
}
companion object {
private val LOG = Logger.getLogger(AADAccessTokenManagerImpl::class.java.name)
private const val ALGORITHM_IDENTIFIER = AlgorithmIdentifiers.RSA_USING_SHA256
private const val RSA_KEY_LENGTH = 2048
private const val SALT_CLAIM = "salt"
private const val SALT_LENGTH = 64
private const val DEFAULT_TTL_IN_MINUTES = 5f // 5 mins
}
} | apache-2.0 | be22df612559ba45f660628fd9a1f495 | 37.43617 | 141 | 0.701274 | 4.554855 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/source/online/russian/Readmanga.kt | 1 | 7638 | /*
* This file is part of TachiyomiEX. as of commit bf05952582807b469e721cf8ca3be36e8db17f28
*
* TachiyomiEX 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 file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package eu.kanade.tachiyomi.data.source.online.russian
import android.content.Context
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.source.Language
import eu.kanade.tachiyomi.data.source.RU
import eu.kanade.tachiyomi.data.source.Sources
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.data.source.online.ParsedOnlineSource
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
class Readmanga(override val source: Sources) : ParsedOnlineSource() {
override val baseUrl = "http://readmanga.me"
override val lang: Language get() = RU
override fun supportsLatest() = true
override fun popularMangaInitialUrl() = "$baseUrl/list?sortType=rate"
override fun latestUpdatesInitialUrl() = "$baseUrl/list?sortType=updated"
override fun searchMangaInitialUrl(query: String, filters: List<Filter>) =
"$baseUrl/search?q=$query&${filters.map { it.id + "=in" }.joinToString("&")}"
override fun popularMangaSelector() = "div.desc"
override fun popularMangaFromElement(element: Element, manga: Manga) {
element.select("h3 > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.attr("title")
}
}
override fun popularMangaNextPageSelector() = "a.nextLink"
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element, manga: Manga) {
element.select("h3 > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.attr("title")
}
}
// max 200 results
override fun searchMangaNextPageSelector() = null
override fun mangaDetailsParse(document: Document, manga: Manga) {
val infoElement = document.select("div.leftContent").first()
manga.author = infoElement.select("span.elem_author").first()?.text()
manga.genre = infoElement.select("span.elem_genre").text().replace(" ,", ",")
manga.description = infoElement.select("div.manga-description").text()
manga.status = parseStatus(infoElement.html())
manga.thumbnail_url = infoElement.select("img").attr("data-full")
}
private fun parseStatus(element: String): Int {
when {
element.contains("<h3>Запрещена публикация произведения по копирайту</h3>") -> return Manga.LICENSED
element.contains("<h1 class=\"names\"> Сингл") || element.contains("<b>Перевод:</b> завершен") -> return Manga.COMPLETED
element.contains("<b>Перевод:</b> продолжается") -> return Manga.ONGOING
else -> return Manga.UNKNOWN
}
}
override fun chapterListSelector() = "div.chapters-link tbody tr"
override fun chapterFromElement(element: Element, chapter: Chapter) {
val urlElement = element.select("a").first()
chapter.setUrlWithoutDomain(urlElement.attr("href") + "?mature=1")
chapter.name = urlElement.text().replace(" новое", "")
chapter.date_upload = element.select("td:eq(1)").first()?.text()?.let {
SimpleDateFormat("dd/MM/yy", Locale.US).parse(it).time
} ?: 0
}
override fun parseChapterNumber(chapter: Chapter) {
chapter.chapter_number = -2f
}
override fun pageListParse(response: Response, pages: MutableList<Page>) {
val html = response.body().string()
val beginIndex = html.indexOf("rm_h.init( [")
val p = Pattern.compile("'.+?','.+?',\".+?\"")
val m = p.matcher(html.substring(beginIndex, html.indexOf("], 0, false);", beginIndex)))
var i = 0
while (m.find()) {
val urlParts = m.group().replace("[\"\']+".toRegex(), "").split(',')
pages.add(Page(i++, "", urlParts[1] + urlParts[0] + urlParts[2]))
}
}
override fun pageListParse(document: Document, pages: MutableList<Page>) { }
override fun imageUrlParse(document: Document) = ""
/* [...document.querySelectorAll("tr.advanced_option:nth-child(1) > td:nth-child(3) span.js-link")].map((el,i) => {
* const onClick=el.getAttribute('onclick');const id=onClick.substr(31,onClick.length-33);
* return `Filter("${id}", "${el.textContent.trim()}")` }).join(',\n')
* on http://readmanga.me/search
*/
override fun getFilterList(): List<Filter> = listOf(
Filter("el_5685", "арт"),
Filter("el_2155", "боевик"),
Filter("el_2143", "боевые искусства"),
Filter("el_2148", "вампиры"),
Filter("el_2142", "гарем"),
Filter("el_2156", "гендерная интрига"),
Filter("el_2146", "героическое фэнтези"),
Filter("el_2152", "детектив"),
Filter("el_2158", "дзёсэй"),
Filter("el_2141", "додзинси"),
Filter("el_2118", "драма"),
Filter("el_2154", "игра"),
Filter("el_2119", "история"),
Filter("el_2137", "кодомо"),
Filter("el_2136", "комедия"),
Filter("el_2147", "махо-сёдзё"),
Filter("el_2126", "меха"),
Filter("el_2132", "мистика"),
Filter("el_2133", "научная фантастика"),
Filter("el_2135", "повседневность"),
Filter("el_2151", "постапокалиптика"),
Filter("el_2130", "приключения"),
Filter("el_2144", "психология"),
Filter("el_2121", "романтика"),
Filter("el_2124", "самурайский боевик"),
Filter("el_2159", "сверхъестественное"),
Filter("el_2122", "сёдзё"),
Filter("el_2128", "сёдзё-ай"),
Filter("el_2134", "сёнэн"),
Filter("el_2139", "сёнэн-ай"),
Filter("el_2129", "спорт"),
Filter("el_2138", "сэйнэн"),
Filter("el_2153", "трагедия"),
Filter("el_2150", "триллер"),
Filter("el_2125", "ужасы"),
Filter("el_2140", "фантастика"),
Filter("el_2131", "фэнтези"),
Filter("el_2127", "школа"),
Filter("el_2149", "этти"),
Filter("el_2123", "юри")
)
} | gpl-3.0 | d692d85ec1c2af0844e3fdbbf41f6d9b | 40.234286 | 132 | 0.623701 | 3.80137 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findJavaPropertyUsages/javaPropertyUsagesK.0.kt | 3 | 395 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtProperty
// OPTIONS: usages
open class A {
open var <caret>p: Int = 1
}
class AA : A() {
override var p: Int = 1
}
class B : J() {
override var p: Int = 1
}
fun test() {
val t = A().p
A().p = 1
val t = AA().p
AA().p = 1
val t = J().p
J().p = 1
val t = B().p
B().p = 1
}
// DISABLE-ERRORS
// FIR_IGNORE | apache-2.0 | cc4780066c5cbcb939c1baede08e263a | 12.2 | 51 | 0.493671 | 2.743056 | false | false | false | false |
YutaKohashi/FakeLineApp | app/src/main/java/jp/yuta/kohashi/fakelineapp/views/view/CustomProgDiag.kt | 1 | 2269 | package jp.yuta.kohashi.fakelineapp.views.view
import android.app.ProgressDialog
import android.content.Context
import android.os.Handler
/**
* Author : yutakohashi
* Project name : FakeLineApp
* Date : 27 / 09 / 2017
*/
class CustomProgDiag(context: Context?) : ProgressDialog(context) {
// start time
private var mStartTime: Long = 0
// show at least milliseconds
private var mDuration: Long = 0
// showing?
private var showing: Boolean = false
private var mHandler: Handler? = null
private var mRunnable: Runnable? = null
/**
* ミリ単位ダイアログを表示する最低時間を指定
*
* @param duration
*/
fun show(duration: Long) {
show(duration, 0)
}
/**
* @param duration 最低何秒間表示するか
* @param start 何秒後からダイアログ表示
*/
fun show(duration: Long, start: Long) {
mDuration = duration
showing = false
if (start == 0L) {
showDiag()
return
}
mHandler = Handler()
mRunnable = Runnable { showDiag() }
mHandler!!.postDelayed(mRunnable, start)
}
fun dismiss(callback: Callback) {
if (!showing) {
showing = false
mHandler!!.removeCallbacks(mRunnable)
callback.callback()
return
}
val endTime = System.currentTimeMillis()
val diffTime = endTime - mStartTime
if (diffTime < mDuration) {
Handler().postDelayed({
[email protected]()
callback.callback()
}, mDuration - diffTime)
} else {
super.dismiss()
callback.callback()
}
}
/**
* ダイアログ表示
*/
private fun showDiag() {
showing = true
mStartTime = System.currentTimeMillis()
show()
mShowDialogCallback?.dialogShowed()
}
private var mShowDialogCallback:OnShowDialogCallback? = null
fun setShowDialogCalbackListener(l:OnShowDialogCallback){
mShowDialogCallback = l
}
interface Callback {
fun callback()
}
interface OnShowDialogCallback{
fun dialogShowed()
}
} | mit | 4ec5657a6f781fb716d8eed6f52b05f4 | 21.604167 | 67 | 0.579069 | 4.417515 | false | false | false | false |
smmribeiro/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/indices/EntityStorageInternalIndex.kt | 9 | 2926 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.indices
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.diagnostic.trace
import com.intellij.workspaceModel.storage.impl.EntityId
import com.intellij.workspaceModel.storage.impl.containers.BidirectionalLongSetMap
import org.jetbrains.annotations.TestOnly
//typealias EntityStorageIndex = BidirectionalSetMap<EntityId, T>
internal typealias EntityStorageIndex<T> = BidirectionalLongSetMap<T>
open class EntityStorageInternalIndex<T> private constructor(
internal open val index: EntityStorageIndex<T>,
protected val oneToOneAssociation: Boolean
) {
constructor(oneToOneAssociation: Boolean) : this(EntityStorageIndex<T>(), oneToOneAssociation)
internal fun getIdsByEntry(entry: T): List<EntityId>? = index.getKeysByValue(entry)?.toList()
internal fun getEntryById(id: EntityId): T? = index[id]
internal fun entries(): Collection<T> {
return index.values
}
class MutableEntityStorageInternalIndex<T> private constructor(
// Do not write to [index] directly! Create a method in this index and call [startWrite] before write.
override var index: EntityStorageIndex<T>,
oneToOneAssociation: Boolean
) : EntityStorageInternalIndex<T>(index, oneToOneAssociation) {
private var freezed = true
internal fun index(id: EntityId, entry: T? = null) {
startWrite()
if (entry == null) {
LOG.trace { "Removing $id from index" }
index.remove(id)
return
}
LOG.trace { "Index $id to $entry" }
index.put(id, entry)
if (oneToOneAssociation) {
if ((index.getKeysByValue(entry)?.size ?: 0) > 1) {
thisLogger().error("One to one association is violated. Id: $id, Entity: $entry. This id is already associated with ${index.getKeysByValue(entry)}")
}
}
}
@TestOnly
internal fun clear() {
startWrite()
index.clear()
}
@TestOnly
internal fun copyFrom(another: EntityStorageInternalIndex<T>) {
startWrite()
this.index.putAll(another.index)
}
private fun startWrite() {
if (!freezed) return
freezed = false
index = index.copy()
}
fun toImmutable(): EntityStorageInternalIndex<T> {
freezed = true
return EntityStorageInternalIndex(this.index, this.oneToOneAssociation)
}
companion object {
fun <T> from(other: EntityStorageInternalIndex<T>): MutableEntityStorageInternalIndex<T> {
if (other is MutableEntityStorageInternalIndex<T>) other.freezed = true
return MutableEntityStorageInternalIndex(other.index, other.oneToOneAssociation)
}
val LOG = logger<MutableEntityStorageInternalIndex<*>>()
}
}
}
| apache-2.0 | 6789857e9e5b1bce81b1e5ec7e70e7c6 | 33.423529 | 158 | 0.712235 | 4.48773 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/Gaps.kt | 1 | 846 | // 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.ui.dsl.gridLayout
import com.intellij.ui.dsl.checkNonNegative
import com.intellij.util.ui.JBEmptyBorder
data class Gaps(val top: Int = 0, val left: Int = 0, val bottom: Int = 0, val right: Int = 0) {
companion object {
@JvmField
val EMPTY = Gaps(0)
}
init {
checkNonNegative("top", top)
checkNonNegative("left", left)
checkNonNegative("bottom", bottom)
checkNonNegative("right", right)
}
constructor(size: Int) : this(size, size, size, size)
val width: Int
get() = left + right
val height: Int
get() = top + bottom
}
fun Gaps.toJBEmptyBorder(): JBEmptyBorder {
return JBEmptyBorder(top, left, bottom, right)
}
| apache-2.0 | 8a97ea4b0bf79cb47f0ba114e836aba6 | 25.4375 | 158 | 0.692671 | 3.662338 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/LoggerProviderOverrideTest.kt | 2 | 1370 | // 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.internal.statistics
import com.intellij.internal.statistic.eventLog.StatisticsEventLogProviderUtil
import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider
import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider.Companion.EP_NAME
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.LoadingOrder
import com.intellij.testFramework.fixtures.BasePlatformTestCase
class LoggerProviderOverrideTest : BasePlatformTestCase() {
companion object {
private const val fusRecorderId = "FUS"
}
private class TestLoggerProvider: StatisticsEventLoggerProvider(fusRecorderId, 123) {
override fun isRecordEnabled() = false
override fun isSendEnabled() = false
}
override fun setUp() {
super.setUp()
installEP()
}
fun installEP() {
val ep = ApplicationManager.getApplication().extensionArea.getExtensionPoint(EP_NAME)
ep.registerExtension(TestLoggerProvider(), LoadingOrder.FIRST, project)
}
fun testFUSLoggerProviderOverridden() {
val provider = StatisticsEventLogProviderUtil.getEventLogProvider(fusRecorderId)
assertInstanceOf(provider, TestLoggerProvider::class.java)
}
} | apache-2.0 | 4ee3b2ae7a05bb6632fcbcfb88cc51eb | 37.083333 | 140 | 0.80365 | 4.875445 | false | true | false | false |
smmribeiro/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/MergeRangeList.kt | 12 | 1664 | // 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.idea.svn.mergeinfo
import org.jetbrains.idea.svn.SvnBundle.message
import org.jetbrains.idea.svn.api.ErrorCode.MERGE_INFO_PARSE_ERROR
import org.jetbrains.idea.svn.commandLine.SvnBindException
data class MergeRangeList(val ranges: Set<MergeRange>) {
companion object {
@JvmStatic
@Throws(SvnBindException::class)
fun parseMergeInfo(value: String): Map<String, MergeRangeList> = if (value.isEmpty()) emptyMap()
else value.lineSequence().map { parseLine(it) }.toMap()
@Throws(SvnBindException::class)
fun parseRange(value: String): MergeRange {
val revisions = value.removeSuffix("*").split('-')
if (revisions.isEmpty() || revisions.size > 2) throwParseFailed(value)
val start = parseRevision(revisions[0])
val end = if (revisions.size == 2) parseRevision(revisions[1]) else start
return MergeRange(start, end, value.lastOrNull() != '*')
}
private fun parseLine(value: String): Pair<String, MergeRangeList> {
val parts = value.split(':')
if (parts.size != 2) throwParseFailed(value)
return Pair(parts[0], MergeRangeList(parts[1].splitToSequence(',').map { parseRange(it) }.toSet()))
}
private fun parseRevision(value: String) = try {
value.toLong()
}
catch (e: NumberFormatException) {
throwParseFailed(value)
}
private fun throwParseFailed(value: String): Nothing =
throw SvnBindException(MERGE_INFO_PARSE_ERROR, message("error.could.not.parse.merge.info", value))
}
} | apache-2.0 | 7522b2b77259143a41fb50b4e0f8a1a6 | 38.642857 | 140 | 0.701923 | 3.97136 | false | false | false | false |
tomatrocho/insapp-material | app/src/main/java/fr/insapp/insapp/adapters/PostRecyclerViewAdapter.kt | 2 | 9181 | package fr.insapp.insapp.adapters
import android.content.Intent
import android.text.util.Linkify
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestOptions
import com.varunest.sparkbutton.SparkEventListener
import fr.insapp.insapp.R
import fr.insapp.insapp.activities.AssociationActivity
import fr.insapp.insapp.activities.PostActivity
import fr.insapp.insapp.activities.isPostLikedBy
import fr.insapp.insapp.http.ServiceGenerator
import fr.insapp.insapp.models.Association
import fr.insapp.insapp.models.Post
import fr.insapp.insapp.models.PostInteraction
import fr.insapp.insapp.utility.Utils
import fr.insapp.insapp.utility.inflate
import kotlinx.android.synthetic.main.post.view.*
import kotlinx.android.synthetic.main.post.view.post_date
import kotlinx.android.synthetic.main.post.view.post_name
import kotlinx.android.synthetic.main.post_with_avatars.view.post_association_avatar
import kotlinx.android.synthetic.main.reactions.view.*
import kotlinx.android.synthetic.main.row_post.view.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
/**
* Created by thomas on 19/11/2016.
* Kotlin rewrite on 28/08/2019.
*/
class PostRecyclerViewAdapter(
val posts: MutableList<Post>,
private val requestManager: RequestManager,
private val layout: Int
) : RecyclerView.Adapter<PostRecyclerViewAdapter.PostViewHolder>() {
fun addItem(post: Post) {
this.posts.add(post)
this.notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = PostViewHolder(parent.inflate(layout), requestManager, layout)
override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
val post = posts[position]
holder.bindPost(post)
}
override fun getItemCount() = posts.size
class PostViewHolder(
private val view: View,
private val requestManager: RequestManager,
private val layoutId: Int
) : RecyclerView.ViewHolder(view), View.OnClickListener {
private var post: Post? = null
init {
view.setOnClickListener(this)
}
fun bindPost(post: Post) {
this.post = post
val context = itemView.context
view.post_name.text = post.title
view.post_date.text = Utils.displayedDate(post.date)
// available layouts are row_post, post or post_with_avatars
if (layoutId != R.layout.post) {
// association avatar
val call = ServiceGenerator.client.getAssociationFromId(post.association)
call.enqueue(object : Callback<Association> {
override fun onResponse(call: Call<Association>, response: Response<Association>) {
if (response.isSuccessful) {
val association = response.body()
if (association != null) {
requestManager
.load(ServiceGenerator.CDN_URL + association.profilePicture)
.apply(RequestOptions.circleCropTransform())
.transition(withCrossFade())
.into(view.post_association_avatar)
// listener
view.post_association_avatar.setOnClickListener { context.startActivity(Intent(context, AssociationActivity::class.java).putExtra("association", association)) }
}
} else {
Toast.makeText(context, "PostRecyclerViewAdapter", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Association>, t: Throwable) {
Toast.makeText(context, "PostRecyclerViewAdapter", Toast.LENGTH_LONG).show()
}
})
}
if (layoutId == R.layout.row_post) {
requestManager
.load(ServiceGenerator.CDN_URL + post.image)
.apply(RequestOptions().transforms(CenterCrop(), RoundedCorners(8)))
.transition(withCrossFade())
.into(view.post_thumbnail)
} else {
view.post_placeholder.setImageSize(post.imageSize)
requestManager
.load(ServiceGenerator.CDN_URL + post.image)
.transition(withCrossFade())
.into(view.post_image)
view.post_text.text = post.description
view.like_counter.text = String.format(Locale.FRANCE, "%d", post.likes.size)
view.comment_counter.text = String.format(Locale.FRANCE, "%d", post.comments.size)
// description links
Linkify.addLinks(view.post_text, Linkify.ALL)
Utils.convertToLinkSpan(context, view.post_text)
// like button
val user = Utils.user
if (user != null) {
val userId = user.id
view.like_button.isChecked = post.isPostLikedBy(userId)
view.like_button.setEventListener(object : SparkEventListener {
override fun onEvent(icon: ImageView, buttonState: Boolean) {
if (buttonState) {
val call = ServiceGenerator.client.likePost(post.id, userId)
call.enqueue(object : Callback<PostInteraction> {
override fun onResponse(call: Call<PostInteraction>, response: Response<PostInteraction>) {
if (response.isSuccessful) {
if (response.body() != null) {
view.like_counter.text = String.format(Locale.FRANCE, "%d", post.likes.size + 1)
}
} else {
Toast.makeText(context, "PostRecyclerViewAdapter", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<PostInteraction>, t: Throwable) {
Toast.makeText(context, "PostRecyclerViewAdapter", Toast.LENGTH_LONG).show()
}
})
} else {
val call = ServiceGenerator.client.dislikePost(post.id, userId)
call.enqueue(object : Callback<PostInteraction> {
override fun onResponse(call: Call<PostInteraction>, response: Response<PostInteraction>) {
if (response.isSuccessful) {
if (response.body() != null) {
view.like_counter.text = String.format(Locale.FRANCE, "%d", post.likes.size - 1)
}
} else {
Toast.makeText(context, "PostRecyclerViewAdapter", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<PostInteraction>, t: Throwable) {
Toast.makeText(context, "PostRecyclerViewAdapter", Toast.LENGTH_LONG).show()
}
})
}
}
override fun onEventAnimationEnd(button: ImageView?, buttonState: Boolean) {}
override fun onEventAnimationStart(button: ImageView?, buttonState: Boolean) {}
})
}
// comment button
view.comment_button.setOnClickListener { context.startActivity(Intent(context, PostActivity::class.java).putExtra("post", post)) }
}
// hide image if necessary
if (post.image.isEmpty()) {
view.post_placeholder.visibility = View.GONE
view.post_image.visibility = View.GONE
}
}
override fun onClick(v: View) {
val context = itemView.context
context.startActivity(Intent(context, PostActivity::class.java).putExtra("post", post))
}
}
}
| mit | 2f10a07b03af1d9b63ced8951b97cff7 | 42.719048 | 192 | 0.547544 | 5.432544 | false | false | false | false |
Jire/Charlatano | src/main/kotlin/com/charlatano/overlay/transparency/win7/DWM_BLURBEHIND.kt | 1 | 1246 | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.overlay.transparency.win7
import com.sun.jna.Structure
import com.sun.jna.platform.win32.WinDef
class DWM_BLURBEHIND : Structure() {
@JvmField
var dwFlags: WinDef.DWORD? = null
@JvmField
var fEnable = false
@JvmField
var hRgnBlur: WinDef.HRGN? = null
@JvmField
var fTransitionOnMaximized = false
override fun getFieldOrder() = listOf("dwFlags", "fEnable", "hRgnBlur", "fTransitionOnMaximized")
} | agpl-3.0 | ba64f5d0789fe89500ce744bcb829aae | 30.175 | 98 | 0.74077 | 3.643275 | false | false | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/adventurecreation/impl/SAdventureCreation.kt | 1 | 1227 | package pt.joaomneto.titancompanion.adventurecreation.impl
import android.view.View
import java.io.BufferedWriter
import java.io.IOException
import kotlinx.android.synthetic.main.fragment_53s_adventurecreation_vital_statistics.*
import pt.joaomneto.titancompanion.R
import pt.joaomneto.titancompanion.adventurecreation.AdventureCreation
import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.s.SVitalStatisticsFragment
import pt.joaomneto.titancompanion.util.AdventureFragmentRunner
import pt.joaomneto.titancompanion.util.DiceRoller
class SAdventureCreation : AdventureCreation(
arrayOf(
AdventureFragmentRunner(
R.string.title_adventure_creation_vitalstats,
SVitalStatisticsFragment::class
)
)
) {
private var gold = -1
@Throws(IOException::class)
override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) {
bw.write("currentFaith=1\n")
bw.write("currentInfection=0\n")
bw.write("provisions=5\n")
bw.write("provisionsValue=4\n")
bw.write("gold=$gold\n")
}
override fun rollGamebookSpecificStats(view: View) {
gold = DiceRoller.rollD6() + 4
goldValue.text = "$gold"
}
}
| lgpl-3.0 | 4c7209e28a467be05702c15fcc787cfb | 32.162162 | 94 | 0.740016 | 4.320423 | false | false | false | false |
spring-projects/spring-security | config/src/main/kotlin/org/springframework/security/config/annotation/web/Saml2Dsl.kt | 2 | 4719 | /*
* Copyright 2002-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 org.springframework.security.config.annotation.web
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configurers.saml2.Saml2LoginConfigurer
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
/**
* A Kotlin DSL to configure [HttpSecurity] SAML2 login using idiomatic Kotlin code.
*
* @author Eleftheria Stein
* @since 5.3
* @property relyingPartyRegistrationRepository the [RelyingPartyRegistrationRepository] of relying parties,
* each party representing a service provider, SP and this host, and identity provider, IDP pair that
* communicate with each other.
* @property loginPage the login page to redirect to if authentication is required (i.e.
* "/login")
* @property authenticationSuccessHandler the [AuthenticationSuccessHandler] used after
* authentication success
* @property authenticationFailureHandler the [AuthenticationFailureHandler] used after
* authentication success
* @property failureUrl the URL to send users if authentication fails
* @property loginProcessingUrl the URL to validate the credentials
* @property permitAll whether to grant access to the urls for [failureUrl] as well as
* for the [HttpSecurityBuilder], the [loginPage] and [loginProcessingUrl] for every user
* @property authenticationManager the [AuthenticationManager] to be used during SAML 2
* authentication.
*/
@SecurityMarker
class Saml2Dsl {
var relyingPartyRegistrationRepository: RelyingPartyRegistrationRepository? = null
var loginPage: String? = null
var authenticationSuccessHandler: AuthenticationSuccessHandler? = null
var authenticationFailureHandler: AuthenticationFailureHandler? = null
var failureUrl: String? = null
var loginProcessingUrl: String? = null
var permitAll: Boolean? = null
var authenticationManager: AuthenticationManager? = null
private var defaultSuccessUrlOption: Pair<String, Boolean>? = null
/**
* Grants access to the urls for [failureUrl] as well as for the [HttpSecurityBuilder], the
* [loginPage] and [loginProcessingUrl] for every user.
*/
fun permitAll() {
permitAll = true
}
/**
* Specifies where users will be redirected after authenticating successfully if
* they have not visited a secured page prior to authenticating or [alwaysUse]
* is true.
*
* @param defaultSuccessUrl the default success url
* @param alwaysUse true if the [defaultSuccessUrl] should be used after
* authentication despite if a protected page had been previously visited
*/
fun defaultSuccessUrl(defaultSuccessUrl: String, alwaysUse: Boolean) {
defaultSuccessUrlOption = Pair(defaultSuccessUrl, alwaysUse)
}
internal fun get(): (Saml2LoginConfigurer<HttpSecurity>) -> Unit {
return { saml2Login ->
relyingPartyRegistrationRepository?.also { saml2Login.relyingPartyRegistrationRepository(relyingPartyRegistrationRepository) }
loginPage?.also { saml2Login.loginPage(loginPage) }
failureUrl?.also { saml2Login.failureUrl(failureUrl) }
loginProcessingUrl?.also { saml2Login.loginProcessingUrl(loginProcessingUrl) }
permitAll?.also { saml2Login.permitAll(permitAll!!) }
defaultSuccessUrlOption?.also {
saml2Login.defaultSuccessUrl(defaultSuccessUrlOption!!.first, defaultSuccessUrlOption!!.second)
}
authenticationSuccessHandler?.also { saml2Login.successHandler(authenticationSuccessHandler) }
authenticationFailureHandler?.also { saml2Login.failureHandler(authenticationFailureHandler) }
authenticationManager?.also { saml2Login.authenticationManager(authenticationManager) }
}
}
}
| apache-2.0 | a3d6c502818de5430fbabb33071cf0e1 | 48.15625 | 138 | 0.76139 | 5.079656 | false | true | false | false |
aosp-mirror/platform_frameworks_support | jetifier/jetifier/core/src/test/kotlin/com/android/tools/build/jetifier/core/type/JavaTypeTest.kt | 1 | 1704 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.jetifier.core.type
import com.google.common.truth.Truth
import org.junit.Test
class JavaTypeTest {
@Test fun javaType_testFromDotVersion() {
val type = JavaType.fromDotVersion("test.MyClass.FIELD")
Truth.assertThat(type.fullName).isEqualTo("test/MyClass/FIELD")
}
@Test fun javaType_testParent() {
val type = JavaType.fromDotVersion("test.MyClass.FIELD")
val result = type.getParentType().toDotNotation()
Truth.assertThat(result).isEqualTo("test.MyClass")
}
@Test fun javaType_testParent_identity() {
val type = JavaType.fromDotVersion("test")
val result = type.getParentType().toDotNotation()
Truth.assertThat(result).isEqualTo("test")
}
@Test fun javaType_remapeWithNewRootType() {
val type = JavaType.fromDotVersion("test.MyClass\$Inner")
val remapWith = JavaType.fromDotVersion("hello.NewClass")
Truth.assertThat(type.remapWithNewRootType(remapWith).toDotNotation())
.isEqualTo("hello.NewClass\$Inner")
}
} | apache-2.0 | 376a23df3135d470533305e8015ce955 | 33.1 | 78 | 0.704225 | 4.207407 | false | true | false | false |
stephanenicolas/heatControl | app/src/main/java/com/github/stephanenicolas/heatcontrol/features/control/usecases/ControlController.kt | 1 | 4028 | package com.github.stephanenicolas.heatcontrol.features.control.usecases
import com.github.stephanenicolas.heatcontrol.base.network.*
import com.github.stephanenicolas.heatcontrol.features.control.state.ControlStore
import com.github.stephanenicolas.heatcontrol.features.control.state.ErrorControlAction
import com.github.stephanenicolas.heatcontrol.features.control.state.RefreshTemperaturesControlAction
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Inject
class ControlController @Inject constructor(val baseUrlProvider: BaseUrlProvider,
val controlHeatStore: ControlStore,
val ketRequestInterceptor: KeyRequestInterceptor,
val ipRequestInterceptor: IPRequestInterceptor) {
private val subscriptions: CompositeDisposable = CompositeDisposable()
fun detach() {
subscriptions.dispose()
}
fun refreshTemperatures() {
val heatControlApi = createRetrofit()
if (heatControlApi != null) {
val disposable = heatControlApi.getTargetTemperature()
.zipWith(heatControlApi.getAmbientTemperature(), BiFunction<HeatResponse,HeatResponse,Pair<String,String>> { t1, t2 -> combineTemperatures(t1, t2) })
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onSuccessGetTemperatures,
this::onFailureGetTemp)
subscriptions.add(disposable)
}
}
fun combineTemperatures(ambientHeatResponse: HeatResponse, targetHeatResponse: HeatResponse): Pair<String, String> {
return Pair(ambientHeatResponse.data, targetHeatResponse.data)
}
fun setTargetTemperature(targetTemp: String) {
val heatControlApi = createRetrofit()
if (heatControlApi != null) {
val disposable = heatControlApi.setTargetTemperature(targetTemp)
.flatMap({heatControlApi.getTargetTemperature()})
.zipWith(heatControlApi.getAmbientTemperature(), BiFunction<HeatResponse,HeatResponse,Pair<String,String>> { t1, t2 -> combineTemperatures(t1, t2) })
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onSuccessGetTemperatures,
this::onFailureGetTemp)
subscriptions.add(disposable)
}
}
private fun onSuccessGetTemperatures(temperaturePair: Pair<String, String>) {
val action = RefreshTemperaturesControlAction(temperaturePair.first.toFloat(), temperaturePair.second.toFloat())
controlHeatStore.dispatch(action)
}
private fun onFailureGetTemp(throwable: Throwable) {
val action = ErrorControlAction(throwable)
controlHeatStore.dispatch(action)
}
private fun createRetrofit(): HeatControlApi? {
if (baseUrlProvider.httpUrl == null) {
onFailureGetTemp(IllegalStateException("No base url defined"))
return null
}
val clientBuilder = OkHttpClient.Builder()
clientBuilder.interceptors().add(ketRequestInterceptor)
clientBuilder.interceptors().add(ipRequestInterceptor)
val retrofit = Retrofit.Builder()
.baseUrl(baseUrlProvider.httpUrl)
.client(clientBuilder.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(HeatControlApi::class.java)
}
}
| apache-2.0 | 3b6b55d1c7c94335aaf1017052ff3386 | 44.772727 | 169 | 0.684459 | 5.204134 | false | false | false | false |
ilya-g/kotlinx.collections.immutable | core/commonMain/src/implementations/immutableSet/PersistentHashSetIterator.kt | 1 | 3206 | /*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package kotlinx.collections.immutable.implementations.immutableSet
import kotlinx.collections.immutable.internal.assert
import kotlin.js.JsName
internal open class PersistentHashSetIterator<E>(node: TrieNode<E>) : Iterator<E> {
protected val path = mutableListOf(TrieNodeIterator<E>())
protected var pathLastIndex = 0
@JsName("_hasNext")
private var hasNext = true
init {
path[0].reset(node.buffer)
pathLastIndex = 0
ensureNextElementIsReady()
}
private fun moveToNextNodeWithData(pathIndex: Int): Int {
if (path[pathIndex].hasNextElement()) {
return pathIndex
}
if (path[pathIndex].hasNextNode()) {
val node = path[pathIndex].currentNode()
if (pathIndex + 1 == path.size) {
path.add(TrieNodeIterator())
}
path[pathIndex + 1].reset(node.buffer)
return moveToNextNodeWithData(pathIndex + 1)
}
return -1
}
private fun ensureNextElementIsReady() {
if (path[pathLastIndex].hasNextElement()) {
return
}
for(i in pathLastIndex downTo 0) {
var result = moveToNextNodeWithData(i)
if (result == -1 && path[i].hasNextCell()) {
path[i].moveToNextCell()
result = moveToNextNodeWithData(i)
}
if (result != -1) {
pathLastIndex = result
return
}
if (i > 0) {
path[i - 1].moveToNextCell()
}
}
hasNext = false
}
override fun hasNext(): Boolean {
return hasNext
}
override fun next(): E {
if (!hasNext)
throw NoSuchElementException()
val result = path[pathLastIndex].nextElement()
ensureNextElementIsReady()
return result
}
protected fun currentElement(): E {
assert(hasNext())
return path[pathLastIndex].currentElement()
}
}
internal class TrieNodeIterator<out E> {
private var buffer = TrieNode.EMPTY.buffer
private var index = 0
fun reset(buffer: Array<Any?>, index: Int = 0) {
this.buffer = buffer
this.index = index
}
fun hasNextCell(): Boolean {
return index < buffer.size
}
fun moveToNextCell() {
assert(hasNextCell())
index++
}
fun hasNextElement(): Boolean {
return hasNextCell() && buffer[index] !is TrieNode<*>
}
fun currentElement(): E {
assert(hasNextElement())
@Suppress("UNCHECKED_CAST")
return buffer[index] as E
}
fun nextElement(): E {
assert(hasNextElement())
@Suppress("UNCHECKED_CAST")
return buffer[index++] as E
}
fun hasNextNode(): Boolean {
return hasNextCell() && buffer[index] is TrieNode<*>
}
fun currentNode(): TrieNode<out E> {
assert(hasNextNode())
@Suppress("UNCHECKED_CAST")
return buffer[index] as TrieNode<E>
}
}
| apache-2.0 | 440eec27f2090b9bf9ff673e117bd914 | 25.065041 | 107 | 0.575483 | 4.490196 | false | false | false | false |
javiyt/nftweets | app/src/main/java/yt/javi/nftweets/ui/twitter/TwitterTimeLineActivity.kt | 1 | 2111 | package yt.javi.nftweets.ui.twitter
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import com.twitter.sdk.android.core.models.Tweet
import com.twitter.sdk.android.tweetui.SearchTimeline
import com.twitter.sdk.android.tweetui.Timeline
import com.twitter.sdk.android.tweetui.TweetTimelineRecyclerViewAdapter
import com.twitter.sdk.android.tweetui.UserTimeline
import kotlinx.android.synthetic.main.activity_twitter_time_line.*
import yt.javi.nftweets.R
class TwitterTimeLineActivity : AppCompatActivity() {
companion object {
val EXTRA_TWITTER_ACCOUNT = "twitter_account"
val EXTRA_TEAM_NAME = "team_name"
val EXTRA_TWITTER_TIMELINE_TYPE = "twitter_timeline_type"
}
enum class TimelineType {
USER, SEARCH
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_twitter_time_line)
val recyclerView = timeline_list
recyclerView.layoutManager = LinearLayoutManager(this)
val searchTimeline: Timeline<Tweet> = if (TimelineType.valueOf(intent.getStringExtra(EXTRA_TWITTER_TIMELINE_TYPE)) == TimelineType.USER)
UserTimeline.Builder()
.screenName(intent.getStringExtra(EXTRA_TWITTER_ACCOUNT))
.build()
else
SearchTimeline.Builder()
.query("#" + intent.getStringExtra(EXTRA_TWITTER_ACCOUNT))
.build()
recyclerView.adapter = TweetTimelineRecyclerViewAdapter.Builder(this)
.setTimeline(searchTimeline)
.setViewStyle(R.style.tw__TweetLightWithActionsStyle)
.build()
twitter_toolbar.title = intent.getStringExtra(EXTRA_TEAM_NAME)
setSupportActionBar(twitter_toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
| apache-2.0 | c91cf393318d28950aae5d1ed3cc2255 | 34.779661 | 144 | 0.699668 | 4.754505 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/traktapi/TraktTools2.kt | 1 | 6718 | package com.battlelancer.seriesguide.traktapi
import android.content.Context
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.shows.tools.AddUpdateShowTools.ShowResult
import com.battlelancer.seriesguide.util.Errors
import com.battlelancer.seriesguide.util.isRetryError
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.Result
import com.github.michaelbull.result.andThen
import com.github.michaelbull.result.mapError
import com.github.michaelbull.result.runCatching
import com.uwetrottmann.trakt5.entities.BaseShow
import com.uwetrottmann.trakt5.entities.LastActivities
import com.uwetrottmann.trakt5.entities.LastActivity
import com.uwetrottmann.trakt5.entities.LastActivityMore
import com.uwetrottmann.trakt5.entities.Ratings
import com.uwetrottmann.trakt5.entities.Show
import com.uwetrottmann.trakt5.enums.Extended
import com.uwetrottmann.trakt5.enums.IdType
import com.uwetrottmann.trakt5.enums.Type
import retrofit2.Response
object TraktTools2 {
data class SearchResult(val result: ShowResult, val show: Show?)
/**
* Look up a show by its TMDB ID, may return `null` if not found.
*/
fun getShowByTmdbId(showTmdbId: Int, context: Context): Result<Show?, TraktError> {
val action = "show trakt lookup"
val trakt = SgApp.getServicesComponent(context).trakt()
return runCatching {
trakt.search()
.idLookup(
IdType.TMDB,
showTmdbId.toString(),
Type.SHOW,
Extended.FULL,
1,
1
).execute()
}.mapError {
Errors.logAndReport(action, it)
if (it.isRetryError()) TraktRetry else TraktStop
}.andThen {
if (it.isSuccessful) {
val result = it.body()?.firstOrNull()
if (result != null) {
if (result.show != null) {
return@andThen Ok(result.show)
} else {
// If there is a result, it should contain a show.
Errors.logAndReport(action, it, "show of result is null")
}
}
return@andThen Ok(null) // Not found.
} else {
Errors.logAndReport(action, it)
}
return@andThen Err(TraktStop)
}
}
enum class ServiceResult {
SUCCESS,
AUTH_ERROR,
API_ERROR
}
@JvmStatic
fun getCollectedOrWatchedShows(
isCollectionNotWatched: Boolean,
context: Context
): Pair<Map<Int, BaseShow>?, ServiceResult> {
val traktSync = SgApp.getServicesComponent(context).traktSync()!!
val action = if (isCollectionNotWatched) "get collection" else "get watched"
try {
val response: Response<List<BaseShow>> = if (isCollectionNotWatched) {
traktSync.collectionShows(null).execute()
} else {
traktSync.watchedShows(null).execute()
}
if (response.isSuccessful) {
return Pair(mapByTmdbId(response.body()), ServiceResult.SUCCESS)
} else {
if (SgTrakt.isUnauthorized(context, response)) {
return Pair(null, ServiceResult.AUTH_ERROR)
}
Errors.logAndReport(action, response)
}
} catch (e: Exception) {
Errors.logAndReport(action, e)
}
return Pair(null, ServiceResult.API_ERROR)
}
@JvmStatic
fun mapByTmdbId(traktShows: List<BaseShow>?): Map<Int, BaseShow> {
if (traktShows == null) return emptyMap()
val traktShowsMap = HashMap<Int, BaseShow>(traktShows.size)
for (traktShow in traktShows) {
val tmdbId = traktShow.show?.ids?.tmdb
if (tmdbId == null || traktShow.seasons.isNullOrEmpty()) {
continue // trakt show misses required data, skip.
}
traktShowsMap[tmdbId] = traktShow
}
return traktShowsMap
}
fun getEpisodeRatings(
context: Context,
showTraktId: String,
seasonNumber: Int,
episodeNumber: Int
): Pair<Double, Int>? {
val ratings: Ratings =
SgTrakt.executeCall(
SgApp.getServicesComponent(context).trakt()
.episodes().ratings(showTraktId, seasonNumber, episodeNumber),
"get episode rating"
) ?: return null
val rating = ratings.rating
val votes = ratings.votes
return if (rating != null && votes != null) {
Pair(rating, votes)
} else {
null
}
}
data class LastActivities(
val episodes: LastActivityMore,
val shows: LastActivity,
val movies: LastActivityMore,
)
fun getLastActivity(context: Context): Result<LastActivities, TraktError> {
val action = "get last activity"
return runCatching {
SgApp.getServicesComponent(context).trakt().sync()
.lastActivities()
.execute()
}.mapError {
Errors.logAndReport(action, it)
if (it.isRetryError()) TraktRetry else TraktStop
}.andThen { response ->
if (response.isSuccessful) {
val lastActivities = response.body()
val episodes = lastActivities?.episodes
val shows = lastActivities?.shows
val movies = lastActivities?.movies
if (episodes != null && shows != null && movies != null) {
return@andThen Ok(
LastActivities(
episodes = episodes,
shows = shows,
movies = movies
)
)
} else {
Errors.logAndReport(action, response, "last activity is null")
}
} else {
if (!SgTrakt.isUnauthorized(context, response)) {
Errors.logAndReport(action, response)
}
}
return@andThen Err(TraktStop)
}
}
}
sealed class TraktError
/**
* The API request might succeed if tried again after a brief delay
* (e.g. time outs or other temporary network issues).
*/
object TraktRetry : TraktError()
/**
* The API request is unlikely to succeed if retried, at least right now
* (e.g. API bugs or changes).
*/
object TraktStop : TraktError()
| apache-2.0 | 0f80e7ed5f17c8b9639b78e18e270f92 | 34.172775 | 87 | 0.576809 | 4.854046 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/il/print.kt | 1 | 2586 | package edu.kit.iti.formal.automation.il
import edu.kit.iti.formal.automation.st.StructuredTextPrinter
import edu.kit.iti.formal.automation.st.ast.ANONYM
import edu.kit.iti.formal.util.CodeWriter
import edu.kit.iti.formal.util.joinInto
/**
*
* @author Alexander Weigl
* @version 1 (21.02.19)
*/
class IlPrinter(val writer: CodeWriter) : IlTraversalVisitor() {
val stPrinter = StructuredTextPrinter(writer)
override fun defaultVisit(top: IlAst) {
writer.write("// Could not print out: $top")
}
override fun visit(variable: IlOperand.Variable) {
variable.ref.accept(stPrinter)
}
override fun visit(constant: IlOperand.Constant) {
constant.literal.accept(stPrinter)
}
override fun visit(jump: JumpInstr) {
writer.write("${jump.type} ${jump.target}").nl()
}
override fun visit(simple: SimpleInstr) {
writer.write("${simple.type} ")
simple.operand?.accept(this)
writer.nl()
}
override fun visit(funCall: FunctionCallInstr) {
funCall.function.accept(stPrinter)
writer.write(" ")
funCall.operands.joinInto(writer, ", ") {
it.accept(this)
}
writer.nl()
}
override fun visit(expr: ExprInstr) {
writer.write("${expr.operand} ")
if (expr.operandi != null && expr.instr == null) {
expr.operandi?.also {
it.accept(this@IlPrinter)
}
} else if (expr.operandi != null || expr.instr != null) {
writer.cblock("(", ")") {
expr.operandi?.also {
it.accept(this@IlPrinter)
}
expr.instr?.let {
writer.nl()
it.accept(this@IlPrinter)
}
}
}
writer.nl()
}
override fun visit(call: CallInstr) {
if (call.type != CallOperand.IMPLICIT_CALLED) {
writer.write("${call.type} ")
}
call.ref.accept(stPrinter)
writer.cblock("(", ")") {
call.parameters.joinInto(writer, "") {
it.accept(this@IlPrinter)
writer.nl()
}
}
writer.nl()
}
override fun visit(param: IlParameter) {
if (param.left == ANONYM) {
param.right.accept(this)
} else {
if (param.negated)
writer.write("NOT ")
writer.write(param.left)
writer.write(if (param.input) " := " else " => ")
param.right.accept(this)
}
}
} | gpl-3.0 | 2cdb0f933c478c9839668b699671402f | 27.119565 | 65 | 0.540603 | 3.882883 | false | false | false | false |
Takhion/android-extras-delegates | library/src/main/java/me/eugeniomarletti/extras/PropertyDelegate.kt | 1 | 2569 | package me.eugeniomarletti.extras
import kotlin.reflect.KProperty
typealias TypeReader<T, R> = (R) -> T
typealias TypeWriter<T, R> = (T) -> R
typealias ExtraReader<This, R> = This.(name: String) -> R
typealias ExtraWriter<This, R> = This.(name: String, value: R) -> Any?
interface DelegateProvider<out T> {
operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): T
}
/**
* A property delegate that can read and write from a receiver of type [This].
*/
interface PropertyDelegate<in This, T> : DelegateProvider<PropertyDelegate<This, T>> {
operator fun getValue(thisRef: This, property: KProperty<*>): T
operator fun setValue(thisRef: This, property: KProperty<*>, value: T)
}
/**
* Helper to create a [PropertyDelegate].
*
* @param R The raw type that will be read/written directly to the receiver of type [This].
* @param T The transformed type (from [R]) that will be read/written from the property.
* @param typeReader Transforms the raw type [R] in the property type [T] when reading from the receiver of type [This].
* @param typeWriter Transforms the property type [T] in the raw type [R] when writing to the receiver of type [This].
* @param extraReader Reads the value from the receiver of type [This].
* @param extraWriter Writes the value to the receiver of type [This].
* @param name An optional name for the property. If missing, a compile-time constant will be used equal to the qualified name of the class
* in which the property is declared plus the real name of the property itself.
* @param customPrefix An optional prefix for the property name, to be used before the real name of the property.
* Note that this is ignored if [name] is present.
*/
@PublishedApi internal inline fun <This, T, R> PropertyDelegate(
crossinline extraReader: ExtraReader<This, R>,
crossinline extraWriter: ExtraWriter<This, R>,
crossinline typeReader: TypeReader<T, R>,
crossinline typeWriter: TypeWriter<T, R>,
name: String? = null,
customPrefix: String? = null
) = object : PropertyDelegate<This, T> {
private lateinit var name: String private set
override operator fun provideDelegate(thisRef: Any?, property: KProperty<*>) = apply {
this.name = name ?: property.defaultDelegateName(customPrefix)
}
override fun getValue(thisRef: This, property: KProperty<*>): T =
typeReader(extraReader(thisRef, this.name))
override fun setValue(thisRef: This, property: KProperty<*>, value: T) {
value?.let { extraWriter(thisRef, this.name, typeWriter(it)) }
}
} | mit | b4d6ec56114746942e9a12a37d9f0519 | 43.310345 | 139 | 0.7174 | 4.058452 | false | false | false | false |
arcao/Geocaching4Locus | app/src/main/java/com/arcao/geocaching4locus/import_bookmarks/fragment/BookmarkViewModel.kt | 1 | 6210 | package com.arcao.geocaching4locus.import_bookmarks.fragment
import android.annotation.SuppressLint
import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.arcao.geocaching4locus.R
import com.arcao.geocaching4locus.base.BaseViewModel
import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider
import com.arcao.geocaching4locus.base.usecase.GetListGeocachesUseCase
import com.arcao.geocaching4locus.base.usecase.GetPointsFromGeocacheCodesUseCase
import com.arcao.geocaching4locus.base.usecase.WritePointToPackPointsFileUseCase
import com.arcao.geocaching4locus.base.usecase.entity.GeocacheListEntity
import com.arcao.geocaching4locus.base.usecase.entity.ListGeocacheEntity
import com.arcao.geocaching4locus.base.util.AnalyticsManager
import com.arcao.geocaching4locus.base.util.Command
import com.arcao.geocaching4locus.base.util.invoke
import com.arcao.geocaching4locus.error.exception.IntendedException
import com.arcao.geocaching4locus.error.handler.ExceptionHandler
import com.arcao.geocaching4locus.import_bookmarks.paging.ListGeocachesDataSource
import com.arcao.geocaching4locus.settings.manager.FilterPreferenceManager
import com.arcao.geocaching4locus.update.UpdateActivity
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import locus.api.manager.LocusMapManager
import timber.log.Timber
@SuppressLint("StaticFieldLeak")
class BookmarkViewModel(
geocacheList: GeocacheListEntity,
private val getListGeocaches: GetListGeocachesUseCase,
private val context: Context,
private val exceptionHandler: ExceptionHandler,
private val getPointsFromGeocacheCodes: GetPointsFromGeocacheCodesUseCase,
private val writePointToPackPointsFile: WritePointToPackPointsFileUseCase,
private val filterPreferenceManager: FilterPreferenceManager,
private val locusMapManager: LocusMapManager,
private val analyticsManager: AnalyticsManager,
dispatcherProvider: CoroutinesDispatcherProvider
) : BaseViewModel(dispatcherProvider) {
val pagerFlow: Flow<PagingData<ListGeocacheEntity>>
val selection = MutableLiveData<List<ListGeocacheEntity>>().apply {
value = emptyList()
}
val action = Command<BookmarkAction>()
private var job: Job? = null
init {
val pageSize = 25
val config = PagingConfig(
pageSize = pageSize,
enablePlaceholders = false,
initialLoadSize = 2 * pageSize
)
pagerFlow = Pager(
config,
pagingSourceFactory = {
ListGeocachesDataSource(
geocacheList.guid,
getListGeocaches,
config
)
}
).flow.cachedIn(viewModelScope)
}
fun download() {
if (job?.isActive == true) {
job?.cancel()
}
job = mainLaunch {
val selection = selection.value ?: return@mainLaunch
analyticsManager.actionImportBookmarks(selection.size, false)
computationLaunch {
val geocacheCodes = selection.map { it.referenceCode }.toTypedArray()
Timber.d("source: import_from_bookmark;gccodes=%s", geocacheCodes)
val importIntent = locusMapManager.createSendPointsIntent(
callImport = true,
center = true
)
var receivedGeocaches = 0
try {
showProgress(
R.string.progress_download_geocaches,
maxProgress = geocacheCodes.size
) {
val channel = getPointsFromGeocacheCodes(
geocacheCodes,
filterPreferenceManager.simpleCacheData,
filterPreferenceManager.geocacheLogsCount
).map { list ->
receivedGeocaches += list.size
updateProgress(
progress = receivedGeocaches,
maxProgress = geocacheCodes.size
)
// apply additional downloading full geocache if required
if (filterPreferenceManager.simpleCacheData) {
list.forEach { point ->
point.gcData?.cacheID?.let { cacheId ->
point.setExtraOnDisplay(
context.packageName,
UpdateActivity::class.java.name,
UpdateActivity.PARAM_SIMPLE_CACHE_ID,
cacheId
)
}
}
}
list
}
writePointToPackPointsFile(channel)
}
} catch (e: Exception) {
mainContext {
action(
BookmarkAction.Error(
if (receivedGeocaches > 0) {
exceptionHandler(IntendedException(e, importIntent))
} else {
exceptionHandler(e)
}
)
)
}
return@computationLaunch
}
mainContext {
action(BookmarkAction.Finish(importIntent))
}
}
}
}
fun cancelProgress() {
job?.cancel()
}
fun handleLoadError(e: Throwable) {
action(BookmarkAction.LoadingError(exceptionHandler(e)))
}
}
| gpl-3.0 | 9a63d7e72540635b5a4dfb042ef3f34a | 38.55414 | 88 | 0.577778 | 5.68161 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/connectivityQuietHours/receivers/NotificationHelper.kt | 1 | 4751 | package com.itachi1706.cheesecakeutilities.modules.connectivityQuietHours.receivers
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.annotation.Nullable
import androidx.core.app.NotificationCompat
import com.itachi1706.cheesecakeutilities.modules.connectivityQuietHours.ConnectivityQuietHoursActivity
import com.itachi1706.cheesecakeutilities.modules.connectivityQuietHours.QHConstants
import com.itachi1706.cheesecakeutilities.R
import java.text.DateFormat
import java.util.*
import kotlin.collections.ArrayList
/**
* Created by Kenneth on 1/1/2019.
* for com.itachi1706.cheesecakeutilities.modules.ConnectivityQuietHours in CheesecakeUtilities
*/
internal class NotificationHelper private constructor() {
init {
throw java.lang.IllegalStateException("Utility class. Do not instantiate like this")
}
companion object {
var lines: ArrayList<String>? = null
var summaryId = -9999
const val NOTIFICATION_SUM_CANCEL = "summary_cancelled"
const val NOTIFICATION_CANCEL = "subitem_cancelled"
const val NOTIFICATION_GROUP = "connectivityqh"
fun sendNotification(context: Context, notificationLevel: Int, workDone: Boolean, state: Boolean, connection: String) {
val time = DateFormat.getTimeInstance().format(Date(System.currentTimeMillis()))
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
QHConstants.createNotificationChannel(notificationManager) // Create the Notification Channel
val contentTitle = connection + " Quiet Hour " + if (state) "Enabled" else "Disabled"
val mBuilder = NotificationCompat.Builder(context, QHConstants.QH_NOTIFICATION_CHANNEL)
mBuilder.setSmallIcon(R.drawable.notification_icon).setContentTitle(contentTitle)
.setContentText("$connection state toggled on $time")
.setAutoCancel(true)
.setGroup(NOTIFICATION_GROUP)
.setDeleteIntent(createDeleteIntent(context, NOTIFICATION_CANCEL, contentTitle))
.setContentIntent(PendingIntent.getActivity(context, 0, Intent(context, ConnectivityQuietHoursActivity::class.java), 0))
val random = Random()
if (lines == null) lines = ArrayList()
if (summaryId == -9999) summaryId = random.nextInt()
when (notificationLevel) {
QHConstants.QH_NOTIFY_ALWAYS, QHConstants.QH_NOTIFY_DEBUG -> {
lines!!.add(contentTitle)
createSummaryNotification(context, notificationManager)
notificationManager.notify(random.nextInt(), mBuilder.build())
}
QHConstants.QH_NOTIFY_WHEN_TRIGGERED -> if (workDone) {
lines!!.add(contentTitle)
createSummaryNotification(context, notificationManager)
notificationManager.notify(random.nextInt(), mBuilder.build())
}
}
}
fun createSummaryNotification(context: Context, manager: NotificationManager) {
if (lines == null || lines!!.size <= 0) return // Don't do anything if there is no intent
val summaryNotification = NotificationCompat.Builder(context, QHConstants.QH_NOTIFICATION_CHANNEL)
val summaryBuilder = NotificationCompat.InboxStyle().setSummaryText(lines!!.size.toString() + " changes toggled").setBigContentTitle(lines!!.size.toString() + " changes")
for (s in lines!!) {
summaryBuilder.addLine(s)
}
summaryNotification.setDeleteIntent(createDeleteIntent(context, NOTIFICATION_SUM_CANCEL, null)).setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Quiet Hour Updates").setContentText(lines!!.size.toString() + " changes").setGroupSummary(true).setGroup(NOTIFICATION_GROUP)
.setStyle(summaryBuilder)
manager.notify(summaryId, summaryNotification.build())
}
fun addToLines(text: String) {
if (lines == null) lines = ArrayList()
lines!!.add(text)
}
fun createDeleteIntent(context: Context, action: String, @Nullable content: String?): PendingIntent {
val del = Intent(context, DeleteNotificationIntent::class.java)
del.action = action
if (content != null) del.putExtra("data", content)
val random = Random()
return PendingIntent.getBroadcast(context, random.nextInt(5000), del, PendingIntent.FLAG_CANCEL_CURRENT)
}
}
}
| mit | 8e7c018d86b0fa604350a7008ba54e91 | 51.788889 | 182 | 0.677963 | 5.152928 | false | false | false | false |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/gpaCalculator/fragment/BaseGpaFragment.kt | 1 | 3907 | package com.itachi1706.cheesecakeutilities.modules.gpaCalculator.fragment
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.ValueEventListener
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.GpaCalcFirebaseUtils
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.GpaRecyclerAdapter
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.MainViewActivity
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.interfaces.StateSwitchListener
import com.itachi1706.cheesecakeutilities.R
import com.itachi1706.cheesecakeutilities.recyclerAdapters.SwipeEditDeleteCallback
import com.itachi1706.cheesecakeutilities.util.FirebaseUtils
import com.itachi1706.helperlib.helpers.LogHelper
import java.util.*
/**
* Created by Kenneth on 16/7/2019.
* for com.itachi1706.cheesecakeutilities.modules.gpaCalculator.fragment in CheesecakeUtilities
*/
abstract class BaseGpaFragment : Fragment(), SwipeEditDeleteCallback.ISwipeCallback {
var callback: StateSwitchListener? = null
lateinit var adapter: GpaRecyclerAdapter
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is MainViewActivity) {
callback = context
}
}
var listener: ValueEventListener? = null
override fun onStart() {
super.onStart()
if (listener != null) {
FirebaseUtils.removeListener(listener!!)
listener = null
LogHelper.e(getLogTag(), "Firebase DB Listeners exists when it should not have, terminating it forcibly")
}
}
override fun onStop() {
super.onStop()
if (listener != null) {
FirebaseUtils.removeListener(listener!!)
LogHelper.i(getLogTag(), "Firebase Listener Unregisted")
listener = null
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_recycler_view, container, false)
val recyclerView = v.findViewById<RecyclerView>(R.id.main_menu_recycler_view)
if (!evaluateToCont(v)) return v
recyclerView.setHasFixedSize(true)
val linearLayoutManager = LinearLayoutManager(context)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
recyclerView.layoutManager = linearLayoutManager
recyclerView.itemAnimator = DefaultItemAnimator()
val itemTouchHelper = ItemTouchHelper(SwipeEditDeleteCallback(this, v.context))
itemTouchHelper.attachToRecyclerView(recyclerView)
// Update layout
adapter = GpaRecyclerAdapter(arrayListOf(), false)
recyclerView.adapter = adapter
callback?.onStateSwitch(getState())
return v
}
abstract fun getState(): Int
abstract fun evaluateToCont(v: View): Boolean
abstract fun getLogTag(): String
abstract fun initContextSelectMode(position: Int): Boolean
fun getTimestampString(startTimestamp: Long, endTimestamp: Long): String {
val calendar = Calendar.getInstance()
val dateFormat = GpaCalcFirebaseUtils.DATE_FORMAT
calendar.timeInMillis = startTimestamp
var timestamp = "${dateFormat.format(calendar.time)} - "
if (endTimestamp == (-1).toLong()) timestamp += "Present"
else {
calendar.timeInMillis = endTimestamp
timestamp += dateFormat.format(calendar.time)
}
return timestamp
}
} | mit | dafcb68e6ab21ac42b56fd8e69d3985e | 38.877551 | 117 | 0.737138 | 5.002561 | false | false | false | false |
dnowak/webflux-twits | src/main/kotlin/twits/events.kt | 1 | 2760 | package twits
import org.apache.commons.lang3.builder.ToStringBuilder
import org.funktionale.tries.Try
import org.slf4j.LoggerFactory
import reactor.core.publisher.Flux
import reactor.core.publisher.toFlux
import java.time.LocalDateTime
import java.util.concurrent.CopyOnWriteArrayList
interface EventRepository {
fun add(event: Event)
fun findByAggregateId(aggregateId: AggregateId): Flux<Event>
fun findByAggregateType(type: AggregateType): Flux<Event>
}
class MemoryEventRepository : EventRepository {
companion object {
private val log = LoggerFactory.getLogger(MemoryEventRepository::class.java)
}
private val events = CopyOnWriteArrayList<Event>()
override fun add(event: Event) {
log.debug("add: {}", event)
events.add(event)
}
override fun findByAggregateId(aggregateId: AggregateId): Flux<Event> = events.toFlux()
.filter { event -> event.aggregateId == aggregateId }
override fun findByAggregateType(type: AggregateType): Flux<Event> = events.toFlux().filter { it.aggregateId.type == type }
fun clear() {
events.clear()
}
}
interface EventListener {
fun onEvent(event: Event)
}
class EventBus(val listeners: Collection<EventListener>) {
fun publish(event: Event) {
listeners.forEach { it.onEvent(event) }
}
}
enum class AggregateType { USER, POST }
data class AggregateId(val type: AggregateType, val id: Any)
interface Event {
val aggregateId: AggregateId
val timestamp: LocalDateTime
}
abstract class UserEvent(val id: UserId) : Event {
override val aggregateId = AggregateId(AggregateType.USER, id)
override val timestamp = LocalDateTime.now()!!
override fun toString(): String {
return ToStringBuilder.reflectionToString(this)
}
}
class UserCreatedEvent(id: UserId) : UserEvent(id)
class FollowerAddedEvent(id: UserId, val followerId: UserId) : UserEvent(id)
class FollowerRemovedEvent(id: UserId, val followerId: UserId) : UserEvent(id)
class FollowingStartedEvent(id: UserId, val followedId: UserId) : UserEvent(id)
class FollowingEndedEvent(id: UserId, val followedId: UserId) : UserEvent(id)
class PostSentEvent(id: UserId, val message: String): UserEvent(id)
class PostReceivedEvent(id: UserId, val author: UserId, val message: String): UserEvent(id)
open class PostEvent(val id: PostId) : Event {
override val aggregateId = AggregateId(AggregateType.POST, id)
override val timestamp = LocalDateTime.now()!!
}
class PostCreatedEvent(id: PostId, val author: UserId, val text: String): PostEvent(id)
fun <E : Any, T : Any> on(target: T, event: E): T {
Try({ target.javaClass.getMethod("on", event.javaClass) }).map { m -> m.invoke(target, event) }
return target
}
| apache-2.0 | af6df3355eed6687a246f65c2b14186b | 31.470588 | 127 | 0.728986 | 4.023324 | false | false | false | false |
serebit/autotitan | src/main/kotlin/api/Templates.kt | 1 | 3486 | package com.serebit.autotitan.api
import com.serebit.autotitan.BotConfig
import com.serebit.autotitan.internal.*
import net.dv8tion.jda.api.events.GenericEvent
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import kotlin.reflect.KType
sealed class InvokeableContainerTemplate {
protected abstract val commands: MutableList<CommandTemplate>
abstract val defaultAccess: Access
fun addCommand(
name: String, description: String, access: Access, parameterTypes: List<KType>,
function: (MessageReceivedEvent, List<Any>) -> Unit
) {
commands += CommandTemplate.Normal(name, description, access, parameterTypes, function)
}
fun addSuspendCommand(
name: String, description: String, access: Access, parameterTypes: List<KType>,
function: suspend (MessageReceivedEvent, List<Any>) -> Unit
) {
commands += CommandTemplate.Suspending(name, description, access, parameterTypes, function)
}
}
class ModuleTemplate(
val name: String,
val isOptional: Boolean = false,
override inline val defaultAccess: Access
) : InvokeableContainerTemplate() {
lateinit var config: BotConfig
private set
val dataManager = DataManager(name)
private val groups = mutableListOf<GroupTemplate>()
private val listeners = mutableListOf<Listener>()
override val commands = mutableListOf<CommandTemplate>()
fun addGroup(template: GroupTemplate) {
require(template.name.isNotBlank())
groups += template
}
fun addListener(function: (GenericEvent) -> Unit) {
listeners += Listener.Normal(function)
}
fun addSuspendListener(function: suspend (GenericEvent) -> Unit) {
listeners += Listener.Suspending(function)
}
internal fun build(config: BotConfig): Module {
this.config = config
return Module(name, isOptional, groups, commands, listeners, config)
}
}
data class GroupTemplate(
val name: String,
val description: String = "",
override inline val defaultAccess: Access
) : InvokeableContainerTemplate() {
override val commands = mutableListOf<CommandTemplate>()
internal fun build() = Group(name.toLowerCase(), description, commands)
}
sealed class CommandTemplate(
val name: String, val description: String,
val access: Access,
val parameterTypes: List<KType>
) {
internal abstract fun build(parent: Group?): Command
class Normal(
name: String, description: String,
access: Access,
parameterTypes: List<KType>,
private inline val function: (MessageReceivedEvent, List<Any>) -> Unit
) : CommandTemplate(name, description, access, parameterTypes) {
private val tokenTypes = parameterTypes.map { TokenType.from(it) }.requireNoNulls()
override fun build(parent: Group?) =
Command.Normal(name.toLowerCase(), description, access, parent, tokenTypes, function)
}
class Suspending(
name: String, description: String,
access: Access,
parameterTypes: List<KType>,
private inline val function: suspend (MessageReceivedEvent, List<Any>) -> Unit
) : CommandTemplate(name, description, access, parameterTypes) {
private val tokenTypes = parameterTypes.map { TokenType.from(it) }.requireNoNulls()
override fun build(parent: Group?) =
Command.Suspending(name.toLowerCase(), description, access, parent, tokenTypes, function)
}
}
| apache-2.0 | 2c5d9ab22e26938bfc5f68a2f94ea862 | 34.212121 | 101 | 0.699082 | 4.629482 | false | true | false | false |
Cardstock/Cardstock | src/main/kotlin/xyz/cardstock/cardstock/commands/BaseCommand.kt | 1 | 3032 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package xyz.cardstock.cardstock.commands
import org.kitteh.irc.client.library.element.User
import org.kitteh.irc.client.library.event.helper.ActorEvent
import java.util.Objects
/**
* The base for all commands. All commands must be annotated on the class level with [Command] to provide metadata about
* that command. If this is not the case, the command will never work and will throw [NullPointerException]s often.
*/
abstract class BaseCommand {
/**
* Performs the action that this command is supposed to perform. Called every time that this command is used.
*/
abstract fun run(event: ActorEvent<User>, callInfo: CallInfo, arguments: List<String>)
/**
* Gets the Command annotation on this command.
* @return The annotation for this command, or null if none was specified.
* @see Command
*/
private fun getCommandAnnotation(): Command? = this.javaClass.getDeclaredAnnotation(Command::class.java)
/**
* The name of this command. Defined by annotation.
* @see Command
*/
open val name: String
get() = this.getCommandAnnotation()!!.name
/**
* The aliases for this command. Defined by annotation.
* @see Command
*/
open val aliases: Array<String>
get() = this.getCommandAnnotation()!!.aliases
/**
* The description of this command. Defined by annotation.
*/
open val description: String
get() = this.getCommandAnnotation()!!.description
/**
* The usage of this command. Defined by annotation.
*
* Usage should resemble something like `"<command> [requiredParameter] (optionalParameter)"`
*/
open val usage: String
get() = this.getCommandAnnotation()!!.usage
/**
* The command type of this command. Defined by annotation.
*/
open val commandType: CommandType
get() = this.getCommandAnnotation()!!.commandType
override fun equals(other: Any?): Boolean {
if (other == null || other !is BaseCommand) return false
return this.name == other.name && this.aliases.toList() == other.aliases.toList() && this.description == other.description && this.usage == other.usage && this.commandType == other.commandType
}
override fun hashCode() = Objects.hash(this.name, this.aliases, this.description, this.usage)
/**
* An enum defining where commands may be used.
*/
enum class CommandType {
/**
* A command with this type may be used only in channels.
*/
CHANNEL,
/**
* A command with this type may be used only in private messages between the bot and a [User].
*/
PRIVATE,
/**
* A command with this type may be used in both channels and private messages.
*/
BOTH
}
}
| mpl-2.0 | 064c61d074c48e6f7afd07f52cf28836 | 33.067416 | 200 | 0.653364 | 4.419825 | false | false | false | false |
christophpickl/kpotpourri | common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/io/keyboard.kt | 1 | 5704 | package com.github.christophpickl.kpotpourri.common.io
import com.github.christophpickl.kpotpourri.common.KPotpourriException
/**
* Provide user interaction via keyboard for different ways of prompting for input.
*/
object Keyboard {
private val INPUT_SIGN = ">>"
/**
* Read user input line in a null safe way.
*/
fun readLine() = kotlin.io.readLine() ?: throw KPotpourriException("readLine() returned null (must likely you've redirected System.in)")
/**
* Reads a confirmation boolean from stdin by y/n input, and an optional default value if hit enter immediately.
*/
fun readConfirmation(prompt: String, defaultConfirm: Boolean? = null): Boolean {
println(prompt)
val preprompt = when (defaultConfirm) {
true -> "Y/n"
false -> "y/N"
else -> "y/n"
}
do {
print("[$preprompt] $INPUT_SIGN ")
val input = readLine().trim()
if (input.toLowerCase() == "y") {
return true
}
if (input.toLowerCase() == "n") {
return false
}
if (defaultConfirm != null && input == "") {
return defaultConfirm
}
if (input != "") {
val defaultExplanation = when (defaultConfirm) {
true -> " (or hit Enter for 'y')"
false -> " (or hit Enter for 'n')"
else -> ""
}
println("Invalid input '$input'. Please enter either 'y' or 'n'$defaultExplanation.")
}
} while (true)
}
fun readWithDefault(prompt: String, default: String): String {
println(prompt)
print("[$default] $INPUT_SIGN ")
val read = readLine()
if (read.isEmpty()) {
return default
}
return read
}
/**
* Read input based on a predefined set of answers indexed by 1-based numbers.
*/
fun readOptions(prompt: String, options: List<String>, defaultBehaviour: ReadOptionsDefaultBehaviour<String> = ReadOptionsDefaultBehaviour.Disabled()): String {
if (options.isEmpty()) {
throw KPotpourriException("Must provide at least one option!")
}
if (defaultBehaviour is ReadOptionsDefaultBehaviour.DefaultValue<String> && !options.contains(defaultBehaviour.value)) {
throw KPotpourriException("Default option '$defaultBehaviour' must be within: $options")
}
println(prompt)
options.forEachIndexed { i, opt ->
val defaultSuffix = when (defaultBehaviour) {
is ReadOptionsDefaultBehaviour.Disabled<*> -> ""
is ReadOptionsDefaultBehaviour.SelectFirst<*> -> if (i == 0) " (default)" else ""
is ReadOptionsDefaultBehaviour.DefaultValue<String> -> if (defaultBehaviour.value == opt) " (default)" else ""
}
println("[${i + 1}] $opt$defaultSuffix")
}
do {
print("$INPUT_SIGN ")
val rawInput = readLine().trim()
if (rawInput == "") {
if (defaultBehaviour is ReadOptionsDefaultBehaviour.DefaultValue<String>) {
return defaultBehaviour.value
} else if (defaultBehaviour is ReadOptionsDefaultBehaviour.SelectFirst<String>) {
return options[0]
} else { // Disabled
continue
}
}
val intInput = rawInput.toIntOrNull()
if (intInput == null) {
println("Invalid input: '$rawInput'")
continue
}
if (intInput < 1 || intInput > options.size) {
println("Invalid index: $intInput (must be between 1-${options.size})")
continue
}
return options[intInput - 1]
} while (true)
}
/**
* Read input based on a predefined set of typed answers indexed by 1-based numbers.
*/
fun <T : ToPrintStringable> readTypedOptions(prompt: String, options: List<T>, defaultBehaviour: ReadOptionsDefaultBehaviour<T> = ReadOptionsDefaultBehaviour.Disabled()): T {
if (options.map { it.toPrintString() }.distinct().size != options.size) throw KPotpourriException("Options contain duplicate entries!")
val optionsByPrintString = options.associateBy { it.toPrintString() }
val stringDefaultOption = when (defaultBehaviour) {
is ReadOptionsDefaultBehaviour.SelectFirst<T> -> ReadOptionsDefaultBehaviour.SelectFirst<String>()
is ReadOptionsDefaultBehaviour.Disabled<T> -> ReadOptionsDefaultBehaviour.Disabled<String>()
is ReadOptionsDefaultBehaviour.DefaultValue<T> -> ReadOptionsDefaultBehaviour.DefaultValue(defaultBehaviour.value.toPrintString())
}
val input = readOptions(prompt, optionsByPrintString.keys.toList(), stringDefaultOption)
return optionsByPrintString[input]!!
}
}
/**
* Predefined typed options need to be stringifyable.
*/
interface ToPrintStringable {
/**
* Representation to the user of an option.
*/
fun toPrintString(): String
}
/**
* Default behavioiur when reading predefined typed options.
*/
sealed class ReadOptionsDefaultBehaviour<T> {
/** No default option available. */
class Disabled<T> : ReadOptionsDefaultBehaviour<T>()
/** Select the very first option if hit enter. */
class SelectFirst<T> : ReadOptionsDefaultBehaviour<T>()
/** Select a predefined option if hit enter. */
data class DefaultValue<T>(val value: T) : ReadOptionsDefaultBehaviour<T>()
}
| apache-2.0 | 9a461fc9da330588b079aeb0b9fd82f4 | 37.540541 | 178 | 0.595898 | 4.71405 | false | false | false | false |
RogaLabs/social-login | lib/src/main/java/com/rogalabs/lib/common/CommonLoginPresenter.kt | 1 | 1322 | package com.rogalabs.lib.common
import android.content.Intent
import android.support.v4.app.FragmentActivity
import com.rogalabs.lib.CommonCallback
import com.rogalabs.lib.LoginContract
import com.rogalabs.lib.server.ResponseHandler
import com.rogalabs.lib.server.restclient.CommonLoginClient
import org.json.JSONObject
/**
* Created by cleylsonsouza on 20/09/16.
* On MacBook Pro, Roga Labs.
*/
class CommonLoginPresenter(val view: LoginContract.View?) : LoginContract.CommonLoginPresenter {
private var callback: CommonCallback? = null
private var activity: FragmentActivity? = null
override fun create(activity: FragmentActivity?) {
this.activity = activity
}
override fun pause() {
}
override fun destroy() {
}
override fun activityResult(requestCode: Int, resultCode: Int, data: Intent) {
}
override fun signIn(url: String, params: JSONObject, callback: CommonCallback) {
this.callback = callback
CommonLoginClient.getInstance(activity).createPOST(url, params,
{ result ->
callback.onSuccess(result)
},
{ volleyError ->
val handler = ResponseHandler()
callback.onError(handler.errorHandler(volleyError))
})
}
} | mit | 6d7f2d7007678bb989408b60845dbeab | 29.068182 | 96 | 0.673222 | 4.542955 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/KotlinScriptType.kt | 1 | 2054 | /*
* Copyright 2018 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
*
* 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.gradle.kotlin.dsl.support
import java.io.File
fun kotlinScriptTypeFor(candidate: File): KotlinScriptType? =
KotlinScriptTypeMatch.forFile(candidate)?.scriptType
enum class KotlinScriptType {
INIT, SETTINGS, PROJECT
}
data class KotlinScriptTypeMatch(
val scriptType: KotlinScriptType,
val match: Match
) {
companion object {
fun forFile(file: File): KotlinScriptTypeMatch? =
forName(file.name)
fun forName(name: String): KotlinScriptTypeMatch? =
candidates.firstOrNull { it.match.matches(name) }
private
val candidates =
listOf(
KotlinScriptTypeMatch(KotlinScriptType.SETTINGS, Match.Whole("settings.gradle.kts")),
KotlinScriptTypeMatch(KotlinScriptType.SETTINGS, Match.Suffix(".settings.gradle.kts")),
KotlinScriptTypeMatch(KotlinScriptType.INIT, Match.Suffix(".init.gradle.kts")),
KotlinScriptTypeMatch(KotlinScriptType.PROJECT, Match.Suffix(".gradle.kts")))
}
}
sealed class Match {
abstract val value: String
abstract fun matches(candidate: String): Boolean
data class Whole(override val value: String) : Match() {
override fun matches(candidate: String) = candidate == value
}
data class Suffix(override val value: String) : Match() {
override fun matches(candidate: String) = candidate.endsWith(value)
}
}
| apache-2.0 | b23040fae069e042ec355e84efc0e11e | 29.205882 | 103 | 0.695716 | 4.436285 | false | false | false | false |
owncloud/android | owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt | 1 | 28806 | /*
* ownCloud Android client application
*
* @author Andy Scherzinger
* @author Christian Schabesberger
* @author David González Verdugo
* @author Shashvat Kedia
* @author Abel García de Prada
* @author Juan Carlos Garrote Gascón
* Copyright (C) 2021 ownCloud GmbH.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity
import android.accounts.Account
import android.accounts.AccountManager
import android.accounts.AccountManagerFuture
import android.accounts.OnAccountsUpdateListener
import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.AppCompatImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.GravityCompat
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import androidx.drawerlayout.widget.DrawerLayout.DrawerListener
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.navigation.NavigationView
import com.owncloud.android.BuildConfig
import com.owncloud.android.MainApp.Companion.initDependencyInjection
import com.owncloud.android.R
import com.owncloud.android.authentication.AccountUtils
import com.owncloud.android.extensions.goToUrl
import com.owncloud.android.extensions.openPrivacyPolicy
import com.owncloud.android.extensions.sendEmail
import com.owncloud.android.lib.common.OwnCloudAccount
import com.owncloud.android.presentation.UIResult
import com.owncloud.android.presentation.ui.settings.SettingsActivity
import com.owncloud.android.presentation.viewmodels.drawer.DrawerViewModel
import com.owncloud.android.utils.AvatarUtils
import com.owncloud.android.utils.DisplayUtils
import com.owncloud.android.utils.PreferenceUtils
import org.koin.androidx.viewmodel.ext.android.viewModel
import timber.log.Timber
import kotlin.math.ceil
/**
* Base class to handle setup of the drawer implementation including user switching and avatar fetching and fallback
* generation.
*/
abstract class DrawerActivity : ToolbarActivity() {
private val drawerViewModel by viewModel<DrawerViewModel>()
private var menuAccountAvatarRadiusDimension = 0f
private var currentAccountAvatarRadiusDimension = 0f
private var otherAccountAvatarRadiusDimension = 0f
private var drawerToggle: ActionBarDrawerToggle? = null
private var isAccountChooserActive = false
private var checkedMenuItem = Menu.NONE
/**
* accounts for the (max) three displayed accounts in the drawer header.
*/
private var accountsWithAvatars = arrayOfNulls<Account>(3)
/**
* Initializes the drawer and its content.
* This method needs to be called after the content view has been set.
*/
protected open fun setupDrawer() {
// Allow or disallow touches with other visible windows
getDrawerLayout()?.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(this)
getNavView()?.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(this)
// Set background header image and logo, if any
if (resources.getBoolean(R.bool.use_drawer_background_header)) {
getDrawerHeaderBackground()?.setImageResource(R.drawable.drawer_header_background)
}
if (resources.getBoolean(R.bool.use_drawer_logo)) {
getDrawerLogo()?.setImageResource(R.drawable.drawer_logo)
}
getDrawerAccountChooserToggle()?.setImageResource(R.drawable.ic_down)
isAccountChooserActive = false
//Notch support
getNavView()?.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
v.rootWindowInsets.displayCutout?.let {
getDrawerActiveUser()?.layoutParams?.height =
DisplayUtils.getDrawerHeaderHeight(it.safeInsetTop, resources)
}
}
}
override fun onViewDetachedFromWindow(v: View) {}
})
setupDrawerContent()
getDrawerActiveUser()?.setOnClickListener { toggleAccountList() }
drawerToggle =
object : ActionBarDrawerToggle(this, getDrawerLayout(), R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
override fun onDrawerClosed(view: View) {
super.onDrawerClosed(view)
// standard behavior of drawer is to switch to the standard menu on closing
if (isAccountChooserActive) {
toggleAccountList()
}
drawerToggle?.isDrawerIndicatorEnabled = false
invalidateOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
drawerToggle?.isDrawerIndicatorEnabled = true
invalidateOptionsMenu()
}
}
// Set the drawer toggle as the DrawerListener
getDrawerLayout()?.addDrawerListener(drawerToggle as ActionBarDrawerToggle)
drawerToggle?.isDrawerIndicatorEnabled = false
}
/**
* setup drawer content, basically setting the item selected listener.
*
*/
protected open fun setupDrawerContent() {
val navigationView: NavigationView = getNavView() ?: return
// Disable help or feedback on customization
if (!resources.getBoolean(R.bool.help_enabled)) {
navigationView.menu.removeItem(R.id.drawer_menu_help)
}
if (!resources.getBoolean(R.bool.feedback_enabled)) {
navigationView.menu.removeItem(R.id.drawer_menu_feedback)
}
if (!resources.getBoolean(R.bool.multiaccount_support)) {
navigationView.menu.removeItem(R.id.drawer_menu_accounts)
}
if (!resources.getBoolean(R.bool.privacy_policy_enabled)) {
navigationView.menu.removeItem(R.id.drawer_menu_privacy_policy)
}
navigationView.setNavigationItemSelectedListener { menuItem: MenuItem ->
getDrawerLayout()?.closeDrawers()
when (menuItem.itemId) {
R.id.nav_settings -> {
val settingsIntent = Intent(applicationContext, SettingsActivity::class.java)
startActivity(settingsIntent)
}
R.id.drawer_menu_account_add -> createAccount(false)
R.id.drawer_menu_account_manage -> {
val manageAccountsIntent = Intent(applicationContext, ManageAccountsActivity::class.java)
startActivityForResult(manageAccountsIntent, ACTION_MANAGE_ACCOUNTS)
}
R.id.drawer_menu_feedback -> openFeedback()
R.id.drawer_menu_help -> openHelp()
R.id.drawer_menu_privacy_policy -> openPrivacyPolicy()
Menu.NONE -> {
accountClicked(menuItem.title.toString())
}
else -> Timber.i("Unknown drawer menu item clicked: %s", menuItem.title)
}
true
}
// handle correct state
navigationView.menu.setGroupVisible(R.id.drawer_menu_accounts, isAccountChooserActive)
}
fun setCheckedItemAtBottomBar(checkedMenuItem: Int) {
getBottomNavigationView()?.menu?.findItem(checkedMenuItem)?.isChecked = true
}
/**
* Initializes the bottom navigation bar, its content and highlights the menu item with the given id.
* This method needs to be called after the content view has been set.
*
* @param menuItemId the menu item to be checked/highlighted
*/
open fun setupNavigationBottomBar(menuItemId: Int) {
// Allow or disallow touches with other visible windows
getBottomNavigationView()?.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(this)
setCheckedItemAtBottomBar(menuItemId)
getBottomNavigationView()?.setOnNavigationItemSelectedListener { menuItem: MenuItem ->
bottomBarNavigationTo(menuItem.itemId, getBottomNavigationView()?.selectedItemId == menuItem.itemId)
true
}
}
private fun bottomBarNavigationTo(menuItemId: Int, isCurrentOptionActive: Boolean) {
when (menuItemId) {
R.id.nav_all_files -> navigateToOption(FileListOption.ALL_FILES)
R.id.nav_uploads -> if (!isCurrentOptionActive) {
val uploadListIntent = Intent(applicationContext, UploadListActivity::class.java)
uploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(uploadListIntent)
}
R.id.nav_available_offline_files -> navigateToOption(FileListOption.AV_OFFLINE)
R.id.nav_shared_by_link_files -> navigateToOption(FileListOption.SHARED_BY_LINK)
}
}
private fun openHelp() {
goToUrl(url = getString(R.string.url_help))
}
private fun openFeedback() {
val feedbackMail = getString(R.string.mail_feedback)
val feedback = "Android v" + BuildConfig.VERSION_NAME + " - " + getString(R.string.drawer_feedback)
sendEmail(email = feedbackMail, subject = feedback)
}
/**
* sets the new/current account and restarts. In case the given account equals the actual/current account the
* call will be ignored.
*
* @param accountName The account name to be set
*/
private fun accountClicked(accountName: String) {
if (drawerViewModel.getCurrentAccount(this)?.name != accountName) {
if (drawerViewModel.setCurrentAccount(applicationContext, accountName)) {
// Refresh dependencies to be used in selected account
initDependencyInjection()
restart()
} else {
Timber.d("Was not able to change account")
// TODO: Handle this error (?)
}
}
}
/**
* click method for mini avatars in drawer header.
*
* @param view the clicked ImageView
*/
open fun onAccountDrawerClick(view: View) {
accountClicked(view.contentDescription.toString())
}
/**
* checks if the drawer exists and is opened.
*
* @return `true` if the drawer is open, else `false`
*/
open fun isDrawerOpen(): Boolean = getDrawerLayout()?.isDrawerOpen(GravityCompat.START) ?: false
/**
* closes the drawer.
*/
open fun closeDrawer() {
getDrawerLayout()?.closeDrawer(GravityCompat.START)
}
/**
* opens the drawer.
*/
open fun openDrawer() {
getDrawerLayout()?.openDrawer(GravityCompat.START)
}
/**
* Enable or disable interaction with all drawers.
*
* @param lockMode The new lock mode for the given drawer. One of [DrawerLayout.LOCK_MODE_UNLOCKED],
* [DrawerLayout.LOCK_MODE_LOCKED_CLOSED] or [DrawerLayout.LOCK_MODE_LOCKED_OPEN].
*/
open fun setDrawerLockMode(lockMode: Int) {
getDrawerLayout()?.setDrawerLockMode(lockMode)
}
/**
* updates the account list in the drawer.
*/
private fun updateAccountList() {
val accounts = drawerViewModel.getAccounts(this)
if (getNavView() != null && getDrawerLayout() != null) {
if (accounts.isNotEmpty()) {
repopulateAccountList(accounts)
setAccountInDrawer(drawerViewModel.getCurrentAccount(this) ?: accounts.first())
populateDrawerOwnCloudAccounts()
// activate second/end account avatar
accountsWithAvatars[1]?.let { account ->
getDrawerAccountEnd()?.let {
AvatarUtils().loadAvatarForAccount(
imageView = it,
account = account,
displayRadius = otherAccountAvatarRadiusDimension
)
}
}
if (accountsWithAvatars[1] == null) {
getDrawerAccountEnd()?.isVisible = false
}
// activate third/middle account avatar
accountsWithAvatars[2]?.let { account ->
getDrawerAccountMiddle()?.let {
AvatarUtils().loadAvatarForAccount(
imageView = it,
account = account,
displayRadius = otherAccountAvatarRadiusDimension
)
}
}
if (accountsWithAvatars[2] == null) {
getDrawerAccountMiddle()?.isVisible = false
}
} else {
getDrawerAccountEnd()?.isVisible = false
getDrawerAccountMiddle()?.isVisible = false
}
}
}
/**
* re-populates the account list.
*
* @param accounts list of accounts
*/
private fun repopulateAccountList(accounts: List<Account>?) {
val navigationView = getNavView() ?: return
val navigationMenu = navigationView.menu
// remove all accounts from list
navigationMenu.removeGroup(R.id.drawer_menu_accounts)
// add all accounts to list except current one
accounts?.filter { it.name != account?.name }?.forEach {
val accountMenuItem: MenuItem =
navigationMenu.add(R.id.drawer_menu_accounts, Menu.NONE, MENU_ORDER_ACCOUNT, it.name)
AvatarUtils().loadAvatarForAccount(
menuItem = accountMenuItem,
account = it,
fetchIfNotCached = false,
displayRadius = menuAccountAvatarRadiusDimension
)
}
// re-add add-account and manage-accounts
if (getResources().getBoolean(R.bool.multiaccount_support)) {
navigationMenu.add(
R.id.drawer_menu_accounts, R.id.drawer_menu_account_add,
MENU_ORDER_ACCOUNT_FUNCTION,
resources.getString(R.string.prefs_add_account)
).setIcon(R.drawable.ic_plus_grey)
}
navigationMenu.add(
R.id.drawer_menu_accounts, R.id.drawer_menu_account_manage,
MENU_ORDER_ACCOUNT_FUNCTION,
resources.getString(R.string.drawer_manage_accounts)
).setIcon(R.drawable.ic_group)
// adding sets menu group back to visible, so safety check and setting invisible
showMenu()
}
/**
* Updates the quota in the drawer
*/
private fun updateQuota() {
Timber.d("Update Quota")
val account = drawerViewModel.getCurrentAccount(this) ?: return
drawerViewModel.getStoredQuota(account.name)
drawerViewModel.userQuota.observe(this) { event ->
when (val uiResult = event.peekContent()) {
is UIResult.Success -> {
uiResult.data?.let { userQuota ->
when {
userQuota.available < 0 -> { // Pending, unknown or unlimited free storage
getAccountQuotaBar()?.run {
isVisible = true
progress = 0
}
getAccountQuotaText()?.text = String.format(
getString(R.string.drawer_unavailable_free_storage),
DisplayUtils.bytesToHumanReadable(userQuota.used, this)
)
}
userQuota.available == 0L -> { // Quota 0, guest users
getAccountQuotaBar()?.isVisible = false
getAccountQuotaText()?.text = getString(R.string.drawer_unavailable_used_storage)
}
else -> { // Limited quota
// Update progress bar rounding up to next int. Example: quota is 0.54 => 1
getAccountQuotaBar()?.run {
progress = ceil(userQuota.getRelative()).toInt()
isVisible = true
}
getAccountQuotaText()?.text = String.format(
getString(R.string.drawer_quota),
DisplayUtils.bytesToHumanReadable(userQuota.used, this),
DisplayUtils.bytesToHumanReadable(userQuota.getTotal(), this),
userQuota.getRelative()
)
}
}
}
}
is UIResult.Loading -> getAccountQuotaText()?.text = getString(R.string.drawer_loading_quota)
is UIResult.Error -> getAccountQuotaText()?.text = getString(R.string.drawer_unavailable_used_storage)
}
}
}
override fun setupRootToolbar(title: String, isSearchEnabled: Boolean) {
super.setupRootToolbar(title, isSearchEnabled)
val toolbarLeftIcon = findViewById<ImageView>(R.id.root_toolbar_left_icon)
toolbarLeftIcon.setOnClickListener { openDrawer() }
}
/**
* Sets the given account data in the drawer in case the drawer is available. The account name is shortened
* beginning from the @-sign in the username.
*
* @param account the account to be set in the drawer
*/
protected fun setAccountInDrawer(account: Account) {
if (getDrawerLayout() != null) {
getDrawerUserNameFull()?.text = account.name
try {
val ocAccount = OwnCloudAccount(account, this)
getDrawerUserName()?.text = ocAccount.displayName
} catch (e: Exception) {
Timber.w("Couldn't read display name of account; using account name instead")
getDrawerUserName()?.text = AccountUtils.getUsernameOfAccount(account.name)
}
getDrawerCurrentAccount()?.let {
AvatarUtils().loadAvatarForAccount(
imageView = it,
account = account,
displayRadius = currentAccountAvatarRadiusDimension
)
updateQuota()
}
}
}
/**
* Toggle between standard menu and account list including saving the state.
*/
private fun toggleAccountList() {
isAccountChooserActive = !isAccountChooserActive
showMenu()
}
/**
* depending on the #mIsAccountChooserActive flag shows the account chooser or the standard menu.
*/
private fun showMenu() {
val navigationView = getNavView() ?: return
val accountCount = drawerViewModel.getAccounts(this).size
getDrawerAccountChooserToggle()?.setImageResource(if (isAccountChooserActive) R.drawable.ic_up else R.drawable.ic_down)
navigationView.menu.setGroupVisible(R.id.drawer_menu_accounts, isAccountChooserActive)
navigationView.menu.setGroupVisible(R.id.drawer_menu_settings_etc, !isAccountChooserActive)
getDrawerLogo()?.isVisible = !isAccountChooserActive || accountCount < USER_ITEMS_ALLOWED_BEFORE_REMOVING_CLOUD
}
/**
* checks/highlights the provided menu item if the drawer has been initialized and the menu item exists.
*
* @param menuItemId the menu item to be highlighted
*/
protected open fun setDrawerMenuItemChecked(menuItemId: Int) {
val navigationView = getNavView()
if (navigationView != null && navigationView.menu.findItem(menuItemId) != null) {
navigationView.menu.findItem(menuItemId).isChecked = true
checkedMenuItem = menuItemId
} else {
Timber.w("setDrawerMenuItemChecked has been called with invalid menu-item-ID")
}
}
private fun cleanupUnusedAccountDirectories() {
val accountManager = AccountManager.get(this)
accountManager.addOnAccountsUpdatedListener(OnAccountsUpdateListener {
val accounts = AccountUtils.getAccounts(this)
drawerViewModel.deleteUnusedUserDirs(accounts)
updateAccountList()
}, Handler(), false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
isAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false)
checkedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE)
}
currentAccountAvatarRadiusDimension = resources.getDimension(R.dimen.nav_drawer_header_avatar_radius)
otherAccountAvatarRadiusDimension =
resources.getDimension(R.dimen.nav_drawer_header_avatar_other_accounts_radius)
menuAccountAvatarRadiusDimension = resources.getDimension(R.dimen.nav_drawer_menu_avatar_radius)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, isAccountChooserActive)
outState.putInt(KEY_CHECKED_MENU_ITEM, checkedMenuItem)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
isAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false)
checkedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE)
// (re-)setup drawer state
showMenu()
// check/highlight the menu item if present
if (checkedMenuItem != Menu.NONE) {
setDrawerMenuItemChecked(checkedMenuItem)
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle?.let {
it.syncState()
if (isDrawerOpen()) {
it.isDrawerIndicatorEnabled = true
}
}
updateAccountList()
updateQuota()
cleanupUnusedAccountDirectories()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
drawerToggle?.onConfigurationChanged(newConfig)
}
override fun onBackPressed() {
if (isDrawerOpen()) {
closeDrawer()
return
}
super.onBackPressed()
}
override fun onResume() {
super.onResume()
setDrawerMenuItemChecked(checkedMenuItem)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// update Account list and active account if Manage Account activity replies with
// - ACCOUNT_LIST_CHANGED = true
// - RESULT_OK
if (requestCode == ACTION_MANAGE_ACCOUNTS && resultCode == Activity.RESULT_OK && data!!.getBooleanExtra(
ManageAccountsActivity.KEY_ACCOUNT_LIST_CHANGED,
false
)
) {
// current account has changed
if (data.getBooleanExtra(ManageAccountsActivity.KEY_CURRENT_ACCOUNT_CHANGED, false)) {
account = AccountUtils.getCurrentOwnCloudAccount(this)
// Refresh dependencies to be used in selected account
initDependencyInjection()
restart()
} else {
updateAccountList()
updateQuota()
}
}
}
override fun onAccountCreationSuccessful(future: AccountManagerFuture<Bundle?>?) {
super.onAccountCreationSuccessful(future)
updateAccountList()
updateQuota()
// Refresh dependencies to be used in selected account
initDependencyInjection()
restart()
}
/**
* populates the avatar drawer array with the first three ownCloud [Account]s while the first element is
* always the current account.
*/
private fun populateDrawerOwnCloudAccounts() {
accountsWithAvatars = arrayOfNulls(3)
val accountsAll = drawerViewModel.getAccounts(this)
val currentAccount = drawerViewModel.getCurrentAccount(this)
val otherAccounts = accountsAll.filter { it != currentAccount }
accountsWithAvatars[0] = currentAccount
accountsWithAvatars[1] = otherAccounts.getOrNull(0)
accountsWithAvatars[2] = otherAccounts.getOrNull(1)
}
private fun getDrawerLayout(): DrawerLayout? = findViewById(R.id.drawer_layout)
private fun getNavView(): NavigationView? = findViewById(R.id.nav_view)
private fun getDrawerLogo(): AppCompatImageView? = findViewById(R.id.drawer_logo)
private fun getBottomNavigationView(): BottomNavigationView? = findViewById(R.id.bottom_nav_view)
private fun getAccountQuotaText(): TextView? = findViewById(R.id.account_quota_text)
private fun getAccountQuotaBar(): ProgressBar? = findViewById(R.id.account_quota_bar)
private fun getDrawerAccountChooserToggle() = findNavigationViewChildById(R.id.drawer_account_chooser_toggle) as ImageView?
private fun getDrawerAccountEnd() = findNavigationViewChildById(R.id.drawer_account_end) as ImageView?
private fun getDrawerAccountMiddle() = findNavigationViewChildById(R.id.drawer_account_middle) as ImageView?
private fun getDrawerActiveUser() = findNavigationViewChildById(R.id.drawer_active_user) as ConstraintLayout?
private fun getDrawerCurrentAccount() = findNavigationViewChildById(R.id.drawer_current_account) as AppCompatImageView?
private fun getDrawerHeaderBackground() = findNavigationViewChildById(R.id.drawer_header_background) as ImageView?
private fun getDrawerUserName(): TextView? = findNavigationViewChildById(R.id.drawer_username) as TextView?
private fun getDrawerUserNameFull(): TextView? = findNavigationViewChildById(R.id.drawer_username_full) as TextView?
/**
* Finds a view that was identified by the id attribute from the drawer header.
*
* @param id the view's id
* @return The view if found or `null` otherwise.
*/
private fun findNavigationViewChildById(id: Int): View {
return (findViewById<View>(R.id.nav_view) as NavigationView).getHeaderView(0).findViewById(id)
}
/**
* Adds other listeners to react on changes of the drawer layout.
*
* @param listener Object interested in changes of the drawer layout.
*/
open fun addDrawerListener(listener: DrawerListener) {
getDrawerLayout()?.addDrawerListener(listener)
}
abstract fun navigateToOption(fileListOption: FileListOption)
/**
* restart helper method which is called after a changing the current account.
*/
protected abstract fun restart()
companion object {
private const val KEY_IS_ACCOUNT_CHOOSER_ACTIVE = "IS_ACCOUNT_CHOOSER_ACTIVE"
private const val KEY_CHECKED_MENU_ITEM = "CHECKED_MENU_ITEM"
private const val ACTION_MANAGE_ACCOUNTS = 101
private const val MENU_ORDER_ACCOUNT = 1
private const val MENU_ORDER_ACCOUNT_FUNCTION = 2
private const val USER_ITEMS_ALLOWED_BEFORE_REMOVING_CLOUD = 4
}
}
| gpl-2.0 | 6ce116773a69d6380aaf1cd2cf813a38 | 41.357353 | 129 | 0.639135 | 5.100584 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/toml/TomlSchema.kt | 3 | 1777 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFileFactory
import org.intellij.lang.annotations.Language
import org.toml.lang.psi.TomlArrayTable
import org.toml.lang.psi.TomlFileType
import org.toml.lang.psi.TomlKeyValueOwner
import org.toml.lang.psi.TomlTable
class TomlSchema private constructor(
private val tables: List<TomlTableSchema>
) {
fun topLevelKeys(isArray: Boolean): Collection<String> =
tables.filter { it.isArray == isArray }.map { it.name }
fun keysForTable(tableName: String): Collection<String> =
tables.find { it.name == tableName }?.keys.orEmpty()
companion object {
fun parse(project: Project, @Language("TOML") example: String): TomlSchema {
val toml = PsiFileFactory.getInstance(project)
.createFileFromText("Cargo.toml", TomlFileType, example)
val tables = toml.children
.filterIsInstance<TomlKeyValueOwner>()
.mapNotNull { it.schema }
return TomlSchema(tables)
}
}
}
private val TomlKeyValueOwner.schema: TomlTableSchema?
get() {
val (name, isArray) = when (this) {
is TomlTable -> header.names.firstOrNull()?.text to false
is TomlArrayTable -> header.names.firstOrNull()?.text to true
else -> return null
}
if (name == null) return null
val keys = entries.mapNotNull { it.key.text }.filter { it != "foo" }
return TomlTableSchema(name, isArray, keys)
}
private class TomlTableSchema(
val name: String,
val isArray: Boolean,
val keys: Collection<String>
)
| mit | 65b360ecba968c93d08c9eb7cba4515e | 30.175439 | 84 | 0.662915 | 4.191038 | false | false | false | false |
consp1racy/android-commons | commons/src/main/java/net/xpece/android/view/ViewLayoutDirection.kt | 1 | 2327 | @file:JvmMultifileClass
@file:JvmName("XpView")
package net.xpece.android.view
import android.annotation.TargetApi
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v4.text.TextUtilsCompat
import android.support.v4.view.ViewCompat
import android.view.View
import net.xpece.android.content.res.layoutDirectionCompat
import java.lang.reflect.Method
import java.util.*
@get:RequiresApi(17)
private val getRawLayoutDirectionMethod: Method by lazy(LazyThreadSafetyMode.NONE) {
// This method didn't exist until API 17. It's hidden API.
View::class.java.getDeclaredMethod("getRawLayoutDirection")
}
val View.rawLayoutDirection: Int
@TargetApi(17) get() = when {
Build.VERSION.SDK_INT >= 17 -> {
getRawLayoutDirectionMethod.invoke(this) as Int // Use hidden API.
}
Build.VERSION.SDK_INT >= 14 -> {
layoutDirection // Until API 17 this method was hidden and returned raw value.
}
else -> ViewCompat.LAYOUT_DIRECTION_LTR // Until API 14 only LTR was a thing.
}
private fun View.resolveLayoutDirection(): Int {
val rawLayoutDirection = rawLayoutDirection
return when (rawLayoutDirection) {
ViewCompat.LAYOUT_DIRECTION_LTR,
ViewCompat.LAYOUT_DIRECTION_RTL -> {
// If it's set to absolute value, return the absolute value.
rawLayoutDirection
}
ViewCompat.LAYOUT_DIRECTION_LOCALE -> {
// This mimics the behavior of View class.
TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault())
}
ViewCompat.LAYOUT_DIRECTION_INHERIT -> {
// This mimics the behavior of View and ViewRootImpl classes.
// Traverse parent views until we find an absolute value or _LOCALE.
(parent as? View)?.resolveLayoutDirection() ?: run {
// If we're not attached return the value from Configuration object.
resources.configuration.layoutDirectionCompat
}
}
else -> throw IllegalStateException()
}
}
val View.realLayoutDirection: Int
@TargetApi(19) get() =
if (Build.VERSION.SDK_INT >= 19 && isLayoutDirectionResolved) {
layoutDirection
} else {
resolveLayoutDirection()
}
| apache-2.0 | 3ccd5cf2b3687bb90c62185c66bc33bf | 35.936508 | 90 | 0.673399 | 4.635458 | false | false | false | false |
MyDogTom/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/naming/ConstantNaming.kt | 1 | 1158 | package io.gitlab.arturbosch.detekt.rules.style.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.SubRule
import org.jetbrains.kotlin.psi.KtVariableDeclaration
class ConstantNaming(config: Config = Config.empty) : SubRule<KtVariableDeclaration>(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Style,
debt = Debt.FIVE_MINS)
private val constantPattern = Regex(valueOrDefault(CONSTANT_PATTERN, "^([A-Z_]*|serialVersionUID)$"))
override fun apply(element: KtVariableDeclaration) {
if (doesntMatchPattern((element))) {
report(CodeSmell(
issue.copy(description = "Constant names should match the pattern: $constantPattern"),
Entity.from(element)))
}
}
fun doesntMatchPattern(element: KtVariableDeclaration) = !element.identifierName().matches(constantPattern)
companion object {
const val CONSTANT_PATTERN = "constantPattern"
}
}
| apache-2.0 | b3b6a35626c5929964ec7d32286d2cd6 | 36.354839 | 108 | 0.787565 | 3.809211 | false | true | false | false |
daemontus/glucose | compat/src/main/java/com/glucose/app/PresenterFragment.kt | 2 | 5302 | package com.glucose.app
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.glucose.app.PresenterFragment.Companion.ROOT_PRESENTER_ARGS_KEY
import com.glucose.app.PresenterFragment.Companion.ROOT_PRESENTER_CLASS_KEY
import com.glucose.app.presenter.LifecycleException
/**
* A Fragment implementation which provides a basic context for planting a viable
* Presenter tree.
*
* There are two ways of creating a valid instance of [PresenterFragment], mainly in relation
* to the root presenter class which will be displayed in the Presenter tree.
*
* You can either subclass it and call the constructor with [rootPresenter] and [rootArguments]
* (just as you would an the [RootCompatActivity]):
*
* class MyFragment() : PresenterFragment(MyPresenter::class.java, bundle("data" with 42))
*
* However, if you don't wish to implement any special features, you can provide this
* data using the fragment arguments, using the [ROOT_PRESENTER_ARGS_KEY] and
* [ROOT_PRESENTER_CLASS_KEY] keys:
*
* val fragment = PresenterFragment()
* fragment.arguments = (PresenterFragment.ROOT_PRESENTER_CLASS_KEY with MyPresenter::class.java) and
* (PresenterFragment.ROOT_PRESENTER_ARGS_KEY with myCustomArgs)
*
* (In both cases, the arguments are optional, just as everywhere else)
*
* Other usage is similar to the [RootCompatActivity], but due to the limitations of Fragments,
* some functionality is not guaranteed.
*
* Known problems:
* 1. Fragments don't receive onBackPressed and onTrimMemory callbacks. If you need this
* functionality, you have implement your own notification mechanism. (The methods are provided,
* you just have to call them yourself)
* 2. You have to make sure state of the fragment is properly restored (the state of presenter will
* be saved into the bundle in [onSaveInstanceState], just make sure it's not lost).
* 3. If the fragment is used as a nested fragment, you have to make sure activity results and
* permission results are delivered to that fragment.
*/
open class PresenterFragment(
private var rootPresenter: Class<out Presenter>? = null,
private var rootArguments: Bundle? = null
) : Fragment() {
companion object {
@JvmField val ROOT_PRESENTER_CLASS_KEY = "glucose:root_presenter_class"
@JvmField val ROOT_PRESENTER_ARGS_KEY = "glucose:root_presenter_args"
}
protected var presenterContext: PresenterDelegate? = null
private set
private var savedState: Bundle? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedState = savedInstanceState
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context !is Activity) {
throw LifecycleException("PresenterFragment cannot be attached to $context which is not an Activity")
}
val clazz = rootPresenter ?:
Presenter::class.java.javaClass.cast(arguments.getSerializable(ROOT_PRESENTER_CLASS_KEY))
val args = rootArguments ?: arguments.getBundle(ROOT_PRESENTER_ARGS_KEY) ?: Bundle()
presenterContext = PresenterDelegate(context, clazz, args)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return presenterContext!!.onCreate(savedState)
}
override fun onStart() {
super.onStart()
presenterContext!!.onStart()
}
override fun onResume() {
super.onResume()
presenterContext!!.onResume()
}
override fun onPause() {
super.onPause()
presenterContext!!.onPause()
}
override fun onStop() {
super.onStop()
presenterContext!!.onStop()
}
override fun onDestroyView() {
//have to do it here, because the presenters shouldn't outlive the UI
presenterContext!!.onDestroy()
presenterContext = null
super.onDestroyView()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
presenterContext?.onConfigurationChanged(newConfig)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
presenterContext?.onActivityResult(requestCode, resultCode, data)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
presenterContext?.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
presenterContext?.onSaveInstanceState(outState)
}
fun onBackPressed(): Boolean {
return presenterContext?.onBackPressed() ?: false
}
fun onTrimMemory(level: Int) {
presenterContext?.onTrimMemory(level)
}
} | mit | 858b0ba8fb9288c60312e0789713f90d | 36.878571 | 119 | 0.720294 | 4.708703 | false | true | false | false |
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/utils/DividerItemDecoration.kt | 1 | 1186 | package nl.ecci.hamers.utils
import android.R
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import androidx.recyclerview.widget.RecyclerView
class DividerItemDecoration(context: Context) : RecyclerView.ItemDecoration() {
private val mDivider: Drawable
init {
val styledAttributes = context.obtainStyledAttributes(ATTRS)
mDivider = styledAttributes.getDrawable(0)!!
styledAttributes.recycle()
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + mDivider.intrinsicHeight
mDivider.setBounds(left, top, right, bottom)
mDivider.draw(c)
}
}
companion object {
private val ATTRS = intArrayOf(R.attr.listDivider)
}
} | gpl-3.0 | 61ede68a4fdf9bca7189173d3c82d106 | 28.675 | 89 | 0.684654 | 5.004219 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/model/IconResource.kt | 1 | 4866 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.model
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.net.Uri
import android.os.Parcelable
import androidx.annotation.VisibleForTesting
import java.util.Locale
import kotlinx.parcelize.Parcelize
import org.json.JSONException
import org.json.JSONObject
import org.openhab.habdroid.util.appendQueryParameter
import org.openhab.habdroid.util.getIconFormat
import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.getStringOrNull
@Parcelize
data class IconResource internal constructor(
internal val icon: String,
internal val isOh2: Boolean,
internal val customState: String?
) : Parcelable {
fun toUrl(context: Context, includeState: Boolean): String {
return toUrl(includeState, context.getPrefs().getIconFormat())
}
@VisibleForTesting
fun toUrl(includeState: Boolean, iconFormat: IconFormat): String {
if (!isOh2) {
return "images/$icon.png"
}
val suffix = when (iconFormat) {
IconFormat.Png -> "PNG"
IconFormat.Svg -> "SVG"
}
val builder = Uri.Builder()
.path("icon/")
.appendPath(icon)
.appendQueryParameter("format", suffix)
.appendQueryParameter("anyFormat", true)
if (!customState.isNullOrEmpty() && includeState) {
builder.appendQueryParameter("state", customState)
}
return builder.build().toString()
}
fun withCustomState(state: String): IconResource {
return IconResource(icon, isOh2, state)
}
}
fun SharedPreferences.getIconResource(key: String): IconResource? {
val iconString = getStringOrNull(key) ?: return null
return try {
val obj = JSONObject(iconString)
val icon = obj.getString("icon")
val isOh2 = obj.getInt("ohversion") == 2
val customState = obj.optString("state")
IconResource(icon, isOh2, customState)
} catch (e: JSONException) {
null
}
}
fun SharedPreferences.Editor.putIconResource(key: String, icon: IconResource?): SharedPreferences.Editor {
if (icon == null) {
putString(key, null)
} else {
val iconString = JSONObject()
.put("icon", icon.icon)
.put("ohversion", if (icon.isOh2) 2 else 1)
.put("state", icon.customState)
.toString()
putString(key, iconString)
}
return this
}
fun String?.toOH1IconResource(): IconResource? {
return if (this != null && this != "none") IconResource(this, false, null) else null
}
fun String?.toOH2IconResource(): IconResource? {
return if (this != null && this != "none") IconResource(this, true, "") else null
}
internal fun String?.toOH2WidgetIconResource(item: Item?, type: Widget.Type, hasMappings: Boolean): IconResource? {
if (this == null || this == "none") {
return null
}
val itemState = item?.state
var iconState = itemState?.asString.orEmpty()
if (itemState != null) {
if (item.isOfTypeOrGroupType(Item.Type.Color)) {
// For items that control a color item fetch the correct icon
if (type == Widget.Type.Slider || type == Widget.Type.Switch && !hasMappings) {
try {
iconState = itemState.asBrightness.toString()
if (type == Widget.Type.Switch) {
iconState = if (iconState == "0") "OFF" else "ON"
}
} catch (e: Exception) {
iconState = "OFF"
}
} else if (itemState.asHsv != null) {
val color = itemState.asHsv.toColor()
iconState = String.format(
Locale.US, "#%02x%02x%02x",
Color.red(color), Color.green(color), Color.blue(color))
}
} else if (type == Widget.Type.Switch && !hasMappings && !item.isOfTypeOrGroupType(Item.Type.Rollershutter)) {
// For switch items without mappings (just ON and OFF) that control a dimmer item
// and which are not ON or OFF already, set the state to "OFF" instead of 0
// or to "ON" to fetch the correct icon
iconState = if (itemState.asString == "0" || itemState.asString == "OFF") "OFF" else "ON"
}
}
return IconResource(this, true, iconState)
}
enum class IconFormat {
Png,
Svg
}
| epl-1.0 | 415d1e337c1af098eeab642643f34646 | 32.791667 | 118 | 0.626182 | 4.13073 | false | false | false | false |
Nearsoft/nearbooks-android | app/src/main/java/com/nearsoft/nearbooks/models/view/Book.kt | 2 | 3841 | package com.nearsoft.nearbooks.models.view
import android.databinding.BaseObservable
import android.databinding.Bindable
import android.os.Parcel
import android.os.Parcelable
import com.nearsoft.nearbooks.BR
/**
* Book view model.
* Created by epool on 5/1/16.
*/
class Book : BaseObservable, Parcelable {
companion object {
@JvmField val CREATOR: Parcelable.Creator<Book> = object : Parcelable.Creator<Book> {
override fun createFromParcel(source: Parcel): Book {
return Book(source)
}
override fun newArray(size: Int): Array<Book?> {
return arrayOfNulls(size)
}
}
}
var id: String? = null
@Bindable get() = field
set(id) {
field = id
notifyPropertyChanged(BR.id)
}
var title: String? = null
@Bindable get() = field
set(title) {
field = title
notifyPropertyChanged(BR.title)
}
var author: String? = null
@Bindable get() = field
set(author) {
field = author
notifyPropertyChanged(BR.author)
}
var releaseYear: String? = null
@Bindable get() = field
set(releaseYear) {
field = releaseYear
notifyPropertyChanged(BR.releaseYear)
}
var description: String? = null
@Bindable get() = field
set(description) {
field = description
notifyPropertyChanged(BR.description)
}
var numberOfCopies: Int = 0
@Bindable get() = field
set(numberOfCopies) {
field = numberOfCopies
notifyPropertyChanged(BR.numberOfCopies)
}
var numberOfDaysAllowedForBorrowing: Int = 0
@Bindable get() = field
set(numberOfDaysAllowedForBorrowing) {
field = numberOfDaysAllowedForBorrowing
notifyPropertyChanged(BR.numberOfDaysAllowedForBorrowing)
}
var isAvailable: Boolean = false
@Bindable get() = field
set(available) {
field = available
notifyPropertyChanged(BR.available)
}
var borrows: MutableList<Borrow> = mutableListOf()
@Bindable get() = field
set(borrows) {
field = borrows
notifyPropertyChanged(BR.borrows)
}
constructor() {
}
constructor(book: com.nearsoft.nearbooks.models.realm.Book) {
id = book.id
title = book.title
author = book.author
releaseYear = book.releaseYear
description = book.description
numberOfCopies = book.numberOfCopies
numberOfDaysAllowedForBorrowing = book.numberOfDaysAllowedForBorrowing
isAvailable = book.isAvailable
for (borrow in book.borrows.orEmpty()) {
borrows.add(Borrow(borrow))
}
}
protected constructor(parcel: Parcel) {
id = parcel.readString()
title = parcel.readString()
author = parcel.readString()
releaseYear = parcel.readString()
description = parcel.readString()
numberOfCopies = parcel.readInt()
numberOfDaysAllowedForBorrowing = parcel.readInt()
isAvailable = parcel.readByte().toInt() != 0
parcel.readList(borrows, Borrow::class.java.classLoader)
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(id)
dest.writeString(title)
dest.writeString(author)
dest.writeString(releaseYear)
dest.writeString(description)
dest.writeInt(numberOfCopies)
dest.writeInt(numberOfDaysAllowedForBorrowing)
dest.writeByte(if (isAvailable) 1.toByte() else 0.toByte())
dest.writeList(borrows)
}
}
| mit | 044a650b683b4afd2a6e917e36be8728 | 28.775194 | 93 | 0.605051 | 4.771429 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/NettyThreadOnlyHelper.kt | 1 | 1763 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network
import com.google.common.reflect.TypeToken
import org.lanternpowered.server.network.packet.Packet
import org.lanternpowered.server.network.packet.PacketHandler
import java.util.concurrent.ConcurrentHashMap
object NettyThreadOnlyHelper {
private val map = ConcurrentHashMap<Class<out PacketHandler<out Packet>>, Boolean>()
fun isHandlerNettyThreadOnly(handlerClass: Class<out PacketHandler<out Packet>>): Boolean {
return this.map.computeIfAbsent(handlerClass) { isHandlerNettyThreadOnly0(it) }
}
private fun isHandlerNettyThreadOnly0(handlerClass: Class<out PacketHandler<out Packet>>): Boolean {
for (method in handlerClass.methods) {
if (method.name != "handle" || method.parameterCount != 2 || method.isSynthetic) {
continue
}
val params = method.parameterTypes
if (params[0] != NetworkContext::class.java) {
continue
}
val messageType = TypeToken.of(handlerClass)
.getSupertype(PacketHandler::class.java)
.resolveType(PacketHandler::class.java.typeParameters[0])
if (messageType.rawType != params[1]) {
continue
}
if (method.getAnnotation(NettyThreadOnly::class.java) != null) {
return true
}
}
return false
}
}
| mit | 939b45f104159785c9fd8e33e0c9c122 | 36.510638 | 104 | 0.653432 | 4.555556 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/rcon/RconServer.kt | 1 | 4655 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
/*
* Copyright (c) 2011-2014 Glowstone - Tad Hardesty
* Copyright (c) 2010-2011 Lightstone - Graham Edgecombe
*
* 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.lanternpowered.server.network.rcon
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
import io.netty.channel.EventLoopGroup
import io.netty.channel.socket.SocketChannel
import org.lanternpowered.api.util.collections.concurrentHashMapOf
import org.lanternpowered.server.network.TransportType
import org.lanternpowered.server.util.executor.LanternExecutorService
import org.lanternpowered.server.util.netty.addChannelFutureListener
import org.spongepowered.api.service.rcon.RconService
import java.io.Closeable
import java.net.InetSocketAddress
import java.net.SocketAddress
import java.util.concurrent.CompletableFuture
class RconServer(
private val password: String,
val syncExecutor: LanternExecutorService,
private val bossGroup: EventLoopGroup,
private val workerGroup: EventLoopGroup
) : RconService, Closeable {
private val connectionByHostname = concurrentHashMapOf<String, LanternRconConnection>()
private lateinit var bootstrap: ServerBootstrap
private var endpoint: Channel? = null
lateinit var address: InetSocketAddress
private set
fun init(address: SocketAddress): CompletableFuture<Boolean> {
val transportType = TransportType.findBestType()
this.address = address as InetSocketAddress
this.bootstrap = ServerBootstrap()
.group(this.bossGroup, this.workerGroup)
.channelFactory(transportType.serverSocketChannelFactory)
.childHandler(object : ChannelInitializer<SocketChannel>() {
public override fun initChannel(ch: SocketChannel) {
ch.pipeline()
.addLast(RconFramingHandler())
.addLast(RconHandler(this@RconServer, password))
}
})
val result = CompletableFuture<Boolean>()
this.bootstrap.bind(address)
.addChannelFutureListener { future ->
if (future.isSuccess) {
this.endpoint = future.channel()
result.complete(true)
} else {
result.complete(false)
}
}
return result
}
override fun close() {
check(this::bootstrap.isInitialized) { "The rcon server wasn't initialized." }
// Don't allow any new connections
this.endpoint?.close()
// Close all open connections
for (connection in this.connectionByHostname.values)
connection.close()
}
fun add(connection: LanternRconConnection) {
this.connectionByHostname[connection.address.hostName] = connection
}
fun remove(connection: LanternRconConnection) {
this.connectionByHostname.remove(connection.address.hostName)
}
fun getByHostName(hostname: String): LanternRconConnection? = this.connectionByHostname[hostname]
override fun isRconEnabled(): Boolean = true
override fun getRconPassword(): String = this.password
}
| mit | 392c6e850f93025e1abbfc317c109ece | 40.19469 | 101 | 0.698389 | 4.784173 | false | false | false | false |
aucd29/common | library/src/main/java/net/sarangnamu/common/BkFile.kt | 1 | 6069 | /*
* Copyright 2016 Burke Choi All rights reserved.
* http://www.sarangnamu.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE", "unused")
package net.sarangnamu.common
import android.content.res.AssetManager
import org.slf4j.LoggerFactory
import java.io.File
import java.io.InputStream
/**
* Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 10. 17.. <p/>
*/
/**
* 파일이나 디렉토리의 전체 크기를 반환 한다
*/
fun File.totalLength(): Long {
if (!exists()) {
return 0
}
var total: Long = 0
if (isDirectory) {
listFiles().forEach {
if (it.isDirectory) {
total += it.totalLength()
} else {
total += it.length()
}
}
} else {
total = this.length()
}
return total
}
/**
* 파일이나 디렉토리를 복사 한다 (하위 폴더 포함)
*/
fun File.copy(target: File, listener:FileListener? = null) {
val log = LoggerFactory.getLogger(File::class.java)
if (!this.exists()) {
listener?.finish(FileListener.NOT_FOUND)
return
}
listener?.run {
if (total == 0L) {
total = totalLength()
}
}
if (isDirectory) {
listFiles().forEach {
if (it.isDirectory) {
it.copy(File(target, "${it.parentFile.name}/${it.name}"), listener)
} else {
if (!target.exists()) {
target.mkdirs()
}
if (log.isTraceEnabled()) {
log.trace("${it.absolutePath} -> ${target.absolutePath}/${it.name}")
}
it.inputStream().use { ism ->
ism.copyFile(File(target, it.name), listener)
}
}
}
} else {
if (!target.exists()) {
target.mkdirs()
}
if (log.isTraceEnabled()) {
log.trace("${this.absolutePath} -> ${target.absolutePath}/${this.name}")
}
this.inputStream().use { ism ->
ism.copyFile(File(target, this.name), listener)
}
}
}
private fun InputStream.copyFile(target: File, listener: FileListener? = null) {
if (target.exists()) {
target.delete()
}
target.outputStream().use { osm ->
val buff = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = read(buff)
while (bytes >= 0) {
osm.write(buff, 0, bytes)
listener?.run {
current += bytes
progress()
trace()
}
// 이거 이쁘게 하는 방법이 없나. -_ -;
// jump 는 while 갈 수가 없고...
if (listener != null && listener.cancel) {
// stop file copy event
listener.finish(FileListener.CANCELED)
break;
}
bytes = read(buff)
}
listener?.run {
if (cancel) {
return
}
if (total == 0L) {
finish(FileListener.DONE)
} else {
if (percent == 100) {
finish(FileListener.DONE)
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////
//
// ASSETS
//
////////////////////////////////////////////////////////////////////////////////////
fun AssetManager.copy(srcPath: String, destPath: String, listener: FileListener? = null) {
val list = this.list(srcPath)
listener?.let {
if (it.total == 0L) {
it.total = this.totalLength(srcPath)
}
}
if (list.size == 0) {
this.open(srcPath).use {
val f = File(destPath, srcPath)
if (!f.parentFile.exists()) {
f.parentFile.mkdirs()
}
this.open(srcPath).copyFile(f, listener)
}
} else {
list.forEach {
this.copy("$srcPath/$it", destPath, listener)
}
}
}
fun AssetManager.totalLength(srcPath: String): Long {
val list = this.list(srcPath)
var length: Long = 0
if (list.size == 0) {
this.open(srcPath).use {
val buff = ByteArray(DEFAULT_BUFFER_SIZE)
var bytes = 0
do {
length += bytes
bytes = it.read(buff)
} while (bytes >= 0)
}
return length
} else {
list.forEach {
length += this.totalLength("$srcPath/$it")
}
}
return length
}
////////////////////////////////////////////////////////////////////////////////////
//
// FileListener
//
////////////////////////////////////////////////////////////////////////////////////
abstract class FileListener {
private val log = LoggerFactory.getLogger(FileListener::class.java)
companion object {
val DONE = 1
val NOT_FOUND = -1
val CANCELED = -2
}
var cancel = false
var percent: Int = 0
var current: Long = 0
var total: Long = 0
val ignore: Boolean = false
open fun progress() {
if (total != 0L && !ignore) {
percent = (current.toDouble() / total.toDouble() * 100.0).toInt()
}
}
fun trace() {
if (log.isTraceEnabled()) {
log.trace("$percent% (${current.toFileSizeString()} / ${total.toFileSizeString()})")
}
}
abstract fun finish(code: Int)
} | apache-2.0 | 9fa6ee1300a55f082a73fb9d4e52ec8c | 24.147679 | 96 | 0.482799 | 4.296323 | false | false | false | false |
ihmc/dspcap | src/main/kotlin/us/ihmc/aci/dspro/pcap/disservice/MessageInfo.kt | 1 | 3591 | package us.ihmc.aci.dspro.pcap.disservice
import io.pkts.buffer.Buffer
import us.ihmc.aci.dspro.pcap.readString
/**
* Created by gbenincasa on 10/31/17.
*/
class MessageInfo(
val group: String,
val publisher: String,
val sequenceId: Long,
val chunkId: Short,
val objectId: String,
val instanceId: String,
val referredObjectId: String,
val annotationMetadata: ByteArray,
val tag: Int,
val clientId: Int,
val clientType: Short,
val mimeType: String,
val totalLength: Long,
val fragmentOffset: Long,
val fragmentLength: Long,
val historyWindow: Int,
val priority: Short,
val acknowledgment: Boolean,
val referredObject: ByteArray,
val totalNumberOfChunks: Short) {
public constructor(group: String, publisher: String, sequenceId: Long, chunkId: Short, objectId: String, instanceId: String,
totalLength: Long, fragmentLength: Long, totalNumberOfChunks: Short)
: this (group, publisher,sequenceId, chunkId, objectId, instanceId, "", ByteArray(0),
0, 0, 0.toShort(), "", totalLength, 0, fragmentLength, 0,
0.toShort(), false, ByteArray(0), totalNumberOfChunks)
companion object {
fun getMessageInfo(buf: Buffer): MessageInfo {
val isChunk = buf.readUnsignedByte().toInt() == 1
val group = readString(buf, buf.readUnsignedShort())
val publisher = readString(buf, buf.readUnsignedShort())
val sequenceId = buf.readUnsignedInt()
val chunkId = buf.readUnsignedByte()
val objectId = readString(buf, buf.readUnsignedShort())
val instanceId = readString(buf, buf.readUnsignedShort())
val referredObjectId = readString(buf, buf.readUnsignedShort())
var annotationMetadataLen = buf.readUnsignedInt()
val annotationMetadata = if (annotationMetadataLen > 0) buf.readBytes(annotationMetadataLen.toInt()).array
else ByteArray(0)
val tag = buf.readUnsignedShort()
val clientId = buf.readUnsignedShort()
val clientType = buf.readUnsignedByte()
val mimeType = readString(buf, buf.readUnsignedShort())
val totalLength = buf.readUnsignedInt()
val fragmentOffset = buf.readUnsignedInt()
val fragmentLength = buf.readUnsignedInt()
val historyWindow = buf.readUnsignedShort()
val priority = buf.readUnsignedByte()
buf.readBytes(8) // Expiration
val acknowledgment = buf.readUnsignedByte().toInt() == 1
val referredObjectLen = if(isChunk) 0 else buf.readUnsignedShort()
val referredObject = if (referredObjectLen > 0) buf.readBytes(referredObjectLen).array else ByteArray(0)
val totalNumberOfChunks = if (isChunk) {
buf.readUnsignedByte()
} else {
buf.readUnsignedByte()
buf.readUnsignedInt()
0
}
return MessageInfo(group, publisher, sequenceId, chunkId, objectId, instanceId, referredObjectId,
annotationMetadata, tag, clientId, clientType, mimeType, totalLength, fragmentOffset,
fragmentLength, historyWindow, priority, acknowledgment, referredObject, totalNumberOfChunks)
}
}
init {
}
fun isComplete(): Boolean = fragmentLength == totalLength
fun isDSProMessage(): Boolean = group.startsWith("DSPro")
} | mit | 9edab5cfa2b9b42136706725ed79577c | 39.359551 | 128 | 0.630465 | 4.892371 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/base/launchUntil.kt | 1 | 3721 | package com.pr0gramm.app.ui.base
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.*
import com.pr0gramm.app.Logger
import kotlinx.coroutines.*
fun AppCompatActivity.launchUntilPause(
ignoreErrors: Boolean = false,
busyIndicator: Boolean = false,
block: suspend CoroutineScope.() -> Unit): Job {
return launchUntil(this, lifecycle, ignoreErrors, busyIndicator, block, Lifecycle.Event.ON_PAUSE)
}
fun AppCompatActivity.launchUntilStop(
ignoreErrors: Boolean = false,
busyIndicator: Boolean = false,
block: suspend CoroutineScope.() -> Unit): Job {
return launchUntil(this, lifecycle, ignoreErrors, busyIndicator, block, Lifecycle.Event.ON_STOP)
}
fun AppCompatActivity.launchUntilDestroy(
ignoreErrors: Boolean = false,
busyIndicator: Boolean = false,
block: suspend CoroutineScope.() -> Unit): Job {
return lifecycleScope.launch(block = decorate(this, ignoreErrors, busyIndicator, block))
}
fun Fragment.launchUntilPause(
ignoreErrors: Boolean = false,
busyIndicator: Boolean = false,
block: suspend CoroutineScope.() -> Unit): Job {
return launchUntil(requireContext(), lifecycle, ignoreErrors, busyIndicator, block, Lifecycle.Event.ON_PAUSE)
}
fun Fragment.launchUntilStop(
ignoreErrors: Boolean = false,
busyIndicator: Boolean = false,
block: suspend CoroutineScope.() -> Unit): Job {
return launchUntil(requireContext(), lifecycle, ignoreErrors, busyIndicator, block, Lifecycle.Event.ON_STOP)
}
fun Fragment.launchUntilViewDestroy(
ignoreErrors: Boolean = false,
busyIndicator: Boolean = false,
block: suspend CoroutineScope.() -> Unit): Job {
return launchInViewScope(ignoreErrors, busyIndicator, block)
}
fun Fragment.launchInViewScope(
ignoreErrors: Boolean = false,
busyIndicator: Boolean = false,
block: suspend CoroutineScope.() -> Unit): Job {
return viewLifecycleOwner.lifecycleScope.launch(
block = decorate(requireContext(), ignoreErrors, busyIndicator, block)
)
}
fun Fragment.launchUntilDestroy(
ignoreErrors: Boolean = false,
busyIndicator: Boolean = false,
block: suspend CoroutineScope.() -> Unit): Job {
return launchUntil(requireContext(), lifecycle, ignoreErrors, busyIndicator, block, Lifecycle.Event.ON_DESTROY)
}
private class UntilEventController(
private val lifecycle: Lifecycle,
private val job: Job, private val event: Lifecycle.Event) : LifecycleEventObserver {
private val logger = Logger("UntilEventController")
init {
lifecycle.addObserver(this)
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (this.event === event) {
logger.debug { "Stop job $job at event $event" }
job.cancel()
finish()
}
}
fun finish() {
lifecycle.removeObserver(this)
}
}
private fun launchUntil(context: Context, lifecycle: Lifecycle, ignoreErrors: Boolean, busyIndicator: Boolean,
block: suspend CoroutineScope.() -> Unit, cancelOnEvent: Lifecycle.Event): Job {
return lifecycle.coroutineScope.launch {
val job = SupervisorJob(parent = coroutineContext[Job])
val controller = withContext(Dispatchers.Main.immediate) {
UntilEventController(lifecycle, job, cancelOnEvent)
}
try {
withContext(job, decorate(context, ignoreErrors, busyIndicator, block))
} finally {
controller.finish()
}
}
}
| mit | a645724a1ae12ff126751d8aa651b0e9 | 30.533898 | 115 | 0.68315 | 4.770513 | false | false | false | false |
FHannes/intellij-community | platform/platform-tests/testSrc/com/intellij/ide/updates/UpdateInfoParsingTest.kt | 8 | 4890 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.updates
import com.intellij.openapi.updateSettings.impl.ChannelStatus
import com.intellij.openapi.updateSettings.impl.UpdateChannel
import com.intellij.openapi.updateSettings.impl.UpdatesInfo
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.loadElement
import org.junit.Test
import java.net.URL
import java.text.SimpleDateFormat
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class UpdateInfoParsingTest {
@Test fun liveJetbrainsUpdateFile() {
val info = load(URL("http://www.jetbrains.com/updates/updates.xml").readText())
assertNotNull(info["IC"])
}
@Test fun liveAndroidUpdateFile() {
val info = load(URL("https://dl.google.com/android/studio/patches/updates.xml").readText())
assertNotNull(info["AI"])
}
@Test fun emptyChannels() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<code>IC</code>
</product>
</products>""".trimIndent())
val product = info["IU"]!!
assertEquals("IntelliJ IDEA", product.name)
assertEquals(0, product.channels.size)
assertEquals(product, info["IC"])
}
@Test fun oneProductOnly() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="idea90" name="IntelliJ IDEA 9 updates" status="release" url="https://www.jetbrains.com/idea/whatsnew">
<build number="95.627" version="9.0.4">
<message>IntelliJ IDEA 9.0.4 is available. Please visit https://www.jetbrains.com/idea to learn more and download it.</message>
<patch from="95.429" size="2"/>
</build>
</channel>
<channel id="IDEA10EAP" name="IntelliJ IDEA X EAP" status="eap" licensing="eap" url="http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP">
<build number="98.520" version="10" releaseDate="20110403">
<message>IntelliJ IDEA X RC is available. Please visit hhttp://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP to learn more.</message>
<button name="Download" url="http://www.jetbrains.com/idea" download="true"/>
</build>
</channel>
</product>
</products>""".trimIndent())
val product = info["IU"]!!
assertEquals("IntelliJ IDEA", product.name)
assertEquals(2, product.channels.size)
val channel = product.channels.find { it.id == "IDEA10EAP" }!!
assertEquals(ChannelStatus.EAP, channel.status)
assertEquals(UpdateChannel.LICENSING_EAP, channel.licensing)
assertEquals(1, channel.builds.size)
val build = channel.builds[0]
assertEquals(BuildNumber.fromString("98.520"), build.number)
assertEquals("2011-04-03", SimpleDateFormat("yyyy-MM-dd").format(build.releaseDate))
assertNotNull(build.downloadUrl)
assertEquals(0, build.patches.size)
assertEquals(1, product.channels.find { it.id == "idea90" }!!.builds[0].patches.size)
}
@Test fun targetRanges() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="IDEA_EAP" status="eap">
<build number="2016.2.123" version="2016.2" targetSince="0" targetUntil="145.*"/>
<build number="2016.2.123" version="2016.2" targetSince="2016.1" targetUntil="2016.1.*"/>
<build number="2016.1.11" version="2016.1"/>
</channel>
</product>
</products>""".trimIndent())
assertEquals(2, info["IU"]!!.channels[0].builds.count { it.target != null })
}
@Test fun fullBuildNumbers() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="IDEA_EAP" status="eap">
<build number="162.100" fullNumber="162.100.1" version="2016.2">
<patch from="162.99" fullFrom="162.99.2" size="1"/>
</build>
</channel>
</product>
</products>""".trimIndent())
val buildInfo = info["IU"]!!.channels[0].builds[0]
assertEquals("162.100.1", buildInfo.number.asString())
assertEquals("162.99.2", buildInfo.patches[0].fromBuild.asString())
}
private fun load(text: String) = UpdatesInfo(loadElement(text))
} | apache-2.0 | e98147d67d973bb7e80c2e10f93f94a2 | 37.511811 | 155 | 0.652761 | 3.915132 | false | true | false | false |
renyuneyun/Easer | app/src/main/java/ryey/easer/core/log/ProfileLoadedLog.kt | 1 | 2017 | /*
* Copyright (c) 2016 - 2019 Rui Zhao <[email protected]>
*
* This file is part of Easer.
*
* Easer 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.
*
* Easer 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 Easer. If not, see <http://www.gnu.org/licenses/>.
*/
package ryey.easer.core.log
import android.os.Parcel
import android.os.Parcelable
import ryey.easer.Utils
class ProfileLoadedLog : BasicLog {
val profileName: String
constructor(profile: String, extraInfo: String? = null) : super(extraInfo) {
this.profileName = profile
}
override fun equals(other: Any?): Boolean {
if (!super.equals(other))
return false
other as ProfileLoadedLog
if (!Utils.nullableEqual(profileName, other.profileName))
return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + profileName.hashCode()
return result
}
constructor(parcel: Parcel) : super(parcel) {
profileName = parcel.readString()!!
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeString(profileName)
}
companion object CREATOR : Parcelable.Creator<ProfileLoadedLog> {
override fun createFromParcel(parcel: Parcel): ProfileLoadedLog {
return ProfileLoadedLog(parcel)
}
override fun newArray(size: Int): Array<ProfileLoadedLog?> {
return arrayOfNulls(size)
}
}
} | gpl-3.0 | 03067f87950f5f02a70ecde537d04c24 | 29.575758 | 80 | 0.673773 | 4.319058 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.