content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
This file is part of Subsonic.
Subsonic 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.
Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2020 (C) Jozsef Varga
*/
package org.moire.ultrasonic.activity
import android.view.LayoutInflater
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupMenu
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView.SectionedAdapter
import java.text.Collator
import org.moire.ultrasonic.R
import org.moire.ultrasonic.data.ActiveServerProvider.Companion.isOffline
import org.moire.ultrasonic.domain.Artist
import org.moire.ultrasonic.domain.MusicDirectory
import org.moire.ultrasonic.util.ImageLoader
import org.moire.ultrasonic.util.Util
/**
* Creates a Row in a RecyclerView which contains the details of an Artist
*/
class ArtistRowAdapter(
private var artistList: List<Artist>,
private var folderName: String,
private var shouldShowHeader: Boolean,
val onArtistClick: (Artist) -> Unit,
val onContextMenuClick: (MenuItem, Artist) -> Boolean,
val onFolderClick: (view: View) -> Unit,
private val imageLoader: ImageLoader
) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), SectionedAdapter {
/**
* Sets the data to be displayed in the RecyclerView
*/
fun setData(data: List<Artist>) {
artistList = data.sortedWith(compareBy(Collator.getInstance()) { t -> t.name })
notifyDataSetChanged()
}
/**
* Sets the name of the folder to be displayed n the Header (first) row
*/
fun setFolderName(name: String) {
folderName = name
notifyDataSetChanged()
}
/**
* Holds the view properties of an Artist row
*/
class ArtistViewHolder(
itemView: View
) : RecyclerView.ViewHolder(itemView) {
var section: TextView = itemView.findViewById(R.id.row_section)
var textView: TextView = itemView.findViewById(R.id.row_artist_name)
var layout: RelativeLayout = itemView.findViewById(R.id.row_artist_layout)
var coverArt: ImageView = itemView.findViewById(R.id.artist_coverart)
var coverArtId: String? = null
}
/**
* Holds the view properties of the Header row
*/
class HeaderViewHolder(
itemView: View
) : RecyclerView.ViewHolder(itemView) {
var folderName: TextView = itemView.findViewById(R.id.select_artist_folder_2)
var layout: LinearLayout = itemView.findViewById(R.id.select_artist_folder)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
if (viewType == TYPE_ITEM) {
val row = LayoutInflater.from(parent.context)
.inflate(R.layout.artist_list_item, parent, false)
return ArtistViewHolder(row)
}
val header = LayoutInflater.from(parent.context)
.inflate(R.layout.select_artist_header, parent, false)
return HeaderViewHolder(header)
}
override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
if ((holder is ArtistViewHolder) && (holder.coverArtId != null)) {
imageLoader.cancel(holder.coverArtId)
}
super.onViewRecycled(holder)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is ArtistViewHolder) {
val listPosition = if (shouldShowHeader) position - 1 else position
holder.textView.text = artistList[listPosition].name
holder.section.text = getSectionForArtist(listPosition)
holder.layout.setOnClickListener { onArtistClick(artistList[listPosition]) }
holder.layout.setOnLongClickListener { view -> createPopupMenu(view, listPosition) }
holder.coverArtId = artistList[listPosition].coverArt
if (Util.getShouldShowArtistPicture(holder.coverArt.context)) {
holder.coverArt.visibility = View.VISIBLE
imageLoader.loadImage(
holder.coverArt,
MusicDirectory.Entry().apply { coverArt = holder.coverArtId },
false, 0, false, true, R.drawable.ic_contact_picture
)
} else {
holder.coverArt.visibility = View.GONE
}
} else if (holder is HeaderViewHolder) {
holder.folderName.text = folderName
holder.layout.setOnClickListener { onFolderClick(holder.layout) }
}
}
override fun getItemCount() = if (shouldShowHeader) artistList.size + 1 else artistList.size
override fun getItemViewType(position: Int): Int {
return if (position == 0 && shouldShowHeader) TYPE_HEADER else TYPE_ITEM
}
override fun getSectionName(position: Int): String {
var listPosition = if (shouldShowHeader) position - 1 else position
// Show the first artist's initial in the popup when the list is
// scrolled up to the "Select Folder" row
if (listPosition < 0) listPosition = 0
return getSectionFromName(artistList[listPosition].name ?: " ")
}
private fun getSectionForArtist(artistPosition: Int): String {
if (artistPosition == 0)
return getSectionFromName(artistList[artistPosition].name ?: " ")
val previousArtistSection = getSectionFromName(
artistList[artistPosition - 1].name ?: " "
)
val currentArtistSection = getSectionFromName(
artistList[artistPosition].name ?: " "
)
return if (previousArtistSection == currentArtistSection) "" else currentArtistSection
}
private fun getSectionFromName(name: String): String {
var section = name.first().toUpperCase()
if (!section.isLetter()) section = '#'
return section.toString()
}
private fun createPopupMenu(view: View, position: Int): Boolean {
val popup = PopupMenu(view.context, view)
val inflater: MenuInflater = popup.menuInflater
inflater.inflate(R.menu.select_artist_context, popup.menu)
val downloadMenuItem = popup.menu.findItem(R.id.artist_menu_download)
downloadMenuItem?.isVisible = !isOffline(view.context)
popup.setOnMenuItemClickListener { menuItem ->
onContextMenuClick(menuItem, artistList[position])
}
popup.show()
return true
}
companion object {
private const val TYPE_HEADER = 0
private const val TYPE_ITEM = 1
}
}
| ultrasonic/src/main/kotlin/org/moire/ultrasonic/activity/ArtistRowAdapter.kt | 2780335733 |
package uk.colessoft.android.hilllist.domain
class GeographImageDetail {
/**
* @return The title
*/
/**
* @param title The title
*/
var title: String? = null
/**
* @return The description
*/
/**
* @param description The description
*/
var description: String? = null
/**
* @return The link
*/
/**
* @param link The link
*/
var link: String? = null
/**
* @return The author
*/
/**
* @param author The author
*/
var author: String? = null
/**
* @return The category
*/
/**
* @param category The category
*/
var category: String? = null
/**
* @return The guid
*/
/**
* @param guid The guid
*/
var guid: String? = null
/**
* @return The source
*/
/**
* @param source The source
*/
var source: String? = null
/**
* @return The date
*/
/**
* @param date The date
*/
var date: Int = 0
/**
* @return The imageTaken
*/
/**
* @param imageTaken The imageTaken
*/
var imageTaken: String? = null
/**
* @return The lat
*/
/**
* @param lat The lat
*/
var lat: String? = null
/**
* @return The _long
*/
/**
* @param _long The long
*/
var long: String? = null
/**
* @return The thumb
*/
/**
* @param thumb The thumb
*/
var thumb: String? = null
/**
* @return The thumbTag
*/
/**
* @param thumbTag The thumbTag
*/
var thumbTag: String? = null
/**
* @return The licence
*/
/**
* @param licence The licence
*/
var licence: String? = null
/**
* No args constructor for use in serialization
*/
constructor() {}
/**
* @param licence
* @param link
* @param date
* @param imageTaken
* @param guid
* @param author
* @param title
* @param category
* @param source
* @param _long
* @param description
* @param thumbTag
* @param thumb
* @param lat
*/
constructor(title: String, description: String, link: String, author: String, category: String, guid: String, source: String, date: Int, imageTaken: String, lat: String, _long: String, thumb: String, thumbTag: String, licence: String) {
this.title = title
this.description = description
this.link = link
this.author = author
this.category = category
this.guid = guid
this.source = source
this.date = date
this.imageTaken = imageTaken
this.lat = lat
this.long = _long
this.thumb = thumb
this.thumbTag = thumbTag
this.licence = licence
}
} | app/src/main/java/uk/colessoft/android/hilllist/domain/GeographImageDetail.kt | 2338077791 |
package ru.arsich.messenger.mvp.models
import com.vk.sdk.api.VKError
import com.vk.sdk.api.VKRequest
import com.vk.sdk.api.VKResponse
import com.vk.sdk.api.model.VKApiGetMessagesResponse
import com.vk.sdk.api.model.VKApiMessage
import ru.arsich.messenger.vk.VKApiMessageHistory
import java.lang.Exception
class ChatRepository {
companion object {
val CHAT_PAGE_SIZE = 40
}
private val messagesSubscribers: MutableList<RequestMessagesListener> = mutableListOf()
fun addMessagesSubscriber(subscriber: RequestMessagesListener) {
messagesSubscribers.add(subscriber)
}
fun removeMessagesSubscriber(subscriber: RequestMessagesListener) {
messagesSubscribers.remove(subscriber)
}
// cache only last selected chat, no reload after orientation change
private var lastChatId: Int = -1
private var lastMessages: MutableList<VKApiMessage> = ArrayList()
fun requestMessages(chatId: Int, offset: Int = 0) {
if (chatId != lastChatId) {
// clear cache
lastMessages.clear()
lastChatId = chatId
}
if (offset < lastMessages.size) {
// return date from cache
sendMessagesToSubscribers(lastMessages.subList(offset, lastMessages.lastIndex))
return
}
val startMessageId = -1
val request = VKApiMessageHistory.get(chatId, offset, startMessageId, CHAT_PAGE_SIZE)
request.attempts = 3
request.executeWithListener(object: VKRequest.VKRequestListener() {
override fun onComplete(response: VKResponse?) {
if (response != null) {
val result = response.parsedModel as VKApiGetMessagesResponse
val list = result.items.toList()
lastMessages.addAll(list)
sendMessagesToSubscribers(list)
}
}
override fun onError(error: VKError?) {
error?.let {
if (it.httpError != null) {
sendErrorToSubscribers(it.httpError)
} else if (it.apiError != null) {
sendErrorToSubscribers(Exception(it.apiError.errorMessage))
} else {
sendErrorToSubscribers(Exception(it.errorMessage))
}
}
}
})
}
private fun sendMessagesToSubscribers(messages: List<VKApiMessage>) {
for (subscriber in messagesSubscribers) {
subscriber.onMessagesReceived(messages)
}
}
private fun sendErrorToSubscribers(error: Exception) {
for (subscriber in messagesSubscribers) {
subscriber.onMessagesError(error)
}
}
interface RequestMessagesListener {
fun onMessagesReceived(messages: List<VKApiMessage>)
fun onMessagesError(error: Exception)
}
} | app/src/main/kotlin/ru/arsich/messenger/mvp/models/ChatRepository.kt | 2483994496 |
/*
* Copyright (C) 2017 Mantas Varnagiris.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.mvcoding.expensius.feature.premium
interface Billing : BillingFlow, BillingProductsService | app/src/main/kotlin/com/mvcoding/expensius/feature/premium/Billing.kt | 3554512973 |
package com.twitter.meil_mitu.twitter4hk.api.lists.subscribers
import com.twitter.meil_mitu.twitter4hk.AbsGet
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.OauthType
import com.twitter.meil_mitu.twitter4hk.ResponseData
import com.twitter.meil_mitu.twitter4hk.converter.IUserConverter
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
class Show<TUser> : AbsGet<ResponseData<TUser>> {
protected val json: IUserConverter<TUser>
var listId: Long? by longParam("list_id")
var userId: Long? by longParam("user_id")
var screenName: String? by stringParam("screen_name")
var slug: String? by stringParam("slug")
var ownerScreenName: String? by stringParam("owner_screen_name")
var ownerId: Long? by longParam("owner_id")
var includeEntities: Boolean? by booleanParam("include_entities")
var skipStatus: Boolean? by booleanParam("skip_status")
override val url = "https://api.twitter.com/1.1/lists/subscribers/show.json"
override val allowOauthType = OauthType.oauth1 or OauthType.oauth2
override val isAuthorization = true
constructor(
oauth: AbsOauth,
json: IUserConverter<TUser>,
listId: Long,
userId: Long) : super(oauth) {
this.json = json
this.listId = listId
this.userId = userId
}
constructor(
oauth: AbsOauth,
json: IUserConverter<TUser>,
listId: Long,
screenName: String) : super(oauth) {
this.json = json
this.listId = listId
this.screenName = screenName
}
constructor(
oauth: AbsOauth,
json: IUserConverter<TUser>,
slug: String,
userId: Long) : super(oauth) {
this.json = json
this.slug = slug
this.userId = userId
}
constructor(
oauth: AbsOauth,
json: IUserConverter<TUser>,
slug: String,
screenName: String) : super(oauth) {
this.json = json
this.slug = slug
this.screenName = screenName
}
@Throws(Twitter4HKException::class)
override fun call(): ResponseData<TUser> {
return json.toUserResponseData(oauth.get(this))
}
}
| library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/lists/subscribers/Show.kt | 4067036245 |
package com.habitrpg.android.habitica.utils
import android.annotation.SuppressLint
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParseException
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.inventory.Customization
import io.realm.Realm
import io.realm.RealmList
import java.lang.reflect.Type
import java.text.SimpleDateFormat
class CustomizationDeserializer : JsonDeserializer<List<Customization>> {
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): List<Customization> {
val jsonObject = json.asJsonObject
val customizations = RealmList<Customization>()
val realm = Realm.getDefaultInstance()
val existingCustomizations = realm.copyFromRealm(realm.where(Customization::class.java).findAll())
if (jsonObject.has("shirt")) {
for (customization in existingCustomizations) {
if (jsonObject.has(customization.type)) {
var nestedObject = jsonObject.get(customization.type).asJsonObject
if (customization.category != null) {
if (nestedObject.has(customization.category)) {
nestedObject = nestedObject.get(customization.category).asJsonObject
} else {
continue
}
}
if (nestedObject.has(customization.identifier)) {
customizations.add(this.parseCustomization(customization, customization.type, customization.category, customization.identifier, nestedObject.get(customization.identifier).asJsonObject))
nestedObject.remove(customization.identifier)
}
}
}
for (type in listOf("shirt", "skin", "chair")) {
for ((key, value) in jsonObject.get(type).asJsonObject.entrySet()) {
customizations.add(this.parseCustomization(null, type, null, key, value.asJsonObject))
}
}
for ((key, value) in jsonObject.get("hair").asJsonObject.entrySet()) {
for ((key1, value1) in value.asJsonObject.entrySet()) {
customizations.add(this.parseCustomization(null, "hair", key, key1, value1.asJsonObject))
}
}
} else {
for (customization in existingCustomizations) {
if (jsonObject.has(customization.customizationSet)) {
val nestedObject = jsonObject.get(customization.customizationSet).asJsonObject
if (nestedObject.has(customization.identifier)) {
customizations.add(this.parseBackground(customization, customization.customizationSet ?: "", customization.identifier, nestedObject.get(customization.identifier).asJsonObject))
nestedObject.remove(customization.identifier)
}
}
}
for ((key, value) in jsonObject.entrySet()) {
for ((key1, value1) in value.asJsonObject.entrySet()) {
customizations.add(this.parseBackground(null, key, key1, value1.asJsonObject))
}
}
}
realm.close()
return customizations
}
private fun parseCustomization(existingCustomizaion: Customization?, type: String?, category: String?, key: String?, entry: JsonObject): Customization {
var customization = existingCustomizaion
if (customization == null) {
customization = Customization()
customization.identifier = key
customization.type = type
if (category != null) {
customization.category = category
}
}
if (entry.has("price")) {
customization.price = entry.get("price").asInt
}
if (entry.has("set")) {
val setInfo = entry.get("set").asJsonObject
customization.customizationSet = setInfo.get("key").asString
if (setInfo.has("setPrice")) {
customization.setPrice = setInfo.get("setPrice").asInt
}
if (setInfo.has("text")) {
customization.customizationSetName = setInfo.get("text").asString
}
@SuppressLint("SimpleDateFormat") val format = SimpleDateFormat("yyyy-MM-dd")
try {
if (setInfo.has("availableFrom")) {
customization.availableFrom = format.parse(setInfo.get("availableFrom").asString)
}
if (setInfo.has("availableUntil")) {
customization.availableUntil = format.parse(setInfo.get("availableUntil").asString)
}
} catch (e: Exception) {
RxErrorHandler.reportError(e)
}
}
return customization
}
private fun parseBackground(existingCustomization: Customization?, setName: String, key: String?, entry: JsonObject): Customization {
var customization = existingCustomization
if (customization == null) {
customization = Customization()
customization.customizationSet = setName
val readableSetName = setName.substring(13, 17) + "." + setName.substring(11, 13)
customization.customizationSetName = readableSetName
customization.type = "background"
customization.identifier = key
}
when (setName) {
"incentiveBackgrounds" -> {
customization.customizationSetName = "Login Incentive"
customization.price = 0
customization.setPrice = 0
customization.isBuyable = false
}
"timeTravelBackgrounds" -> {
customization.customizationSetName = "Time Travel Backgrounds"
customization.price = 1
customization.setPrice = 0
customization.isBuyable = false
}
else -> {
customization.price = 7
customization.setPrice = 15
}
}
customization.text = entry.get("text").asString
customization.notes = entry.asJsonObject.get("notes").asString
return customization
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/utils/CustomizationDeserializer.kt | 424546816 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package androidx.fragment.lint
import androidx.fragment.lint.stubs.BACK_CALLBACK_STUBS
import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.checks.infrastructure.TestFile
import com.android.tools.lint.checks.infrastructure.TestLintResult
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class BackPressedDispatcherCallbackDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = UnsafeFragmentLifecycleObserverDetector()
override fun getIssues(): MutableList<Issue> =
mutableListOf(UnsafeFragmentLifecycleObserverDetector.BACK_PRESSED_ISSUE)
private fun check(vararg files: TestFile): TestLintResult {
return lint().files(*files, *BACK_CALLBACK_STUBS)
.run()
}
@Test
fun pass() {
check(
kotlin(
"""
package com.example
import androidx.fragment.app.Fragment
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedCallback
import com.example.test.Foo
class TestFragment : Fragment {
override fun onCreateView() {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(getViewLifecycleOwner(), OnBackPressedCallback {})
}
override fun onViewCreated() {
test()
val foo = Foo()
foo.addCallback(this)
foo.callback(this)
}
private fun test() {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(getViewLifecycleOwner(), OnBackPressedCallback {})
test()
}
}
"""
),
kotlin(
"""
package com.example.test
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedCallback
class Foo {
fun addCallback(fragment: Fragment) {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(LifecycleOwner(), OnBackPressedCallback {})
}
fun callback(fragment: Fragment) {}
}
"""
)
)
.expectClean()
}
@Test
fun inMethodFails() {
check(
kotlin(
"""
package com.example
import androidx.fragment.app.Fragment
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedCallback
class TestFragment : Fragment {
override fun onCreateView() {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(this, OnBackPressedCallback {})
}
}
"""
)
)
.expect(
"""
src/com/example/TestFragment.kt:12: Error: Use viewLifecycleOwner as the LifecycleOwner. [FragmentBackPressedCallback]
dispatcher.addCallback(this, OnBackPressedCallback {})
~~~~
1 errors, 0 warnings
"""
)
.checkFix(
null,
kotlin(
"""
package com.example
import androidx.fragment.app.Fragment
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedCallback
class TestFragment : Fragment {
override fun onCreateView() {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(viewLifecycleOwner, OnBackPressedCallback {})
}
}
"""
)
)
}
@Test
fun helperMethodFails() {
check(
kotlin(
"""
package com.example
import androidx.fragment.app.Fragment
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedCallback
class TestFragment : Fragment {
override fun onCreateView() {
test()
}
private fun test() {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(this, OnBackPressedCallback {})
}
}
"""
)
)
.expect(
"""
src/com/example/TestFragment.kt:16: Error: Use viewLifecycleOwner as the LifecycleOwner. [FragmentBackPressedCallback]
dispatcher.addCallback(this, OnBackPressedCallback {})
~~~~
1 errors, 0 warnings
"""
)
.checkFix(
null,
kotlin(
"""
package com.example
import androidx.fragment.app.Fragment
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedCallback
class TestFragment : Fragment {
override fun onCreateView() {
test()
}
private fun test() {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(viewLifecycleOwner, OnBackPressedCallback {})
}
}
"""
)
)
}
@Test
fun externalCallFails() {
check(
kotlin(
"""
package com.example
import androidx.fragment.app.Fragment
import com.example.test.Foo
class TestFragment : Fragment {
override fun onCreateView() {
test()
}
private fun test() {
val foo = Foo()
foo.addCallback(this)
}
}
"""
),
kotlin(
"""
package com.example.test
import androidx.fragment.app.Fragment
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedCallback
class Foo {
fun addCallback(fragment: Fragment) {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(fragment, OnBackPressedCallback {})
}
}
"""
)
)
.expect(
"""
src/com/example/test/Foo.kt:11: Error: Unsafe call to addCallback with Fragment instance as LifecycleOwner from TestFragment.onCreateView. [FragmentBackPressedCallback]
dispatcher.addCallback(fragment, OnBackPressedCallback {})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
"""
)
}
@Test
fun externalHelperMethodFails() {
check(
kotlin(
"""
package com.example
import androidx.fragment.app.Fragment
import com.example.test.Foo
class TestFragment : Fragment {
override fun onCreateView() {
test()
}
private fun test() {
val foo = Foo()
foo.addCallback(this)
}
}
"""
),
kotlin(
"""
package com.example.test
import androidx.fragment.app.Fragment
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedCallback
class Foo {
private lateinit val fragment: Fragment
fun addCallback(fragment: Fragment) {
this.fragment = fragment
callback()
}
private fun callback() {
val dispatcher = OnBackPressedDispatcher()
dispatcher.addCallback(fragment, OnBackPressedCallback {})
}
}
"""
)
)
.expect(
"""
src/com/example/test/Foo.kt:18: Error: Unsafe call to addCallback with Fragment instance as LifecycleOwner from TestFragment.onCreateView. [FragmentBackPressedCallback]
dispatcher.addCallback(fragment, OnBackPressedCallback {})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 errors, 0 warnings
"""
)
}
}
| fragment/fragment-lint/src/test/java/androidx/fragment/lint/BackPressedDispatcherCallbackDetectorTest.kt | 4069566999 |
/*
* 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.paging
import androidx.paging.LoadState.NotLoading
internal class MutableLoadStateCollection {
var refresh: LoadState = NotLoading.Incomplete
var prepend: LoadState = NotLoading.Incomplete
var append: LoadState = NotLoading.Incomplete
fun snapshot() = LoadStates(
refresh = refresh,
prepend = prepend,
append = append,
)
fun get(loadType: LoadType) = when (loadType) {
LoadType.REFRESH -> refresh
LoadType.APPEND -> append
LoadType.PREPEND -> prepend
}
fun set(type: LoadType, state: LoadState) = when (type) {
LoadType.REFRESH -> refresh = state
LoadType.APPEND -> append = state
LoadType.PREPEND -> prepend = state
}
fun set(states: LoadStates) {
refresh = states.refresh
append = states.append
prepend = states.prepend
}
} | paging/paging-common/src/main/kotlin/androidx/paging/MutableLoadStateCollection.kt | 2917055035 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opencl.templates
import org.lwjgl.generator.*
import org.lwjgl.opencl.*
val khr_fp64 = "KHRFP64".nativeClassCL("khr_fp64", KHR) {
documentation = "Native bindings to the $extensionLink extension."
IntConstant(
"cl_device_info",
"DEVICE_DOUBLE_FP_CONFIG"..0x1032
)
} | modules/templates/src/main/kotlin/org/lwjgl/opencl/templates/khr_fp64.kt | 329137216 |
/*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.database.table
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import org.andstatus.app.data.DbUtils
import org.andstatus.app.data.DownloadStatus
/**
* Table for both public and private notes
* i.e. for tweets, dents, notices
* and also for "direct messages", "direct dents" etc.
*/
object NoteTable : BaseColumns {
val TABLE_NAME: String = "note"
// Table columns are below:
/*
* {@link BaseColumns#_ID} is primary key in this database
* No, we can not rename the {@link BaseColumns#_ID}, it should always be "_id".
* See <a href="http://stackoverflow.com/questions/3359414/android-column-id-does-not-exist">Android column '_id' does not exist?</a>
*/
/**
* ID of the originating (source) system ("Social Network": twitter.com, identi.ca, ... ) where the row was created
*/
val ORIGIN_ID: String = OriginTable.ORIGIN_ID
/**
* ID in the originating system
* The id is not unique for this table, because we have IDs from different systems in one column
* and IDs from different systems may overlap.
*/
val NOTE_OID: String = "note_oid"
/**
* See [DownloadStatus]. Defaults to [DownloadStatus.UNKNOWN]
*/
val NOTE_STATUS: String = "note_status"
/** Conversation ID, internal to AndStatus */
val CONVERSATION_ID: String = "conversation_id"
/** ID of the conversation in the originating system (if the system supports this) */
val CONVERSATION_OID: String = "conversation_oid"
/**
* A link to the representation of the resource. Currently this is simply URL to the HTML
* representation of the resource (its "permalink")
*/
val URL: String = "url"
/** A simple, human-readable, plain-text name for the Note */
val NAME: String = "note_name"
/** A natural language summarization of the object.
* Used as a Content Warning (CW) if [.SENSITIVE] flag is set.
*/
val SUMMARY: String = "summary"
/** Content of the note */
val CONTENT: String = "content"
/** Name and Content text, prepared for easy searching in a database */
val CONTENT_TO_SEARCH: String = "content_to_search"
/**
* String generally describing Client's software used to post this note
* It's like "User Agent" string in the browsers?!: "via ..."
* (This is "source" field in tweets)
*/
val VIA: String = "via"
/**
* If not null: Link to the #_ID in this table
*/
val IN_REPLY_TO_NOTE_ID: String = "in_reply_to_note_id"
/**
* Date and time when the note was created or updated in the originating system.
* We store it as long milliseconds.
*/
val UPDATED_DATE: String = "note_updated_date"
/** Date and time when the Note was first LOADED into this database
* or if it was not LOADED yet, when the row was inserted into this database */
val INS_DATE: String = "note_ins_date"
/** [org.andstatus.app.net.social.Visibility] */
val VISIBILITY: String = "public" // TODO: rename
/** Indicates that some users may wish to apply discretion about viewing its content, whether due to nudity,
* violence, or any other likely aspects that viewers may be sensitive to.
* See [Activity Streams extensions](https://www.w3.org/wiki/Activity_Streams_extensions#as:sensitive_property) */
val SENSITIVE: String = "sensitive"
/** Some of my accounts favorited this note */
val FAVORITED: String = "favorited"
/** The Note is reblogged by some of my actors
* In some sense REBLOGGED is like FAVORITED.
* Main difference: visibility. REBLOGGED are shown for all followers in their Home timelines.
*/
val REBLOGGED: String = "reblogged"
val LIKES_COUNT: String = "favorite_count" // TODO: rename
val REBLOGS_COUNT: String = "reblog_count" // TODO: rename
val REPLIES_COUNT: String = "reply_count" // TODO: rename. To be calculated locally?!
val ATTACHMENTS_COUNT: String = "attachments_count"
// Columns, which duplicate other existing info. Here to speed up data retrieval
val AUTHOR_ID: String = "note_author_id"
/**
* If not null: to which Sender this note is a reply = Actor._ID
* This field is not necessary but speeds up IN_REPLY_TO_NAME calculation
*/
val IN_REPLY_TO_ACTOR_ID: String = "in_reply_to_actor_id"
// Derived columns (they are not stored in this table but are result of joins and aliasing)
/** Alias for the primary key */
val NOTE_ID: String = "note_id"
fun create(db: SQLiteDatabase) {
DbUtils.execSQL(db, "CREATE TABLE " + TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ORIGIN_ID + " INTEGER NOT NULL,"
+ NOTE_OID + " TEXT NOT NULL,"
+ NOTE_STATUS + " INTEGER NOT NULL DEFAULT 0,"
+ CONVERSATION_ID + " INTEGER NOT NULL DEFAULT 0" + ","
+ CONVERSATION_OID + " TEXT,"
+ URL + " TEXT,"
+ NAME + " TEXT,"
+ SUMMARY + " TEXT,"
+ CONTENT + " TEXT,"
+ CONTENT_TO_SEARCH + " TEXT,"
+ VIA + " TEXT,"
+ AUTHOR_ID + " INTEGER NOT NULL DEFAULT 0,"
+ IN_REPLY_TO_NOTE_ID + " INTEGER,"
+ IN_REPLY_TO_ACTOR_ID + " INTEGER,"
+ VISIBILITY + " INTEGER NOT NULL DEFAULT 0,"
+ SENSITIVE + " INTEGER NOT NULL DEFAULT 0,"
+ FAVORITED + " INTEGER NOT NULL DEFAULT 0,"
+ REBLOGGED + " INTEGER NOT NULL DEFAULT 0,"
+ LIKES_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ REBLOGS_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ REPLIES_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ ATTACHMENTS_COUNT + " INTEGER NOT NULL DEFAULT 0,"
+ INS_DATE + " INTEGER NOT NULL,"
+ UPDATED_DATE + " INTEGER NOT NULL DEFAULT 0"
+ ")")
DbUtils.execSQL(db, "CREATE UNIQUE INDEX idx_note_origin ON " + TABLE_NAME + " ("
+ ORIGIN_ID + ", "
+ NOTE_OID
+ ")"
)
// Index not null rows only, see https://www.sqlite.org/partialindex.html
DbUtils.execSQL(db, "CREATE INDEX idx_note_in_reply_to_note_id ON " + TABLE_NAME + " ("
+ IN_REPLY_TO_NOTE_ID
+ ")"
)
DbUtils.execSQL(db, "CREATE INDEX idx_note_conversation_id ON " + TABLE_NAME + " ("
+ CONVERSATION_ID
+ ")"
)
DbUtils.execSQL(db, "CREATE INDEX idx_conversation_oid ON " + TABLE_NAME + " ("
+ ORIGIN_ID + ", "
+ CONVERSATION_OID
+ ")"
)
}
}
| app/src/main/kotlin/org/andstatus/app/database/table/NoteTable.kt | 1154747338 |
package ru.fantlab.android.data.dao.response
import com.github.kittinunf.fuel.core.ResponseDeserializable
import ru.fantlab.android.data.dao.model.BlogArticle
import ru.fantlab.android.provider.rest.DataManager
data class BlogArticlesVoteResponse(
val likesCount: String
) {
class Deserializer : ResponseDeserializable<BlogArticlesVoteResponse> {
override fun deserialize(content: String): BlogArticlesVoteResponse {
val article = DataManager.gson.fromJson(content, BlogArticle.Article.Stats::class.java)
return BlogArticlesVoteResponse(article.likeCount ?: "0")
}
}
} | app/src/main/kotlin/ru/fantlab/android/data/dao/response/BlogArticlesVoteResponse.kt | 964870318 |
/**
* Copyright © MyCollab
*
* 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.mycollab.common.service
import com.mycollab.cache.IgnoreCacheClass
import com.mycollab.common.domain.MonitorItem
import com.mycollab.common.domain.criteria.MonitorSearchCriteria
import com.mycollab.db.persistence.service.IDefaultService
import com.mycollab.module.user.domain.SimpleUser
/**
* @author MyCollab Ltd.
* @since 1.0
*/
@IgnoreCacheClass
interface MonitorItemService : IDefaultService<Int, MonitorItem, MonitorSearchCriteria> {
fun isUserWatchingItem(username: String, type: String, typeId: String): Boolean
fun getWatchers(type: String, typeId: Int): List<SimpleUser>
fun saveMonitorItems(monitorItems: Collection<MonitorItem>)
}
| mycollab-services/src/main/java/com/mycollab/common/service/MonitorItemService.kt | 3694792528 |
package org.remdev.android.kotlinapp.activity.presenters
import android.support.v4.app.FragmentActivity
import org.remdev.android.kotlinapp.StatusCodes
import org.remdev.android.kotlinapp.activity.BaseKotlinAppActivity
import org.remdev.android.kotlinapp.commanders.WeatherCommander
import org.remdev.android.kotlinapp.models.WeatherItem
import org.remdev.android.kotlinapp.rest.*
class WeatherPresenter (
private val activity : FragmentActivity,
private val callback : WeatherPresenterCallback
) : WeatherDriver.WeatherDriverCallback {
private val commander : WeatherCommander
init {
commander = WeatherCommander(activity, this@WeatherPresenter)
commander.connectService()
}
fun loadWeather(city : String) {
if (activity is BaseKotlinAppActivity) {
activity.showProgress("Loading $city weather")
}
commander.loadWeather(city)
}
override fun onWeatherLoaded(success: Boolean, errorCode: Int, itemList: MutableList<WeatherItem>?) {
if (activity is BaseKotlinAppActivity) {
activity.hideProgress()
}
if (success) {
callback.onLoaded(itemList!!)
} else {
val msg = when(errorCode) {
StatusCodes.ERROR_CODE_CITY_NOT_FOUND -> "City was not found"
StatusCodes.ERROR_CODE_CONNECTION_BROKEN -> "No Internet connection"
else -> "Unknown error"
}
activity.toast(msg)
}
}
fun destroy() {
commander.disconnect()
}
interface WeatherPresenterCallback {
fun onLoaded(data: List<WeatherItem>);
}
} | commander-sample-app/src/main/java/org/remdev/android/kotlinapp/activity/presenters/WeatherPresenter.kt | 501685840 |
/*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.domain.model
import android.content.Context
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
interface OpenUriModel {
fun openUri(context: Context, uri: String)
fun setUseCustomTabs(use: Boolean)
fun mayLaunchUrl(url: String)
fun mayLaunchUrl(urls: List<String>)
}
| mobile/src/main/java/net/mm2d/dmsexplorer/domain/model/OpenUriModel.kt | 892286513 |
package org.jetbrains.haskell.external
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nullable
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.ModuleUtilCore
import org.json.simple.JSONArray
import java.io.File
import org.jetbrains.haskell.util.copyFile
import org.json.simple.JSONObject
import org.jetbrains.haskell.util.LineColPosition
import com.intellij.openapi.vfs.LocalFileSystem
import java.util.HashSet
import sun.nio.cs.StandardCharsets
import java.io.ByteArrayInputStream
import org.jetbrains.haskell.util.getRelativePath
import com.intellij.openapi.application.ModalityState
import java.util.regex.Pattern
import java.util.ArrayList
import org.jetbrains.haskell.config.HaskellSettings
public class HaskellExternalAnnotator() : ExternalAnnotator<PsiFile, List<ErrorMessage>>() {
override fun collectInformation(file: PsiFile): PsiFile {
return file
}
fun copyContent(basePath: VirtualFile, destination: File) {
if (!destination.exists()) {
destination.mkdir()
}
val localFileSystem = LocalFileSystem.getInstance()!!
val destinationFiles = HashSet(destination.list()!!.toList())
for (child in basePath.getChildren()!!) {
destinationFiles.remove(child.getName())
if (child.getName().equals(".idea")) {
continue
}
if (child.getName().equals("dist")) {
continue
}
if (child.getName().equals(".buildwrapper")) {
continue
}
val destinationFile = File(destination, child.getName())
if (child.isDirectory()) {
copyContent(child, destinationFile)
} else {
val childTime = child.getModificationStamp()
val document = FileDocumentManager.getInstance().getCachedDocument(child)
if (document != null) {
val stream = ByteArrayInputStream(document.getText().toByteArray(child.getCharset()));
copyFile(stream, destinationFile)
} else {
val destinationTime = localFileSystem.findFileByIoFile(destinationFile)?.getModificationStamp()
if (destinationTime == null || childTime > destinationTime) {
copyFile(child.getInputStream()!!, destinationFile)
}
}
}
}
for (file in destinationFiles) {
if (file.endsWith(".hs")) {
File(destination, file).delete()
}
}
}
fun getResultFromGhcModi(psiFile: PsiFile,
baseDir: VirtualFile,
file: VirtualFile): List<ErrorMessage> {
ApplicationManager.getApplication()!!.invokeAndWait(object : Runnable {
override fun run() {
FileDocumentManager.getInstance().saveAllDocuments()
}
}, ModalityState.any())
val ghcModi = psiFile.getProject().getComponent(javaClass<GhcModi>())!!
val relativePath = getRelativePath(baseDir.getPath(), file.getPath())
val result = ghcModi.runCommand("check $relativePath")
val errors = ArrayList<ErrorMessage>()
for (resultLine in result) {
val matcher = Pattern.compile("(.*):(\\d*):(\\d*):(.*)").matcher(resultLine)
if (matcher.find()) {
val path = matcher.group(1)!!
val line = Integer.parseInt(matcher.group(2)!!)
val col = Integer.parseInt(matcher.group(3)!!)
val msg = matcher.group(4)!!.replace("\u0000", "\n")
val severity = if (msg.startsWith("Warning")) {
ErrorMessage.Severity.Warning
} else {
ErrorMessage.Severity.Error
}
if (relativePath == path) {
errors.add(ErrorMessage(msg, path, severity, line, col, line, col))
}
}
}
return errors
}
fun getResultFromBuidWrapper(psiFile: PsiFile,
moduleContent: VirtualFile,
file: VirtualFile): List<ErrorMessage> {
ApplicationManager.getApplication()!!.invokeAndWait(object : Runnable {
override fun run() {
FileDocumentManager.getInstance().saveAllDocuments()
}
}, ModalityState.any())
copyContent(moduleContent, File(moduleContent.getCanonicalPath()!!, ".buildwrapper"))
val out = BuildWrapper.init(psiFile).build1(file)
if (out != null) {
val errors = out.get(1) as JSONArray
return errors.map {
ErrorMessage.fromJson(it!!)
}
}
return listOf()
}
fun getProjectBaseDir(psiFile: PsiFile): VirtualFile? {
return psiFile.getProject().getBaseDir()
}
override fun doAnnotate(psiFile: PsiFile?): List<ErrorMessage> {
val file = psiFile!!.getVirtualFile()
if (file == null) {
return listOf()
}
val baseDir = getProjectBaseDir(psiFile)
if (baseDir == null) {
return listOf()
}
if (!(HaskellSettings.getInstance().getState().useGhcMod!!)) {
return listOf();
}
if (!file.isInLocalFileSystem()) {
return listOf()
}
return getResultFromGhcModi(psiFile, baseDir, file)
}
override fun apply(file: PsiFile, annotationResult: List<ErrorMessage>?, holder: AnnotationHolder) {
for (error in annotationResult!!) {
val start = LineColPosition(error.line, error.column).getOffset(file)
val end = LineColPosition(error.eLine, error.eColumn).getOffset(file)
val element = file.findElementAt(start)
if (element != null) {
when (error.severity) {
ErrorMessage.Severity.Error -> holder.createErrorAnnotation(element, error.text);
ErrorMessage.Severity.Warning -> holder.createWarningAnnotation(element, error.text);
}
} else {
when (error.severity) {
ErrorMessage.Severity.Error -> holder.createErrorAnnotation(TextRange(start, end), error.text);
ErrorMessage.Severity.Warning -> holder.createWarningAnnotation(TextRange(start, end), error.text);
}
}
}
}
}
| plugin/src/org/jetbrains/haskell/external/HaskellExternalAnnotator.kt | 1615247760 |
package com.designdemo.uaha
import android.app.Application
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
import androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
import com.designdemo.uaha.util.PREF_DARK_MODE
import com.designdemo.uaha.util.PREF_FILE
class HistorianApplication : Application() {
companion object {
private const val TAG = "HistorianApplication"
}
override fun onCreate() {
super.onCreate()
// The default value is different after Android Q
val defaultNightMode = when (Build.VERSION.SDK_INT) {
in Int.MIN_VALUE..Build.VERSION_CODES.P -> MODE_NIGHT_AUTO_BATTERY
else -> MODE_NIGHT_FOLLOW_SYSTEM
}
Log.d("MSW", "This is the default nigh tmode setting: $defaultNightMode")
// If the user has previously set a value for darkMode, use that
val sharedPref = applicationContext.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE)
?: return
val darkMode = sharedPref.getInt(PREF_DARK_MODE, defaultNightMode)
Log.d(TAG, "MSW Historian Value $darkMode and the current value for Build.VERSION.SDK_INT is ${Build.VERSION.SDK_INT}")
AppCompatDelegate.setDefaultNightMode(darkMode)
}
} | app/src/main/java/com/designdemo/uaha/HistorianApplication.kt | 1122707907 |
package org.smileLee.cyls.qqbot
import sun.dc.path.PathException
class TreeNode<T : QQBot<T>> {
interface RunnerForJava<T : QQBot<T>> {
fun run(str: String, qqBot: T)
}
val name: String
val runner: (String, T) -> Unit
val children = HashMap<String, TreeNode<T>>()
//used in kotlin
constructor(name: String, parent: TreeNode<T>, runner: (String, T) -> Unit) {
this.name = name
this.runner = runner
parent.children.put(name, this)
}
constructor(name: String, runner: (String, T) -> Unit) {
this.name = name
this.runner = runner
}
//used in java
constructor(name: String, parent: TreeNode<T>?, runner: RunnerForJava<T>) {
this.name = name
this.runner = { str, qqBot -> runner.run(str, qqBot) }
parent?.children?.put(name, this)
}
constructor(name: String, runner: RunnerForJava<T>) {
this.name = name
this.runner = { str, cyls -> runner.run(str, cyls) }
}
fun findPath(path: List<String>, index: Int = 0): TreeNode<T> = if (index == path.size) this
else children[path[index]]?.findPath(path, index + 1) ?: throw PathException()
fun run(message: String, qqBot: T) = runner(message, qqBot)
}
| src/main/kotlin/org/smileLee/cyls/qqbot/TreeNode.kt | 2354674713 |
package ktx
const val gdxVersion = "1.10.0"
const val kotlinCoroutinesVersion = "1.6.0"
const val ashleyVersion = "1.7.4"
const val visUiVersion = "1.5.0"
const val spekVersion = "1.2.1"
const val kotlinTestVersion = "2.0.7"
const val kotlinMockitoVersion = "2.1.0"
const val assertjVersion = "3.11.1"
const val junitVersion = "4.12"
const val slf4jVersion = "1.7.26"
const val wireMockVersion = "2.24.0"
const val ktlintVersion = "0.42.1"
| buildSrc/src/main/kotlin/ktx/Versions.kt | 2469834105 |
package de.tum.`in`.tumcampusapp.component.ui.transportation.api
data class MvvServingLine(
val name: String = "",
val direction: String = "",
val symbol: String = ""
)
| app/src/main/java/de/tum/in/tumcampusapp/component/ui/transportation/api/MvvServingLine.kt | 3762316835 |
package de.tum.`in`.tumcampusapp.component.ui.overview
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.content.Intent.ACTION_VIEW
import android.content.pm.PackageManager.NameNotFoundException
import android.net.Uri
import android.os.Bundle
import android.preference.PreferenceManager
import android.text.format.DateUtils
import android.view.View
import android.view.ViewGroup
import android.widget.TableLayout
import android.widget.TableRow
import android.widget.TextView
import androidx.core.content.pm.PackageInfoCompat
import de.psdev.licensesdialog.LicensesDialog
import de.tum.`in`.tumcampusapp.BuildConfig
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Utils
import kotlinx.android.synthetic.main.activity_information.*
/**
* Provides information about this app and all contributors
*/
class InformationActivity : BaseActivity(R.layout.activity_information) {
private val rowParams = TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.displayDebugInfo()
button_facebook.setOnClickListener {
openFacebook()
}
button_github.setOnClickListener {
startActivity(Intent(ACTION_VIEW, Uri.parse(getString(R.string.github_link))))
}
button_privacy.setOnClickListener {
startActivity(Intent(ACTION_VIEW, Uri.parse(getString(R.string.url_privacy_policy))))
}
button_licenses.setOnClickListener {
LicensesDialog.Builder(this)
.setNotices(R.raw.notices)
.setShowFullLicenseText(false)
.setIncludeOwnLicense(true)
.build()
.show()
}
}
/**
* Open the Facebook app or view page in a browser if Facebook is not installed.
*/
private fun openFacebook() {
try {
packageManager.getPackageInfo("com.facebook.katana", 0)
val intent = Intent(ACTION_VIEW, Uri.parse(getString(R.string.facebook_link_app)))
startActivity(intent)
} catch (e: Exception) {
// Don't make any assumptions about another app, just start the browser instead
val default = Intent(ACTION_VIEW, Uri.parse(getString(R.string.facebook_link)))
startActivity(default)
}
}
private fun displayDebugInfo() {
// Setup showing of debug information
val sp = PreferenceManager.getDefaultSharedPreferences(this)
try {
val packageInfo = packageManager.getPackageInfo(packageName, 0)
this.addDebugRow(debugInfos, "App version", packageInfo.versionName)
} catch (ignore: NameNotFoundException) {
}
this.addDebugRow(debugInfos, "TUM ID", sp.getString(Const.LRZ_ID, ""))
val token = sp.getString(Const.ACCESS_TOKEN, "")
if (token == "") {
this.addDebugRow(debugInfos, "TUM access token", "")
} else {
this.addDebugRow(debugInfos, "TUM access token", token?.substring(0, 5) + "...")
}
this.addDebugRow(debugInfos, "Bug reports", sp.getBoolean(Const.BUG_REPORTS, false).toString() + " ")
this.addDebugRow(debugInfos, "REG ID", Utils.getSetting(this, Const.FCM_REG_ID, ""))
this.addDebugRow(debugInfos, "REG transmission", DateUtils.getRelativeDateTimeString(this,
Utils.getSettingLong(this, Const.FCM_REG_ID_LAST_TRANSMISSION, 0),
DateUtils.MINUTE_IN_MILLIS, DateUtils.DAY_IN_MILLIS * 2, 0).toString())
try {
val packageInfo = packageManager.getPackageInfo(packageName, 0)
this.addDebugRow(debugInfos, "Version code", PackageInfoCompat.getLongVersionCode(packageInfo).toString())
} catch (ignore: NameNotFoundException) {
}
this.addDebugRow(debugInfos, "Build configuration", BuildConfig.DEBUG.toString())
debugInfos.visibility = View.VISIBLE
}
private fun addDebugRow(tableLayout: TableLayout, label: String, value: String?) {
val tableRow = TableRow(this)
tableRow.layoutParams = rowParams
val labelTextView = TextView(this).apply {
text = label
layoutParams = rowParams
val padding = resources.getDimensionPixelSize(R.dimen.material_small_padding)
setPadding(0, 0, padding, 0)
}
tableRow.addView(labelTextView)
val valueTextView = TextView(this).apply {
text = value
layoutParams = rowParams
isClickable = true
setOnLongClickListener {
val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(label, value)
clipboard.setPrimaryClip(clip)
true
}
}
tableRow.addView(valueTextView)
tableLayout.addView(tableRow)
}
}
| app/src/main/java/de/tum/in/tumcampusapp/component/ui/overview/InformationActivity.kt | 3536778109 |
package de.tum.`in`.tumcampusapp.component.ui.chat
import android.view.View
import android.widget.TextView
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatMessage
import de.tum.`in`.tumcampusapp.component.ui.overview.CardInteractionListener
import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder
import kotlinx.android.synthetic.main.card_chat_messages.view.*
class ChatMessagesCardViewHolder(
itemView: View,
interactionListener: CardInteractionListener
) : CardViewHolder(itemView, interactionListener) {
@Suppress("UNUSED_PARAMETER")
fun bind(roomName: String, roomId: Int, roomIdStr: String, unreadMessages: List<ChatMessage>) {
with(itemView) {
chatRoomNameTextView.text = if (unreadMessages.size > 5) {
context.getString(R.string.card_message_title, roomName, unreadMessages.size)
} else {
roomName
}
if (contentContainerLayout.childCount == 0) {
// We have not yet inflated the chat messages
unreadMessages.asSequence()
.map { message ->
val memberName = message.member.displayName
context.getString(R.string.card_message_line, memberName, message.text)
}
.map { messageText ->
TextView(context, null, R.style.CardBody).apply {
text = messageText
}
}
.toList()
.forEach { textView ->
contentContainerLayout.addView(textView)
}
}
}
}
} | app/src/main/java/de/tum/in/tumcampusapp/component/ui/chat/ChatMessagesCardViewHolder.kt | 1812440619 |
package com.google.firebase.example.mlkit.kotlin
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.OnFailureListener
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.face.FirebaseVisionFace
import com.google.firebase.ml.vision.face.FirebaseVisionFaceContour
import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions
import com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark
class FaceDetectionActivity : AppCompatActivity() {
private fun detectFaces(image: FirebaseVisionImage) {
// [START set_detector_options]
val options = FirebaseVisionFaceDetectorOptions.Builder()
.setClassificationMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
.setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
.setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
.setMinFaceSize(0.15f)
.enableTracking()
.build()
// [END set_detector_options]
// [START get_detector]
val detector = FirebaseVision.getInstance()
.getVisionFaceDetector(options)
// [END get_detector]
// [START fml_run_detector]
val result = detector.detectInImage(image)
.addOnSuccessListener { faces ->
// Task completed successfully
// [START_EXCLUDE]
// [START get_face_info]
for (face in faces) {
val bounds = face.boundingBox
val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees
val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees
// If landmark detection was enabled (mouth, ears, eyes, cheeks, and
// nose available):
val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR)
leftEar?.let {
val leftEarPos = leftEar.position
}
// If classification was enabled:
if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
val smileProb = face.smilingProbability
}
if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
val rightEyeOpenProb = face.rightEyeOpenProbability
}
// If face tracking was enabled:
if (face.trackingId != FirebaseVisionFace.INVALID_ID) {
val id = face.trackingId
}
}
// [END get_face_info]
// [END_EXCLUDE]
}
.addOnFailureListener { e ->
// Task failed with an exception
// ...
}
// [END fml_run_detector]
}
private fun faceOptionsExamples() {
// [START mlkit_face_options_examples]
// High-accuracy landmark detection and face classification
val highAccuracyOpts = FirebaseVisionFaceDetectorOptions.Builder()
.setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
.setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
.setClassificationMode(FirebaseVisionFaceDetectorOptions.ALL_CLASSIFICATIONS)
.build()
// Real-time contour detection of multiple faces
val realTimeOpts = FirebaseVisionFaceDetectorOptions.Builder()
.setContourMode(FirebaseVisionFaceDetectorOptions.ALL_CONTOURS)
.build()
// [END mlkit_face_options_examples]
}
private fun processFaceList(faces: List<FirebaseVisionFace>) {
// [START mlkit_face_list]
for (face in faces) {
val bounds = face.boundingBox
val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees
val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees
// If landmark detection was enabled (mouth, ears, eyes, cheeks, and
// nose available):
val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR)
leftEar?.let {
val leftEarPos = leftEar.position
}
// If contour detection was enabled:
val leftEyeContour = face.getContour(FirebaseVisionFaceContour.LEFT_EYE).points
val upperLipBottomContour = face.getContour(FirebaseVisionFaceContour.UPPER_LIP_BOTTOM).points
// If classification was enabled:
if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
val smileProb = face.smilingProbability
}
if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
val rightEyeOpenProb = face.rightEyeOpenProbability
}
// If face tracking was enabled:
if (face.trackingId != FirebaseVisionFace.INVALID_ID) {
val id = face.trackingId
}
}
// [END mlkit_face_list]
}
}
| mlkit/app/src/main/java/com/google/firebase/example/mlkit/kotlin/FaceDetectionActivity.kt | 859735422 |
package cz.richter.david.astroants
import java.util.*
fun <T> indexedArrayListSpliterator(iterable: Iterable<IndexedValue<T>>, size: Int): Spliterator<IndexedValue<T>> =
Spliterators.spliterator(iterable.iterator(), size.toLong(),
Spliterator.ORDERED.or(Spliterator.SIZED).or(Spliterator.SUBSIZED).or(Spliterator.NONNULL))
| src/main/kotlin/cz/richter/david/astroants/Utils.kt | 2487556511 |
package sqlbuilder.impl.mappers
import sqlbuilder.mapping.BiMapper
import sqlbuilder.mapping.ToObjectMappingParameters
import sqlbuilder.mapping.ToSQLMappingParameters
import java.sql.Types
/**
* @author Laurent Van der Linden.
*/
class CharMapper : BiMapper {
override fun toObject(params: ToObjectMappingParameters): Char? {
val string = params.resultSet.getString(params.index)
if (string != null && string.isNotEmpty()) return string[0]
return null
}
override fun toSQL(params: ToSQLMappingParameters) {
if (params.value == null) {
params.preparedStatement.setNull(params.index, Types.VARCHAR)
} else {
params.preparedStatement.setString(params.index, params.value.toString())
}
}
override fun handles(targetType: Class<*>): Boolean {
return targetType == Char::class.java || java.lang.Character::class.java == targetType
}
} | src/main/kotlin/sqlbuilder/impl/mappers/CharMapper.kt | 1441977329 |
package org.stepic.droid.notifications
import java.util.Calendar
import javax.inject.Inject
class NotificationTimeCheckerImpl
@Inject constructor(
private var startHour: Int,
private var endHour: Int)
: NotificationTimeChecker {
private val invertAnswer: Boolean
init {
if (endHour < 0 || startHour < 0) {
throw IllegalArgumentException("interval bounds cannot be negative")
}
if (endHour > 23 || startHour > 23) {
throw IllegalArgumentException("interval bounds cannot be greater than 23")
}
if (endHour >= startHour) {
invertAnswer = false
} else {
startHour = startHour.xor(endHour)
endHour = startHour.xor(endHour)
startHour = startHour.xor(endHour)
invertAnswer = true
}
}
override fun isNight(nowMillis: Long): Boolean {
val calendar = Calendar.getInstance()
calendar.timeInMillis = nowMillis
val nowHourInt = calendar.get(Calendar.HOUR_OF_DAY)
val result: Boolean = nowHourInt in startHour until endHour
return result.xor(invertAnswer)
}
}
| app/src/main/java/org/stepic/droid/notifications/NotificationTimeCheckerImpl.kt | 176318661 |
package org.stepik.android.view.onboarding.ui.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_onboarding_course_lists.*
import kotlinx.android.synthetic.main.item_onboarding.view.*
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.ui.activities.MainFeedActivity
import org.stepik.android.domain.onboarding.analytic.OnboardingOpenedAnalyticEvent
import org.stepik.android.domain.onboarding.analytic.OnboardingCourseListSelectedAnalyticEvent
import org.stepik.android.domain.onboarding.analytic.OnboardingCompletedAnalyticEvent
import org.stepik.android.domain.onboarding.analytic.OnboardingClosedAnalyticEvent
import org.stepik.android.domain.onboarding.analytic.OnboardingBackToGoalsAnalyticEvent
import org.stepik.android.view.onboarding.model.OnboardingCourseList
import org.stepik.android.view.onboarding.model.OnboardingGoal
import ru.nobird.android.ui.adapterdelegates.dsl.adapterDelegate
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
import javax.inject.Inject
class OnboardingCourseListsActivity : AppCompatActivity(R.layout.activity_onboarding_course_lists) {
companion object {
private const val EXTRA_ONBOARDING_GOAL = "onboarding_goal"
fun createIntent(context: Context, onboardingGoal: OnboardingGoal): Intent =
Intent(context, OnboardingCourseListsActivity::class.java)
.putExtra(EXTRA_ONBOARDING_GOAL, onboardingGoal)
init {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}
}
private val onboardingGoal by lazy { intent.getParcelableExtra<OnboardingGoal>(EXTRA_ONBOARDING_GOAL) }
@Inject
internal lateinit var analytic: Analytic
@Inject
internal lateinit var screenManager: ScreenManager
@Inject
internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper
private val courseListsAdapter: DefaultDelegateAdapter<OnboardingCourseList> = DefaultDelegateAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
App.component().inject(this)
analytic.report(OnboardingOpenedAnalyticEvent(screen = 2))
courseListsHeader.text = onboardingGoal.title
courseListsAdapter += createCourseListsAdapterDelegate { onboardingCourseList ->
sharedPreferenceHelper.personalizedCourseList = onboardingCourseList.id
analytic.report(OnboardingCourseListSelectedAnalyticEvent(onboardingCourseList.title, onboardingCourseList.id))
analytic.report(OnboardingCompletedAnalyticEvent)
closeOnboarding()
}
courseListsAdapter.items = onboardingGoal.courseLists
courseListsRecycler.layoutManager = LinearLayoutManager(this)
courseListsRecycler.adapter = courseListsAdapter
backAction.setOnClickListener {
onBackPressed()
}
dismissButton.setOnClickListener {
analytic.report(OnboardingClosedAnalyticEvent(screen = 2))
closeOnboarding()
}
}
override fun onBackPressed() {
analytic.report(OnboardingBackToGoalsAnalyticEvent)
super.onBackPressed()
}
private fun createCourseListsAdapterDelegate(onItemClicked: (OnboardingCourseList) -> Unit) =
adapterDelegate<OnboardingCourseList, OnboardingCourseList>(layoutResId = R.layout.item_onboarding) {
val itemContainer = itemView.itemContainer
val itemIcon = itemView.itemIcon
val itemTitle = itemView.itemTitle
itemView.setOnClickListener { item?.let(onItemClicked) }
onBind { data ->
itemIcon.text = data.icon
itemTitle.text = data.title
itemIcon.setBackgroundResource(R.drawable.onboarding_goal_yellow_green_gradient)
if (data.isFeatured) {
itemContainer.setBackgroundResource(R.drawable.onboarding_featured_background)
}
}
}
private fun closeOnboarding() {
sharedPreferenceHelper.afterOnboardingPassed()
sharedPreferenceHelper.setPersonalizedOnboardingWasShown()
val isLogged = sharedPreferenceHelper.authResponseFromStore != null
if (isLogged) {
screenManager.showMainFeed(this, MainFeedActivity.CATALOG_INDEX)
} else {
screenManager.showLaunchScreen(this)
}
finish()
}
} | app/src/main/java/org/stepik/android/view/onboarding/ui/activity/OnboardingCourseListsActivity.kt | 1786353700 |
package org.livingdoc.repositories.file
import java.io.File
import java.nio.file.Paths
/**
* Class to handle resolving file for the [FileRepository].
*/
open class FileResolver {
/**
* Returns an [File] for the given document root and identifier.
*/
open fun resolveFile(documentRoot: String, documentIdentifier: String): DocumentFile {
val file = Paths.get(documentRoot, documentIdentifier).toFile()
when (file.exists()) {
true -> return DocumentFile(file)
false -> throw FileDocumentNotFoundException(documentIdentifier, file.toPath())
}
}
}
| livingdoc-repository-file/src/main/kotlin/org/livingdoc/repositories/file/FileResolver.kt | 1222132185 |
package org.logout.notifications.telegram.infobipbot
import org.junit.Test
/**
* Created by sulion on 11.05.17.
*/
class InfobipTelegramBotTest {
@Test
fun sendCompositeMessages() {
val lines = listOf("abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ",
"abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca abc abc cab bca ")
var temp = StringBuilder()
val results = ArrayList<String>()
for (line in lines) {
if (temp.length + line.length > 300) {
results.add(temp.toString())
temp = StringBuilder()
}
temp.append(line)
}
print(results.size)
}
} | src/test/kotlin/org/logout/notifications/telegram/infobipbot/InfobipTelegramBotTest.kt | 4026300864 |
package eu.kanade.presentation.browse
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import eu.kanade.tachiyomi.ui.browse.source.SourcesPresenter
@Stable
interface SourcesState {
var dialog: SourcesPresenter.Dialog?
val isLoading: Boolean
val items: List<SourceUiModel>
val isEmpty: Boolean
}
fun SourcesState(): SourcesState {
return SourcesStateImpl()
}
class SourcesStateImpl : SourcesState {
override var dialog: SourcesPresenter.Dialog? by mutableStateOf(null)
override var isLoading: Boolean by mutableStateOf(true)
override var items: List<SourceUiModel> by mutableStateOf(emptyList())
override val isEmpty: Boolean by derivedStateOf { items.isEmpty() }
}
| app/src/main/java/eu/kanade/presentation/browse/SourcesState.kt | 172784815 |
package de.mannodermaus.rxbonjour.platforms.desktop
import io.reactivex.disposables.Disposable
import java.util.concurrent.atomic.AtomicBoolean
internal class RunActionDisposable(private val action: () -> Unit) : Disposable {
private val disposed: AtomicBoolean = AtomicBoolean(false)
override fun dispose() {
if (disposed.compareAndSet(false, true)) {
action.invoke()
}
}
override fun isDisposed(): Boolean = disposed.get()
}
| rxbonjour-platforms/rxbonjour-platform-desktop/src/main/kotlin/de/mannodermaus/rxbonjour/platforms/desktop/RunActionDisposable.kt | 1440822084 |
package eu.kanade.tachiyomi.ui.base.controller
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.SimpleSwapChangeHandler
/**
* A controller that displays a dialog window, floating on top of its activity's window.
* This is a wrapper over [Dialog] object like [android.app.DialogFragment].
*
* Implementations should override this class and implement [.onCreateDialog] to create a custom dialog, such as an [android.app.AlertDialog]
*/
abstract class DialogController : Controller {
protected var dialog: Dialog? = null
private set
private var dismissed = false
/**
* Convenience constructor for use when no arguments are needed.
*/
protected constructor() : super(null)
/**
* Constructor that takes arguments that need to be retained across restarts.
*
* @param args Any arguments that need to be retained.
*/
protected constructor(args: Bundle?) : super(args)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
dialog = onCreateDialog(savedViewState)
dialog!!.setOwnerActivity(activity!!)
dialog!!.setOnDismissListener { dismissDialog() }
if (savedViewState != null) {
val dialogState = savedViewState.getBundle(SAVED_DIALOG_STATE_TAG)
if (dialogState != null) {
dialog!!.onRestoreInstanceState(dialogState)
}
}
return View(activity) // stub view
}
override fun onSaveViewState(view: View, outState: Bundle) {
super.onSaveViewState(view, outState)
val dialogState = dialog!!.onSaveInstanceState()
outState.putBundle(SAVED_DIALOG_STATE_TAG, dialogState)
}
override fun onAttach(view: View) {
super.onAttach(view)
dialog!!.show()
}
override fun onDetach(view: View) {
super.onDetach(view)
dialog!!.hide()
}
override fun onDestroyView(view: View) {
super.onDestroyView(view)
dialog!!.setOnDismissListener(null)
dialog!!.dismiss()
dialog = null
}
/**
* Display the dialog, create a transaction and pushing the controller.
* @param router The router on which the transaction will be applied
*/
open fun showDialog(router: Router) {
showDialog(router, null)
}
/**
* Display the dialog, create a transaction and pushing the controller.
* @param router The router on which the transaction will be applied
* @param tag The tag for this controller
*/
fun showDialog(router: Router, tag: String?) {
dismissed = false
router.pushController(
RouterTransaction.with(this)
.pushChangeHandler(SimpleSwapChangeHandler(false))
.popChangeHandler(SimpleSwapChangeHandler(false))
.tag(tag),
)
}
/**
* Dismiss the dialog and pop this controller
*/
fun dismissDialog() {
if (dismissed) {
return
}
router.popController(this)
dismissed = true
}
/**
* Build your own custom Dialog container such as an [android.app.AlertDialog]
*
* @param savedViewState A bundle for the view's state, which would have been created in [.onSaveViewState] or `null` if no saved state exists.
* @return Return a new Dialog instance to be displayed by the Controller
*/
protected abstract fun onCreateDialog(savedViewState: Bundle?): Dialog
companion object {
private const val SAVED_DIALOG_STATE_TAG = "android:savedDialogState"
}
}
| app/src/main/java/eu/kanade/tachiyomi/ui/base/controller/DialogController.kt | 879393294 |
/*
* Copyright 2017 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nomic.core
import nomic.core.fact.NameFact
import nomic.core.fact.VersionFact
import org.junit.Test
private class NameFactHandler(val plugin: TestPlugin) : FactHandler<NameFact> {
override fun commit(box: BundledBox, fact: NameFact) {
println("Message: ${plugin.welcomeMsg} ${fact.name}")
}
override fun rollback(box: InstalledBox, fact: NameFact) {
println("Bye ${fact.name}")
}
}
private class VersionFactHandler: FactHandler<VersionFact> {
override fun commit(box: BundledBox, fact: VersionFact) {
println("Version ${fact.version}")
}
override fun rollback(box: InstalledBox, fact: VersionFact) {
println("Bye ${fact.version}")
}
}
private class TestPlugin : Plugin() {
val welcomeMsg: String = "Hello"
override fun configureMapping(): FactMapping =
listOf(
NameFact::class.java to { NameFactHandler(this) },
VersionFact::class.java to ::VersionFactHandler
)
}
/**
* @author [email protected]
*/
class PluginTest {
@Test
fun `the plugin should route the facts into correct handlers`() {
val plugin = TestPlugin()
plugin.commit(BundledBox.empty, NameFact("Harry Potter"))
plugin.commit(BundledBox.empty, VersionFact("1.0"))
}
} | nomic-core/src/test/kotlin/nomic/core/PluginTest.kt | 4150883954 |
package info.nightscout.androidaps.danars.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danars.DanaRSTestBase
import org.junit.Assert
import org.junit.Test
class DanaRsPacketHistoryBolusTest : DanaRSTestBase() {
private val packetInjector = HasAndroidInjector {
AndroidInjector {
if (it is DanaRSPacket) {
it.aapsLogger = aapsLogger
it.dateUtil = dateUtil
}
if (it is DanaRSPacketHistoryBolus) {
it.rxBus = rxBus
}
}
}
@Test fun runTest() {
val packet = DanaRSPacketHistoryBolus(packetInjector, System.currentTimeMillis())
Assert.assertEquals("REVIEW__BOLUS", packet.friendlyName)
}
} | danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBolusTest.kt | 3656419872 |
/*
* 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.web.servlet
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer
import org.springframework.security.config.web.servlet.headers.*
import org.springframework.security.web.header.HeaderWriter
import org.springframework.security.web.header.writers.*
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter
/**
* A Kotlin DSL to configure [HttpSecurity] headers using idiomatic Kotlin code.
*
* @author Eleftheria Stein
* @since 5.3
* @property defaultsDisabled whether all of the default headers should be included in the response
*/
@SecurityMarker
class HeadersDsl {
private var contentTypeOptions: ((HeadersConfigurer<HttpSecurity>.ContentTypeOptionsConfig) -> Unit)? = null
private var xssProtection: ((HeadersConfigurer<HttpSecurity>.XXssConfig) -> Unit)? = null
private var cacheControl: ((HeadersConfigurer<HttpSecurity>.CacheControlConfig) -> Unit)? = null
private var hsts: ((HeadersConfigurer<HttpSecurity>.HstsConfig) -> Unit)? = null
private var frameOptions: ((HeadersConfigurer<HttpSecurity>.FrameOptionsConfig) -> Unit)? = null
private var hpkp: ((HeadersConfigurer<HttpSecurity>.HpkpConfig) -> Unit)? = null
private var contentSecurityPolicy: ((HeadersConfigurer<HttpSecurity>.ContentSecurityPolicyConfig) -> Unit)? = null
private var referrerPolicy: ((HeadersConfigurer<HttpSecurity>.ReferrerPolicyConfig) -> Unit)? = null
private var featurePolicyDirectives: String? = null
private var permissionsPolicy: ((HeadersConfigurer<HttpSecurity>.PermissionsPolicyConfig) -> Unit)? = null
private var disabled = false
private var headerWriters = mutableListOf<HeaderWriter>()
var defaultsDisabled: Boolean? = null
/**
* Configures the [XContentTypeOptionsHeaderWriter] which inserts the <a href=
* "https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx"
* >X-Content-Type-Options header</a>
*
* @param contentTypeOptionsConfig the customization to apply to the header
*/
fun contentTypeOptions(contentTypeOptionsConfig: ContentTypeOptionsDsl.() -> Unit) {
this.contentTypeOptions = ContentTypeOptionsDsl().apply(contentTypeOptionsConfig).get()
}
/**
* <strong>Note this is not comprehensive XSS protection!</strong>
*
* <p>
* Allows customizing the [XXssProtectionHeaderWriter] which adds the <a href=
* "https://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx"
* >X-XSS-Protection header</a>
* </p>
*
* @param xssProtectionConfig the customization to apply to the header
*/
fun xssProtection(xssProtectionConfig: XssProtectionConfigDsl.() -> Unit) {
this.xssProtection = XssProtectionConfigDsl().apply(xssProtectionConfig).get()
}
/**
* Allows customizing the [CacheControlHeadersWriter]. Specifically it adds the
* following headers:
* <ul>
* <li>Cache-Control: no-cache, no-store, max-age=0, must-revalidate</li>
* <li>Pragma: no-cache</li>
* <li>Expires: 0</li>
* </ul>
*
* @param cacheControlConfig the customization to apply to the header
*/
fun cacheControl(cacheControlConfig: CacheControlDsl.() -> Unit) {
this.cacheControl = CacheControlDsl().apply(cacheControlConfig).get()
}
/**
* Allows customizing the [HstsHeaderWriter] which provides support for <a
* href="https://tools.ietf.org/html/rfc6797">HTTP Strict Transport Security
* (HSTS)</a>.
*
* @param hstsConfig the customization to apply to the header
*/
fun httpStrictTransportSecurity(hstsConfig: HttpStrictTransportSecurityDsl.() -> Unit) {
this.hsts = HttpStrictTransportSecurityDsl().apply(hstsConfig).get()
}
/**
* Allows customizing the [XFrameOptionsHeaderWriter] which add the X-Frame-Options
* header.
*
* @param frameOptionsConfig the customization to apply to the header
*/
fun frameOptions(frameOptionsConfig: FrameOptionsDsl.() -> Unit) {
this.frameOptions = FrameOptionsDsl().apply(frameOptionsConfig).get()
}
/**
* Allows customizing the [HpkpHeaderWriter] which provides support for <a
* href="https://tools.ietf.org/html/rfc7469">HTTP Public Key Pinning (HPKP)</a>.
*
* @param hpkpConfig the customization to apply to the header
*/
fun httpPublicKeyPinning(hpkpConfig: HttpPublicKeyPinningDsl.() -> Unit) {
this.hpkp = HttpPublicKeyPinningDsl().apply(hpkpConfig).get()
}
/**
* Allows configuration for <a href="https://www.w3.org/TR/CSP2/">Content Security Policy (CSP) Level 2</a>.
*
* <p>
* Calling this method automatically enables (includes) the Content-Security-Policy header in the response
* using the supplied security policy directive(s).
* </p>
*
* @param contentSecurityPolicyConfig the customization to apply to the header
*/
fun contentSecurityPolicy(contentSecurityPolicyConfig: ContentSecurityPolicyDsl.() -> Unit) {
this.contentSecurityPolicy = ContentSecurityPolicyDsl().apply(contentSecurityPolicyConfig).get()
}
/**
* Allows configuration for <a href="https://www.w3.org/TR/referrer-policy/">Referrer Policy</a>.
*
* <p>
* Configuration is provided to the [ReferrerPolicyHeaderWriter] which support the writing
* of the header as detailed in the W3C Technical Report:
* </p>
* <ul>
* <li>Referrer-Policy</li>
* </ul>
*
* @param referrerPolicyConfig the customization to apply to the header
*/
fun referrerPolicy(referrerPolicyConfig: ReferrerPolicyDsl.() -> Unit) {
this.referrerPolicy = ReferrerPolicyDsl().apply(referrerPolicyConfig).get()
}
/**
* Allows configuration for <a href="https://wicg.github.io/feature-policy/">Feature
* Policy</a>.
*
* <p>
* Calling this method automatically enables (includes) the Feature-Policy
* header in the response using the supplied policy directive(s).
* <p>
*
* @param policyDirectives policyDirectives the security policy directive(s)
*/
@Deprecated("Use 'permissionsPolicy { }' instead.")
fun featurePolicy(policyDirectives: String) {
this.featurePolicyDirectives = policyDirectives
}
/**
* Allows configuration for <a href="https://w3c.github.io/webappsec-permissions-policy/">Permissions
* Policy</a>.
*
* <p>
* Calling this method automatically enables (includes) the Permissions-Policy
* header in the response using the supplied policy directive(s).
* <p>
*
* @param permissionsPolicyConfig the customization to apply to the header
*/
fun permissionsPolicy(permissionsPolicyConfig: PermissionsPolicyDsl.() -> Unit) {
this.permissionsPolicy = PermissionsPolicyDsl().apply(permissionsPolicyConfig).get()
}
/**
* Adds a [HeaderWriter] instance.
*
* @param headerWriter the [HeaderWriter] instance to add
* @since 5.4
*/
fun addHeaderWriter(headerWriter: HeaderWriter) {
this.headerWriters.add(headerWriter)
}
/**
* Disable all HTTP security headers.
*
* @since 5.4
*/
fun disable() {
disabled = true
}
@Suppress("DEPRECATION")
internal fun get(): (HeadersConfigurer<HttpSecurity>) -> Unit {
return { headers ->
defaultsDisabled?.also {
if (defaultsDisabled!!) {
headers.defaultsDisabled()
}
}
contentTypeOptions?.also {
headers.contentTypeOptions(contentTypeOptions)
}
xssProtection?.also {
headers.xssProtection(xssProtection)
}
cacheControl?.also {
headers.cacheControl(cacheControl)
}
hsts?.also {
headers.httpStrictTransportSecurity(hsts)
}
frameOptions?.also {
headers.frameOptions(frameOptions)
}
hpkp?.also {
headers.httpPublicKeyPinning(hpkp)
}
contentSecurityPolicy?.also {
headers.contentSecurityPolicy(contentSecurityPolicy)
}
referrerPolicy?.also {
headers.referrerPolicy(referrerPolicy)
}
featurePolicyDirectives?.also {
headers.featurePolicy(featurePolicyDirectives)
}
permissionsPolicy?.also {
headers.permissionsPolicy(permissionsPolicy)
}
headerWriters.forEach { headerWriter ->
headers.addHeaderWriter(headerWriter)
}
if (disabled) {
headers.disable()
}
}
}
}
| config/src/main/kotlin/org/springframework/security/config/web/servlet/HeadersDsl.kt | 3098131884 |
package com.github.ahant.validator.validation
import com.github.ahant.validator.annotation.FieldInfo
import com.github.ahant.validator.validation.FieldValidatorType.STRING
import com.github.ahant.validator.validation.FieldValidatorType.ZIP
import com.github.ahant.validator.validation.util.CountryCode
/**
* Created by ahant on 7/16/2016.
*/
class Address {
@FieldInfo(validatorType = STRING, optional = false)
var addressLine1: String? = null
@FieldInfo(optional = true, validatorType = STRING)
var addressLine2: String? = null
@FieldInfo(validatorType = STRING, optional = false)
var city: String? = null
@FieldInfo(validatorType = STRING, optional = false)
var state: String? = null
@FieldInfo(validatorType = STRING, optional = false)
var country = "India"
@FieldInfo(validatorType = ZIP, optional = false)
var zip: String? = null
@FieldInfo(validatorType = ZIP, countryCode = CountryCode.US, optional = false)
var usZip: String? = null
}
| src/test/kotlin/com/github/ahant/validator/validation/Address.kt | 284832089 |
// 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.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.completion.impl.RealPrefixMatchingWeigher
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.openapi.util.TextRange
import com.intellij.patterns.ElementPattern
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.MemberDescriptor
import org.jetbrains.kotlin.idea.completion.handlers.WithExpressionPrefixInsertHandler
import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.intentions.InsertExplicitTypeArgumentsIntention
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor
import kotlin.math.max
class LookupElementsCollector(
private val onFlush: () -> Unit,
private val prefixMatcher: PrefixMatcher,
private val completionParameters: CompletionParameters,
resultSet: CompletionResultSet,
sorter: CompletionSorter,
private val filter: ((LookupElement) -> Boolean)?,
private val allowExpectDeclarations: Boolean
) {
var bestMatchingDegree = Int.MIN_VALUE
private set
private val elements = ArrayList<LookupElement>()
private val resultSet = resultSet.withPrefixMatcher(prefixMatcher).withRelevanceSorter(sorter)
private val postProcessors = ArrayList<(LookupElement) -> LookupElement>()
private val processedCallables = HashSet<CallableDescriptor>()
var isResultEmpty: Boolean = true
private set
fun flushToResultSet() {
if (elements.isNotEmpty()) {
onFlush()
resultSet.addAllElements(elements)
elements.clear()
isResultEmpty = false
}
}
fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) {
postProcessors.add(processor)
}
fun addDescriptorElements(
descriptors: Iterable<DeclarationDescriptor>,
lookupElementFactory: AbstractLookupElementFactory,
notImported: Boolean = false,
withReceiverCast: Boolean = false,
prohibitDuplicates: Boolean = false
) {
for (descriptor in descriptors) {
addDescriptorElements(descriptor, lookupElementFactory, notImported, withReceiverCast, prohibitDuplicates)
}
}
fun addDescriptorElements(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory,
notImported: Boolean = false,
withReceiverCast: Boolean = false,
prohibitDuplicates: Boolean = false
) {
if (prohibitDuplicates && descriptor is CallableDescriptor && unwrapIfImportedFromObject(descriptor) in processedCallables) return
var lookupElements = lookupElementFactory.createStandardLookupElementsForDescriptor(descriptor, useReceiverTypes = true)
if (withReceiverCast) {
lookupElements = lookupElements.map { it.withReceiverCast() }
}
addElements(lookupElements, notImported)
if (prohibitDuplicates && descriptor is CallableDescriptor) processedCallables.add(unwrapIfImportedFromObject(descriptor))
}
fun addElement(element: LookupElement, notImported: Boolean = false) {
if (!prefixMatcher.prefixMatches(element)) {
return
}
if (!allowExpectDeclarations) {
val descriptor = (element.`object` as? DeclarationLookupObject)?.descriptor
if ((descriptor as? MemberDescriptor)?.isExpect == true) return
}
if (notImported) {
element.putUserData(NOT_IMPORTED_KEY, Unit)
if (isResultEmpty && elements.isEmpty()) { /* without these checks we may get duplicated items */
addElement(element.suppressAutoInsertion())
} else {
addElement(element)
}
return
}
val decorated = JustTypingLookupElementDecorator(element, completionParameters)
var result: LookupElement = decorated
for (postProcessor in postProcessors) {
result = postProcessor(result)
}
val declarationLookupObject = result.`object` as? DeclarationLookupObject
if (declarationLookupObject != null) {
result = DeclarationLookupObjectLookupElementDecorator(result, declarationLookupObject)
}
if (filter?.invoke(result) != false) {
elements.add(result)
}
val matchingDegree = RealPrefixMatchingWeigher.getBestMatchingDegree(result, prefixMatcher)
bestMatchingDegree = max(bestMatchingDegree, matchingDegree)
}
fun addElements(elements: Iterable<LookupElement>, notImported: Boolean = false) {
elements.forEach { addElement(it, notImported) }
}
fun restartCompletionOnPrefixChange(prefixCondition: ElementPattern<String>) {
resultSet.restartCompletionOnPrefixChange(prefixCondition)
}
}
private class JustTypingLookupElementDecorator(element: LookupElement, private val completionParameters: CompletionParameters) :
LookupElementDecorator<LookupElement>(element) {
// used to avoid insertion of spaces before/after ',', '=' on just typing
private fun isJustTyping(context: InsertionContext, element: LookupElement): Boolean {
if (!completionParameters.isAutoPopup) return false
val insertedText = context.document.getText(TextRange(context.startOffset, context.tailOffset))
return insertedText == element.getUserDataDeep(KotlinCompletionCharFilter.JUST_TYPING_PREFIX)
}
override fun getDecoratorInsertHandler(): InsertHandler<LookupElementDecorator<LookupElement>> = InsertHandler { context, decorator ->
delegate.handleInsert(context)
if (context.shouldAddCompletionChar() && !isJustTyping(context, this)) {
when (context.completionChar) {
',' -> WithTailInsertHandler.COMMA.postHandleInsert(context, delegate)
'=' -> WithTailInsertHandler.EQ.postHandleInsert(context, delegate)
'!' -> {
WithExpressionPrefixInsertHandler("!").postHandleInsert(context)
context.setAddCompletionChar(false)
}
}
}
val (typeArgs, exprOffset) = argList ?: return@InsertHandler
val beforeCaret = context.file.findElementAt(exprOffset) ?: return@InsertHandler
val callExpr = when (val beforeCaretExpr = beforeCaret.prevSibling) {
is KtCallExpression -> beforeCaretExpr
is KtDotQualifiedExpression -> beforeCaretExpr.collectDescendantsOfType<KtCallExpression>().lastOrNull()
else -> null
} ?: return@InsertHandler
InsertExplicitTypeArgumentsIntention.applyTo(callExpr, typeArgs, true)
}
}
private class DeclarationLookupObjectLookupElementDecorator(
element: LookupElement,
private val declarationLookupObject: DeclarationLookupObject
) : LookupElementDecorator<LookupElement>(element) {
override fun getPsiElement() = declarationLookupObject.psiElement
}
private fun unwrapIfImportedFromObject(descriptor: CallableDescriptor): CallableDescriptor =
if (descriptor is ImportedFromObjectCallableDescriptor<*>) descriptor.callableFromObject else descriptor
| plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt | 1435288562 |
package arcs.core.storage.driver.testutil
import arcs.core.storage.Driver
import arcs.core.storage.DriverProvider
import arcs.core.storage.StorageKey
import arcs.core.storage.driver.volatiles.VolatileDriverImpl
import arcs.core.storage.driver.volatiles.VolatileEntry
import arcs.core.storage.driver.volatiles.VolatileMemory
import arcs.core.storage.driver.volatiles.VolatileMemoryImpl
import arcs.core.storage.keys.RamDiskStorageKey
import arcs.core.type.Type
import kotlin.reflect.KClass
/**
* [DriverProvider] implementation which registers itself as capable of handling
* [RamDiskStorageKey]s, but uses a [SlowVolatileMemory] bound to the instance, rather than a
* global static [VolatileMemory] (the way it is done for [RamDiskDriverProvider]).
*
* Provide a [waitOp] callback to be able to control when an operation is allowed to finish.
*/
class SlowRamDiskDriverProvider(
waitOp: suspend (SlowVolatileMemory.MemoryOp, StorageKey?) -> Unit
) : DriverProvider {
val memory = SlowVolatileMemory(waitOp)
override fun willSupport(storageKey: StorageKey) = storageKey is RamDiskStorageKey
override suspend fun <Data : Any> getDriver(
storageKey: StorageKey,
dataClass: KClass<Data>,
type: Type
): Driver<Data> = VolatileDriverImpl.create(storageKey, dataClass, memory)
override suspend fun removeAllEntities() = Unit
override suspend fun removeEntitiesCreatedBetween(
startTimeMillis: Long,
endTimeMillis: Long
) = Unit
}
/**
* Essentially the same as [VolatileMemoryImpl], except that [waitOp] is used before the operations
* exposed by [VolatileMemory] (implemented by [VolatileMemoryImpl]) are called - allowing the
* developer to suspend the calling coroutine until they are ready for the operation to proceed.
*/
@Suppress("UNCHECKED_CAST")
class SlowVolatileMemory(
private val waitOp: suspend (MemoryOp, StorageKey?) -> Unit
) : VolatileMemory {
private val delegate = VolatileMemoryImpl()
override val token: String
get() = delegate.token
override suspend fun contains(key: StorageKey): Boolean {
waitOp(MemoryOp.Contains, key)
return delegate.contains(key)
}
override suspend fun <Data : Any> get(key: StorageKey): VolatileEntry<Data>? {
waitOp(MemoryOp.Get, key)
return delegate.get(key)
}
override suspend fun <Data : Any> set(
key: StorageKey,
value: VolatileEntry<Data>
): VolatileEntry<Data>? {
waitOp(MemoryOp.Set, key)
return delegate.set(key, value)
}
override suspend fun <Data : Any> update(
key: StorageKey,
updater: (VolatileEntry<Data>?) -> VolatileEntry<Data>
): Pair<Boolean, VolatileEntry<Data>> {
waitOp(MemoryOp.Update, key)
return delegate.update(key, updater)
}
override fun countEntities(): Long = delegate.countEntities()
override suspend fun clear() {
waitOp(MemoryOp.Clear, null)
delegate.clear()
}
override suspend fun addListener(listener: (StorageKey, Any?) -> Unit) {
delegate.addListener(listener)
}
override suspend fun removeListener(listener: (StorageKey, Any?) -> Unit) {
delegate.removeListener(listener)
}
/**
* Type of operation which was performed. Passed to the delaySource callback associated with a
* [SlowVolatileMemory].
*/
enum class MemoryOp {
Contains, Get, Set, Update, Clear
}
}
| java/arcs/core/storage/driver/testutil/SlowRamDisk.kt | 3942833713 |
package arcs.core.policy.proto
import arcs.core.data.Annotation
import arcs.core.data.proto.PolicyProto
import arcs.core.data.proto.PolicyRetentionProto
import arcs.core.data.proto.PolicyTargetProto
import arcs.core.policy.Policy
import arcs.core.policy.PolicyField
import arcs.core.policy.PolicyRetention
import arcs.core.policy.PolicyTarget
import arcs.core.policy.StorageMedium
import arcs.core.policy.UsageType
import com.google.common.truth.Truth.assertThat
import kotlin.test.assertFailsWith
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class PolicyProtoTest {
@Test
fun roundTrip_policy() {
val policy = Policy(
name = "foo",
description = "bar",
egressType = "baz",
targets = emptyList(),
configs = emptyMap(),
annotations = listOf(ANNOTATION)
)
assertThat(policy.encode().decode()).isEqualTo(policy)
}
@Test
fun decode_policy_requiresName() {
val e = assertFailsWith<IllegalArgumentException> {
PolicyProto.getDefaultInstance().decode()
}
assertThat(e).hasMessageThat().startsWith("Policy name is missing.")
}
@Test
fun decode_policy_requiresEgressType() {
val e = assertFailsWith<IllegalArgumentException> {
PolicyProto.newBuilder().setName("foo").build().decode()
}
assertThat(e).hasMessageThat().startsWith("Egress type is missing.")
}
@Test
fun roundTrip_target() {
val policy = Policy(
name = "foo",
egressType = "Logging",
targets = listOf(
PolicyTarget(
schemaName = "schema",
maxAgeMs = 123,
retentions = listOf(
PolicyRetention(medium = StorageMedium.DISK, encryptionRequired = true)
),
fields = emptyList(),
annotations = listOf(ANNOTATION)
)
)
)
assertThat(policy.encode().decode()).isEqualTo(policy)
}
@Test
fun decode_retention_requiresMedium() {
val proto = PolicyProto.newBuilder()
.setName("foo")
.setEgressType("Logging")
.addTargets(
PolicyTargetProto.newBuilder()
.addRetentions(PolicyRetentionProto.getDefaultInstance())
)
.build()
val e = assertFailsWith<UnsupportedOperationException> { proto.decode() }
assertThat(e).hasMessageThat().startsWith("Unknown retention medium:")
}
@Test
fun roundTrip_fields() {
val policy = Policy(
name = "foo",
egressType = "Logging",
targets = listOf(
PolicyTarget(
schemaName = "schema",
retentions = listOf(
PolicyRetention(medium = StorageMedium.RAM, encryptionRequired = true)
),
fields = listOf(
PolicyField(
fieldPath = listOf("field1"),
rawUsages = setOf(UsageType.JOIN),
redactedUsages = mapOf(
"label" to setOf(UsageType.EGRESS, UsageType.JOIN)
),
subfields = emptyList(),
annotations = listOf(ANNOTATION)
),
PolicyField(
fieldPath = listOf("field2"),
rawUsages = setOf(UsageType.ANY),
subfields = emptyList(),
annotations = listOf(ANNOTATION)
)
)
)
)
)
assertThat(policy.encode().decode()).isEqualTo(policy)
}
@Test
fun roundTrip_subfields() {
val policy = Policy(
name = "foo",
egressType = "Logging",
targets = listOf(
PolicyTarget(
schemaName = "schema",
fields = listOf(
PolicyField(
fieldPath = listOf("parent"),
rawUsages = emptySet(),
redactedUsages = emptyMap(),
subfields = listOf(
PolicyField(
fieldPath = listOf("parent", "child"),
rawUsages = emptySet(),
redactedUsages = emptyMap(),
subfields = emptyList(),
annotations = emptyList()
)
),
annotations = emptyList()
)
)
)
)
)
assertThat(policy.encode().decode()).isEqualTo(policy)
}
@Test
fun roundTrip_configs() {
val policy = Policy(
name = "foo",
egressType = "Logging",
configs = mapOf("config" to mapOf("k1" to "v1", "k2" to "v2"))
)
assertThat(policy.encode().decode()).isEqualTo(policy)
}
companion object {
val ANNOTATION = Annotation("custom", mapOf())
}
}
| javatests/arcs/core/policy/proto/PolicyProtoTest.kt | 2644759969 |
package com.fsck.k9.mailstore
import com.fsck.k9.crypto.EncryptionExtractor
import com.fsck.k9.mail.Message
import com.fsck.k9.mail.MessageDownloadState
import com.fsck.k9.message.extractors.AttachmentCounter
import com.fsck.k9.message.extractors.MessageFulltextCreator
import com.fsck.k9.message.extractors.MessagePreviewCreator
class SaveMessageDataCreator(
private val encryptionExtractor: EncryptionExtractor,
private val messagePreviewCreator: MessagePreviewCreator,
private val messageFulltextCreator: MessageFulltextCreator,
private val attachmentCounter: AttachmentCounter
) {
fun createSaveMessageData(
message: Message,
downloadState: MessageDownloadState,
subject: String? = null
): SaveMessageData {
val now = System.currentTimeMillis()
val date = message.sentDate?.time ?: now
val internalDate = message.internalDate?.time ?: now
val displaySubject = subject ?: message.subject
val encryptionResult = encryptionExtractor.extractEncryption(message)
return if (encryptionResult != null) {
SaveMessageData(
message = message,
subject = displaySubject,
date = date,
internalDate = internalDate,
downloadState = downloadState,
attachmentCount = encryptionResult.attachmentCount,
previewResult = encryptionResult.previewResult,
textForSearchIndex = encryptionResult.textForSearchIndex,
encryptionType = encryptionResult.encryptionType
)
} else {
SaveMessageData(
message = message,
subject = displaySubject,
date = date,
internalDate = internalDate,
downloadState = downloadState,
attachmentCount = attachmentCounter.getAttachmentCount(message),
previewResult = messagePreviewCreator.createPreview(message),
textForSearchIndex = messageFulltextCreator.createFulltext(message),
encryptionType = null
)
}
}
}
| app/core/src/main/java/com/fsck/k9/mailstore/SaveMessageDataCreator.kt | 1581150097 |
// 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.platform
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.Key
import com.intellij.psi.util.ParameterizedCachedValue
import com.intellij.psi.util.ParameterizedCachedValueProvider
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.core.util.AvailabilityProvider
import org.jetbrains.kotlin.idea.core.util.isClassAvailableInModule
import org.jetbrains.kotlin.idea.highlighter.KotlinTestRunLineMarkerContributor.Companion.getTestStateIcon
import org.jetbrains.kotlin.idea.util.string.joinWithEscape
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.IdePlatformKind
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.has
import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.platform.js.JsPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatform
import org.jetbrains.kotlin.platform.konan.NativePlatform
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import javax.swing.Icon
private val TEST_FQ_NAME = FqName("kotlin.test.Test")
private val IGNORE_FQ_NAME = FqName("kotlin.test.Ignore")
private val GENERIC_KOTLIN_TEST_AVAILABLE_KEY = Key<ParameterizedCachedValue<Boolean, Module>>("GENERIC_KOTLIN_TEST_AVAILABLE")
private val GENERIC_KOTLIN_TEST_AVAILABLE_PROVIDER_WITHOUT_TEST_SCOPE: ParameterizedCachedValueProvider<Boolean, Module> = GenericKotlinTestAvailabilityProvider(includeTests = false)
private val GENERIC_KOTLIN_TEST_AVAILABLE_PROVIDER_WITH_TEST_SCOPE = GenericKotlinTestAvailabilityProvider(true)
private class GenericKotlinTestAvailabilityProvider(includeTests: Boolean) : AvailabilityProvider(
includeTests,
fqNames = setOf(TEST_FQ_NAME.asString()),
javaClassLookup = true,
// `kotlin.test.Test` could be a typealias
aliasLookup = true,
// `kotlin.test.Test` could be expected/actual annotation class
kotlinFullClassLookup = true
)
fun getGenericTestIcon(
declaration: KtNamedDeclaration,
descriptorProvider: () -> DeclarationDescriptor?,
initialLocations: () -> List<String>?
): Icon? {
val locations = initialLocations()?.toMutableList() ?: return null
// fast check if `kotlin.test.Test` is available in a module scope
declaration.isClassAvailableInModule(
GENERIC_KOTLIN_TEST_AVAILABLE_KEY,
GENERIC_KOTLIN_TEST_AVAILABLE_PROVIDER_WITHOUT_TEST_SCOPE,
GENERIC_KOTLIN_TEST_AVAILABLE_PROVIDER_WITH_TEST_SCOPE
)?.takeUnless { it }?.let { return null }
val clazz = when (declaration) {
is KtClassOrObject -> declaration
is KtNamedFunction -> declaration.containingClassOrObject ?: return null
else -> return null
}
val descriptor = descriptorProvider() ?: return null
if (!descriptor.isKotlinTestDeclaration()) return null
locations += clazz.parentsWithSelf.filterIsInstance<KtNamedDeclaration>()
.mapNotNull { it.name }
.toList().asReversed()
val testName = (declaration as? KtNamedFunction)?.name
if (testName != null) {
locations += "$testName"
}
val prefix = if (testName != null) "test://" else "suite://"
val url = prefix + locations.joinWithEscape('.')
return getTestStateIcon(listOf("java:$url", url), declaration)
}
private tailrec fun DeclarationDescriptor.isIgnored(): Boolean {
if (annotations.any { it.fqName == IGNORE_FQ_NAME }) {
return true
}
val containingClass = containingDeclaration as? ClassDescriptor ?: return false
return containingClass.isIgnored()
}
fun DeclarationDescriptor.isKotlinTestDeclaration(): Boolean {
if (isIgnored()) {
return false
}
if (annotations.any { it.fqName == TEST_FQ_NAME }) {
return true
}
val classDescriptor = this as? ClassDescriptorWithResolutionScopes ?: return false
return classDescriptor.declaredCallableMembers.any { it.isKotlinTestDeclaration() }
}
internal fun IdePlatformKind.isCompatibleWith(platform: TargetPlatform): Boolean {
return when (this) {
is JvmIdePlatformKind -> platform.has(JvmPlatform::class)
is NativeIdePlatformKind -> platform.has(NativePlatform::class)
is JsIdePlatformKind -> platform.has(JsPlatform::class)
is CommonIdePlatformKind -> true
else -> false
}
} | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/platform/testRunningUtils.kt | 1052885131 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.datatypes
import com.maddyhome.idea.vim.ex.ExException
data class VimList(val values: MutableList<VimDataType>) : VimDataType() {
operator fun get(index: Int): VimDataType = this.values[index]
override fun asDouble(): Double {
throw ExException("E745: Using a List as a Number")
}
override fun asString(): String {
throw ExException("E730: Using a List as a String")
}
override fun toVimNumber(): VimInt {
throw ExException("E745: Using a List as a Number")
}
override fun toString(): String {
val result = StringBuffer("[")
result.append(values.joinToString(separator = ", ") { if (it is VimString) "'$it'" else it.toString() })
result.append("]")
return result.toString()
}
override fun asBoolean(): Boolean {
throw ExException("E745: Using a List as a Number")
}
override fun deepCopy(level: Int): VimDataType {
return if (level > 0) {
VimList(values.map { it.deepCopy(level - 1) }.toMutableList())
} else {
this
}
}
override fun lockVar(depth: Int) {
this.isLocked = true
if (depth > 1) {
for (value in values) {
value.lockVar(depth - 1)
}
}
}
override fun unlockVar(depth: Int) {
this.isLocked = false
if (depth > 1) {
for (value in values) {
value.unlockVar(depth - 1)
}
}
}
}
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/datatypes/VimList.kt | 3651223874 |
/*
* Copyright 2020 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.configurationcache.serialization.codecs.jos
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.beans.BeanStateReader
import org.gradle.configurationcache.serialization.readDouble
import org.gradle.configurationcache.serialization.readFloat
import org.gradle.configurationcache.serialization.readShort
import org.gradle.configurationcache.serialization.runReadOperation
import java.io.InputStream
import java.io.ObjectInputStream
import java.io.ObjectInputValidation
import java.io.OutputStream
internal
class ObjectInputStreamAdapter(
private
val bean: Any,
private
val beanStateReader: BeanStateReader,
private
val readContext: ReadContext
) : ObjectInputStream() {
override fun defaultReadObject() = beanStateReader.run {
readContext.runReadOperation {
readStateOf(bean)
}
}
override fun readObjectOverride(): Any? = readContext.runReadOperation {
read()
}
override fun readInt(): Int = readContext.readInt()
override fun readUTF(): String = readContext.readString()
override fun read(b: ByteArray): Int = inputStream.read(b)
override fun markSupported(): Boolean = inputStream.markSupported()
override fun mark(readlimit: Int) = inputStream.mark(readlimit)
override fun reset() = inputStream.reset()
override fun read(): Int = inputStream.read()
override fun readChar(): Char = readContext.readInt().toChar()
override fun readUnsignedByte(): Int = readByte().let {
require(it >= 0)
it.toInt()
}
override fun readByte(): Byte = readContext.readByte()
override fun readUnsignedShort(): Int = readShort().let {
require(it >= 0)
it.toInt()
}
override fun readShort(): Short = readContext.readShort()
override fun readLong(): Long = readContext.readLong()
override fun readFloat(): Float = readContext.readFloat()
override fun readDouble(): Double = readContext.readDouble()
override fun readBoolean(): Boolean = readContext.readBoolean()
// TODO:configuration-cache override Java 11 API for compatibility with Java 11
// override fun readNBytes(len: Int): ByteArray = inputStream.readNBytes(len)
override fun readNBytes(b: ByteArray, off: Int, len: Int): Int = inputStream.readNBytes(b, off, len)
override fun skip(n: Long): Long = inputStream.skip(n)
override fun registerValidation(obj: ObjectInputValidation?, prio: Int) = Unit
override fun close() = Unit
override fun available(): Int = inputStream.available()
override fun skipBytes(len: Int): Int = inputStream.skip(len.toLong()).toInt()
override fun read(buf: ByteArray, off: Int, len: Int): Int = inputStream.read(buf, off, len)
override fun readLine(): String = unsupported("ObjectInputStream.readLine")
override fun readFully(buf: ByteArray) = unsupported("ObjectInputStream.readFully")
override fun readFully(buf: ByteArray, off: Int, len: Int) = unsupported("ObjectInputStream.readFully")
override fun readUnshared(): Any = unsupported("ObjectInputStream.readUnshared")
override fun readFields(): GetField = unsupported("ObjectInputStream.readFields")
override fun transferTo(out: OutputStream): Long = unsupported("ObjectInputStream.transferTo")
override fun readAllBytes(): ByteArray = unsupported("ObjectInputStream.readAllBytes")
private
val inputStream: InputStream
get() = readContext.inputStream
}
internal
fun unsupported(feature: String): Nothing =
throw UnsupportedOperationException("'$feature' is not supported by the Gradle configuration cache.")
| subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/jos/ObjectInputStreamAdapter.kt | 1076686336 |
package org.hexworks.zircon.internal.component.renderer
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.graphics.TileGraphics
import org.hexworks.zircon.internal.component.impl.DefaultVBox
class DefaultVBoxRenderer : ComponentRenderer<DefaultVBox> {
override fun render(tileGraphics: TileGraphics, context: ComponentRenderContext<DefaultVBox>) {
tileGraphics.fill(Tile.defaultTile())
tileGraphics.applyStyle(context.currentStyle)
}
}
| zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/renderer/DefaultVBoxRenderer.kt | 1160320403 |
package org.wordpress.android.widgets
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.annotation.AttrRes
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.NestedScrollingChild3
import androidx.core.view.NestedScrollingChildHelper
import org.wordpress.android.R
// Coordinator Layout that can be nested inside another Coordinator Layout and propagate
// its scroll state to it
// https://stackoverflow.com/a/37660246/569430
class NestedCoordinatorLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
@AttrRes
@SuppressLint("PrivateResource")
defStyleAttr: Int = R.attr.coordinatorLayoutStyle
) : CoordinatorLayout(context, attrs, defStyleAttr), NestedScrollingChild3 {
private val helper = NestedScrollingChildHelper(this)
init {
isNestedScrollingEnabled = true
}
override fun isNestedScrollingEnabled(): Boolean = helper.isNestedScrollingEnabled
override fun setNestedScrollingEnabled(enabled: Boolean) {
helper.isNestedScrollingEnabled = enabled
}
override fun hasNestedScrollingParent(type: Int): Boolean =
helper.hasNestedScrollingParent(type)
override fun hasNestedScrollingParent(): Boolean = helper.hasNestedScrollingParent()
override fun onStartNestedScroll(child: View, target: View, axes: Int, type: Int): Boolean {
val superResult = super.onStartNestedScroll(child, target, axes, type)
return startNestedScroll(axes, type) || superResult
}
override fun onStartNestedScroll(child: View, target: View, axes: Int): Boolean {
val superResult = super.onStartNestedScroll(child, target, axes)
return startNestedScroll(axes) || superResult
}
override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) {
val superConsumed = intArrayOf(0, 0)
super.onNestedPreScroll(target, dx, dy, superConsumed, type)
val thisConsumed = intArrayOf(0, 0)
dispatchNestedPreScroll(dx, dy, consumed, null, type)
consumed[0] = superConsumed[0] + thisConsumed[0]
consumed[1] = superConsumed[1] + thisConsumed[1]
}
override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray) {
val superConsumed = intArrayOf(0, 0)
super.onNestedPreScroll(target, dx, dy, superConsumed)
val thisConsumed = intArrayOf(0, 0)
dispatchNestedPreScroll(dx, dy, consumed, null)
consumed[0] = superConsumed[0] + thisConsumed[0]
consumed[1] = superConsumed[1] + thisConsumed[1]
}
override fun onNestedScroll(
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
type: Int,
consumed: IntArray
) {
dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null, type)
super.onNestedScroll(
target,
dxConsumed,
dyConsumed,
dxUnconsumed,
dyUnconsumed,
type,
consumed
)
}
override fun onNestedScroll(
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
type: Int
) {
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type)
dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null, type)
}
override fun onNestedScroll(
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int
) {
super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed)
dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null)
}
override fun onStopNestedScroll(target: View, type: Int) {
super.onStopNestedScroll(target, type)
stopNestedScroll(type)
}
override fun onStopNestedScroll(target: View) {
super.onStopNestedScroll(target)
stopNestedScroll()
}
override fun onNestedPreFling(target: View, velocityX: Float, velocityY: Float): Boolean {
val superResult = super.onNestedPreFling(target, velocityX, velocityY)
return dispatchNestedPreFling(velocityX, velocityY) || superResult
}
override fun onNestedFling(
target: View,
velocityX: Float,
velocityY: Float,
consumed: Boolean
): Boolean {
val superResult = super.onNestedFling(target, velocityX, velocityY, consumed)
return dispatchNestedFling(velocityX, velocityY, consumed) || superResult
}
override fun startNestedScroll(axes: Int, type: Int): Boolean =
helper.startNestedScroll(axes, type)
override fun startNestedScroll(axes: Int): Boolean = helper.startNestedScroll(axes)
override fun stopNestedScroll(type: Int) {
helper.stopNestedScroll(type)
}
override fun stopNestedScroll() {
helper.stopNestedScroll()
}
override fun dispatchNestedScroll(
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
offsetInWindow: IntArray?,
type: Int,
consumed: IntArray
) {
helper.dispatchNestedScroll(
dxConsumed,
dyConsumed,
dxUnconsumed,
dyUnconsumed,
offsetInWindow,
type,
consumed
)
}
override fun dispatchNestedScroll(
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
offsetInWindow: IntArray?,
type: Int
): Boolean = helper.dispatchNestedScroll(
dxConsumed,
dyConsumed,
dxUnconsumed,
dyUnconsumed,
offsetInWindow,
type
)
override fun dispatchNestedScroll(
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
offsetInWindow: IntArray?
): Boolean = helper.dispatchNestedScroll(
dxConsumed,
dyConsumed,
dxUnconsumed,
dyUnconsumed,
offsetInWindow
)
override fun dispatchNestedPreScroll(
dx: Int,
dy: Int,
consumed: IntArray?,
offsetInWindow: IntArray?,
type: Int
): Boolean = helper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type)
override fun dispatchNestedPreScroll(
dx: Int,
dy: Int,
consumed: IntArray?,
offsetInWindow: IntArray?
): Boolean = helper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow)
override fun dispatchNestedPreFling(velocityX: Float, velocityY: Float): Boolean =
helper.dispatchNestedPreFling(velocityX, velocityY)
override fun dispatchNestedFling(
velocityX: Float,
velocityY: Float,
consumed: Boolean
): Boolean = helper.dispatchNestedFling(velocityX, velocityY, consumed)
}
| WordPress/src/main/java/org/wordpress/android/widgets/NestedCoordinatorLayout.kt | 2598424727 |
package org.wordpress.android.ui.qrcodeauth
import android.content.Context
import android.content.Intent
import android.os.Bundle
import dagger.hilt.android.AndroidEntryPoint
import org.wordpress.android.databinding.QrcodeauthActivityBinding
import org.wordpress.android.ui.LocaleAwareActivity
@AndroidEntryPoint
class QRCodeAuthActivity : LocaleAwareActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
with(QrcodeauthActivityBinding.inflate(layoutInflater)) {
setContentView(root)
}
}
companion object {
@JvmStatic
fun start(context: Context) {
context.startActivity(newIntent(context))
}
@JvmStatic
fun newIntent(context: Context, uri: String? = null, fromDeeplink: Boolean = false): Intent {
val intent = Intent(context, QRCodeAuthActivity::class.java).apply {
putExtra(DEEP_LINK_URI_KEY, uri)
putExtra(IS_DEEP_LINK_KEY, fromDeeplink)
}
return intent
}
const val IS_DEEP_LINK_KEY = "is_deep_link_key"
const val DEEP_LINK_URI_KEY = "deep_link_uri_key"
}
}
| WordPress/src/main/java/org/wordpress/android/ui/qrcodeauth/QRCodeAuthActivity.kt | 2323523852 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.test
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.execution.process.ProcessOutputTypes
import org.jetbrains.kotlin.idea.debugger.coroutine.data.CoroutineInfoData
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineDebugProbesProxy
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences
abstract class AbstractCoroutineDumpTest : KotlinDescriptorTestCaseWithStackFrames() {
override fun doMultiFileTest(files: TestFiles, preferences: DebuggerPreferences) {
for (i in 0..countBreakpointsNumber(files.wholeFile)) {
doOnBreakpoint {
try {
printCoroutinesDump()
} finally {
resume(this)
}
}
}
}
private fun SuspendContextImpl.printCoroutinesDump() {
val infoCache = CoroutineDebugProbesProxy(this).dumpCoroutines()
if (!infoCache.isOk()) {
throw AssertionError("Dump failed")
}
val states = infoCache.cache
print(stringDump(states), ProcessOutputTypes.SYSTEM)
}
private fun stringDump(infoData: List<CoroutineInfoData>) = buildString {
infoData.forEach {
appendLine("\"${it.descriptor.name}#${it.descriptor.id}\", state: ${it.descriptor.state}")
}
}
}
| plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractCoroutineDumpTest.kt | 1565383 |
// "Add type 'Double' to parameter 'value'" "true"
class CollectionDefault(vararg val value = doubleArrayOf(1.0, 2.2)<caret>) | plugins/kotlin/idea/tests/testData/quickfix/addTypeAnnotationToValueParameter/annotationWithVarargDoubleArray.kt | 2452921712 |
package kotlinfromjava
// top-level function in Logger.kt
fun logMessage(message: String) = println(message) | kotlin/Mastering-Kotlin-master/Chapter02/src/kotlinfromjava/Logger.kt | 1641973956 |
/*
* The MIT License (MIT)
* Copyright (c) 2016 DataRank, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.simplymeasured.elasticsearch.plugins.tempest.balancer
import org.eclipse.collections.api.list.ListIterable
/**
* Capture the moves for a given batch plus some cluster stats assuming the batch is applied
*/
class MoveActionBatch(val moves: ListIterable<MoveAction>, val overhead: Long, val risk: Double, val score: Double) {
fun buildMoveDescriptions(): ListIterable<MoveDescription> = moves.collect { it.buildMoveDescription() }
} | src/main/java/com/simplymeasured/elasticsearch/plugins/tempest/balancer/MoveActionBatch.kt | 3971809753 |
package org.snakeskin.dsl
import com.revrobotics.CANSparkMax
import com.revrobotics.CANSparkMaxLowLevel
import org.snakeskin.component.Hardware
import org.snakeskin.component.ISparkMaxDevice
import org.snakeskin.component.SparkMaxOutputVoltageReadingMode
import org.snakeskin.component.impl.HardwareSparkMaxDevice
import org.snakeskin.component.impl.NullSparkMaxDevice
import org.snakeskin.runtime.SnakeskinPlatform
import org.snakeskin.runtime.SnakeskinRuntime
/**
* Creates a new SPARK MAX device object in brushed mode.
* @param hardwareId THe CAN ID of the SPARK MAX
* @param encoderCpr Counts per rev of attached quadrature encoder, or 0 if no encoder is attached
* @param voltageReadingMode The mode to read output voltage from the SPARK MAX
* @param useAlternateEncoderPinout Whether or not to use the "alternate encoder" pinout
* @param mockProducer Function which returns a mock object representing the device, used for emulating hardware
*/
inline fun Hardware.createBrushedSparkMax(
hardwareId: Int,
encoderCpr: Int = 0,
voltageReadingMode: SparkMaxOutputVoltageReadingMode = SparkMaxOutputVoltageReadingMode.MultiplyVbusSystem,
useAlternateEncoderPinout: Boolean = false,
mockProducer: () -> ISparkMaxDevice = { throw NotImplementedError("No mock SPARK MAX implementation provided") }
) = when (SnakeskinRuntime.platform) {
SnakeskinPlatform.UNDEFINED -> NullSparkMaxDevice.INSTANCE
SnakeskinPlatform.FRC_ROBORIO -> HardwareSparkMaxDevice(CANSparkMax(
hardwareId,
CANSparkMaxLowLevel.MotorType.kBrushed
), voltageReadingMode, useAlternateEncoderPinout, encoderCpr)
else -> mockProducer()
}
/**
* Creates a new SPARK MAX device object in brushless mode, using the internal encoder.
* @param hardwareId THe CAN ID of the SPARK MAX
* @param voltageReadingMode The mode to read output voltage from the SPARK MAX
* @param mockProducer Function which returns a mock object representing the device, used for emulating hardware
*/
inline fun Hardware.createBrushlessSparkMax(
hardwareId: Int,
voltageReadingMode: SparkMaxOutputVoltageReadingMode = SparkMaxOutputVoltageReadingMode.MultiplyVbusSystem,
mockProducer: () -> ISparkMaxDevice = { throw NotImplementedError("No mock SPARK MAX implementation provided") }
) = when (SnakeskinRuntime.platform) {
SnakeskinPlatform.UNDEFINED -> NullSparkMaxDevice.INSTANCE
SnakeskinPlatform.FRC_ROBORIO -> HardwareSparkMaxDevice(CANSparkMax(
hardwareId,
CANSparkMaxLowLevel.MotorType.kBrushless
), voltageReadingMode, false)
else -> mockProducer()
}
/**
* Creates a new SPARK MAX device object in brushless mode, using an external encoder in the "alternate pinout".
* @param hardwareId THe CAN ID of the SPARK MAX
* @param encoderCpr Counts per rev of attached quadrature encoder
* @param voltageReadingMode The mode to read output voltage from the SPARK MAX
* @param mockProducer Function which returns a mock object representing the device, used for emulating hardware
*/
inline fun Hardware.createBrushlessSparkMaxWithEncoder(
hardwareId: Int,
encoderCpr: Int,
voltageReadingMode: SparkMaxOutputVoltageReadingMode = SparkMaxOutputVoltageReadingMode.MultiplyVbusSystem,
mockProducer: () -> ISparkMaxDevice = { throw NotImplementedError("No mock SPARK MAX implementation provided") }
) = when (SnakeskinRuntime.platform) {
SnakeskinPlatform.UNDEFINED -> NullSparkMaxDevice.INSTANCE
SnakeskinPlatform.FRC_ROBORIO -> HardwareSparkMaxDevice(CANSparkMax(
hardwareId,
CANSparkMaxLowLevel.MotorType.kBrushless
), voltageReadingMode, true, encoderCpr)
else -> mockProducer()
}
/**
* Allows access to hardware device functions of a SPARK MAX device
* @param sparkMaxDevice The SPARK MAX device object
* @param action The action to run on the hardware. If the runtime is not hardware, the action will not be run
*/
inline fun useHardware(sparkMaxDevice: ISparkMaxDevice, action: CANSparkMax.() -> Unit) {
if (sparkMaxDevice is HardwareSparkMaxDevice) {
action(sparkMaxDevice.device)
}
} | SnakeSkin-REV/src/main/kotlin/org/snakeskin/dsl/RevHardwareExtensions.kt | 986438897 |
/*
* HiddenSpan.kt
*
* Copyright 2018 Michael Farrell <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.ui
import android.graphics.Canvas
import android.graphics.Paint
import android.text.style.ReplacementSpan
/**
* Span which is not drawn on screen.
*
* This is used to include elements in a TextView which a screen reader should speak, but
* should not be displayed on the screen.
*
* This is used to make some labels sound more natural, where they otherwise require
* Unicode characters without sufficient meaning to be read.
*/
class HiddenSpan : ReplacementSpan() {
override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {}
override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int = 0
}
| src/main/java/au/id/micolous/metrodroid/ui/HiddenSpan.kt | 2470282846 |
/*
* Copyright (c) 2021
*
* 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.acra.config
import com.faendir.kotlin.autodsl.AutoDsl
import org.acra.annotation.AcraDsl
import org.acra.ktx.plus
import java.util.concurrent.TimeUnit
/**
* Limiter configuration
*
* @author F43nd1r
* @since 26.10.2017
*/
@AutoDsl(dslMarker = AcraDsl::class)
class LimiterConfiguration(
/**
* enables this plugin
*/
val enabled: Boolean = true,
/**
* Unit of [period]
*
* @since 5.0.0
*/
val periodUnit: TimeUnit = TimeUnit.DAYS,
/**
* number of [periodUnit]s in which to limit reports
*
* Reports which have been collected before this will not be considered for any limits except [failedReportLimit]
*
* @since 5.0.0
*/
val period: Long = 7,
/**
* general limit of reports per period
*
* @since 5.0.0
*/
val overallLimit: Int = 25,
/**
* limit for reports with the same stacktrace per period
*
* @since 5.0.0
*/
val stacktraceLimit: Int = 3,
/**
* limit for reports with the same exception class per period
*
* @since 5.0.0
*/
val exceptionClassLimit: Int = 10,
/**
* limit for unsent reports to keep
*
* @since 5.0.0
*/
val failedReportLimit: Int = 5,
/**
* toast shown when a report was not collected or sent because a limit was exceeded
*
* @since 5.0.0
*/
val ignoredCrashToast: String? = null,
/**
* This property can be used to determine whether old (out of date) reports should be sent or not.
*
* @since 5.3.0
*/
val deleteReportsOnAppUpdate: Boolean = true,
/**
* Resetting limits after an app update allows you to see if a bug still exists.
*
* @since 5.3.0
*/
val resetLimitsOnAppUpdate: Boolean = true,
) : Configuration {
override fun enabled(): Boolean = enabled
}
fun CoreConfigurationBuilder.limiter(initializer: LimiterConfigurationBuilder.() -> Unit) {
pluginConfigurations += LimiterConfigurationBuilder().apply(initializer).build()
}
| acra-limiter/src/main/java/org/acra/config/LimiterConfiguration.kt | 3986004493 |
package io.github.fvasco.pinpoi.dao
import android.content.Context
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import io.github.fvasco.pinpoi.model.PlacemarkCollection
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* @author Francesco Vasco
*/
@RunWith(AndroidJUnit4::class)
class PlacemarkCollectionDaoTest {
private lateinit var dao: PlacemarkCollectionDao
lateinit var instrumentationContext: Context
@Before
fun setUp() {
instrumentationContext = InstrumentationRegistry.getInstrumentation().context
dao = PlacemarkCollectionDao(instrumentationContext)
dao.open()
for (pc in dao.findAllPlacemarkCollection()) {
dao.delete(pc)
}
}
@After
fun tearDown() {
dao.close()
}
@Test
fun testFindPlacemarkCollectionCategory() {
val pc = PlacemarkCollection()
pc.name = "test"
pc.description = "description"
pc.source = "source"
pc.category = "CATEGORY"
pc.lastUpdate = System.currentTimeMillis()
dao.insert(pc)
val list = dao.findAllPlacemarkCollectionCategory()
assertEquals(1, list.size)
val category = list[0]
assertEquals("CATEGORY", category)
}
@Test
fun testFindPlacemarkCollection() {
val pc = PlacemarkCollection()
pc.name = "test"
pc.description = "description"
pc.source = "source"
pc.category = "CATEGORY"
pc.lastUpdate = 1
pc.poiCount = 2
dao.insert(pc)
val id = pc.id
// check findPlacemarkCollectionById
val dbpc = dao.findPlacemarkCollectionById(id) ?: error("not found")
assertEquals(id, dbpc.id)
assertEquals("test", dbpc.name)
assertEquals("description", dbpc.description)
assertEquals("source", dbpc.source)
assertEquals("CATEGORY", dbpc.category)
assertEquals(1, dbpc.lastUpdate)
assertEquals(2, dbpc.poiCount)
pc.name = "test2"
pc.description = "description2"
pc.source = "source2"
pc.category = "CATEGORY2"
pc.lastUpdate = 5
pc.poiCount = 6
dao.update(pc)
// check findAllPlacemarkCollection
val list1 = dao.findAllPlacemarkCollection()
assertEquals(1, list1.size)
val pc0 = list1[0]
assertNotNull(pc0)
assertEquals(id, pc0.id)
assertEquals("test2", pc0.name)
assertEquals("description2", pc0.description)
assertEquals("source2", pc0.source)
assertEquals("CATEGORY2", pc0.category)
assertEquals(5, pc0.lastUpdate)
assertEquals(6, pc0.poiCount)
dao.delete(pc)
val list0 = dao.findAllPlacemarkCollection()
assertTrue(list0.isEmpty())
assertNull(dao.findPlacemarkCollectionById(1))
}
@Test
fun testFindPlacemarkCollectionByName() {
val pc = PlacemarkCollection()
pc.name = "test"
pc.description = "description"
pc.source = "source"
pc.category = "CATEGORY"
pc.lastUpdate = 5
pc.poiCount = 6
dao.insert(pc)
val id = pc.id
// check findPlacemarkCollectionByName
val dbpc = dao.findPlacemarkCollectionByName("test") ?: error("test not found")
assertEquals(id, dbpc.id)
assertEquals("test", dbpc.name)
assertEquals("description", dbpc.description)
assertEquals("source", dbpc.source)
assertEquals("CATEGORY", dbpc.category)
assertEquals(5, dbpc.lastUpdate)
assertEquals(6, dbpc.poiCount)
}
} | app/src/androidTest/java/io/github/fvasco/pinpoi/dao/PlacemarkCollectionDaoTest.kt | 2889060184 |
package io.github.knes1.kotao.brew
import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.StaticHandler
import io.vertx.ext.web.handler.sockjs.BridgeOptions
import io.vertx.ext.web.handler.sockjs.SockJSHandler
import io.vertx.kotlin.ext.web.handler.sockjs.PermittedOptions
import java.io.File
import java.nio.charset.Charset
/**
* Web server serving the generated content. It also listens on "updates" vertx event bus address for messages to
* update the fronted. Any such messages is passed via injected SockJS to the browser which then reloads the page.
*
* Web server is implemented as vertx verticle.
*
* @author knesek
* Created on: 5/26/17
*/
class WebServer(
val webRoot: String
) : AbstractVerticle() {
override fun start() {
val server = vertx.createHttpServer()
val router = Router.router(vertx)
val sockJSHandler = SockJSHandler.create(vertx)
val options = BridgeOptions().addOutboundPermitted(PermittedOptions("updates"))
sockJSHandler.bridge(options)
// Handler for Kotao administrative static files and scripts
router.route("/_kotao/static/*").handler(StaticHandler.create())
// Handler for Kotao event bus used for pushing updates
router.route("/_kotao/eventbus/*").handler(sockJSHandler)
// Injection handler that intercepts html files and injects Kotlin admin scripts,
// otherwise it delegates to static handler
router.get("/*").handler {
val response = it.response()
if (it.request().uri().endsWith("/")) {
it.reroute(it.request().uri() + "index.html")
return@handler
}
val file = File(webRoot + it.request().uri())
if (file.isDirectory) {
it.reroute(it.request().uri() + "index.html")
return@handler
}
if (!it.request().uri().endsWith("html")) {
it.next()
return@handler
}
if (!file.exists()) {
it.next()
return@handler
}
it.vertx().executeBlocking({ future: Future<String> ->
val contents = file.readText(Charset.forName("UTF-8"))
val injected = contents.replace("<body>", """<body>
<script src="/_kotao/static/sockjs.min.js"></script>
<script src='/_kotao/static/vertx-eventbus.js'></script>
<script src='/_kotao/static/spin.min.js'></script>
<script src='/_kotao/static/kotao.js'></script>
"""
)
future.complete(injected)
}, { asyncResult ->
if (asyncResult.succeeded()) {
response.end(asyncResult.result(), "UTF-8")
} else {
// In case of any kind of failure resulting from our injection logic, we just delegate
// to static handler to handle it.
it.next()
}
})
}
// Static serving files from the output. Read only flag set to false to prevent caching.
router.route("/*").handler(StaticHandler.create(webRoot).setFilesReadOnly(false))
server.requestHandler {
router.accept(it)
}.listen(8080)
}
} | src/main/kotlin/io/github/knes1/kotao/brew/WebServer.kt | 3733168149 |
package org.jetbrains.completion.full.line.settings.state
import com.intellij.lang.Language
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.completion.full.line.language.*
import org.jetbrains.completion.full.line.models.ModelType
@State(
name = "MLServerCompletionSettings",
storages = [Storage("MLServerCompletionSettings.xml", deprecated = true), Storage("full.line.xml")]
)
class MLServerCompletionSettings : PersistentStateComponent<GeneralState> {
private var state = GeneralState()
// ----------------------------- Methods for state persisting ------------------------------ //
override fun initializeComponent() {
loadEvaluationConfig()
}
override fun loadState(state: GeneralState) {
this.state.langStates.forEach {
state.langStates.putIfAbsent(it.key, it.value)
}
this.state = state
}
companion object {
fun isExtended() = Registry.get("full.line.expand.settings").asBoolean()
fun getInstance(): MLServerCompletionSettings {
return service()
}
val availableLanguages: List<Language>
get() = FullLineLanguageSupporter.supportedLanguages()
}
// ----------------------------------- State getters --------------------------------------- //
override fun getState() = state
fun getLangState(language: Language): LangState = getLangStateSafe(language)
?: throw IllegalArgumentException("Language ${language.displayName} is not supported")
private fun getLangStateSafe(language: Language): LangState? = state.langStates[language.id]
?: language.baseLanguage?.let { state.langStates[it.id] }
// ------------------------------ Common settings getters ---------------------------------- //
fun isEnabled(): Boolean = state.enable
fun isGreyTextMode(): Boolean = state.useGrayText
fun enableStringsWalking(language: Language): Boolean = getLangState(language).stringsWalking
fun showScore(language: Language): Boolean = getLangState(language).showScore
fun topN(): Int? = if (state.useTopN) state.topN else null
fun groupTopN(language: Language): Int? = getModelState(language).let { if (it.useGroupTopN) it.groupTopN else null }
fun checkRedCode(language: Language): Boolean = getLangState(language).redCodePolicy != RedCodePolicy.SHOW
fun hideRedCode(language: Language): Boolean = getLangState(language).redCodePolicy == RedCodePolicy.FILTER
@Suppress("REDUNDANT_ELSE_IN_WHEN")
fun getModelState(langState: LangState, type: ModelType = state.modelType): ModelState {
return when (type) {
ModelType.Cloud -> langState.cloudModelState
ModelType.Local -> langState.localModelState
else -> throw IllegalArgumentException("Got unexpected modelType `${type}`.")
}
}
fun getModelState(language: Language, modelType: ModelType): ModelState = getModelState(getLangState(language), modelType)
fun getModelMode(): ModelType = state.modelType
fun getModelState(language: Language): ModelState = getModelState(getLangState(language))
// --------------------------- Language-specific settings getters -------------------------- //
fun isLanguageSupported(language: Language): Boolean = getLangStateSafe(language) != null
// Check if completion enabled for current language or if the current language is based on supported
fun isEnabled(language: Language): Boolean {
// TODO: add correct handle for not specified language. Hotfix in 0.2.1
return try {
getLangState(language).enabled && isEnabled()
}
catch (e: Exception) {
false
}
}
private fun loadEvaluationConfig() {
val isTesting = System.getenv("flcc_evaluating") ?: return
if (!isTesting.toBoolean()) return
// General settings
System.getenv("flcc_enable")?.toBoolean()?.let { state.enable = it }
System.getenv("flcc_topN")?.toInt()?.let {
state.useTopN = true
state.topN = it
}
System.getenv("flcc_useGrayText")?.toBoolean()?.let { state.useGrayText = it }
System.getenv("flcc_modelType")?.let { state.modelType = ModelType.valueOf(it) }
// Registries
System.getenv("flcc_max_latency")?.let {
Registry.get("full.line.server.host.max.latency").setValue(it.toInt())
}
System.getenv("flcc_only_proposals")?.let {
Registry.get("full.line.only.proposals").setValue(it.toBoolean())
}
System.getenv("flcc_multi_token_only")?.let {
Registry.get("full.line.multi.token.everywhere").setValue(it.toBoolean())
}
System.getenv("flcc_caching")?.let {
Registry.get("full.line.enable.caching").setValue(it.toBoolean())
}
// Language-specific settings
val langId = System.getenv("flcc_language") ?: return
val langState = state.langStates
.mapKeys { (k, _) -> k.toLowerCase() }
.getValue(langId)
System.getenv("flcc_enabled")?.toBoolean()?.let { langState.enabled = it }
System.getenv("flcc_onlyFullLines")?.toBoolean()?.let { langState.onlyFullLines = it }
System.getenv("flcc_stringsWalking")?.toBoolean()?.let { langState.stringsWalking = it }
System.getenv("flcc_showScore")?.toBoolean()?.let { langState.showScore = it }
System.getenv("flcc_redCodePolicy")?.let { langState.redCodePolicy = RedCodePolicy.valueOf(it) }
System.getenv("flcc_groupAnswers")?.toBoolean()?.let { langState.groupAnswers = it }
// Lang-registries
@Suppress("UnresolvedPluginConfigReference") System.getenv("flcc_host")?.let {
Registry.get("full.line.server.host.${langId.toLowerCase()}").setValue(it)
Registry.get("full.line.server.host.psi.${langId.toLowerCase()}").setValue(it)
}
// Beam search configuration
val modelState = getModelState(langState)
System.getenv("flcc_numIterations")?.toInt()?.let { modelState.numIterations = it }
System.getenv("flcc_beamSize")?.toInt()?.let { modelState.beamSize = it }
System.getenv("flcc_diversityGroups")?.toInt()?.let { modelState.diversityGroups = it }
System.getenv("flcc_diversityStrength")?.toDouble()?.let { modelState.diversityStrength = it }
System.getenv("flcc_lenPow")?.toDouble()?.let { modelState.lenPow = it }
System.getenv("flcc_lenBase")?.toDouble()?.let { modelState.lenBase = it }
System.getenv("flcc_groupTopN")?.toInt()?.let {
modelState.useGroupTopN = true
modelState.groupTopN = it
}
System.getenv("flcc_customContextLength")?.toInt()?.let {
modelState.useCustomContextLength = true
modelState.customContextLength = it
}
System.getenv("flcc_minimumPrefixDist")?.toDouble()?.let { modelState.minimumPrefixDist = it }
System.getenv("flcc_minimumEditDist")?.toDouble()?.let { modelState.minimumEditDist = it }
System.getenv("flcc_keepKinds")?.let {
modelState.keepKinds = it.removePrefix("[").removeSuffix("]")
.split(",").asSequence()
.onEach { it.trim() }.filter { it.isNotBlank() }
.map { KeepKind.valueOf(it) }.toMutableSet()
}
System.getenv("flcc_psiBased")?.toBoolean()?.let { modelState.psiBased = it }
}
}
| plugins/full-line/src/org/jetbrains/completion/full/line/settings/state/MLServerCompletionSettings.kt | 1008888228 |
// 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.intellij.plugins.markdown.editor.images
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.html.HtmlTag
import com.intellij.psi.util.parentOfType
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.lang.MarkdownLanguage
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownImage
internal class MarkdownConfigureImageIntention: PsiElementBaseIntentionAction() {
override fun getFamilyName(): String = text
override fun getText(): String {
return MarkdownBundle.message("markdown.configure.image.text")
}
override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
val (targetElement, provider) = findElementAndProvider(element) ?: return
ApplicationManager.getApplication().invokeLater {
provider.performAction(targetElement)
}
}
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean {
return findElementAndProvider(element) != null
}
override fun checkFile(file: PsiFile?): Boolean {
return super.checkFile(file) && file?.viewProvider?.baseLanguage == MarkdownLanguage.INSTANCE
}
companion object {
private val markdownProvider by lazy { ConfigureMarkdownImageLineMarkerProvider() }
private val htmlProvider by lazy { ConfigureHtmlImageLineMarkerProvider() }
private val textHtmlProvider by lazy { ConfigureTextHtmlImageLineMarkerProvider() }
private val searchFunctions by lazy { arrayOf(::findForMarkdown, ::findForHtml, ::findForTextHtml) }
private fun findForMarkdown(element: PsiElement): Pair<PsiElement, ConfigureImageLineMarkerProviderBase<*>>? {
val targetElement = element.parentOfType<MarkdownImage>(withSelf = true) ?: return null
return targetElement to markdownProvider
}
private fun findForHtml(element: PsiElement): Pair<PsiElement, ConfigureImageLineMarkerProviderBase<*>>? {
val targetElement = element.parentOfType<HtmlTag>(withSelf = true)?.takeIf { it.name == "img" } ?: return null
return targetElement to htmlProvider
}
private fun findForTextHtml(element: PsiElement): Pair<PsiElement, ConfigureImageLineMarkerProviderBase<*>>? {
val targetElement = textHtmlProvider.obtainOuterElement(element) ?: return null
return targetElement to textHtmlProvider
}
private fun findElementAndProvider(element: PsiElement): Pair<PsiElement, ConfigureImageLineMarkerProviderBase<*>>? {
for (find in searchFunctions) {
return find.invoke(element) ?: continue
}
return null
}
}
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/editor/images/MarkdownConfigureImageIntention.kt | 3099040303 |
// 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.ide.bookmark.providers
import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.bookmark.BookmarkProvider
import com.intellij.ide.projectView.impl.ModuleGroupUrl
import com.intellij.ide.projectView.impl.ModuleUrl
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService
import com.intellij.openapi.util.text.StringUtil
internal class ModuleBookmarkProvider(private val project: Project) : BookmarkProvider {
override fun getWeight() = 200
override fun getProject() = project
internal val moduleManager
get() = if (project.isDisposed) null else ModuleManager.getInstance(project)
internal val projectSettingsService
get() = if (project.isDisposed) null else ProjectSettingsService.getInstance(project)
override fun compare(bookmark1: Bookmark, bookmark2: Bookmark): Int {
bookmark1 as ModuleBookmark
bookmark2 as ModuleBookmark
if (bookmark1.isGroup && !bookmark2.isGroup) return -1
if (!bookmark1.isGroup && bookmark2.isGroup) return +1
return StringUtil.naturalCompare(bookmark1.name, bookmark2.name)
}
override fun createBookmark(map: MutableMap<String, String>) =
map["group"]?.let { ModuleBookmark(this, it, true) } ?: map["module"]?.let { ModuleBookmark(this, it, false) }
private fun createGroupBookmark(name: String?) = name?.let { ModuleBookmark(this, it, true) }
private fun createModuleBookmark(name: String?) = name?.let { ModuleBookmark(this, it, false) }
override fun createBookmark(context: Any?): ModuleBookmark? = when (context) {
is ModuleGroupUrl -> createGroupBookmark(context.url)
is ModuleUrl -> createModuleBookmark(context.url)
is Module -> createModuleBookmark(context.name)
else -> null
}
}
| platform/lang-impl/src/com/intellij/ide/bookmark/providers/ModuleBookmarkProvider.kt | 3376633470 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.api.dto
import com.intellij.collaboration.api.dto.GraphQLFragment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import org.jetbrains.plugins.gitlab.api.data.GitLabAccessLevel
@GraphQLFragment("graphql/fragment/member.graphql")
class GitLabMemberDTO(
val id: String,
val user: GitLabUserDTO,
accessLevel: AccessLevel
) {
val accessLevel: GitLabAccessLevel = parseAccessLevel(accessLevel.stringValue)
class AccessLevel(val stringValue: String)
companion object {
private val logger: Logger = logger<GitLabMemberDTO>()
private fun parseAccessLevel(accessLevel: String) = try {
GitLabAccessLevel.valueOf(accessLevel)
}
catch (_: IllegalArgumentException) {
logger.error("Unable to parse access level")
GitLabAccessLevel.NO_ACCESS
}
}
} | plugins/gitlab/src/org/jetbrains/plugins/gitlab/api/dto/GitLabMemberDTO.kt | 2983668643 |
// EXTRACTION_TARGET: property with initializer
val a = 1
fun foo(): String {
return <selection>"1"+getString()</selection>
}
fun getString(): String {
return "1"
} | plugins/kotlin/idea/tests/testData/refactoring/introduceConstant/binaryExpression/stringPlusPartNotConst.kt | 4018252870 |
// 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.jps
import com.intellij.openapi.compiler.CompileContext
import com.intellij.openapi.compiler.CompileTask
import com.intellij.openapi.compiler.CompilerMessageCategory
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.project.stateStore
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.config.SettingConstants
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinArtifactsDownloader
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import com.intellij.openapi.application.runReadAction
class SetupKotlinJpsPluginBeforeCompileTask : CompileTask {
override fun execute(context: CompileContext): Boolean {
val project = context.project
val jpsVersion = KotlinJpsPluginSettings.supportedJpsVersion(
project = project,
onUnsupportedVersion = { context.addErrorWithReferenceToKotlincXml(it) }
) ?: return true
return KotlinArtifactsDownloader.lazyDownloadMissingJpsPluginDependencies(
project = project,
jpsVersion = jpsVersion,
indicator = context.progressIndicator,
onError = { context.addError(it) }
)
}
private fun CompileContext.addError(@Nls(capitalization = Nls.Capitalization.Sentence) msg: String) =
addMessage(CompilerMessageCategory.ERROR, msg, null, -1, -1)
private fun CompileContext.addErrorWithReferenceToKotlincXml(@Nls(capitalization = Nls.Capitalization.Sentence) msg: String) {
val virtualFile = project.stateStore
.directoryStorePath
?.resolve(SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE)
?.let(VirtualFileManager.getInstance()::findFileByNioPath)
val psiFile = runReadAction { virtualFile?.toPsiFile(project) }
addMessage(CompilerMessageCategory.ERROR, msg, virtualFile?.url, -1, -1, psiFile)
}
}
| plugins/kotlin/base/jps/src/org/jetbrains/kotlin/idea/jps/SetupKotlinJpsPluginBeforeCompileTask.kt | 310379465 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.importing.workspaceModel
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.module.impl.ModuleManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.util.containers.addIfNotNull
import com.intellij.workspaceModel.ide.impl.FileInDirectorySourceNames
import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.idea.maven.importing.MavenImportUtil
import org.jetbrains.idea.maven.importing.StandardMavenModuleType
import org.jetbrains.idea.maven.importing.tree.MavenModuleImportData
import org.jetbrains.idea.maven.importing.tree.MavenTreeModuleImportData
import org.jetbrains.idea.maven.importing.tree.dependency.*
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.model.MavenConstants
import org.jetbrains.idea.maven.project.MavenImportingSettings
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.utils.MavenLog
internal class WorkspaceModuleImporter(
private val project: Project,
private val importData: MavenTreeModuleImportData,
private val virtualFileUrlManager: VirtualFileUrlManager,
private val builder: MutableEntityStorage,
private val existingEntitySourceNames: FileInDirectorySourceNames,
private val importingSettings: MavenImportingSettings,
private val folderImportingContext: WorkspaceFolderImporter.FolderImportingContext,
private val stats: WorkspaceImportStats
) {
private val externalSource = ExternalProjectSystemRegistry.getInstance().getSourceById(EXTERNAL_SOURCE_ID)
fun importModule(): ModuleEntity {
val baseModuleDir = virtualFileUrlManager.fromPath(importData.mavenProject.directory)
val moduleName = importData.moduleData.moduleName
val moduleLibrarySource = JpsEntitySourceFactory.createEntitySourceForModule(project, baseModuleDir, externalSource,
existingEntitySourceNames,
moduleName + ModuleManagerEx.IML_EXTENSION)
val dependencies = collectDependencies(moduleName, importData.dependencies, moduleLibrarySource)
val moduleEntity = createModuleEntity(moduleName, importData.mavenProject, importData.moduleData.type, dependencies,
moduleLibrarySource)
configureModuleEntity(importData, moduleEntity, folderImportingContext)
return moduleEntity
}
private fun reuseOrCreateProjectLibrarySource(libraryName: String): EntitySource {
return JpsEntitySourceFactory.createEntitySourceForProjectLibrary(project, externalSource, existingEntitySourceNames, libraryName)
}
private fun createModuleEntity(moduleName: String,
mavenProject: MavenProject,
mavenModuleType: StandardMavenModuleType,
dependencies: List<ModuleDependencyItem>,
entitySource: EntitySource): ModuleEntity {
val moduleEntity = builder.addModuleEntity(moduleName, dependencies, entitySource, ModuleTypeId.JAVA_MODULE)
val externalSystemModuleOptionsEntity = ExternalSystemModuleOptionsEntity(entitySource) {
ExternalSystemData(moduleEntity, mavenProject.file.path, mavenModuleType).write(this)
}
builder.addEntity(externalSystemModuleOptionsEntity)
return moduleEntity
}
private fun configureModuleEntity(importData: MavenModuleImportData,
moduleEntity: ModuleEntity,
folderImportingContext: WorkspaceFolderImporter.FolderImportingContext) {
val folderImporter = WorkspaceFolderImporter(builder, virtualFileUrlManager, importingSettings, folderImportingContext)
val importFolderHolder = folderImporter.createContentRoots(importData.mavenProject, importData.moduleData.type, moduleEntity,
stats)
importJavaSettings(moduleEntity, importData, importFolderHolder)
}
private fun collectDependencies(moduleName: String,
dependencies: List<Any>,
moduleLibrarySource: EntitySource): List<ModuleDependencyItem> {
val result = ArrayList<ModuleDependencyItem>(2 + dependencies.size)
result.add(ModuleDependencyItem.InheritedSdkDependency)
result.add(ModuleDependencyItem.ModuleSourceDependency)
for (dependency in dependencies) {
val created = when (dependency) {
is SystemDependency ->
createSystemDependency(moduleName, dependency.artifact) { moduleLibrarySource }
is LibraryDependency ->
createLibraryDependency(dependency.artifact) { reuseOrCreateProjectLibrarySource(dependency.artifact.libraryName) }
is AttachedJarDependency ->
createLibraryDependency(dependency.artifact,
toScope(dependency.scope),
{
dependency.rootPaths.map { (url, type) ->
LibraryRoot(virtualFileUrlManager.fromUrl(pathToUrl(url)), type)
}
},
{ reuseOrCreateProjectLibrarySource(dependency.artifact) })
is ModuleDependency ->
ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(dependency.artifact),
false,
toScope(dependency.scope),
dependency.isTestJar)
is BaseDependency ->
createLibraryDependency(dependency.artifact) { reuseOrCreateProjectLibrarySource(dependency.artifact.libraryName) }
else -> null
}
result.addIfNotNull(created)
}
return result
}
private fun pathToUrl(it: String) = VirtualFileManager.constructUrl(JarFileSystem.PROTOCOL, it) + JarFileSystem.JAR_SEPARATOR
private fun toScope(scope: DependencyScope): ModuleDependencyItem.DependencyScope =
when (scope) {
DependencyScope.RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME
DependencyScope.TEST -> ModuleDependencyItem.DependencyScope.TEST
DependencyScope.PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED
else -> ModuleDependencyItem.DependencyScope.COMPILE
}
private fun createSystemDependency(moduleName: String,
artifact: MavenArtifact,
sourceProvider: () -> EntitySource): ModuleDependencyItem.Exportable.LibraryDependency {
assert(MavenConstants.SCOPE_SYSTEM == artifact.scope)
val libraryId = LibraryId(artifact.libraryName, LibraryTableId.ModuleLibraryTableId(moduleId = ModuleId(moduleName)))
addLibraryEntity(libraryId,
{
val classes = MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)
listOf(LibraryRoot(virtualFileUrlManager.fromUrl(classes), LibraryRootTypeId.COMPILED))
},
sourceProvider)
return ModuleDependencyItem.Exportable.LibraryDependency(libraryId, false, artifact.dependencyScope)
}
private fun createLibraryDependency(artifact: MavenArtifact,
sourceProvider: () -> EntitySource): ModuleDependencyItem.Exportable.LibraryDependency {
assert(MavenConstants.SCOPE_SYSTEM != artifact.scope)
val libraryRootsProvider = {
val classes = MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)
val sources = MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, "sources", "jar")
val javadoc = MavenImportUtil.getArtifactUrlForClassifierAndExtension(artifact, "javadoc", "jar")
listOf(
LibraryRoot(virtualFileUrlManager.fromUrl(classes), LibraryRootTypeId.COMPILED),
LibraryRoot(virtualFileUrlManager.fromUrl(sources), LibraryRootTypeId.SOURCES),
LibraryRoot(virtualFileUrlManager.fromUrl(javadoc), JAVADOC_TYPE),
)
}
return createLibraryDependency(artifact.libraryName,
artifact.dependencyScope,
libraryRootsProvider,
sourceProvider)
}
private fun createLibraryDependency(
libraryName: String,
scope: ModuleDependencyItem.DependencyScope,
libraryRootsProvider: () -> List<LibraryRoot>,
sourceProvider: () -> EntitySource
): ModuleDependencyItem.Exportable.LibraryDependency {
val libraryId = LibraryId(libraryName, LibraryTableId.ProjectLibraryTableId)
addLibraryEntity(libraryId, libraryRootsProvider, sourceProvider)
return ModuleDependencyItem.Exportable.LibraryDependency(libraryId, false, scope)
}
private fun addLibraryEntity(
libraryId: LibraryId,
libraryRootsProvider: () -> List<LibraryRoot>, // lazy provider to avoid roots creation for already added libraries
sourceProvider: () -> EntitySource) {
if (libraryId in builder) return
builder.addLibraryEntity(libraryId.name,
libraryId.tableId,
libraryRootsProvider(),
emptyList(),
sourceProvider())
}
private val MavenArtifact.dependencyScope: ModuleDependencyItem.DependencyScope
get() = when (scope) {
MavenConstants.SCOPE_RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME
MavenConstants.SCOPE_TEST -> ModuleDependencyItem.DependencyScope.TEST
MavenConstants.SCOPE_PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED
else -> ModuleDependencyItem.DependencyScope.COMPILE
}
private fun importJavaSettings(moduleEntity: ModuleEntity,
importData: MavenModuleImportData,
importFolderHolder: WorkspaceFolderImporter.CachedProjectFolders) {
val languageLevel = MavenImportUtil.getLanguageLevel(importData.mavenProject) { importData.moduleData.sourceLanguageLevel }
var inheritCompilerOutput = true
var compilerOutputUrl: VirtualFileUrl? = null
var compilerOutputUrlForTests: VirtualFileUrl? = null
val moduleType = importData.moduleData.type
if (moduleType.containsCode && importingSettings.isUseMavenOutput) {
inheritCompilerOutput = false
if (moduleType.containsMain) {
compilerOutputUrl = virtualFileUrlManager.fromPath(importFolderHolder.outputPath)
}
if (moduleType.containsTest) {
compilerOutputUrlForTests = virtualFileUrlManager.fromPath(importFolderHolder.testOutputPath)
}
}
builder.addJavaModuleSettingsEntity(inheritCompilerOutput, false, compilerOutputUrl, compilerOutputUrlForTests,
languageLevel.name, moduleEntity, moduleEntity.entitySource)
}
companion object {
val JAVADOC_TYPE: LibraryRootTypeId = LibraryRootTypeId("JAVADOC")
val EXTERNAL_SOURCE_ID get() = ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID
}
class ExternalSystemData(val moduleEntity: ModuleEntity, val mavenProjectFilePath: String, val mavenModuleType: StandardMavenModuleType) {
fun write(entity: ExternalSystemModuleOptionsEntity.Builder) {
entity.externalSystemModuleVersion = VERSION
entity.module = moduleEntity
entity.externalSystem = EXTERNAL_SOURCE_ID
// Can't use 'entity.linkedProjectPath' since it implies directory (and used to set working dir for Run Configurations).
entity.linkedProjectId = FileUtil.toSystemIndependentName(mavenProjectFilePath)
entity.externalSystemModuleType = mavenModuleType.name
}
companion object {
const val VERSION = "223-2"
fun isFromLegacyImport(entity: ExternalSystemModuleOptionsEntity): Boolean {
return entity.externalSystem == EXTERNAL_SOURCE_ID && entity.externalSystemModuleVersion == null
}
fun tryRead(entity: ExternalSystemModuleOptionsEntity): ExternalSystemData? {
if (entity.externalSystem != EXTERNAL_SOURCE_ID || entity.externalSystemModuleVersion != VERSION) return null
val id = entity.linkedProjectId
if (id == null) {
MavenLog.LOG.debug("ExternalSystemModuleOptionsEntity.linkedProjectId must not be null")
return null
}
val mavenProjectFilePath = FileUtil.toSystemIndependentName(id)
val typeName = entity.externalSystemModuleType
if (typeName == null) {
MavenLog.LOG.debug("ExternalSystemModuleOptionsEntity.externalSystemModuleType must not be null")
return null
}
val moduleType = try {
StandardMavenModuleType.valueOf(typeName)
}
catch (e: Exception) {
MavenLog.LOG.debug(e)
return null
}
return ExternalSystemData(entity.module, mavenProjectFilePath, moduleType)
}
}
}
} | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/workspaceModel/WorkspaceModuleImporter.kt | 3673911704 |
package com.intellij.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.util.containers.ConcurrentList
import com.intellij.util.containers.ContainerUtil
import java.io.InputStream
class CompoundStreamProvider : StreamProvider {
val providers: ConcurrentList<StreamProvider> = ContainerUtil.createConcurrentList<StreamProvider>()
override val enabled: Boolean
get() = providers.any { it.enabled }
override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean = providers.any { it.isApplicable(fileSpec, roamingType) }
override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean = providers.any { it.read(fileSpec, roamingType, consumer) }
override fun processChildren(path: String,
roamingType: RoamingType,
filter: Function1<String, Boolean>,
processor: Function3<String, InputStream, Boolean, Boolean>): Boolean {
return providers.any { it.processChildren(path, roamingType, filter, processor) }
}
override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
providers.forEach {
if (it.isApplicable(fileSpec, roamingType)) {
it.write(fileSpec, content, size, roamingType)
}
}
}
override fun delete(fileSpec: String, roamingType: RoamingType): Boolean = providers.any { it.delete(fileSpec, roamingType) }
} | platform/configuration-store-impl/src/CompoundStreamProvider.kt | 2210710386 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.completion
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.tracker.LookupElementPositionTracker
import com.intellij.ide.plugins.PluginManager
import com.intellij.stats.completion.events.*
import com.intellij.stats.personalization.UserFactorsManager
class CompletionFileLogger(private val installationUID: String,
private val completionUID: String,
private val eventLogger: CompletionEventLogger) : CompletionLogger() {
private val elementToId = mutableMapOf<String, Int>()
private fun registerElement(item: LookupElement): Int {
val itemString = item.idString()
val newId = elementToId.size
elementToId[itemString] = newId
return newId
}
private fun getElementId(item: LookupElement): Int? {
val itemString = item.idString()
return elementToId[itemString]
}
private fun getRecentlyAddedLookupItems(items: List<LookupElement>): List<LookupElement> {
val newElements = items.filter { getElementId(it) == null }
newElements.forEach {
registerElement(it)
}
return newElements
}
private fun List<LookupElement>.toLookupInfos(lookup: LookupImpl): List<LookupEntryInfo> {
val relevanceObjects = lookup.getRelevanceObjects(this, false)
return this.map {
val id = getElementId(it)!!
val relevanceMap = relevanceObjects[it]?.map { Pair(it.first, it.second?.toString()) }?.toMap()
LookupEntryInfo(id, it.lookupString.length, relevanceMap)
}
}
override fun completionStarted(lookup: LookupImpl, isExperimentPerformed: Boolean, experimentVersion: Int) {
val lookupItems = lookup.items
lookupItems.forEach { registerElement(it) }
val relevanceObjects = lookup.getRelevanceObjects(lookupItems, false)
val lookupEntryInfos = lookupItems.map {
val id = getElementId(it)!!
val relevanceMap = relevanceObjects[it]?.map { Pair(it.first, it.second?.toString()) }?.toMap()
LookupEntryInfo(id, it.lookupString.length, relevanceMap)
}
val language = lookup.language()
val ideVersion = PluginManager.BUILD_NUMBER ?: "ideVersion"
val pluginVersion = calcPluginVersion() ?: "pluginVersion"
val mlRankingVersion = "NONE"
val userFactors = lookup.getUserData(UserFactorsManager.USER_FACTORS_KEY) ?: emptyMap()
val event = CompletionStartedEvent(
ideVersion, pluginVersion, mlRankingVersion,
installationUID, completionUID,
language?.displayName,
isExperimentPerformed, experimentVersion,
lookupEntryInfos, userFactors, selectedPosition = 0)
event.isOneLineMode = lookup.editor.isOneLineMode
event.fillCompletionParameters()
eventLogger.log(event)
}
override fun customMessage(message: String) {
val event = CustomMessageEvent(installationUID, completionUID, message)
eventLogger.log(event)
}
override fun afterCharTyped(c: Char, lookup: LookupImpl) {
val lookupItems = lookup.items
val newItems = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup)
val ids = lookupItems.map { getElementId(it)!! }
val currentPosition = lookupItems.indexOf(lookup.currentItem)
val event = TypeEvent(installationUID, completionUID, ids, newItems, currentPosition)
event.fillCompletionParameters()
eventLogger.log(event)
}
override fun downPressed(lookup: LookupImpl) {
val lookupItems = lookup.items
val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup)
val ids = if (newInfos.isNotEmpty()) lookupItems.map { getElementId(it)!! } else emptyList()
val currentPosition = lookupItems.indexOf(lookup.currentItem)
val event = DownPressedEvent(installationUID, completionUID, ids, newInfos, currentPosition)
event.fillCompletionParameters()
eventLogger.log(event)
}
override fun upPressed(lookup: LookupImpl) {
val lookupItems = lookup.items
val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup)
val ids = if (newInfos.isNotEmpty()) lookupItems.map { getElementId(it)!! } else emptyList()
val currentPosition = lookupItems.indexOf(lookup.currentItem)
val event = UpPressedEvent(installationUID, completionUID, ids, newInfos, currentPosition)
event.fillCompletionParameters()
eventLogger.log(event)
}
override fun completionCancelled() {
val event = CompletionCancelledEvent(installationUID, completionUID)
eventLogger.log(event)
}
override fun itemSelectedByTyping(lookup: LookupImpl) {
val newCompletionElements = getRecentlyAddedLookupItems(lookup.items).toLookupInfos(lookup)
val id = currentItemInfo(lookup).id
val history = lookup.itemsHistory()
val completionList = lookup.items.toLookupInfos(lookup)
val event = TypedSelectEvent(installationUID, completionUID, newCompletionElements, id, completionList, history)
event.fillCompletionParameters()
eventLogger.log(event)
}
override fun itemSelectedCompletionFinished(lookup: LookupImpl) {
val newCompletionItems = getRecentlyAddedLookupItems(lookup.items).toLookupInfos(lookup)
val (index, id) = currentItemInfo(lookup)
val history = lookup.itemsHistory()
val completionList = lookup.items.toLookupInfos(lookup)
val event = ExplicitSelectEvent(installationUID, completionUID, newCompletionItems, index, id, completionList, history)
event.fillCompletionParameters()
eventLogger.log(event)
}
private fun currentItemInfo(lookup: LookupImpl): CurrentElementInfo {
val current = lookup.currentItem
return if (current != null) {
val index = lookup.items.indexOf(current)
val id = getElementId(current)!!
CurrentElementInfo(index, id)
} else {
CurrentElementInfo(-1, -1)
}
}
private fun LookupImpl.itemsHistory(): Map<Int, ElementPositionHistory> {
val positionTracker = LookupElementPositionTracker.getInstance()
return items.map { getElementId(it)!! to positionTracker.positionsHistory(this, it).let { ElementPositionHistory(it) } }.toMap()
}
override fun afterBackspacePressed(lookup: LookupImpl) {
val lookupItems = lookup.items
val newInfos = getRecentlyAddedLookupItems(lookupItems).toLookupInfos(lookup)
val ids = lookupItems.map { getElementId(it)!! }
val currentPosition = lookupItems.indexOf(lookup.currentItem)
val event = BackspaceEvent(installationUID, completionUID, ids, newInfos, currentPosition)
event.fillCompletionParameters()
eventLogger.log(event)
}
}
private class CurrentElementInfo(val index: Int, val id: Int) {
operator fun component1() = index
operator fun component2() = id
}
private fun calcPluginVersion(): String? {
val className = CompletionStartedEvent::class.java.name
val id = PluginManager.getPluginByClassName(className)
val plugin = PluginManager.getPlugin(id)
return plugin?.version
}
private fun LookupStateLogData.fillCompletionParameters() {
val params = CompletionUtil.getCurrentCompletionParameters()
originalCompletionType = params?.completionType?.toString() ?: ""
originalInvokationCount = params?.invocationCount ?: -1
} | plugins/stats-collector/src/com/intellij/stats/completion/CompletionLoggerImpl.kt | 1468655158 |
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.http.spa
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.http.content.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import kotlin.test.*
class SinglePageApplicationTest {
@Test
fun fullWithFilesTest() = testApplication {
application {
routing {
singlePageApplication {
filesPath = "jvm/test/io/ktor/server/http/spa"
applicationRoute = "selected"
defaultPage = "Empty3.kt"
ignoreFiles { it.contains("Empty2.kt") }
}
}
}
client.get("/selected").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty3)
}
client.get("/selected/a").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty3)
}
client.get("/selected/Empty2.kt").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty3)
}
client.get("/selected/Empty1.kt").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty1)
}
}
@Test
fun testPageGet() = testApplication {
application {
routing {
singlePageApplication {
filesPath = "jvm/test/io/ktor/server/http/spa"
applicationRoute = "selected"
defaultPage = "Empty3.kt"
}
}
}
client.get("/selected/Empty1.kt").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty1)
}
client.get("/selected").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty3)
}
}
@Test
fun testIgnoreAllRoutes() = testApplication {
application {
routing {
singlePageApplication {
filesPath = "jvm/test/io/ktor/server/http/spa"
defaultPage = "Empty3.kt"
ignoreFiles { true }
}
}
}
client.get("/").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty3)
}
client.get("/a").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty3)
}
client.get("/Empty1.kt").let {
assertEquals(it.status, HttpStatusCode.OK)
assertEquals(it.bodyAsText().trimIndent(), empty3)
}
}
@Test
fun fullWithResourcesTest() = testApplication {
application {
routing {
singlePageApplication {
useResources = true
filesPath = "io.ktor.server.http.spa"
applicationRoute = "selected"
defaultPage = "Empty3.class"
ignoreFiles { it.contains("Empty2.class") }
}
}
}
assertEquals(client.get("/selected").status, HttpStatusCode.OK)
assertEquals(client.get("/selected/a").status, HttpStatusCode.OK)
assertEquals(client.get("/selected/Empty2.kt").status, HttpStatusCode.OK)
assertEquals(client.get("/selected/Empty1.kt").status, HttpStatusCode.OK)
}
@Test
fun testResources() = testApplication {
application {
routing {
singlePageApplication {
useResources = true
filesPath = "io.ktor.server.http.spa"
defaultPage = "SinglePageApplicationTest.class"
}
}
}
assertEquals(HttpStatusCode.OK, client.get("/Empty1.class").status)
assertEquals(HttpStatusCode.OK, client.get("/SinglePageApplicationTest.class").status)
assertEquals(HttpStatusCode.OK, client.get("/a").status)
assertEquals(HttpStatusCode.OK, client.get("/").status)
}
@Test
fun testIgnoreResourceRoutes() = testApplication {
application {
routing {
singlePageApplication {
useResources = true
filesPath = "io.ktor.server.http.spa"
defaultPage = "SinglePageApplicationTest.class"
ignoreFiles { it.contains("Empty1.class") }
ignoreFiles { it.endsWith("Empty2.class") }
}
}
}
assertEquals(HttpStatusCode.OK, client.get("/Empty3.class").status)
assertEquals(HttpStatusCode.OK, client.get("/").status)
assertEquals(HttpStatusCode.OK, client.get("/Empty1.class").status)
assertEquals(HttpStatusCode.OK, client.get("/Empty2.class").status)
}
@Test
fun testIgnoreAllResourceRoutes() = testApplication {
application {
routing {
singlePageApplication {
useResources = true
filesPath = "io.ktor.server.http.spa"
defaultPage = "SinglePageApplicationTest.class"
ignoreFiles { true }
}
}
}
assertEquals(HttpStatusCode.OK, client.get("/SinglePageApplicationTest.class").status)
assertEquals(HttpStatusCode.OK, client.get("/Empty1.class").status)
assertEquals(HttpStatusCode.OK, client.get("/a").status)
assertEquals(HttpStatusCode.OK, client.get("/").status)
}
@Test
fun testShortcut() = testApplication {
application {
routing {
singlePageApplication {
angular("jvm/test/io/ktor/server/http/spa")
}
}
}
assertEquals(HttpStatusCode.OK, client.get("/Empty1.kt").status)
}
private val empty1 = """
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.http.spa
// required for tests
class Empty1
""".trimIndent()
private val empty3 = """
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.http.spa
// required for tests
class Empty3
""".trimIndent()
}
| ktor-server/ktor-server-tests/jvm/test/io/ktor/server/http/spa/SinglePageApplicationTest.kt | 2917904951 |
package io.ktor.utils.io
import io.ktor.utils.io.bits.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.core.internal.*
/**
* Channel for asynchronous writing of sequences of bytes.
* This is a **single-writer channel**.
*
* Operations on this channel cannot be invoked concurrently, unless explicitly specified otherwise
* in description. Exceptions are [close] and [flush].
*/
public expect interface ByteWriteChannel {
/**
* Returns number of bytes that can be written without suspension. Write operations do no suspend and return
* immediately when this number is at least the number of bytes requested for write.
*/
public val availableForWrite: Int
/**
* Returns `true` is channel has been closed and attempting to write to the channel will cause an exception.
*/
public val isClosedForWrite: Boolean
/**
* Returns `true` if channel flushes automatically all pending bytes after every write function call.
* If `false` then flush only happens at manual [flush] invocation or when the buffer is full.
*/
public val autoFlush: Boolean
/**
* Number of bytes written to the channel.
* It is not guaranteed to be atomic so could be updated in the middle of write operation.
*/
public val totalBytesWritten: Long
/**
* A closure causes exception or `null` if closed successfully or not yet closed
*/
public val closedCause: Throwable?
/**
* Writes as much as possible and only suspends if buffer is full
*/
public suspend fun writeAvailable(src: ByteArray, offset: Int, length: Int): Int
public suspend fun writeAvailable(src: ChunkBuffer): Int
/**
* Writes all [src] bytes and suspends until all bytes written. Causes flush if buffer filled up or when [autoFlush]
* Crashes if channel get closed while writing.
*/
public suspend fun writeFully(src: ByteArray, offset: Int, length: Int)
public suspend fun writeFully(src: Buffer)
public suspend fun writeFully(memory: Memory, startIndex: Int, endIndex: Int)
@Suppress("DEPRECATION")
@Deprecated("Use write { } instead.")
public suspend fun writeSuspendSession(visitor: suspend WriterSuspendSession.() -> Unit)
/**
* Writes a [packet] fully or fails if channel get closed before the whole packet has been written
*/
public suspend fun writePacket(packet: ByteReadPacket)
/**
* Writes long number and suspends until written.
* Crashes if channel get closed while writing.
*/
public suspend fun writeLong(l: Long)
/**
* Writes int number and suspends until written.
* Crashes if channel get closed while writing.
*/
public suspend fun writeInt(i: Int)
/**
* Writes short number and suspends until written.
* Crashes if channel get closed while writing.
*/
public suspend fun writeShort(s: Short)
/**
* Writes byte and suspends until written.
* Crashes if channel get closed while writing.
*/
public suspend fun writeByte(b: Byte)
/**
* Writes double number and suspends until written.
* Crashes if channel get closed while writing.
*/
public suspend fun writeDouble(d: Double)
/**
* Writes float number and suspends until written.
* Crashes if channel get closed while writing.
*/
public suspend fun writeFloat(f: Float)
/**
* Invokes [block] when at least 1 byte is available for write.
*/
public suspend fun awaitFreeSpace()
/**
* Closes this channel with an optional exceptional [cause].
* It flushes all pending write bytes (via [flush]).
* This is an idempotent operation -- repeated invocations of this function have no effect and return `false`.
*
* A channel that was closed without a [cause], is considered to be _closed normally_.
* A channel that was closed with non-null [cause] is called a _failed channel_. Attempts to read or
* write on a failed channel throw this cause exception.
*
* After invocation of this operation [isClosedForWrite] starts returning `true` and
* all subsequent write operations throw [ClosedWriteChannelException] or the specified [cause].
* However, [isClosedForRead][ByteReadChannel.isClosedForRead] on the side of [ByteReadChannel]
* starts returning `true` only after all written bytes have been read.
*
* Please note that if the channel has been closed with cause and it has been provided by [reader] or [writer]
* coroutine then the corresponding coroutine will be cancelled with [cause]. If no [cause] provided then no
* cancellation will be propagated.
*/
public fun close(cause: Throwable?): Boolean
/**
* Flushes all pending write bytes making them available for read.
*
* This function is thread-safe and can be invoked in any thread at any time.
* It does nothing when invoked on a closed channel.
*/
public fun flush()
}
public suspend fun ByteWriteChannel.writeAvailable(src: ByteArray): Int = writeAvailable(src, 0, src.size)
public suspend fun ByteWriteChannel.writeFully(src: ByteArray): Unit = writeFully(src, 0, src.size)
public suspend fun ByteWriteChannel.writeShort(s: Int) {
return writeShort((s and 0xffff).toShort())
}
public suspend fun ByteWriteChannel.writeShort(s: Int, byteOrder: ByteOrder) {
return writeShort((s and 0xffff).toShort(), byteOrder)
}
public suspend fun ByteWriteChannel.writeByte(b: Int) {
return writeByte((b and 0xff).toByte())
}
public suspend fun ByteWriteChannel.writeInt(i: Long) {
return writeInt(i.toInt())
}
public suspend fun ByteWriteChannel.writeInt(i: Long, byteOrder: ByteOrder) {
return writeInt(i.toInt(), byteOrder)
}
/**
* Closes this channel with no failure (successfully)
*/
public fun ByteWriteChannel.close(): Boolean = close(null)
public suspend fun ByteWriteChannel.writeStringUtf8(s: CharSequence) {
val packet = buildPacket {
writeText(s)
}
return writePacket(packet)
}
public suspend fun ByteWriteChannel.writeStringUtf8(s: String) {
val packet = buildPacket {
writeText(s)
}
return writePacket(packet)
}
public suspend fun ByteWriteChannel.writeBoolean(b: Boolean) {
return writeByte(if (b) 1 else 0)
}
/**
* Writes UTF16 character
*/
public suspend fun ByteWriteChannel.writeChar(ch: Char) {
return writeShort(ch.code)
}
public suspend inline fun ByteWriteChannel.writePacket(builder: BytePacketBuilder.() -> Unit) {
return writePacket(buildPacket(builder))
}
public suspend fun ByteWriteChannel.writePacketSuspend(builder: suspend BytePacketBuilder.() -> Unit) {
return writePacket(buildPacket { builder() })
}
/**
* Indicates attempt to write on [isClosedForWrite][ByteWriteChannel.isClosedForWrite] channel
* that was closed without a cause. A _failed_ channel rethrows the original [close][ByteWriteChannel.close] cause
* exception on send attempts.
*/
public class ClosedWriteChannelException(message: String?) : CancellationException(message)
| ktor-io/common/src/io/ktor/utils/io/ByteWriteChannel.kt | 4013910851 |
/*
* 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.http
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
private val URL_ALPHABET = ((('a'..'z') + ('A'..'Z') + ('0'..'9')).map { it.code.toByte() }).toSet()
private val URL_ALPHABET_CHARS = ((('a'..'z') + ('A'..'Z') + ('0'..'9'))).toSet()
private val HEX_ALPHABET = (('a'..'f') + ('A'..'F') + ('0'..'9')).toSet()
/**
* https://tools.ietf.org/html/rfc3986#section-2
*/
private val URL_PROTOCOL_PART = setOf(
':', '/', '?', '#', '[', ']', '@', // general
'!', '$', '&', '\'', '(', ')', '*', ',', ';', '=', // sub-components
'-', '.', '_', '~', '+' // unreserved
).map { it.code.toByte() }
/**
* from `pchar` in https://tools.ietf.org/html/rfc3986#section-2
*/
private val VALID_PATH_PART = setOf(
':', '@',
'!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=',
'-', '.', '_', '~'
)
/**
* Characters allowed in attributes according: https://datatracker.ietf.org/doc/html/rfc5987
* attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
*/
internal val ATTRIBUTE_CHARACTERS: Set<Char> = URL_ALPHABET_CHARS + setOf(
'!', '#', '$', '&', '+', '-', '.', '^', '_', '`', '|', '~'
)
/**
* Characters allowed in url according to https://tools.ietf.org/html/rfc3986#section-2.3
*/
private val SPECIAL_SYMBOLS = listOf('-', '.', '_', '~').map { it.code.toByte() }
/**
* Encode url part as specified in
* https://tools.ietf.org/html/rfc3986#section-2
*/
public fun String.encodeURLQueryComponent(
encodeFull: Boolean = false,
spaceToPlus: Boolean = false,
charset: Charset = Charsets.UTF_8
): String = buildString {
val content = charset.newEncoder().encode(this@encodeURLQueryComponent)
content.forEach {
when {
it == ' '.code.toByte() -> if (spaceToPlus) append('+') else append("%20")
it in URL_ALPHABET || (!encodeFull && it in URL_PROTOCOL_PART) -> append(it.toInt().toChar())
else -> append(it.percentEncode())
}
}
}
/**
* Encodes URL path. It escapes all illegal or ambiguous characters keeping all "/" symbols.
*/
public fun String.encodeURLPath(): String = encodeURLPath(encodeSlash = false)
/**
* Encodes URL path segment. It escapes all illegal or ambiguous characters
*/
public fun String.encodeURLPathPart(): String = encodeURLPath(encodeSlash = true)
internal fun String.encodeURLPath(encodeSlash: Boolean): String = buildString {
val charset = Charsets.UTF_8
var index = 0
while (index < [email protected]) {
val current = this@encodeURLPath[index]
if ((!encodeSlash && current == '/') || current in URL_ALPHABET_CHARS || current in VALID_PATH_PART) {
append(current)
index++
continue
}
if (current == '%' &&
index + 2 < [email protected] &&
this@encodeURLPath[index + 1] in HEX_ALPHABET &&
this@encodeURLPath[index + 2] in HEX_ALPHABET
) {
append(current)
append(this@encodeURLPath[index + 1])
append(this@encodeURLPath[index + 2])
index += 3
continue
}
val symbolSize = if (current.isSurrogate()) 2 else 1
// we need to call newEncoder() for every symbol, otherwise it won't work
charset.newEncoder().encode(this@encodeURLPath, index, index + symbolSize).forEach {
append(it.percentEncode())
}
index += symbolSize
}
}
/**
* Encode [this] in percent encoding specified here:
* https://tools.ietf.org/html/rfc5849#section-3.6
*/
public fun String.encodeOAuth(): String = encodeURLParameter()
/**
* Encode [this] as query parameter key.
*/
public fun String.encodeURLParameter(
spaceToPlus: Boolean = false
): String = buildString {
val content = Charsets.UTF_8.newEncoder().encode(this@encodeURLParameter)
content.forEach {
when {
it in URL_ALPHABET || it in SPECIAL_SYMBOLS -> append(it.toInt().toChar())
spaceToPlus && it == ' '.code.toByte() -> append('+')
else -> append(it.percentEncode())
}
}
}
internal fun String.percentEncode(allowedSet: Set<Char>): String {
val encodedCount = count { it !in allowedSet }
if (encodedCount == 0) return this
val resultSize = length + encodedCount * 2
val result = CharArray(resultSize)
var writeIndex = 0
for (index in 0 until length) {
val current = this[index]
if (current in allowedSet) {
result[writeIndex++] = current
} else {
val code = current.code
result[writeIndex++] = '%'
result[writeIndex++] = hexDigitToChar(code shr 4)
result[writeIndex++] = hexDigitToChar(code and 0xf)
}
}
return result.concatToString()
}
/**
* Encode [this] as query parameter value.
*/
internal fun String.encodeURLParameterValue(): String = encodeURLParameter(spaceToPlus = true)
/**
* Decode URL query component
*/
public fun String.decodeURLQueryComponent(
start: Int = 0,
end: Int = length,
plusIsSpace: Boolean = false,
charset: Charset = Charsets.UTF_8
): String = decodeScan(start, end, plusIsSpace, charset)
/**
* Decode percent encoded URL part within the specified range [[start], [end]).
* This function is not intended to decode urlencoded forms so it doesn't decode plus character to space.
*/
public fun String.decodeURLPart(
start: Int = 0,
end: Int = length,
charset: Charset = Charsets.UTF_8
): String = decodeScan(start, end, false, charset)
private fun String.decodeScan(start: Int, end: Int, plusIsSpace: Boolean, charset: Charset): String {
for (index in start until end) {
val ch = this[index]
if (ch == '%' || (plusIsSpace && ch == '+')) {
return decodeImpl(start, end, index, plusIsSpace, charset)
}
}
return if (start == 0 && end == length) toString() else substring(start, end)
}
private fun CharSequence.decodeImpl(
start: Int,
end: Int,
prefixEnd: Int,
plusIsSpace: Boolean,
charset: Charset
): String {
val length = end - start
// if length is big, it probably means it is encoded
val sbSize = if (length > 255) length / 3 else length
val sb = StringBuilder(sbSize)
if (prefixEnd > start) {
sb.append(this, start, prefixEnd)
}
var index = prefixEnd
// reuse ByteArray for hex decoding stripes
var bytes: ByteArray? = null
while (index < end) {
val c = this[index]
when {
plusIsSpace && c == '+' -> {
sb.append(' ')
index++
}
c == '%' -> {
// if ByteArray was not needed before, create it with an estimate of remaining string be all hex
if (bytes == null) {
bytes = ByteArray((end - index) / 3)
}
// fill ByteArray with all the bytes, so Charset can decode text
var count = 0
while (index < end && this[index] == '%') {
if (index + 2 >= end) {
throw URLDecodeException(
"Incomplete trailing HEX escape: ${substring(index)}, in $this at $index"
)
}
val digit1 = charToHexDigit(this[index + 1])
val digit2 = charToHexDigit(this[index + 2])
if (digit1 == -1 || digit2 == -1) {
throw URLDecodeException(
"Wrong HEX escape: %${this[index + 1]}${this[index + 2]}, in $this, at $index"
)
}
bytes[count++] = (digit1 * 16 + digit2).toByte()
index += 3
}
// Decode chars from bytes and put into StringBuilder
// Note: Tried using ByteBuffer and using enc.decode() – it's slower
sb.append(String(bytes, offset = 0, length = count, charset = charset))
}
else -> {
sb.append(c)
index++
}
}
}
return sb.toString()
}
/**
* URL decoder exception
*/
public class URLDecodeException(message: String) : Exception(message)
private fun Byte.percentEncode(): String {
val code = toInt() and 0xff
val array = CharArray(3)
array[0] = '%'
array[1] = hexDigitToChar(code shr 4)
array[2] = hexDigitToChar(code and 0xf)
return array.concatToString()
}
private fun charToHexDigit(c2: Char) = when (c2) {
in '0'..'9' -> c2 - '0'
in 'A'..'F' -> c2 - 'A' + 10
in 'a'..'f' -> c2 - 'a' + 10
else -> -1
}
private fun hexDigitToChar(digit: Int): Char = when (digit) {
in 0..9 -> '0' + digit
else -> 'A' + digit - 10
}
private fun ByteReadPacket.forEach(block: (Byte) -> Unit) {
takeWhile { buffer ->
while (buffer.canRead()) {
block(buffer.readByte())
}
true
}
}
| ktor-http/common/src/io/ktor/http/Codecs.kt | 2166911472 |
package org.fedorahosted.freeotp.data
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.RawQuery
import androidx.room.Transaction
import androidx.room.Update
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQuery
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
@Dao
interface OtpTokenDao {
@Query("select * from otp_tokens order by ordinal")
fun getAll(): Flow<List<OtpToken>>
@Query("select * from otp_tokens where id = :id")
fun get(id: Long): Flow<OtpToken?>
@Query("select ordinal from otp_tokens order by ordinal desc limit 1")
fun getLastOrdinal(): Long?
@Query("delete from otp_tokens where id = :id")
suspend fun deleteById(id: Long): Void
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(otpTokenList: List<OtpToken>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(otpTokenList: OtpToken)
@Update
suspend fun update(otpTokenList: OtpToken)
@Query("update otp_tokens set ordinal = :ordinal where id = :id")
suspend fun updateOrdinal(id: Long, ordinal: Long)
/**
* This incrementCounter won't trigger Flow collect by using raw query
* We do not want increment count triggering flow because it can refresh the token
*/
suspend fun incrementCounter(id: Long) {
incrementCounterRaw(
SimpleSQLiteQuery("update otp_tokens set counter = counter + 1 where id = ?",
arrayOf(id))
)
}
@RawQuery
suspend fun incrementCounterRaw(query: SupportSQLiteQuery): Int
@Transaction
suspend fun movePairs(pairs : List<Pair<Long,Long>>){
for(pair in pairs.listIterator()) {
withContext(Dispatchers.IO) {
val token1 = get(pair.first).first()
val token2 = get(pair.second).first()
if (token1 == null || token2 == null) {
return@withContext
}
updateOrdinal(pair.first, token2.ordinal)
updateOrdinal(pair.second, token1.ordinal)
}
}
}
} | token-data/src/main/java/org/fedorahosted/freeotp/data/OtpTokenDao.kt | 2972875214 |
package com.spreadst.devtools.demos.popup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import javax.swing.Icon
import icons.Icons
class OpenDemoPopupAction : AnAction("Demo Popup", "Open demo popup", null) {
override fun actionPerformed(e: AnActionEvent?) {
val title = "Popup Title"
val values = getValues()
val icons = getIcons()
val popup = JBPopupFactory.getInstance().createListPopup(MyListPopupStep(title, values, icons))
popup.showCenteredInCurrentWindow(e!!.project!!)
}
private fun getValues(): List<String> {
val values = ArrayList<String>()
(0 until 26).mapTo(values) { ('A'.toInt() + it).toChar().toString() }
return values
}
private fun getIcons(): List<Icon> {
val icons = ArrayList<Icon>()
(0 until 26).mapTo(icons) { Icons.DemoEditor }
return icons
}
/**
* http://www.jetbrains.org/intellij/sdk/docs/user_interface_components/popups.html
*/
inner class MyListPopupStep(title: String, values: List<String>, icons: List<Icon>)
: BaseListPopupStep<String>(title, values, icons) {
private var selectedVal: String? = null
override fun onChosen(selectedValue: String?, finalChoice: Boolean): PopupStep<*>? {
selectedVal = selectedValue
return super.onChosen(selectedValue, finalChoice)
}
override fun getFinalRunnable(): Runnable? {
return Runnable { Messages.showMessageDialog("You selected $selectedVal", "Selected Value", Messages.getInformationIcon()) }
}
}
} | src/main/java/com/spreadst/devtools/demos/popup/OpenDemoPopupAction.kt | 1311243269 |
package eu.kanade.tachiyomi.ui.reader.setting
import android.animation.ValueAnimator
import android.os.Bundle
import com.google.android.material.tabs.TabLayout
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.widget.listener.SimpleTabSelectedListener
import eu.kanade.tachiyomi.widget.sheet.TabbedBottomSheetDialog
class ReaderSettingsSheet(
private val activity: ReaderActivity,
private val showColorFilterSettings: Boolean = false,
) : TabbedBottomSheetDialog(activity) {
private val readingModeSettings = ReaderReadingModeSettings(activity)
private val generalSettings = ReaderGeneralSettings(activity)
private val colorFilterSettings = ReaderColorFilterSettings(activity)
private val backgroundDimAnimator by lazy {
val sheetBackgroundDim = window?.attributes?.dimAmount ?: 0.25f
ValueAnimator.ofFloat(sheetBackgroundDim, 0f).also { valueAnimator ->
valueAnimator.duration = 250
valueAnimator.addUpdateListener {
window?.setDimAmount(it.animatedValue as Float)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
behavior.isFitToContents = false
behavior.halfExpandedRatio = 0.25f
val filterTabIndex = getTabViews().indexOf(colorFilterSettings)
binding.tabs.addOnTabSelectedListener(object : SimpleTabSelectedListener() {
override fun onTabSelected(tab: TabLayout.Tab?) {
val isFilterTab = tab?.position == filterTabIndex
// Remove dimmed backdrop so color filter changes can be previewed
backgroundDimAnimator.run {
if (isFilterTab) {
if (animatedFraction < 1f) {
start()
}
} else if (animatedFraction > 0f) {
reverse()
}
}
// Hide toolbars
if (activity.menuVisible != !isFilterTab) {
activity.setMenuVisibility(!isFilterTab)
}
}
})
if (showColorFilterSettings) {
binding.tabs.getTabAt(filterTabIndex)?.select()
}
}
override fun getTabViews() = listOf(
readingModeSettings,
generalSettings,
colorFilterSettings,
)
override fun getTabTitles() = listOf(
R.string.pref_category_reading_mode,
R.string.pref_category_general,
R.string.custom_filter,
)
}
| app/src/main/java/eu/kanade/tachiyomi/ui/reader/setting/ReaderSettingsSheet.kt | 3387462554 |
package eu.kanade.tachiyomi.data.database.models
/**
* Object containing manga, chapter and history
*
* @param manga object containing manga
* @param chapter object containing chater
* @param history object containing history
*/
data class MangaChapterHistory(val manga: Manga, val chapter: Chapter, val history: History)
| app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaChapterHistory.kt | 3571393897 |
package blue.aodev.animeultimetv.presentation.screen
import android.content.Intent
import android.support.v4.app.FragmentActivity
import blue.aodev.animeultimetv.presentation.screen.search.SearchActivity
/**
* This parent class contains common methods that run in every activity such as search.
*/
abstract class LeanbackActivity : FragmentActivity() {
override fun onSearchRequested(): Boolean {
startActivity(Intent(this, SearchActivity::class.java))
return true
}
} | app/src/main/java/blue/aodev/animeultimetv/presentation/screen/LeanbackActivity.kt | 1284742086 |
package org.commcare.gis
import android.app.Application
import android.location.Geocoder
import android.location.Location
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mapbox.mapboxsdk.geometry.LatLng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.commcare.dalvik.R
import org.commcare.util.LogTypes
import org.commcare.utils.GeoUtils
import org.commcare.utils.StringUtils
import org.javarosa.core.services.Logger
import java.lang.IllegalArgumentException
import java.util.*
/**
* @author $|-|!˅@M
*/
class MapboxLocationPickerViewModel(application: Application): AndroidViewModel(application) {
val placeName = MutableLiveData<String>()
private var location = Location("XForm")
fun reverseGeocode(latLng: LatLng) {
viewModelScope.launch(Dispatchers.IO) {
var addressString = ""
val geocoder = Geocoder(getApplication(), Locale.getDefault())
val geoAddress = try {
geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
} catch (e: Exception) {
if (e is IllegalArgumentException) {
Logger.exception("Error while fetching location from geocoder", e)
}
null
}
geoAddress?.let {
if (it.isNotEmpty()) {
val addr = it[0]
val builder = StringBuilder()
for (i in 0..addr.maxAddressLineIndex) {
builder.append(addr.getAddressLine(i))
.append("\n")
}
addressString = builder.toString()
}
}
if (addressString.isEmpty()) {
val builder = StringBuilder()
builder.append(StringUtils.getStringSpannableRobust(getApplication(), R.string.latitude))
.append(": ")
.append(GeoUtils.formatGps(latLng.latitude, "lat"))
.append("\n")
.append(StringUtils.getStringSpannableRobust(getApplication(), R.string.longitude))
.append(": ")
.append(GeoUtils.formatGps(latLng.longitude, "lon"))
.append("\n")
.append(StringUtils.getStringSpannableRobust(getApplication(), R.string.altitude))
.append(": ")
.append(String.format("%.2f", latLng.altitude))
addressString = builder.toString()
}
withContext(Dispatchers.Main) {
location.latitude = latLng.latitude
location.longitude = latLng.longitude
location.altitude = latLng.altitude
location.accuracy = 10.0f
placeName.postValue(addressString)
}
}
}
fun getLocation() = location
}
| app/src/org/commcare/gis/MapboxLocationPickerViewModel.kt | 474571689 |
package com.ashish.movieguide.ui.widget
import android.content.Context
import android.support.v7.widget.AppCompatButton
import android.util.AttributeSet
import com.ashish.movieguide.utils.FontUtils
/**
* Created by Ashish on Jan 07.
*/
class FontButton : AppCompatButton {
constructor(context: Context, attrs: AttributeSet? = null) : super(context, attrs) {
FontUtils.applyFont(this, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
FontUtils.applyFont(this, attrs)
}
} | app/src/main/kotlin/com/ashish/movieguide/ui/widget/FontButton.kt | 777684678 |
// AFTER-WARNING: Parameter 'p1' is never used
// AFTER-WARNING: Parameter 'p2' is never used
open class C(p1: Int, p2: Int)
class D : C(1, <caret>2) | plugins/kotlin/idea/tests/testData/intentions/addNameToArgument/superClassConstructor.kt | 146090029 |
import java.util.stream.Stream
fun main(args: Array<String>) {
val count = Stream.of("abc",<caret> "acd", "ef").map({ it.length }).filter { x -> x % 2 == 0 }.count()
}
| plugins/kotlin/jvm-debugger/test/testData/sequence/psi/streams/positive/location/BetweenParametersAfterComma.kt | 3164623212 |
package org.jetbrains.deft
abstract class Type<T : Obj, B : ObjBuilder<T>>(val base: Type<*, *>? = null) : Obj {
var open: Boolean = false
var abstract: Boolean = false
var sealed: Boolean = false
val inheritanceAllowed get() = open || sealed || abstract
val superTypes: List<Type<*, *>>
get() = base?.superTypes?.toMutableList()?.apply { add(base) } ?: emptyList()
val ival: Class<T> get() = javaClass.enclosingClass as Class<T>
val ivar: Class<B> get() = ival.classes.single { it.simpleName == "Builder" } as Class<B>
open val packageName: String
get() = ival.packageName
open val name by lazy {
if (ival.enclosingClass == null) ival.simpleName else {
var topLevelClass: Class<*> = ival
val outerNames = mutableListOf<String>()
do {
outerNames.add(topLevelClass.simpleName)
topLevelClass = topLevelClass.enclosingClass ?: break
} while (true)
outerNames.reversed().joinToString(".")
}
}
protected open fun loadBuilderFactory(): () -> B {
val ivalClass = ival
val packageName = ivalClass.packageName
val simpleName = name.replace(".", "")
val c = ivalClass.classLoader.loadClass("$packageName.${simpleName}Impl\$Builder")
val ctor = c.constructors.find { it.parameterCount == 0 }!!
return { ctor.newInstance() as B }
}
private val _builder: () -> B by lazy {
loadBuilderFactory()
}
protected fun builder(): B = _builder()
override fun toString(): String = name
} | platform/workspaceModel/storage/src/com/intellij/workspaceModel/deft/api/Type.kt | 1026722474 |
/*
* Copyright (C) 2011 Patrik Akerfeldt
* Copyright (C) 2011 Jake Wharton
*
* 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.pinkal.todo.utils.views.indicator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.graphics.Paint.Style
import android.os.Parcel
import android.os.Parcelable
import android.support.v4.view.MotionEventCompat
import android.support.v4.view.ViewConfigurationCompat
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.LinearLayout.HORIZONTAL
import android.widget.LinearLayout.VERTICAL
import com.pinkal.todo.R
/**
* Draws circles (one for each view). The current view position is filled and
* others are only stroked.
*/
class CirclePageIndicator @JvmOverloads constructor(context: Context, attrs: AttributeSet = null!!,
defStyle: Int = R.attr.vpiCirclePageIndicatorStyle) :
View(context, attrs, defStyle), PageIndicator {
private var mRadius: Float = 0.toFloat()
private val mPaintPageFill = Paint(ANTI_ALIAS_FLAG)
private val mPaintStroke = Paint(ANTI_ALIAS_FLAG)
private val mPaintFill = Paint(ANTI_ALIAS_FLAG)
private var mViewPager: ViewPager? = null
private var mListener: ViewPager.OnPageChangeListener? = null
private var mCurrentPage: Int = 0
private var mSnapPage: Int = 0
private var mPageOffset: Float = 0.toFloat()
private var mScrollState: Int = 0
private var mOrientation: Int = 0
private var mCentered: Boolean = false
private var mSnap: Boolean = false
private val mTouchSlop: Int
private var mLastMotionX = -1f
private var mActivePointerId = INVALID_POINTER
private var mIsDragging: Boolean = false
init {
// if (isInEditMode) return
//Load defaults from resources
val res = resources
val defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color)
val defaultFillColor = res.getColor(R.color.default_circle_indicator_fill_color)
val defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation)
val defaultStrokeColor = res.getColor(R.color.default_circle_indicator_stroke_color)
val defaultStrokeWidth = res.getDimension(R.dimen.default_circle_indicator_stroke_width)
val defaultRadius = res.getDimension(R.dimen.default_circle_indicator_radius)
val defaultCentered = res.getBoolean(R.bool.default_circle_indicator_centered)
val defaultSnap = res.getBoolean(R.bool.default_circle_indicator_snap)
//Retrieve styles attributes
val a = context.obtainStyledAttributes(attrs, R.styleable.CirclePageIndicator, defStyle, 0)
mCentered = a.getBoolean(R.styleable.CirclePageIndicator_centered, defaultCentered)
mOrientation = a.getInt(R.styleable.CirclePageIndicator_android_orientation, defaultOrientation)
mPaintPageFill.style = Style.FILL
mPaintPageFill.color = a.getColor(R.styleable.CirclePageIndicator_pageColor, defaultPageColor)
mPaintStroke.style = Style.STROKE
mPaintStroke.color = a.getColor(R.styleable.CirclePageIndicator_strokeColor, defaultStrokeColor)
mPaintStroke.strokeWidth = a.getDimension(R.styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth)
mPaintFill.style = Style.FILL
mPaintFill.color = a.getColor(R.styleable.CirclePageIndicator_fillColor, defaultFillColor)
mRadius = a.getDimension(R.styleable.CirclePageIndicator_radius, defaultRadius)
mSnap = a.getBoolean(R.styleable.CirclePageIndicator_snap, defaultSnap)
val background = a.getDrawable(R.styleable.CirclePageIndicator_android_background)
if (background != null) {
setBackgroundDrawable(background)
}
a.recycle()
val configuration = ViewConfiguration.get(context)
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration)
}
var isCentered: Boolean
get() = mCentered
set(centered) {
mCentered = centered
invalidate()
}
var pageColor: Int
get() = mPaintPageFill.color
set(pageColor) {
mPaintPageFill.color = pageColor
invalidate()
}
var fillColor: Int
get() = mPaintFill.color
set(fillColor) {
mPaintFill.color = fillColor
invalidate()
}
var orientation: Int
get() = mOrientation
set(orientation) = when (orientation) {
HORIZONTAL, VERTICAL -> {
mOrientation = orientation
requestLayout()
}
else -> throw IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL.")
}
var strokeColor: Int
get() = mPaintStroke.color
set(strokeColor) {
mPaintStroke.color = strokeColor
invalidate()
}
var strokeWidth: Float
get() = mPaintStroke.strokeWidth
set(strokeWidth) {
mPaintStroke.strokeWidth = strokeWidth
invalidate()
}
var radius: Float
get() = mRadius
set(radius) {
mRadius = radius
invalidate()
}
var isSnap: Boolean
get() = mSnap
set(snap) {
mSnap = snap
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (mViewPager == null) {
return
}
val count = mViewPager!!.adapter.count
if (count == 0) {
return
}
if (mCurrentPage >= count) {
setCurrentItem(count - 1)
return
}
val longSize: Int
val longPaddingBefore: Int
val longPaddingAfter: Int
val shortPaddingBefore: Int
if (mOrientation == HORIZONTAL) {
longSize = width
longPaddingBefore = paddingLeft
longPaddingAfter = paddingRight
shortPaddingBefore = paddingTop
} else {
longSize = height
longPaddingBefore = paddingTop
longPaddingAfter = paddingBottom
shortPaddingBefore = paddingLeft
}
val threeRadius = mRadius * 3
val shortOffset = shortPaddingBefore + mRadius
var longOffset = longPaddingBefore + mRadius
if (mCentered) {
longOffset += (longSize - longPaddingBefore - longPaddingAfter) / 2.0f - count * threeRadius / 2.0f
}
var dX: Float
var dY: Float
var pageFillRadius = mRadius
if (mPaintStroke.strokeWidth > 0) {
pageFillRadius -= mPaintStroke.strokeWidth / 2.0f
}
//Draw stroked circles
for (iLoop in 0..count - 1) {
val drawLong = longOffset + iLoop * threeRadius
if (mOrientation == HORIZONTAL) {
dX = drawLong
dY = shortOffset
} else {
dX = shortOffset
dY = drawLong
}
// Only paint fill if not completely transparent
if (mPaintPageFill.alpha > 0) {
canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill)
}
// Only paint stroke if a stroke width was non-zero
if (pageFillRadius != mRadius) {
canvas.drawCircle(dX, dY, mRadius, mPaintStroke)
}
}
//Draw the filled circle according to the current scroll
var cx = (if (mSnap) mSnapPage else mCurrentPage) * threeRadius
if (!mSnap) {
cx += mPageOffset * threeRadius
}
if (mOrientation == HORIZONTAL) {
dX = longOffset + cx
dY = shortOffset
} else {
dX = shortOffset
dY = longOffset + cx
}
canvas.drawCircle(dX, dY, mRadius, mPaintFill)
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
if (super.onTouchEvent(ev)) {
return true
}
if (mViewPager == null || mViewPager!!.adapter.count == 0) {
return false
}
val action = ev.action and MotionEventCompat.ACTION_MASK
when (action) {
MotionEvent.ACTION_DOWN -> {
mActivePointerId = MotionEventCompat.getPointerId(ev, 0)
mLastMotionX = ev.x
}
MotionEvent.ACTION_MOVE -> {
val activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId)
val x = MotionEventCompat.getX(ev, activePointerIndex)
val deltaX = x - mLastMotionX
if (!mIsDragging) {
if (Math.abs(deltaX) > mTouchSlop) {
mIsDragging = true
}
}
if (mIsDragging) {
mLastMotionX = x
if (mViewPager!!.isFakeDragging || mViewPager!!.beginFakeDrag()) {
mViewPager!!.fakeDragBy(deltaX)
}
}
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
if (!mIsDragging) {
val count = mViewPager!!.adapter.count
val width = width
val halfWidth = width / 2f
val sixthWidth = width / 6f
if (mCurrentPage > 0 && ev.x < halfWidth - sixthWidth) {
if (action != MotionEvent.ACTION_CANCEL) {
mViewPager!!.currentItem = mCurrentPage - 1
}
return true
} else if (mCurrentPage < count - 1 && ev.x > halfWidth + sixthWidth) {
if (action != MotionEvent.ACTION_CANCEL) {
mViewPager!!.currentItem = mCurrentPage + 1
}
return true
}
}
mIsDragging = false
mActivePointerId = INVALID_POINTER
if (mViewPager!!.isFakeDragging) mViewPager!!.endFakeDrag()
}
MotionEventCompat.ACTION_POINTER_DOWN -> {
val index = MotionEventCompat.getActionIndex(ev)
mLastMotionX = MotionEventCompat.getX(ev, index)
mActivePointerId = MotionEventCompat.getPointerId(ev, index)
}
MotionEventCompat.ACTION_POINTER_UP -> {
val pointerIndex = MotionEventCompat.getActionIndex(ev)
val pointerId = MotionEventCompat.getPointerId(ev, pointerIndex)
if (pointerId == mActivePointerId) {
val newPointerIndex = if (pointerIndex == 0) 1 else 0
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex)
}
mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId))
}
}
return true
}
override fun setViewPager(view: ViewPager) {
if (mViewPager === view) {
return
}
if (mViewPager != null) {
mViewPager!!.setOnPageChangeListener(null)
}
if (view.adapter == null) {
throw IllegalStateException("ViewPager does not have adapter instance.")
}
mViewPager = view
mViewPager!!.setOnPageChangeListener(this)
invalidate()
}
override fun setViewPager(view: ViewPager, initialPosition: Int) {
setViewPager(view)
setCurrentItem(initialPosition)
}
override fun setCurrentItem(item: Int) {
if (mViewPager == null) {
throw IllegalStateException("ViewPager has not been bound.")
}
mViewPager!!.currentItem = item
mCurrentPage = item
invalidate()
}
override fun notifyDataSetChanged() {
invalidate()
}
override fun onPageScrollStateChanged(state: Int) {
mScrollState = state
if (mListener != null) {
mListener!!.onPageScrollStateChanged(state)
}
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
mCurrentPage = position
mPageOffset = positionOffset
invalidate()
if (mListener != null) {
mListener!!.onPageScrolled(position, positionOffset, positionOffsetPixels)
}
}
override fun onPageSelected(position: Int) {
if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mCurrentPage = position
mSnapPage = position
invalidate()
}
if (mListener != null) {
mListener!!.onPageSelected(position)
}
}
override fun setOnPageChangeListener(listener: ViewPager.OnPageChangeListener) {
mListener = listener
}
/*
* (non-Javadoc)
*
* @see android.view.View#onMeasure(int, int)
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (mOrientation == HORIZONTAL) {
setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec))
} else {
setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec))
}
}
/**
* Determines the width of this view
* @param measureSpec
* * A measureSpec packed into an int
* *
* @return The width of the view, honoring constraints from measureSpec
*/
private fun measureLong(measureSpec: Int): Int {
var result: Int
val specMode = View.MeasureSpec.getMode(measureSpec)
val specSize = View.MeasureSpec.getSize(measureSpec)
if (specMode == View.MeasureSpec.EXACTLY || mViewPager == null) {
//We were told how big to be
result = specSize
} else {
//Calculate the width according the views count
val count = mViewPager!!.adapter.count
result = (paddingLeft.toFloat() + paddingRight.toFloat()
+ count.toFloat() * 2f * mRadius + (count - 1) * mRadius + 1f).toInt()
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == View.MeasureSpec.AT_MOST) {
result = Math.min(result, specSize)
}
}
return result
}
/**
* Determines the height of this view
* @param measureSpec
* * A measureSpec packed into an int
* *
* @return The height of the view, honoring constraints from measureSpec
*/
private fun measureShort(measureSpec: Int): Int {
var result: Int
val specMode = View.MeasureSpec.getMode(measureSpec)
val specSize = View.MeasureSpec.getSize(measureSpec)
if (specMode == View.MeasureSpec.EXACTLY) {
//We were told how big to be
result = specSize
} else {
//Measure the height
result = (2 * mRadius + paddingTop.toFloat() + paddingBottom.toFloat() + 1f).toInt()
//Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == View.MeasureSpec.AT_MOST) {
result = Math.min(result, specSize)
}
}
return result
}
public override fun onRestoreInstanceState(state: Parcelable) {
val savedState = state as SavedState
super.onRestoreInstanceState(savedState.superState)
mCurrentPage = savedState.currentPage
mSnapPage = savedState.currentPage
requestLayout()
}
public override fun onSaveInstanceState(): Parcelable {
val superState = super.onSaveInstanceState()
val savedState = SavedState(superState)
savedState.currentPage = mCurrentPage
return savedState
}
internal class SavedState : View.BaseSavedState {
var currentPage: Int = 0
constructor(superState: Parcelable) : super(superState) {}
private constructor(`in`: Parcel) : super(`in`) {
currentPage = `in`.readInt()
}
override fun writeToParcel(dest: Parcel, flags: Int) {
super.writeToParcel(dest, flags)
dest.writeInt(currentPage)
}
companion object {
val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(`in`: Parcel): SavedState {
return SavedState(`in`)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
companion object {
private val INVALID_POINTER = -1
}
}
| app/src/main/java/com/pinkal/todo/utils/views/indicator/CirclePageIndicator.kt | 1549724974 |
// FIR_IDENTICAL
// FIR_COMPARISON
// COMPILER_ARGUMENTS: -XXLanguage:+SealedInterfaces -XXLanguage:+MultiPlatformProjects
class OuterClass {
seal<caret>
}
// EXIST: "sealed class"
// EXIST: "sealed interface"
// NOTHING_ELSE | plugins/kotlin/completion/tests/testData/keywords/SealedWithoutName.kt | 3266242938 |
package org.intellij.plugins.markdown.parser
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.psi.impl.DebugUtil
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import com.intellij.testFramework.RegistryKeyRule
import junit.framework.TestCase
import org.intellij.plugins.markdown.MarkdownTestingUtil
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.File
@RunWith(JUnit4::class)
class FrontMatterParserTest: LightPlatformCodeInsightTestCase() {
@Rule
@JvmField
val rule = RegistryKeyRule("markdown.experimental.frontmatter.support.enable", true)
@Test
fun `test header block`() = doTest()
private fun doTest() {
val testName = getTestName(true)
configureByFile("$testName.md")
val psi = DebugUtil.psiToString(file, true, false)
val expectedContentPath = File(testDataPath, "$testName.txt")
val expected = FileUtil.loadFile(expectedContentPath, CharsetToolkit.UTF8, true)
TestCase.assertEquals(expected, psi)
}
override fun getTestName(lowercaseFirstLetter: Boolean): String {
val name = super.getTestName(lowercaseFirstLetter)
return name.trimStart().replace(' ', '_')
}
override fun getTestDataPath(): String {
return "${MarkdownTestingUtil.TEST_DATA_PATH}/parser/frontmatter/"
}
}
| plugins/markdown/test/src/org/intellij/plugins/markdown/parser/FrontMatterParserTest.kt | 129441091 |
/*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.format.epub.opf
import jclp.text.ifNotEmpty
import jclp.xml.attribute
import jclp.xml.endTag
import jclp.xml.startTag
import jem.format.epub.Taggable
import org.xmlpull.v1.XmlSerializer
import java.util.*
class ItemRef(val idref: String, var linear: Boolean, var properties: String, id: String = "") : Taggable(id) {
override fun renderTo(xml: XmlSerializer) {
with(xml) {
startTag("itemref")
attribute("idref", idref)
if (!linear) attribute("linear", "no")
properties.ifNotEmpty { attribute("properties", it) }
attr.forEach { attribute(it.key, it.value) }
id.ifNotEmpty { attribute("id", it) }
endTag()
}
}
}
class Spine(var toc: String = "", id: String = "") : Taggable(id) {
private val refs = LinkedList<ItemRef>()
operator fun plusAssign(ref: ItemRef) {
refs += ref
}
operator fun minusAssign(ref: ItemRef) {
refs -= ref
}
fun addRef(idref: String, linear: Boolean = true, properties: String = "", id: String = "") =
ItemRef(idref, linear, properties, id).also { refs += it }
override fun renderTo(xml: XmlSerializer) {
with(xml) {
startTag("spine")
toc.ifNotEmpty { attribute("toc", it) }
attr.forEach { attribute(it.key, it.value) }
id.ifNotEmpty { attribute("id", it) }
refs.forEach { it.renderTo(this) }
endTag()
}
}
}
| jem-formats/src/main/kotlin/jem/format/epub/opf/Spine.kt | 634868966 |
fun test(x: Array<String>, y: Array<*>, z: IntArray): Int {
var ret = 0
for (el in x) { ret += 1 }
for (el in y) { ret += 1 }
for (el in z) { ret += 1 }
return ret
}
| java/ql/test/kotlin/library-tests/for-array-iterators/test.kt | 4194863572 |
package pl.elpassion.elspace.hub.project
interface CachedProjectRepository {
fun getPossibleProjects(): List<Project>
fun saveProjects(projects: List<Project>)
fun hasProjects(): Boolean
}
| el-space-app/src/main/java/pl/elpassion/elspace/hub/project/CachedProjectRepository.kt | 1248169942 |
package evoasm.x64
import kasm.Address
import kasm.CodeModel
import kasm.NativeBuffer
import kasm.address
import kasm.x64.Assembler
import java.util.logging.Logger
class CompiledNumberProgram<T: Number> internal constructor(program: Program, interpreter: Interpreter, val programSetInput: NumberProgramSetInput<T>, val programSetOutput: NumberProgramSetOutput<T>) {
val buffer = NativeBuffer(1024)
companion object {
val LOGGER = Logger.getLogger(CompiledNumberProgram::class.java.name)
}
init {
compile(program, interpreter)
}
private fun compile(program: Program, interpreter: Interpreter) {
Assembler(buffer).apply {
emitStackFrame {
programSetInput.emitLoad(this)
program.forEach {
val interpreterInstruction = interpreter.getInstruction(it)
interpreterInstruction!!.instruction.encode(buffer, interpreterInstruction.instructionParameters)
}
programSetOutput.emitStore(this)
}
}
}
fun run(vararg arguments: T) : T {
arguments.forEachIndexed {index, argument ->
programSetInput[0, index] = argument
}
LOGGER.finer(buffer.toByteString())
buffer.setExecutable(true)
LOGGER.fine("executing compiled program")
buffer.execute()
return programSetOutput[0, 0]
}
}
class Program(val size: Int) {
private val code = UShortArray(size)
operator fun set(index: Int, opcode: InterpreterOpcode) {
code[index] = opcode.code
}
inline fun forEach(action: (InterpreterOpcode) -> Unit) {
for (i in 0 until size) {
action(this[i])
}
}
inline fun forEachIndexed(action: (InterpreterOpcode, Int) -> Unit) {
for (i in 0 until size) {
action(this[i], i)
}
}
operator fun get(index: Int): InterpreterOpcode {
return InterpreterOpcode(code[index])
}
}
class ProgramSet(val programCount: Int, val programSize: Int, val threadCount: Int) {
constructor(size: Int, programSize: Int) : this(size, programSize, 1)
internal val programSizeWithEnd = programSize + 1
internal val perThreadProgramCount = programCount / threadCount
private val perThreadInstructionCountWithHalt = perThreadProgramCount * programSizeWithEnd + 1
val instructionCount = programCount * programSizeWithEnd
private val instructionCountWithHalts = instructionCount + threadCount
private val codeBuffer = NativeBuffer(instructionCountWithHalts.toLong() * UShort.SIZE_BYTES,
CodeModel.LARGE)
internal val byteBuffer = codeBuffer.byteBuffer
private val shortBuffer = byteBuffer.asShortBuffer()
val address: Address = codeBuffer.address
internal var initialized : Boolean = false
fun getAddress(threadIndex: Int): Address {
val offset = (threadIndex * perThreadInstructionCountWithHalt * Short.SIZE_BYTES).toULong()
val address = codeBuffer.address + offset
LOGGER.finest("address: $address, offset: $offset, threadIndex: $threadIndex, bufferSize: ${codeBuffer.byteBuffer.capacity()}")
return address
}
init {
require(programCount % threadCount == 0)
}
companion object {
val LOGGER = Logger.getLogger(ProgramSet::class.java.name)
}
internal fun initialize(haltOpcode: InterpreterOpcode, endOpcode: InterpreterOpcode) {
check(!initialized) {"cannot reuse program set"}
initialized = true
// shortBuffer.put(0, startOpcode.code.toShort())
require(perThreadInstructionCountWithHalt * threadCount == instructionCountWithHalts) {
"${perThreadInstructionCountWithHalt * threadCount} == ${instructionCountWithHalts}"
}
for(threadIndex in 0 until threadCount) {
for (threadProgramIndex in 0 until perThreadProgramCount) {
val offset = calculateOffset(threadIndex, threadProgramIndex, programSize)
require(offset == threadIndex * perThreadInstructionCountWithHalt + threadProgramIndex * programSizeWithEnd + programSize)
shortBuffer.put(offset, endOpcode.code.toShort())
}
val haltOffset = threadIndex * perThreadInstructionCountWithHalt + perThreadInstructionCountWithHalt - 1
LOGGER.finer("setting halt at $haltOffset");
shortBuffer.put(haltOffset, haltOpcode.code.toShort())
}
}
fun toString(interpreter: Interpreter): String {
val builder = StringBuilder()
for(i in 0 until instructionCountWithHalts) {
val interpreterOpcode = InterpreterOpcode(shortBuffer.get(i).toUShort())
val programIndex = i / programSizeWithEnd
val instructionIndex = i % programSizeWithEnd
val threadIndex = i / perThreadInstructionCountWithHalt
val perThreadProgramIndex = i % perThreadInstructionCountWithHalt
val instructionName = if(interpreterOpcode == interpreter.getHaltOpcode()) {
"HALT"
} else if(interpreterOpcode == interpreter.getEndOpcode()) {
"END"
} else {
interpreter.getInstruction(interpreterOpcode).toString()
}
builder.append("$threadIndex:$perThreadProgramIndex:$instructionIndex:$i:$instructionName\t\n")
}
forEach { interpreterOpcode: InterpreterOpcode, threadIndex: Int, perThreadProgramIndex: Int, instructionIndex: Int, instructionOffset: Int ->
}
return builder.toString()
}
operator fun set(programIndex: Int, instructionIndex: Int, opcode: InterpreterOpcode) {
val offset = calculateOffset(programIndex, instructionIndex)
shortBuffer.put(offset, opcode.code.toShort())
}
private inline fun forEach(action: (InterpreterOpcode, Int, Int, Int, Int) -> Unit) {
for(threadIndex in 0 until threadCount) {
for (perThreadProgramIndex in 0 until perThreadProgramCount) {
for (instructionIndex in 0 until programSize) {
val instructionOffset = calculateOffset(threadIndex, perThreadProgramIndex, instructionIndex);
val interpreterOpcode = InterpreterOpcode(shortBuffer.get(instructionOffset).toUShort())
action(interpreterOpcode, threadIndex, perThreadProgramIndex, instructionIndex, instructionOffset)
}
}
}
}
internal inline fun transform(action: (InterpreterOpcode, Int, Int, Int) -> InterpreterOpcode) {
forEach { interpreterOpcode: InterpreterOpcode, threadIndex: Int, perThreadProgramIndex: Int, instructionIndex: Int, instructionOffset: Int ->
shortBuffer.put(instructionOffset, action(interpreterOpcode, threadIndex, perThreadProgramIndex, instructionIndex).code.toShort())
}
}
operator fun get(programIndex: Int, instructionIndex: Int): InterpreterOpcode {
val offset = calculateOffset(programIndex, instructionIndex)
return InterpreterOpcode(shortBuffer.get(offset).toUShort())
}
private fun calculateOffset(threadIndex: Int, perThreadProgramIndex: Int, instructionIndex: Int): Int {
return (threadIndex * perThreadInstructionCountWithHalt + perThreadProgramIndex * programSizeWithEnd + instructionIndex)
}
private fun calculateOffset(programIndex: Int, instructionIndex: Int): Int {
val threadIndex = programIndex / perThreadProgramCount
val threadProgramIndex = programIndex % perThreadProgramCount
return calculateOffset(threadIndex, threadProgramIndex, instructionIndex)
}
fun copyProgramTo(programIndex: Int, program: Program) {
val programOffset = calculateOffset(programIndex, 0)
for (i in 0 until programSize) {
val instructionOffset = programOffset + i
program[i] = InterpreterOpcode(shortBuffer.get(instructionOffset).toUShort())
}
}
internal inline fun copyProgram(fromProgramIndex: Int, toProgramIndex: Int, transformer: (InterpreterOpcode, Int) -> InterpreterOpcode = { io, o -> io}) {
val fromOffset = calculateOffset(fromProgramIndex, 0)
val toOffset = calculateOffset(toProgramIndex, 0)
for (i in 0 until programSizeWithEnd) {
val relativeOffset = i
val interpreterInstruction = InterpreterOpcode(shortBuffer.get(fromOffset + relativeOffset).toUShort())
shortBuffer.put(toOffset + relativeOffset, transformer(interpreterInstruction, i).code.toShort())
}
}
} | src/evoasm/x64/ProgramSet.kt | 3135231111 |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.sleepsamplekotlin.receiver
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.android.example.sleepsamplekotlin.MainApplication
import com.android.example.sleepsamplekotlin.data.SleepRepository
import com.android.example.sleepsamplekotlin.data.db.SleepClassifyEventEntity
import com.android.example.sleepsamplekotlin.data.db.SleepSegmentEventEntity
import com.google.android.gms.location.SleepClassifyEvent
import com.google.android.gms.location.SleepSegmentEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
/**
* Saves Sleep Events to Database.
*/
class SleepReceiver : BroadcastReceiver() {
// Used to launch coroutines (non-blocking way to insert data).
private val scope: CoroutineScope = MainScope()
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "onReceive(): $intent")
val repository: SleepRepository = (context.applicationContext as MainApplication).repository
if (SleepSegmentEvent.hasEvents(intent)) {
val sleepSegmentEvents: List<SleepSegmentEvent> =
SleepSegmentEvent.extractEvents(intent)
Log.d(TAG, "SleepSegmentEvent List: $sleepSegmentEvents")
addSleepSegmentEventsToDatabase(repository, sleepSegmentEvents)
} else if (SleepClassifyEvent.hasEvents(intent)) {
val sleepClassifyEvents: List<SleepClassifyEvent> =
SleepClassifyEvent.extractEvents(intent)
Log.d(TAG, "SleepClassifyEvent List: $sleepClassifyEvents")
addSleepClassifyEventsToDatabase(repository, sleepClassifyEvents)
}
}
private fun addSleepSegmentEventsToDatabase(
repository: SleepRepository,
sleepSegmentEvents: List<SleepSegmentEvent>
) {
if (sleepSegmentEvents.isNotEmpty()) {
scope.launch {
val convertedToEntityVersion: List<SleepSegmentEventEntity> =
sleepSegmentEvents.map {
SleepSegmentEventEntity.from(it)
}
repository.insertSleepSegments(convertedToEntityVersion)
}
}
}
private fun addSleepClassifyEventsToDatabase(
repository: SleepRepository,
sleepClassifyEvents: List<SleepClassifyEvent>
) {
if (sleepClassifyEvents.isNotEmpty()) {
scope.launch {
val convertedToEntityVersion: List<SleepClassifyEventEntity> =
sleepClassifyEvents.map {
SleepClassifyEventEntity.from(it)
}
repository.insertSleepClassifyEvents(convertedToEntityVersion)
}
}
}
companion object {
const val TAG = "SleepReceiver"
fun createSleepReceiverPendingIntent(context: Context): PendingIntent {
val sleepIntent = Intent(context, SleepReceiver::class.java)
return PendingIntent.getBroadcast(
context,
0,
sleepIntent,
PendingIntent.FLAG_CANCEL_CURRENT
)
}
}
}
| SleepSampleKotlin/app/src/main/java/com/android/example/sleepsamplekotlin/receiver/SleepReceiver.kt | 29953406 |
// Use of this source code is governed by The MIT License
// that can be found in the LICENSE file.
package taumechanica.ml
import taumechanica.ml.data.DataFrame
interface Strategy {
fun init(frame: DataFrame)
fun fit(frame: DataFrame): Classifier
}
| src/main/kotlin/ml/Strategy.kt | 3133570875 |
package org.springframework.samples.petclinic.system
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
/**
* Test class for {@link CrashController}
*
* @author Colin But
*/
@RunWith(SpringRunner::class)
// Waiting https://github.com/spring-projects/spring-boot/issues/5574
@Ignore
@WebMvcTest(controllers = arrayOf(CrashController::class))
class CrashControllerTests {
@Autowired
lateinit private var mockMvc: MockMvc
@Test
fun testTriggerException() {
mockMvc.perform(get("/oups")).andExpect(view().name("exception"))
.andExpect(model().attributeExists("exception"))
.andExpect(forwardedUrl("exception")).andExpect(status().isOk())
}
} | audit4j-kotlin-demo-springboot/src/test/kotlin/org/springframework/samples/petclinic/system/CrashControllerTests.kt | 3006526026 |
package net.pagejects.core.forms
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import net.pagejects.core.annotation.FormField
import org.apache.commons.beanutils.PropertyUtils
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.jvm.javaField
import kotlin.reflect.memberProperties
private val cache = CacheBuilder.from(System.getProperty("pagejects.cache", "maximumSize=200,expireAfterWrite=1h")).
build(CacheLoader.from<KClass<*>, Sequence<FormFieldProperty>> {
if (it == null) {
throw KotlinNullPointerException()
}
val propertyDescriptors = PropertyUtils.getPropertyDescriptors(it.java).associateBy { it.name }
it.memberProperties.asSequence().map {
it to propertyDescriptors[it.name]
}.filter {
it.second != null
}.map {
it.first to it.second!!
}.map {
var list = it.second.readMethod.annotations
list += (it.first.javaField?.annotations ?: emptyArray<Annotation>())
list += it.second.writeMethod.annotations
val field = list.asSequence().filter { it is FormField }.map { it as FormField }.firstOrNull()
FormFieldProperty(
name = it.first.name,
type = it.second.propertyType,
getter = it.second.readMethod,
setter = it.second.writeMethod,
__formField = field
)
}.filter {
it.__formField != null
}
})
/**
* This extension return all mutable properties (see [KMutableProperty]) that annotated by @[FormField].
*
* @author Andrey Paslavsky
* @since 0.1
*/
val KClass<*>.formFields: Sequence<FormFieldProperty>
get() = cache[this] | src/main/kotlin/net/pagejects/core/forms/FormFieldsExt.kt | 2807880276 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.runner
import com.intellij.execution.JavaExecutionUtil
import com.intellij.execution.Location
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.LazyRunConfigurationProducer
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.util.ScriptFileUtil
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.util.text.nullize
import org.jetbrains.plugins.groovy.console.GroovyConsoleStateService
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyRunnerPsiUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyRunnerPsiUtil.isRunnable
import org.jetbrains.plugins.groovy.runner.GroovyRunnerUtil.getConfigurationName
class ScriptRunConfigurationProducer : LazyRunConfigurationProducer<GroovyScriptRunConfiguration>() {
override fun getConfigurationFactory(): ConfigurationFactory = GroovyScriptRunConfigurationType.getInstance().configurationFactory
private class Data(val location: Location<PsiElement>,
val element: PsiElement,
val clazz: PsiClass,
val file: GroovyFile,
val virtualFile: VirtualFile)
private fun checkAndExtractData(context: ConfigurationContext): Data? {
val location = context.location ?: return null
val element = location.psiElement
val file = element.containingFile as? GroovyFile ?: return null
val virtualFile = file.virtualFile ?: return null
if (GroovyConsoleStateService.getInstance(location.project).isProjectConsole(virtualFile)) {
return null
}
val clazz = GroovyRunnerPsiUtil.getRunningClass(element) ?: return null
if (clazz !is GroovyScriptClass && !isRunnable(clazz)) {
return null
}
return Data(location, element, clazz, file, virtualFile)
}
override fun setupConfigurationFromContext(configuration: GroovyScriptRunConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>): Boolean {
val data = checkAndExtractData(context) ?: return false
sourceElement.set(data.element)
configuration.setupFromClass(data.clazz, data.virtualFile)
GroovyScriptUtil.getScriptType(data.file).tuneConfiguration(data.file, configuration, data.location)
return true
}
private fun GroovyScriptRunConfiguration.setupFromClass(aClass: PsiClass, virtualFile: VirtualFile) {
workingDirectory = virtualFile.parent?.path
scriptPath = ScriptFileUtil.getScriptFilePath(virtualFile)
name = getConfigurationName(aClass, configurationModule).nullize() ?: virtualFile.name
module = JavaExecutionUtil.findModule(aClass)
}
override fun isConfigurationFromContext(configuration: GroovyScriptRunConfiguration, context: ConfigurationContext): Boolean {
val data = checkAndExtractData(context) ?: return false
return configuration.scriptPath == ScriptFileUtil.getScriptFilePath(data.virtualFile)
&& GroovyScriptUtil.getScriptType(data.file).isConfigurationByLocation(configuration, data.location)
}
}
| plugins/groovy/src/org/jetbrains/plugins/groovy/runner/ScriptRunConfigurationProducer.kt | 360062776 |
import kotlin.reflect.jvm.*
import kotlin.test.assertEquals
var bar: Unit = Unit
fun box(): String {
assertEquals(Unit::class.java, (when {
(::bar) in null -> (::bar)
else -> (::bar)
}).setter.parameters.single().type.javaType)
return "OK"
} | kotlin/kotlin-formal/examples/fuzzer/unit.kt-1416893130.kt_minimized.kt | 1644220241 |
package com.intellij.testFramework
import java.nio.file.FileSystem
fun FileSystem.file(path: String, data: ByteArray): FileSystem {
getPath(path).write(data)
return this
}
fun FileSystem.file(path: String, data: String) = file(path, data.toByteArray()) | platform/testFramework/test-framework-java8/fsBuilder.kt | 2637272066 |
// 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.refactoring.copy
import com.intellij.ide.util.EditorHelper
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.*
import com.intellij.psi.*
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.copy.CopyFilesOrDirectoriesDialog
import com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler
import com.intellij.refactoring.copy.CopyHandlerDelegateBase
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.usageView.UsageInfo
import com.intellij.util.IncorrectOperationException
import com.intellij.util.containers.MultiMap
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests
import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix
import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit
import org.jetbrains.kotlin.idea.core.util.toPsiDirectory
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.createKotlinFile
import org.jetbrains.kotlin.idea.refactoring.move.*
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveConflictChecker
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.sourceRoot
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.UserDataProperty
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.utils.ifEmpty
class CopyKotlinDeclarationsHandler : CopyHandlerDelegateBase() {
companion object {
private val commandName get() = RefactoringBundle.message("copy.handler.copy.files.directories")
@set:TestOnly
var Project.newName: String? by UserDataProperty(Key.create("NEW_NAME"))
private fun PsiElement.getCopyableElement() =
parentsWithSelf.firstOrNull { it is KtFile || (it is KtNamedDeclaration && it.parent is KtFile) } as? KtElement
private fun PsiElement.getDeclarationsToCopy(): List<KtElement> = when (val declarationOrFile = getCopyableElement()) {
is KtFile -> declarationOrFile.declarations.filterIsInstance<KtNamedDeclaration>().ifEmpty { listOf(declarationOrFile) }
is KtNamedDeclaration -> listOf(declarationOrFile)
else -> emptyList()
}
}
private val copyFilesHandler by lazy { CopyFilesOrDirectoriesHandler() }
private fun getSourceFiles(elements: Array<out PsiElement>): Array<PsiFileSystemItem>? {
return elements
.map { it.containingFile ?: it as? PsiFileSystemItem ?: return null }
.toTypedArray()
}
private fun canCopyFiles(elements: Array<out PsiElement>, fromUpdate: Boolean): Boolean {
val sourceFiles = getSourceFiles(elements) ?: return false
if (!sourceFiles.any { it is KtFile }) return false
return copyFilesHandler.canCopy(sourceFiles, fromUpdate)
}
private fun canCopyDeclarations(elements: Array<out PsiElement>): Boolean {
val containingFile =
elements
.flatMap { it.getDeclarationsToCopy().ifEmpty { return false } }
.distinctBy { it.containingFile }
.singleOrNull()
?.containingFile ?: return false
return containingFile.sourceRoot != null
}
override fun canCopy(elements: Array<out PsiElement>, fromUpdate: Boolean): Boolean {
return canCopyDeclarations(elements) || canCopyFiles(elements, fromUpdate)
}
enum class ExistingFilePolicy {
APPEND, OVERWRITE, SKIP
}
private fun getOrCreateTargetFile(
originalFile: KtFile,
targetDirectory: PsiDirectory,
targetFileName: String
): KtFile? {
val existingFile = targetDirectory.findFile(targetFileName)
if (existingFile == originalFile) return null
if (existingFile != null) when (getFilePolicy(existingFile, targetFileName, targetDirectory)) {
ExistingFilePolicy.APPEND -> {
}
ExistingFilePolicy.OVERWRITE -> runWriteAction { existingFile.delete() }
ExistingFilePolicy.SKIP -> return null
}
return runWriteAction {
if (existingFile != null && existingFile.isValid) {
existingFile as KtFile
} else {
createKotlinFile(targetFileName, targetDirectory)
}
}
}
private fun getFilePolicy(
existingFile: PsiFile?,
targetFileName: String,
targetDirectory: PsiDirectory
): ExistingFilePolicy {
val message = KotlinBundle.message(
"text.file.0.already.exists.in.1",
targetFileName,
targetDirectory.virtualFile.path
)
return if (existingFile !is KtFile) {
if (isUnitTestMode()) return ExistingFilePolicy.OVERWRITE
val answer = Messages.showOkCancelDialog(
message,
commandName,
KotlinBundle.message("action.text.overwrite"),
KotlinBundle.message("action.text.cancel"),
Messages.getQuestionIcon()
)
if (answer == Messages.OK) ExistingFilePolicy.OVERWRITE else ExistingFilePolicy.SKIP
} else {
if (isUnitTestMode()) return ExistingFilePolicy.APPEND
val answer = Messages.showYesNoCancelDialog(
message,
commandName,
KotlinBundle.message("action.text.append"),
KotlinBundle.message("action.text.overwrite"),
KotlinBundle.message("action.text.cancel"),
Messages.getQuestionIcon()
)
when (answer) {
Messages.YES -> ExistingFilePolicy.APPEND
Messages.NO -> ExistingFilePolicy.OVERWRITE
else -> ExistingFilePolicy.SKIP
}
}
}
private data class TargetData(
val openInEditor: Boolean,
val newName: String,
val targetDirWrapper: AutocreatingPsiDirectoryWrapper,
val targetSourceRoot: VirtualFile?
)
private data class SourceData(
val project: Project,
val singleElementToCopy: KtElement?,
val elementsToCopy: List<KtElement>,
val originalFile: KtFile,
val initialTargetDirectory: PsiDirectory
)
private fun getTargetDataForUnitTest(sourceData: SourceData): TargetData? {
with(sourceData) {
val targetSourceRoot: VirtualFile = initialTargetDirectory.sourceRoot ?: return null
val newName: String = project.newName ?: singleElementToCopy?.name ?: originalFile.name
if (singleElementToCopy != null && newName.isEmpty()) return null
return TargetData(
openInEditor = false,
newName = newName,
targetDirWrapper = initialTargetDirectory.toDirectoryWrapper(),
targetSourceRoot = targetSourceRoot
)
}
}
private fun getTargetDataForUX(sourceData: SourceData): TargetData? {
val openInEditor: Boolean
val newName: String?
val targetDirWrapper: AutocreatingPsiDirectoryWrapper?
val targetSourceRoot: VirtualFile?
val singleNamedSourceElement = sourceData.singleElementToCopy as? KtNamedDeclaration
if (singleNamedSourceElement !== null) {
val dialog = CopyKotlinDeclarationDialog(singleNamedSourceElement, sourceData.initialTargetDirectory, sourceData.project)
dialog.title = commandName
if (!dialog.showAndGet()) return null
openInEditor = dialog.openInEditor
newName = dialog.newName
targetDirWrapper = dialog.targetDirectory?.toDirectoryWrapper()
targetSourceRoot = dialog.targetSourceRoot
} else {
val dialog = CopyFilesOrDirectoriesDialog(
arrayOf(sourceData.originalFile),
sourceData.initialTargetDirectory,
sourceData.project,
/*doClone = */false
)
if (!dialog.showAndGet()) return null
openInEditor = dialog.openInEditor()
newName = dialog.newName
targetDirWrapper = dialog.targetDirectory?.toDirectoryWrapper()
targetSourceRoot = dialog.targetDirectory?.sourceRoot
}
targetDirWrapper ?: return null
newName ?: return null
if (sourceData.singleElementToCopy != null && newName.isEmpty()) return null
return TargetData(
openInEditor = openInEditor,
newName = newName,
targetDirWrapper = targetDirWrapper,
targetSourceRoot = targetSourceRoot
)
}
private fun collectInternalUsages(sourceData: SourceData, targetData: TargetData) = runReadAction {
val targetPackageName = targetData.targetDirWrapper.getPackageName()
val changeInfo = ContainerChangeInfo(
ContainerInfo.Package(sourceData.originalFile.packageFqName),
ContainerInfo.Package(FqName(targetPackageName))
)
sourceData.elementsToCopy.flatMapTo(LinkedHashSet()) { elementToCopy ->
elementToCopy.getInternalReferencesToUpdateOnPackageNameChange(changeInfo).filter {
val referencedElement = (it as? MoveRenameUsageInfo)?.referencedElement
referencedElement == null || !elementToCopy.isAncestor(referencedElement)
}
}
}
private fun trackedCopyFiles(sourceFiles: Array<out PsiFileSystemItem>, initialTargetDirectory: PsiDirectory?): Set<VirtualFile> {
if (!copyFilesHandler.canCopy(sourceFiles)) return emptySet()
val mapper = object : VirtualFileListener {
val filesCopied = mutableSetOf<VirtualFile>()
override fun fileCopied(event: VirtualFileCopyEvent) {
filesCopied.add(event.file)
}
override fun fileCreated(event: VirtualFileEvent) {
filesCopied.add(event.file)
}
}
with(VirtualFileManager.getInstance()) {
try {
addVirtualFileListener(mapper)
copyFilesHandler.doCopy(sourceFiles, initialTargetDirectory)
} finally {
removeVirtualFileListener(mapper)
}
}
return mapper.filesCopied
}
private fun doCopyFiles(filesToCopy: Array<out PsiFileSystemItem>, initialTargetDirectory: PsiDirectory?) {
if (filesToCopy.isEmpty()) return
val project = filesToCopy[0].project
val psiManager = PsiManager.getInstance(project)
project.executeCommand(commandName) {
val copiedFiles = trackedCopyFiles(filesToCopy, initialTargetDirectory)
copiedFiles.forEach { copiedFile ->
val targetKtFile = psiManager.findFile(copiedFile) as? KtFile
if (targetKtFile !== null) {
runWriteAction {
if (!targetKtFile.packageMatchesDirectoryOrImplicit()) {
targetKtFile.containingDirectory?.getFqNameWithImplicitPrefix()?.quoteIfNeeded()?.let { targetDirectoryFqName ->
targetKtFile.packageFqName = targetDirectoryFqName
}
}
performDelayedRefactoringRequests(project)
}
}
}
}
}
override fun doCopy(elements: Array<out PsiElement>, defaultTargetDirectory: PsiDirectory?) {
if (elements.isEmpty()) return
if (!canCopyDeclarations(elements)) {
getSourceFiles(elements)?.let {
return doCopyFiles(it, defaultTargetDirectory)
}
}
val elementsToCopy = elements.mapNotNull { it.getCopyableElement() }
if (elementsToCopy.isEmpty()) return
val singleElementToCopy = elementsToCopy.singleOrNull()
val originalFile = elementsToCopy.first().containingFile as KtFile
val initialTargetDirectory = defaultTargetDirectory ?: originalFile.containingDirectory ?: return
val project = initialTargetDirectory.project
val sourceData = SourceData(
project = project,
singleElementToCopy = singleElementToCopy,
elementsToCopy = elementsToCopy,
originalFile = originalFile,
initialTargetDirectory = initialTargetDirectory
)
val targetData = if (isUnitTestMode()) getTargetDataForUnitTest(sourceData) else getTargetDataForUX(sourceData)
targetData ?: return
val internalUsages = collectInternalUsages(sourceData, targetData)
markInternalUsages(internalUsages)
val conflicts = collectConflicts(sourceData, targetData, internalUsages)
project.checkConflictsInteractively(conflicts) {
try {
project.executeCommand(commandName) {
doRefactor(sourceData, targetData)
}
} finally {
cleanUpInternalUsages(internalUsages)
}
}
}
private data class RefactoringResult(
val targetFile: PsiFile,
val copiedDeclaration: KtNamedDeclaration?,
val restoredInternalUsages: List<UsageInfo>? = null
)
private fun getTargetFileName(sourceData: SourceData, targetData: TargetData) =
if (targetData.newName.contains(".")) targetData.newName
else targetData.newName + "." + sourceData.originalFile.virtualFile.extension
private fun doRefactor(sourceData: SourceData, targetData: TargetData) {
var refactoringResult: RefactoringResult? = null
try {
val targetDirectory = runWriteAction {
targetData.targetDirWrapper.getOrCreateDirectory(sourceData.initialTargetDirectory)
}
val targetFileName = getTargetFileName(sourceData, targetData)
val isSingleDeclarationInFile =
sourceData.singleElementToCopy is KtNamedDeclaration &&
sourceData.originalFile.declarations.singleOrNull() == sourceData.singleElementToCopy
val fileToCopy = when {
sourceData.singleElementToCopy is KtFile -> sourceData.singleElementToCopy
isSingleDeclarationInFile -> sourceData.originalFile
else -> null
}
refactoringResult = if (fileToCopy !== null) {
doRefactoringOnFile(fileToCopy, sourceData, targetDirectory, targetFileName, isSingleDeclarationInFile)
} else {
val targetFile = getOrCreateTargetFile(sourceData.originalFile, targetDirectory, targetFileName)
?: throw IncorrectOperationException("Could not create target file.")
doRefactoringOnElement(sourceData, targetFile)
}
refactoringResult.copiedDeclaration?.let<KtNamedDeclaration, Unit> { newDeclaration ->
if (targetData.newName == newDeclaration.name) return@let
val selfReferences = ReferencesSearch.search(newDeclaration, LocalSearchScope(newDeclaration)).findAll()
runWriteAction {
selfReferences.forEach { it.handleElementRename(targetData.newName) }
newDeclaration.setName(targetData.newName)
}
}
if (targetData.openInEditor) {
EditorHelper.openInEditor(refactoringResult.targetFile)
}
} catch (e: IncorrectOperationException) {
Messages.showMessageDialog(sourceData.project, e.message, RefactoringBundle.message("error.title"), Messages.getErrorIcon())
} finally {
refactoringResult?.restoredInternalUsages?.let { cleanUpInternalUsages(it) }
}
}
private fun doRefactoringOnFile(
fileToCopy: KtFile,
sourceData: SourceData,
targetDirectory: PsiDirectory,
targetFileName: String,
isSingleDeclarationInFile: Boolean
): RefactoringResult {
val targetFile = runWriteAction {
// implicit package prefix may change after copy
val targetDirectoryFqName = targetDirectory.getFqNameWithImplicitPrefix()
val copiedFile = targetDirectory.copyFileFrom(targetFileName, fileToCopy)
if (copiedFile is KtFile && fileToCopy.packageMatchesDirectoryOrImplicit()) {
targetDirectoryFqName?.quoteIfNeeded()?.let { copiedFile.packageFqName = it }
}
performDelayedRefactoringRequests(sourceData.project)
copiedFile
}
val copiedDeclaration = if (isSingleDeclarationInFile && targetFile is KtFile) {
targetFile.declarations.singleOrNull() as? KtNamedDeclaration
} else null
return RefactoringResult(targetFile, copiedDeclaration)
}
private fun doRefactoringOnElement(
sourceData: SourceData,
targetFile: KtFile
): RefactoringResult {
val restoredInternalUsages = ArrayList<UsageInfo>()
val oldToNewElementsMapping = HashMap<PsiElement, PsiElement>()
runWriteAction {
val newElements = sourceData.elementsToCopy.map { targetFile.add(it.copy()) as KtNamedDeclaration }
sourceData.elementsToCopy.zip(newElements).toMap(oldToNewElementsMapping)
oldToNewElementsMapping[sourceData.originalFile] = targetFile
for (newElement in oldToNewElementsMapping.values) {
restoredInternalUsages += restoreInternalUsages(newElement as KtElement, oldToNewElementsMapping, forcedRestore = true)
postProcessMoveUsages(restoredInternalUsages, oldToNewElementsMapping)
}
performDelayedRefactoringRequests(sourceData.project)
}
val copiedDeclaration = oldToNewElementsMapping.values.filterIsInstance<KtNamedDeclaration>().singleOrNull()
return RefactoringResult(targetFile, copiedDeclaration, restoredInternalUsages)
}
private fun collectConflicts(
sourceData: SourceData,
targetData: TargetData,
internalUsages: HashSet<UsageInfo>
): MultiMap<PsiElement, String> {
if (isUnitTestMode() && BaseRefactoringProcessor.ConflictsInTestsException.isTestIgnore())
return MultiMap.empty()
val targetSourceRootPsi = targetData.targetSourceRoot?.toPsiDirectory(sourceData.project)
?: return MultiMap.empty()
if (sourceData.project != sourceData.originalFile.project) return MultiMap.empty()
val conflictChecker = MoveConflictChecker(
sourceData.project,
sourceData.elementsToCopy,
KotlinDirectoryMoveTarget(FqName.ROOT, targetSourceRootPsi.virtualFile),
sourceData.originalFile
)
return MultiMap<PsiElement, String>().also {
conflictChecker.checkModuleConflictsInDeclarations(internalUsages, it)
conflictChecker.checkVisibilityInDeclarations(it)
}
}
override fun doClone(element: PsiElement) {
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/copy/CopyKotlinDeclarationsHandler.kt | 782868247 |
package mp
/**
* Shows the multi-platform implementation of a class by delegating to an expected sub class. Properties:
*
* * Adds artificial types to the class hierarchy.
* * Allows for platform-specific members in the multi-platform sub class.
*
* See [CommonClassDelegatingToInternalClassHeader] for an alternative way to have a multi-platform implementation of a
* class.
*/
abstract class CommonClassDelegatingToSubClassHeader protected constructor() {
fun execute() {
doIt()
}
protected abstract fun doIt()
}
| common/src/main/kotlin/mp/CommonClassDelegatingToSubClassHeader.kt | 1206506819 |
package com.werb.library
import android.view.View
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.werb.library.action.MoreClickListener
import kotlinx.android.extensions.LayoutContainer
/**
* [MoreViewHolder] Base ViewHolder implement Action fun
* Created by wanbo on 2017/7/2.
*/
abstract class MoreViewHolder<T : Any>(val values: MutableMap<String, Any> = mutableMapOf(), override val containerView: View) : ViewHolder(containerView), LayoutContainer {
val injectValueMap = mutableMapOf<String, Any>()
internal var clickListener: MoreClickListener? = null
fun getItemView(): View = itemView
fun addOnTouchListener(viewId: Int) {
clickListener?.let {
val _this = it
itemView.findViewById<View>(viewId).setOnTouchListener { v, event ->
_this.onItemTouch(v, event, layoutPosition)
}
}
}
fun addOnTouchListener(view: View) {
clickListener?.let {
val _this = it
view.setOnTouchListener { v, event ->
_this.onItemTouch(v, event, layoutPosition)
}
}
}
fun addOnClickListener(viewId: Int) {
itemView.findViewById<View>(viewId).setOnClickListener { clickListener?.onItemClick(it, layoutPosition) }
}
fun addOnClickListener(view: View) {
view.setOnClickListener { clickListener?.onItemClick(it, layoutPosition) }
}
fun addOnLongClickListener(viewId: Int) {
clickListener?.let { it ->
val _this = it
itemView.findViewById<View>(viewId).setOnLongClickListener {
_this.onItemLongClick(it, layoutPosition)
}
}
}
fun addOnLongClickListener(view: View) {
clickListener?.let { it ->
val _this = it
view.setOnLongClickListener {
_this.onItemLongClick(view, layoutPosition)
}
}
}
/** [bindData] bind data with T */
abstract fun bindData(data: T, payloads: List<Any> = arrayListOf())
/** [unBindData] unbind and release resources*/
open fun unBindData() {}
} | library/src/main/kotlin/com/werb/library/MoreViewHolder.kt | 2763566373 |
// 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.fir.analysis.providers.trackers
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.analysis.providers.createModuleWithoutDependenciesOutOfBlockModificationTracker
import org.jetbrains.kotlin.analysis.providers.createProjectWideOutOfBlockModificationTracker
import org.jetbrains.kotlin.idea.base.projectStructure.getMainKtSourceModule
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.util.sourceRoots
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.junit.Assert
import java.io.File
class KotlinModuleOutOfBlockTrackerTest : AbstractMultiModuleTest() {
override fun getTestDataDirectory(): File = error("Should not be called")
fun testThatModuleOutOfBlockChangeInfluenceOnlySingleModule() {
val moduleA = createModuleInTmpDir("a") {
listOf(
FileWithText("main.kt", "fun main() = 10")
)
}
val moduleB = createModuleInTmpDir("b")
val moduleC = createModuleInTmpDir("c")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val moduleCWithTracker = ModuleWithModificationTracker(moduleC)
moduleA.typeInFunctionBody("main.kt", textAfterTyping = "fun main() = hello10")
Assert.assertTrue(
"Out of block modification count for module A with out of block should change after typing, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module B without out of block should not change after typing, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module C without out of block should not change after typing, modification count is ${moduleCWithTracker.modificationCount}",
moduleCWithTracker.changed()
)
}
fun testThatDeleteSymbolInBodyDoesNotLeadToOutOfBlockChange() {
val moduleA = createModuleInTmpDir("a") {
listOf(
FileWithText(
"main.kt", "fun main() {\n" +
"//abc\n" +
"}"
)
)
}
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val file = "${moduleA.sourceRoots.first().url}/${"main.kt"}"
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!!
val ktFile = PsiManager.getInstance(moduleA.project).findFile(virtualFile) as KtFile
configureByExistingFile(virtualFile)
val singleFunction = ktFile.declarations.single() as KtNamedFunction
val comment = PsiTreeUtil.findChildOfType(singleFunction.bodyBlockExpression!!, PsiComment::class.java)!!
editor.caretModel.moveToOffset(comment.textRange.endOffset)
backspace()
PsiDocumentManager.getInstance(moduleA.project).commitAllDocuments()
Assert.assertFalse(
"Out of block modification count for module A with out of block should not change after deleting, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertEquals("fun main() {\n" +
"//ab\n" +
"}", ktFile.text)
}
fun testThatInEveryModuleOutOfBlockWillHappenAfterContentRootChange() {
val moduleA = createModuleInTmpDir("a")
val moduleB = createModuleInTmpDir("b")
val moduleC = createModuleInTmpDir("c")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val moduleCWithTracker = ModuleWithModificationTracker(moduleC)
runWriteAction {
moduleA.sourceRoots.first().createChildData(/* requestor = */ null, "file.kt")
}
Assert.assertTrue(
"Out of block modification count for module A should change after content root change, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertTrue(
"Out of block modification count for module B should change after content root change, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertTrue(
"Out of block modification count for module C should change after content root change modification count is ${moduleCWithTracker.modificationCount}",
moduleCWithTracker.changed()
)
}
fun testThatNonPhysicalFileChangeNotCausingBOOM() {
val moduleA = createModuleInTmpDir("a") {
listOf(
FileWithText("main.kt", "fun main() {}")
)
}
val moduleB = createModuleInTmpDir("b")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val projectWithModificationTracker = ProjectWithModificationTracker(project)
runWriteAction {
val nonPhysicalPsi = KtPsiFactory(moduleA.project).createFile("nonPhysical", "val a = c")
nonPhysicalPsi.add(KtPsiFactory(moduleA.project).createFunction("fun x(){}"))
}
Assert.assertFalse(
"Out of block modification count for module A should not change after non physical file change, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module B should not change after non physical file change, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for project should not change after non physical file change, modification count is ${projectWithModificationTracker.modificationCount}",
projectWithModificationTracker.changed()
)
}
private fun Module.typeInFunctionBody(fileName: String, textAfterTyping: String) {
val file = "${sourceRoots.first().url}/$fileName"
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!!
val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as KtFile
configureByExistingFile(virtualFile)
val singleFunction = ktFile.declarations.single() as KtNamedFunction
editor.caretModel.moveToOffset(singleFunction.bodyExpression!!.textOffset)
type("hello")
PsiDocumentManager.getInstance(project).commitAllDocuments()
Assert.assertEquals(textAfterTyping, ktFile.text)
}
abstract class WithModificationTracker(private val modificationTracker: ModificationTracker) {
private val initialModificationCount = modificationTracker.modificationCount
val modificationCount: Long get() = modificationTracker.modificationCount
fun changed(): Boolean =
modificationTracker.modificationCount != initialModificationCount
}
private class ModuleWithModificationTracker(module: Module) : WithModificationTracker(
module.getMainKtSourceModule()!!.createModuleWithoutDependenciesOutOfBlockModificationTracker(module.project)
)
private class ProjectWithModificationTracker(project: Project) : WithModificationTracker(
project.createProjectWideOutOfBlockModificationTracker()
)
} | plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/trackers/KotlinModuleOutOfBlockTrackerTest.kt | 3954060085 |
package com.virtlink.paplj.terms
import com.virtlink.terms.*
// GENERATED: This file is generated, do not modify.
/**
* The FieldTerm term.
*/
@Suppress("UNCHECKED_CAST")
class FieldTerm(
override val name: StringTerm,
override val type: StringTerm)
: Term(), ClassMemberTerm {
companion object {
/**
* Gets the constructor of this term.
*/
val constructor = TermConstructorOfT("FieldTerm", 2, { create(it) })
/**
* Creates a new term from the specified list of child terms.
*
* @param children The list of child terms.
* @return The created term.
*/
@JvmStatic fun create(children: List<ITerm>): FieldTerm {
if (children.size != constructor.arity) {
throw IllegalArgumentException("children must be ${constructor.arity} in length")
}
val name = children[0] as StringTerm
val type = children[1] as StringTerm
return FieldTerm(name, type)
}
}
override val constructor: ITermConstructor
get() = Companion.constructor
override val children: List<ITerm> by lazy { ChildrenList() }
private inner class ChildrenList: AbstractList<ITerm>() {
override val size: Int
get() = FieldTerm.constructor.arity
override fun get(index: Int): ITerm
= when (index) {
0 -> [email protected]
1 -> [email protected]
else -> throw IndexOutOfBoundsException()
}
}
}
| paplj/src/main/kotlin/com/virtlink/paplj/terms/FieldTerm.kt | 3458150331 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.domain.prefs
import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage
import com.google.samples.apps.iosched.shared.di.IoDispatcher
import com.google.samples.apps.iosched.shared.domain.FlowUseCase
import com.google.samples.apps.iosched.shared.result.Result
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
/**
* Returns whether onboarding has been completed.
*/
open class OnboardingCompletedUseCase @Inject constructor(
private val preferenceStorage: PreferenceStorage,
@IoDispatcher dispatcher: CoroutineDispatcher
) : FlowUseCase<Unit, Boolean>(dispatcher) {
override fun execute(parameters: Unit): Flow<Result<Boolean>> =
preferenceStorage.onboardingCompleted.map { Result.Success(it) }
}
| shared/src/main/java/com/google/samples/apps/iosched/shared/domain/prefs/OnboardingCompletedUseCase.kt | 2836547421 |
package org.jetbrains.haskell.psi.reference
import org.jetbrains.haskell.psi.SomeId
import com.intellij.psi.PsiReferenceBase
import org.jetbrains.haskell.psi.ModuleName
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.haskell.psi.Module
import org.jetbrains.haskell.fileType.HaskellFile
import org.jetbrains.haskell.psi.QCon
import org.jetbrains.haskell.scope.ModuleScope
import org.jetbrains.haskell.psi.ConstructorDeclaration
/**
* Created by atsky on 4/11/14.
*/
class ConstructorReference(val constructor: QCon) : PsiReferenceBase<QCon>(
constructor,
TextRange(0, constructor.textRange!!.length)) {
override fun resolve(): PsiElement? {
for (declaration in getConstructorsList()) {
if (declaration.getDeclarationName() == constructor.text) {
return declaration.getTypeVariable()
}
}
return null
}
fun getConstructorsList() : List<ConstructorDeclaration> {
val module = Module.findModule(constructor)
if (module != null) {
return ModuleScope(module).getVisibleConstructors()
}
return listOf()
}
override fun handleElementRename(newElementName: String?): PsiElement? {
return constructor
}
override fun getVariants(): Array<Any> {
return getConstructorsList().toTypedArray()
}
} | plugin/src/org/jetbrains/haskell/psi/reference/ConstructorReference.kt | 640476395 |
/*
* 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.debugger
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import com.intellij.util.SmartList
import com.intellij.util.containers.putValue
import com.intellij.util.containers.remove
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import gnu.trove.THashMap
import gnu.trove.THashSet
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.all
import org.jetbrains.concurrency.nullPromise
import org.jetbrains.concurrency.resolvedPromise
import java.util.concurrent.atomic.AtomicBoolean
private val IDE_TO_VM_BREAKPOINTS_KEY = Key.create<THashMap<XLineBreakpoint<*>, MutableList<Breakpoint>>>("ideToVmBreakpoints")
abstract class LineBreakpointManager(internal val debugProcess: DebugProcessImpl<*>) {
protected val vmToIdeBreakpoints = THashMap<Breakpoint, MutableList<XLineBreakpoint<*>>>()
private val runToLocationBreakpoints = THashSet<Breakpoint>()
private val lock = Object()
open fun isAnyFirstLineBreakpoint(breakpoint: Breakpoint) = false
private val breakpointResolvedListenerAdded = AtomicBoolean()
fun setBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>) {
val target = synchronized (lock) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.get(breakpoint) }
if (target == null) {
setBreakpoint(vm, breakpoint, debugProcess.getLocationsForBreakpoint(vm, breakpoint))
}
else {
val breakpointManager = vm.breakpointManager
for (vmBreakpoint in target) {
if (!vmBreakpoint.enabled) {
vmBreakpoint.enabled = true
breakpointManager.flush(vmBreakpoint)
.rejected { debugProcess.session.updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_invalid_breakpoint, it.message) }
}
}
}
}
fun removeBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, temporary: Boolean): Promise<*> {
val disable = temporary && debugProcess.mainVm!!.breakpointManager.getMuteMode() !== BreakpointManager.MUTE_MODE.NONE
beforeBreakpointRemoved(breakpoint, disable)
return doRemoveBreakpoint(vm, breakpoint, disable)
}
protected open fun beforeBreakpointRemoved(breakpoint: XLineBreakpoint<*>, disable: Boolean) {
}
fun doRemoveBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, disable: Boolean = false): Promise<*> {
var vmBreakpoints: Collection<Breakpoint> = emptySet()
synchronized (lock) {
if (disable) {
val list = IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.get(breakpoint) ?: return nullPromise()
val iterator = list.iterator()
vmBreakpoints = list
while (iterator.hasNext()) {
val vmBreakpoint = iterator.next()
if ((vmToIdeBreakpoints.get(vmBreakpoint)?.size ?: -1) > 1) {
// we must not disable vm breakpoint - it is used for another ide breakpoints
iterator.remove()
}
}
}
else {
vmBreakpoints = IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.remove(breakpoint) ?: return nullPromise()
for (vmBreakpoint in vmBreakpoints) {
vmToIdeBreakpoints.remove(vmBreakpoint, breakpoint)
if (vmToIdeBreakpoints.containsKey(vmBreakpoint)) {
// we must not remove vm breakpoint - it is used for another ide breakpoints
return nullPromise()
}
}
}
}
if (vmBreakpoints.isEmpty()) {
return nullPromise()
}
val breakpointManager = vm.breakpointManager
val promises = SmartList<Promise<*>>()
if (disable) {
for (vmBreakpoint in vmBreakpoints) {
vmBreakpoint.enabled = false
promises.add(breakpointManager.flush(vmBreakpoint))
}
}
else {
for (vmBreakpoint in vmBreakpoints) {
promises.add(breakpointManager.remove(vmBreakpoint))
}
}
return all(promises)
}
fun setBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>, locations: List<Location>, promiseRef: Ref<Promise<out Breakpoint>>? = null) {
if (locations.isEmpty()) {
return
}
val vmBreakpoints = SmartList<Breakpoint>()
for (location in locations) {
doSetBreakpoint(vm, breakpoint, location, false, promiseRef)?.let { vmBreakpoints.add(it) }
}
synchronized (lock) {
var list = IDE_TO_VM_BREAKPOINTS_KEY.get(vm)
if (list == null) {
list = vm.putUserDataIfAbsent(IDE_TO_VM_BREAKPOINTS_KEY, THashMap())
}
list.put(breakpoint, vmBreakpoints)
for (vmBreakpoint in vmBreakpoints) {
vmToIdeBreakpoints.putValue(vmBreakpoint, breakpoint)
}
}
}
protected fun doSetBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>?, location: Location, isTemporary: Boolean, promiseRef: Ref<Promise<out Breakpoint>>? = null): Breakpoint? {
if (breakpointResolvedListenerAdded.compareAndSet(false, true)) {
vm.breakpointManager.addBreakpointListener(object : BreakpointListener {
override fun resolved(breakpoint: Breakpoint) {
synchronized (lock) { vmToIdeBreakpoints[breakpoint] }?.let {
for (ideBreakpoint in it) {
debugProcess.session.updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_verified_breakpoint, null)
}
}
}
override fun errorOccurred(breakpoint: Breakpoint, errorMessage: String?) {
if (isAnyFirstLineBreakpoint(breakpoint)) {
return
}
if (synchronized (lock) { runToLocationBreakpoints.remove(breakpoint) }) {
debugProcess.session.reportError("Cannot run to cursor: $errorMessage")
return
}
synchronized (lock) { vmToIdeBreakpoints.get(breakpoint) }
?.let {
for (ideBreakpoint in it) {
debugProcess.session.updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_invalid_breakpoint, errorMessage)
}
}
}
override fun nonProvisionalBreakpointRemoved(breakpoint: Breakpoint) {
synchronized (lock) {
vmToIdeBreakpoints.remove(breakpoint)?.let {
for (ideBreakpoint in it) {
IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.remove(ideBreakpoint, breakpoint)
}
it
}
}
?.let {
for (ideBreakpoint in it) {
setBreakpoint(vm, ideBreakpoint, debugProcess.getLocationsForBreakpoint(vm, ideBreakpoint))
}
}
}
})
}
val breakpointManager = vm.breakpointManager
val target = createTarget(breakpoint, breakpointManager, location, isTemporary)
checkDuplicates(target, location, breakpointManager)?.let {
promiseRef?.set(resolvedPromise(it))
return it
}
return breakpointManager.setBreakpoint(target, location.line, location.column, location.url, breakpoint?.conditionExpression?.expression, promiseRef = promiseRef)
}
protected abstract fun createTarget(breakpoint: XLineBreakpoint<*>?, breakpointManager: BreakpointManager, location: Location, isTemporary: Boolean): BreakpointTarget
protected open fun checkDuplicates(newTarget: BreakpointTarget, location: Location, breakpointManager: BreakpointManager): Breakpoint? = null
fun runToLocation(position: XSourcePosition, vm: Vm) {
val addedBreakpoints = doRunToLocation(position)
if (addedBreakpoints.isEmpty()) {
return
}
synchronized (lock) {
runToLocationBreakpoints.addAll(addedBreakpoints)
}
debugProcess.resume(vm)
}
protected abstract fun doRunToLocation(position: XSourcePosition): List<Breakpoint>
fun isRunToCursorBreakpoint(breakpoint: Breakpoint) = synchronized (runToLocationBreakpoints) { runToLocationBreakpoints.contains(breakpoint) }
fun updateAllBreakpoints(vm: Vm) {
val array = synchronized (lock) { IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.keys?.toTypedArray() } ?: return
for (breakpoint in array) {
removeBreakpoint(vm, breakpoint, false)
setBreakpoint(vm, breakpoint)
}
}
fun removeAllBreakpoints(vm: Vm): Promise<*> {
synchronized (lock) {
IDE_TO_VM_BREAKPOINTS_KEY.get(vm)?.clear()
vmToIdeBreakpoints.clear()
runToLocationBreakpoints.clear()
}
return vm.breakpointManager.removeAll()
}
fun clearRunToLocationBreakpoints(vm: Vm) {
val breakpoints = synchronized (lock) {
if (runToLocationBreakpoints.isEmpty) {
return@clearRunToLocationBreakpoints
}
val breakpoints = runToLocationBreakpoints.toArray<Breakpoint>(arrayOfNulls<Breakpoint>(runToLocationBreakpoints.size))
runToLocationBreakpoints.clear()
breakpoints
}
val breakpointManager = vm.breakpointManager
for (breakpoint in breakpoints) {
breakpointManager.remove(breakpoint)
}
}
} | platform/script-debugger/debugger-ui/src/LineBreakpointManager.kt | 2973281023 |
// 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.searching.usages
import com.intellij.psi.PsiPackage
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyzeWithReadAction
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinUsageTypeProvider
import org.jetbrains.kotlin.idea.base.searching.usages.UsageTypeEnum
import org.jetbrains.kotlin.idea.base.searching.usages.UsageTypeEnum.*
import org.jetbrains.kotlin.idea.references.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.util.OperatorNameConventions
internal class KotlinK2UsageTypeProvider : KotlinUsageTypeProvider() {
override fun getUsageTypeEnumByReference(refExpr: KtReferenceExpression): UsageTypeEnum? {
val reference = refExpr.mainReference
check(reference is KtSimpleReference<*>) { "Reference should be KtSimpleReference but not ${reference::class}" }
fun KtAnalysisSession.getFunctionUsageType(functionSymbol: KtFunctionLikeSymbol): UsageTypeEnum? {
when (reference) {
is KtArrayAccessReference ->
return when ((functionSymbol as KtFunctionSymbol).name) {
OperatorNameConventions.GET -> IMPLICIT_GET
OperatorNameConventions.SET -> IMPLICIT_SET
else -> error("Expected get or set operator but resolved to unexpected symbol {functionSymbol.render()}")
}
is KtInvokeFunctionReference -> return IMPLICIT_INVOKE
is KtConstructorDelegationReference -> return null
}
return when {
refExpr.getParentOfTypeAndBranch<KtSuperTypeListEntry> { typeReference } != null -> SUPER_TYPE
functionSymbol is KtConstructorSymbol && refExpr.getParentOfTypeAndBranch<KtAnnotationEntry> { typeReference } != null -> ANNOTATION
with(refExpr.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression }) {
this?.calleeExpression is KtSimpleNameExpression
} -> if (functionSymbol is KtConstructorSymbol) CLASS_NEW_OPERATOR else FUNCTION_CALL
refExpr.getParentOfTypeAndBranch<KtBinaryExpression> { operationReference } != null || refExpr.getParentOfTypeAndBranch<KtUnaryExpression> { operationReference } != null || refExpr.getParentOfTypeAndBranch<KtWhenConditionInRange> { operationReference } != null -> FUNCTION_CALL
else -> null
}
}
return analyzeWithReadAction(refExpr) {
when (val targetElement = reference.resolveToSymbol()) {
is KtClassifierSymbol ->
when (targetElement) {
is KtClassOrObjectSymbol -> when (targetElement.classKind) {
KtClassKind.COMPANION_OBJECT -> COMPANION_OBJECT_ACCESS
KtClassKind.OBJECT -> getVariableUsageType(refExpr)
else -> getClassUsageType(refExpr)
}
else -> getClassUsageType(refExpr)
}
is KtPackageSymbol -> //TODO FIR Implement package symbol type
if (targetElement is PsiPackage) getPackageUsageType(refExpr) else getClassUsageType(refExpr)
is KtVariableLikeSymbol -> getVariableUsageType(refExpr)
is KtFunctionLikeSymbol -> getFunctionUsageType(targetElement)
else -> null
}
}
}
}
| plugins/kotlin/kotlin.searching/src/org/jetbrains/kotlin/idea/searching/usages/KotlinK2UsageTypeProvider.kt | 2002431806 |
package com.github.vhromada.catalog.utils
import com.github.vhromada.catalog.common.entity.Time
import com.github.vhromada.catalog.domain.filter.MusicFilter
import com.github.vhromada.catalog.domain.io.MusicStatistics
import com.github.vhromada.catalog.entity.ChangeMusicRequest
import com.github.vhromada.catalog.entity.Music
import com.github.vhromada.catalog.filter.NameFilter
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import javax.persistence.EntityManager
/**
* Updates music fields.
*
* @return updated music
*/
fun com.github.vhromada.catalog.domain.Music.updated(): com.github.vhromada.catalog.domain.Music {
name = "Name"
normalizedName = "Name"
wikiEn = "enWiki"
wikiCz = "czWiki"
mediaCount = 1
note = "Note"
return this
}
/**
* Updates music fields.
*
* @return updated music
*/
fun Music.updated(): Music {
return copy(
name = "Name",
wikiEn = "enWiki",
wikiCz = "czWiki",
mediaCount = 1,
note = "Note"
)
}
/**
* A class represents utility class for music.
*
* @author Vladimir Hromada
*/
object MusicUtils {
/**
* Count of music
*/
const val MUSIC_COUNT = 3
/**
* Multiplier for media count
*/
private const val MEDIA_COUNT_MULTIPLIER = 10
/**
* Returns list of music.
*
* @return list of music
*/
fun getDomainMusicList(): List<com.github.vhromada.catalog.domain.Music> {
val musicList = mutableListOf<com.github.vhromada.catalog.domain.Music>()
for (i in 1..MUSIC_COUNT) {
musicList.add(getDomainMusic(index = i))
}
return musicList
}
/**
* Returns list of music.
*
* @return list of music
*/
fun getMusicList(): List<Music> {
val musicList = mutableListOf<Music>()
for (i in 1..MUSIC_COUNT) {
musicList.add(getMusic(index = i))
}
return musicList
}
/**
* Returns music for index.
*
* @param index index
* @return music for index
*/
fun getDomainMusic(index: Int): com.github.vhromada.catalog.domain.Music {
val name = "Music $index name"
val music = com.github.vhromada.catalog.domain.Music(
id = index,
uuid = getUuid(index = index),
name = name,
normalizedName = name,
wikiEn = if (index != 1) "Music $index English Wikipedia" else null,
wikiCz = if (index != 1) "Music $index Czech Wikipedia" else null,
mediaCount = index * MEDIA_COUNT_MULTIPLIER,
note = if (index == 2) "Music $index note" else null,
songs = SongUtils.getDomainSongs(music = index)
).fillAudit(audit = AuditUtils.getAudit())
music.songs.forEach { it.music = music }
return music
}
/**
* Returns UUID for index.
*
* @param index index
* @return UUID for index
*/
private fun getUuid(index: Int): String {
return when (index) {
1 -> "9c9f53ce-5576-4d18-8470-5863dbb49c46"
2 -> "21d837eb-258e-4170-b27d-b81c880e9260"
3 -> "66fc3034-223a-486e-8c03-c3f71a733ca9"
else -> throw IllegalArgumentException("Bad index")
}
}
/**
* Returns music.
*
* @param entityManager entity manager
* @param id music ID
* @return music
*/
fun getDomainMusic(entityManager: EntityManager, id: Int): com.github.vhromada.catalog.domain.Music? {
return entityManager.find(com.github.vhromada.catalog.domain.Music::class.java, id)
}
/**
* Returns music for index.
*
* @param index index
* @return music for index
*/
fun getMusic(index: Int): Music {
return Music(
uuid = getUuid(index = index),
name = "Music $index name",
wikiEn = if (index != 1) "Music $index English Wikipedia" else null,
wikiCz = if (index != 1) "Music $index Czech Wikipedia" else null,
mediaCount = index * MEDIA_COUNT_MULTIPLIER,
note = if (index == 2) "Music $index note" else null,
songsCount = SongUtils.SONGS_PER_MUSIC_COUNT,
length = SongUtils.getSongs(music = index).sumOf { it.length }
)
}
/**
* Returns statistics for music.
*
* @return statistics for music
*/
fun getDomainStatistics(): MusicStatistics {
return MusicStatistics(count = MUSIC_COUNT.toLong(), mediaCount = 60L)
}
/**
* Returns statistics for music.
*
* @return statistics for music
*/
fun getStatistics(): com.github.vhromada.catalog.entity.MusicStatistics {
return com.github.vhromada.catalog.entity.MusicStatistics(count = MUSIC_COUNT, songsCount = SongUtils.SONGS_COUNT, mediaCount = 60, length = Time(length = 666).toString())
}
/**
* Returns count of music.
*
* @param entityManager entity manager
* @return count of music
*/
fun getMusicCount(entityManager: EntityManager): Int {
return entityManager.createQuery("SELECT COUNT(m.id) FROM Music m", java.lang.Long::class.java).singleResult.toInt()
}
/**
* Returns music.
*
* @param id ID
* @return music
*/
fun newDomainMusic(id: Int?): com.github.vhromada.catalog.domain.Music {
return com.github.vhromada.catalog.domain.Music(
id = id,
uuid = TestConstants.UUID,
name = "",
normalizedName = "",
wikiEn = null,
wikiCz = null,
mediaCount = 0,
note = null,
songs = mutableListOf()
).updated()
}
/**
* Returns music.
*
* @return music
*/
fun newMusic(): Music {
return Music(
uuid = TestConstants.UUID,
name = "",
wikiEn = null,
wikiCz = null,
mediaCount = 0,
note = null,
songsCount = 0,
length = 0
).updated()
}
/**
* Returns request for changing music.
*
* @return request for changing music
*/
fun newRequest(): ChangeMusicRequest {
return ChangeMusicRequest(
name = "Name",
wikiEn = "enWiki",
wikiCz = "czWiki",
mediaCount = 1,
note = "Note"
)
}
/**
* Asserts list of music deep equals.
*
* @param expected expected list of music
* @param actual actual list of music
*/
fun assertDomainMusicDeepEquals(expected: List<com.github.vhromada.catalog.domain.Music>, actual: List<com.github.vhromada.catalog.domain.Music>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMusicDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts music deep equals.
*
* @param expected expected music
* @param actual actual music
* @param checkSongs true if songs should be checked
*/
fun assertMusicDeepEquals(expected: com.github.vhromada.catalog.domain.Music?, actual: com.github.vhromada.catalog.domain.Music?, checkSongs: Boolean = true) {
if (expected == null) {
assertThat(actual).isNull()
} else {
assertThat(actual).isNotNull
assertSoftly {
it.assertThat(actual!!.id).isEqualTo(expected.id)
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.normalizedName).isEqualTo(expected.normalizedName)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.note).isEqualTo(expected.note)
}
AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!)
if (checkSongs) {
SongUtils.assertDomainSongsDeepEquals(expected = expected.songs, actual = actual.songs)
}
}
}
/**
* Asserts list of music deep equals.
*
* @param expected expected list of music
* @param actual actual list of music
*/
fun assertMusicDeepEquals(expected: List<com.github.vhromada.catalog.domain.Music>, actual: List<Music>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMusicDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts music deep equals.
*
* @param expected expected music
* @param actual actual music
*/
fun assertMusicDeepEquals(expected: com.github.vhromada.catalog.domain.Music, actual: Music) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.note).isEqualTo(expected.note)
it.assertThat(actual.songsCount).isEqualTo(expected.songs.size)
it.assertThat(actual.length).isEqualTo(expected.songs.sumOf { song -> song.length })
}
}
/**
* Asserts list of music deep equals.
*
* @param expected expected list of music
* @param actual actual list of music
*/
fun assertMusicListDeepEquals(expected: List<Music>, actual: List<Music>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertMusicDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts music deep equals.
*
* @param expected expected music
* @param actual actual music
*/
fun assertMusicDeepEquals(expected: Music, actual: Music) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.note).isEqualTo(expected.note)
it.assertThat(actual.songsCount).isEqualTo(expected.songsCount)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
/**
* Asserts request and music deep equals.
*
* @param expected expected request for changing music
* @param actual actual music
* @param uuid UUID
*/
fun assertRequestDeepEquals(expected: ChangeMusicRequest, actual: com.github.vhromada.catalog.domain.Music, uuid: String) {
assertSoftly {
it.assertThat(actual.id).isNull()
it.assertThat(actual.uuid).isEqualTo(uuid)
it.assertThat(actual.name).isEqualTo(expected.name)
it.assertThat(actual.normalizedName).isEqualTo(expected.name)
it.assertThat(actual.wikiEn).isEqualTo(expected.wikiEn)
it.assertThat(actual.wikiCz).isEqualTo(expected.wikiCz)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.note).isEqualTo(expected.note)
it.assertThat(actual.songs).isEmpty()
it.assertThat(actual.createdUser).isNull()
it.assertThat(actual.createdTime).isNull()
it.assertThat(actual.updatedUser).isNull()
it.assertThat(actual.updatedTime).isNull()
}
}
/**
* Asserts filter deep equals.
*
* @param expected expected filter
* @param actual actual filter
*/
fun assertFilterDeepEquals(expected: NameFilter, actual: MusicFilter) {
assertThat(actual.name).isEqualTo(expected.name)
}
/**
* Asserts statistics for musics deep equals.
*
* @param expected expected statistics for musics
* @param actual actual statistics for musics
*/
fun assertStatisticsDeepEquals(expected: MusicStatistics, actual: MusicStatistics) {
assertSoftly {
it.assertThat(actual.count).isEqualTo(expected.count)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
}
}
/**
* Asserts statistics for musics deep equals.
*
* @param expected expected statistics for musics
* @param actual actual statistics for musics
*/
fun assertStatisticsDeepEquals(expected: com.github.vhromada.catalog.entity.MusicStatistics, actual: com.github.vhromada.catalog.entity.MusicStatistics) {
assertSoftly {
it.assertThat(actual.count).isEqualTo(expected.count)
it.assertThat(actual.songsCount).isEqualTo(expected.songsCount)
it.assertThat(actual.mediaCount).isEqualTo(expected.mediaCount)
it.assertThat(actual.length).isEqualTo(expected.length)
}
}
}
| core/src/test/kotlin/com/github/vhromada/catalog/utils/MusicUtils.kt | 2690317527 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.