content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.prof.youtubeparser
object FakeDataFactory {
val listResponse = """
{
"kind": "youtube#searchListResponse",
"etag": "jQfvHzWTvDXgowxV9WgA22pJIoM",
"nextPageToken": "CAIQAA",
"regionCode": "DE",
"pageInfo": {
"totalResults": 1694,
"resultsPerPage": 2
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "Ocm0Jzs7tNzkItSFjDq3et6YkTM",
"id": {
"kind": "youtube#video",
"videoId": "8i6vrlbIVCc"
},
"snippet": {
"publishedAt": "2021-11-11T18:56:09Z",
"channelId": "UCVHFbqXqoYvEWM1Ddxl0QDg",
"title": "Paging: Live Q&A - MAD Skills",
"description": "Welcome to the live Q&A for the Paging series for MAD Skills, hosted by Android Developer Relations Engineer Florina Muntenescu. This time, Florina is joined ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/8i6vrlbIVCc/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/8i6vrlbIVCc/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/8i6vrlbIVCc/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Android Developers",
"liveBroadcastContent": "none",
"publishTime": "2021-11-11T18:56:09Z"
}
},
{
"kind": "youtube#searchResult",
"etag": "Fb9a78wWkrw73rRencla_Lsp1Nc",
"id": {
"kind": "youtube#video",
"videoId": "cR3e_dhy-sQ"
},
"snippet": {
"publishedAt": "2021-11-11T00:00:11Z",
"channelId": "UCVHFbqXqoYvEWM1Ddxl0QDg",
"title": "Now in Android: 51 - Android Developer Summit 2021 recap (part 2)",
"description": "Welcome to Now in Android, your ongoing guide to what's new and notable in the world of Android development. Today, we're covering our second recap from ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/cR3e_dhy-sQ/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/cR3e_dhy-sQ/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/cR3e_dhy-sQ/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Android Developers",
"liveBroadcastContent": "none",
"publishTime": "2021-11-11T00:00:11Z"
}
}
]
}
""".trimIndent()
val statsResponse = """
{
"kind": "youtube#videoListResponse",
"etag": "89tsWMmv_c7IWgg6vqs30MPZ-2c",
"items": [
{
"kind": "youtube#video",
"etag": "mNsuEWPHxE5_2MGWnuhg27GL7bY",
"id": "cR3e_dhy-sQ",
"statistics": {
"viewCount": "3007",
"likeCount": "96",
"dislikeCount": "2",
"favoriteCount": "0",
"commentCount": "2"
}
}
],
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
}
}
""".trimIndent()
} | youtubeparser/src/test/java/com/prof/youtubeparser/FakeDataFactory.kt | 970566331 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.lanternpowered.api.item.inventory
import org.lanternpowered.api.item.inventory.hotbar.ExtendedHotbar
import org.lanternpowered.api.item.inventory.hotbar.Hotbar
import kotlin.contracts.contract
/**
* Gets the normal hotbar as an extended hotbar.
*/
inline fun Hotbar.fix(): ExtendedHotbar {
contract { returns() implies (this@fix is ExtendedHotbar) }
return this as ExtendedHotbar
}
/**
* Gets the normal hotbar as an extended hotbar.
*/
@Deprecated(message = "Redundant call.", replaceWith = ReplaceWith(""))
inline fun ExtendedHotbar.fix(): ExtendedHotbar = this
| src/main/kotlin/org/lanternpowered/api/item/inventory/ExtendedHotbar.kt | 2919522155 |
/* Tested on Onyx Boox Nova 2 */
package org.koreader.launcher.device.epd
import org.koreader.launcher.device.EPDInterface
import org.koreader.launcher.device.epd.qualcomm.QualcommEPDController
class OnyxEPDController : QualcommEPDController(), EPDInterface {
override fun getPlatform(): String {
return "qualcomm"
}
override fun getMode(): String {
return "full-only"
}
override fun getWaveformFull(): Int {
return EINK_WAVEFORM_UPDATE_FULL + EINK_WAVEFORM_MODE_WAIT + EINK_WAVEFORM_MODE_GC16
}
override fun getWaveformPartial(): Int {
return EINK_WAVEFORM_UPDATE_PARTIAL + EINK_WAVEFORM_MODE_GC16
}
override fun getWaveformFullUi(): Int {
return EINK_WAVEFORM_UPDATE_FULL + EINK_WAVEFORM_MODE_REAGL
}
override fun getWaveformPartialUi(): Int {
return EINK_WAVEFORM_UPDATE_PARTIAL + EINK_WAVEFORM_MODE_GC16
}
override fun getWaveformFast(): Int {
return EINK_WAVEFORM_UPDATE_PARTIAL + EINK_WAVEFORM_MODE_DU
}
override fun getWaveformDelay(): Int {
return EINK_WAVEFORM_DELAY
}
override fun getWaveformDelayUi(): Int {
return EINK_WAVEFORM_DELAY_UI
}
override fun getWaveformDelayFast(): Int {
return EINK_WAVEFORM_DELAY_FAST
}
override fun needsView(): Boolean {
return true
}
override fun setEpdMode(targetView: android.view.View,
mode: Int, delay: Long,
x: Int, y: Int, width: Int, height: Int, epdMode: String?)
{
requestEpdMode(targetView, mode, delay, x, y, width, height)
}
override fun resume() {}
override fun pause() {}
}
| app/src/main/java/org/koreader/launcher/device/epd/OnyxEPDController.kt | 1040502037 |
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.persistence
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.content.res.Resources
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.google.samples.apps.topeka.base.R
import com.google.samples.apps.topeka.helper.toIntArray
import com.google.samples.apps.topeka.helper.toStringArray
import com.google.samples.apps.topeka.model.Category
import com.google.samples.apps.topeka.model.JsonAttributes
import com.google.samples.apps.topeka.model.Theme
import com.google.samples.apps.topeka.model.quiz.AlphaPickerQuiz
import com.google.samples.apps.topeka.model.quiz.FillBlankQuiz
import com.google.samples.apps.topeka.model.quiz.FillTwoBlanksQuiz
import com.google.samples.apps.topeka.model.quiz.FourQuarterQuiz
import com.google.samples.apps.topeka.model.quiz.MultiSelectQuiz
import com.google.samples.apps.topeka.model.quiz.OptionsQuiz
import com.google.samples.apps.topeka.model.quiz.PickerQuiz
import com.google.samples.apps.topeka.model.quiz.Quiz
import com.google.samples.apps.topeka.model.quiz.QuizType
import com.google.samples.apps.topeka.model.quiz.SelectItemQuiz
import com.google.samples.apps.topeka.model.quiz.ToggleTranslateQuiz
import com.google.samples.apps.topeka.model.quiz.TrueFalseQuiz
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.Arrays
import kotlin.collections.ArrayList
/**
* Database for storing and retrieving info for categories and quizzes.
*/
class TopekaDatabaseHelper private constructor(
context: Context
) : SQLiteOpenHelper(context.applicationContext, "topeka.db", null, 1) {
private val resources: Resources = context.resources
private var categories: MutableList<Category> = loadCategories()
override fun onCreate(db: SQLiteDatabase) {
with(db) {
execSQL(CategoryTable.CREATE)
execSQL(QuizTable.CREATE)
fillCategoriesAndQuizzes(db)
}
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit
@Throws(JSONException::class, IOException::class)
private fun fillCategoriesAndQuizzes(db: SQLiteDatabase) {
db.transact {
val values = ContentValues() // reduce, reuse
val jsonArray = JSONArray(readCategoriesFromResources())
for (i in 0 until jsonArray.length()) {
with(jsonArray.getJSONObject(i)) {
val id = getString(JsonAttributes.ID)
fillCategory(db, values, this, id)
fillQuizzesForCategory(db, values, getJSONArray(JsonAttributes.QUIZZES), id)
}
}
}
}
private fun readCategoriesFromResources(): String {
val rawCategories = resources.openRawResource(R.raw.categories)
val reader = BufferedReader(InputStreamReader(rawCategories))
return reader.readText()
}
private fun fillCategory(db: SQLiteDatabase,
values: ContentValues,
category: JSONObject,
categoryId: String) {
with(values) {
clear()
put(CategoryTable.COLUMN_ID, categoryId)
put(CategoryTable.COLUMN_NAME, category.getString(JsonAttributes.NAME))
put(CategoryTable.COLUMN_THEME, category.getString(JsonAttributes.THEME))
put(CategoryTable.COLUMN_SOLVED, category.getString(JsonAttributes.SOLVED))
put(CategoryTable.COLUMN_SCORES, category.getString(JsonAttributes.SCORES))
}
db.insert(CategoryTable.NAME, null, values)
}
private fun fillQuizzesForCategory(db: SQLiteDatabase,
values: ContentValues,
quizzes: JSONArray,
categoryId: String) {
var quiz: JSONObject
for (i in 0 until quizzes.length()) {
quiz = quizzes.getJSONObject(i)
with(values) {
clear()
put(QuizTable.FK_CATEGORY, categoryId)
put(QuizTable.COLUMN_TYPE, quiz.getString(JsonAttributes.TYPE))
put(QuizTable.COLUMN_QUESTION, quiz.getString(JsonAttributes.QUESTION))
put(QuizTable.COLUMN_ANSWER, quiz.getString(JsonAttributes.ANSWER))
}
putNonEmptyString(values, quiz, JsonAttributes.OPTIONS, QuizTable.COLUMN_OPTIONS)
putNonEmptyString(values, quiz, JsonAttributes.MIN, QuizTable.COLUMN_MIN)
putNonEmptyString(values, quiz, JsonAttributes.MAX, QuizTable.COLUMN_MAX)
putNonEmptyString(values, quiz, JsonAttributes.START, QuizTable.COLUMN_START)
putNonEmptyString(values, quiz, JsonAttributes.END, QuizTable.COLUMN_END)
putNonEmptyString(values, quiz, JsonAttributes.STEP, QuizTable.COLUMN_STEP)
db.insert(QuizTable.NAME, null, values)
}
}
/**
* Puts a non-empty string to ContentValues provided.
* @param values The place where the data should be put.
*
* @param quiz The quiz potentially containing the data.
*
* @param jsonKey The key to look for.
*
* @param contentKey The key use for placing the data in the database.
*/
private fun putNonEmptyString(values: ContentValues,
quiz: JSONObject,
jsonKey: String,
contentKey: String) {
quiz.optString(jsonKey, null)?.let { values.put(contentKey, it) }
}
/**
* Gets all categories with their quizzes.
* @param fromDatabase `true` if a data refresh is needed, else `false`.
*
* @return All categories stored in the database.
*/
fun getCategories(fromDatabase: Boolean = false): List<Category> {
if (fromDatabase) {
categories.clear()
categories.addAll(loadCategories())
}
return categories
}
private fun loadCategories(): MutableList<Category> {
val data = getCategoryCursor()
val tmpCategories = ArrayList<Category>(data.count)
do {
tmpCategories.add(getCategory(data))
} while (data.moveToNext())
return tmpCategories
}
/**
* Gets all categories wrapped in a [Cursor] positioned at it's first element.
*
* There are **no quizzes** within the categories obtained from this cursor.
*
* @return All categories stored in the database.
*/
@SuppressLint("Recycle")
private fun getCategoryCursor(): Cursor {
synchronized(readableDatabase) {
return readableDatabase
.query(CategoryTable.NAME, CategoryTable.PROJECTION,
null, null, null, null, null)
.also {
it.moveToFirst()
}
}
}
/**
* Gets a category from the given position of the cursor provided.
* @param cursor The Cursor containing the data.
*
* @return The found category.
*/
private fun getCategory(cursor: Cursor): Category {
// "magic numbers" based on CategoryTable#PROJECTION
with(cursor) {
val id = getString(0)
val category = Category(
id = id,
name = getString(1),
theme = Theme.valueOf(getString(2)),
quizzes = getQuizzes(id, readableDatabase),
scores = JSONArray(getString(4)).toIntArray(),
solved = getBooleanFromDatabase(getString(3)))
return category
}
}
private fun getBooleanFromDatabase(isSolved: String?) =
// Json stores booleans as true/false strings, whereas SQLite stores them as 0/1 values.
isSolved?.length == 1 && Integer.valueOf(isSolved) == 1
/**
* Looks for a category with a given id.
* @param categoryId Id of the category to look for.
*
* @return The found category.
*/
fun getCategoryWith(categoryId: String): Category {
val selectionArgs = arrayOf(categoryId)
val data = readableDatabase
.query(CategoryTable.NAME, CategoryTable.PROJECTION,
"${CategoryTable.COLUMN_ID}=?", selectionArgs,
null, null, null)
.also { it.moveToFirst() }
return getCategory(data)
}
/**
* Scooooooooooore!
* @return The score over all Categories.
*/
fun getScore() = with(getCategories()) { sumBy { it.score } }
/**
* Updates values for a category.
* @param category The category to update.
*/
fun updateCategory(category: Category) {
val index = categories.indexOfFirst { it.id == category.id }
if (index != -1) {
with (categories) {
removeAt(index)
add(index, category)
}
}
val categoryValues = createContentValuesFor(category)
writableDatabase.update(CategoryTable.NAME,
categoryValues,
"${CategoryTable.COLUMN_ID}=?",
arrayOf(category.id))
val quizzes = category.quizzes
updateQuizzes(writableDatabase, quizzes)
}
/**
* Updates a list of given quizzes.
* @param writableDatabase The database to write the quizzes to.
*
* @param quizzes The quizzes to write.
*/
private fun updateQuizzes(writableDatabase: SQLiteDatabase, quizzes: List<Quiz<*>>) {
var quiz: Quiz<*>
val quizValues = ContentValues()
val quizArgs = arrayOfNulls<String>(1)
for (i in quizzes.indices) {
quiz = quizzes[i]
quizValues.clear()
quizValues.put(QuizTable.COLUMN_SOLVED, quiz.solved)
quizArgs[0] = quiz.question
writableDatabase.update(QuizTable.NAME, quizValues,
"${QuizTable.COLUMN_QUESTION}=?", quizArgs)
}
}
/**
* Resets the contents of Topeka's database to it's initial state.
*/
fun reset() {
with(writableDatabase) {
delete(CategoryTable.NAME, null, null)
delete(QuizTable.NAME, null, null)
fillCategoriesAndQuizzes(this)
}
}
/**
* Creates objects for quizzes according to a category id.
* @param categoryId The category to create quizzes for.
* @param database The database containing the quizzes.
* @return The found quizzes or an empty list if none were available.
*/
@SuppressLint("Recycle")
private fun getQuizzes(categoryId: String, database: SQLiteDatabase): List<Quiz<*>> {
val quizzes = ArrayList<Quiz<*>>()
val cursor = database.query(QuizTable.NAME,
QuizTable.PROJECTION,
"${QuizTable.FK_CATEGORY} LIKE ?", arrayOf(categoryId),
null, null, null)
cursor.moveToFirst()
do quizzes.add(createQuizDueToType(cursor)) while (cursor.moveToNext())
return quizzes
}
/**
* Creates a quiz corresponding to the projection provided from a cursor row.
* Currently only [QuizTable.PROJECTION] is supported.
* @param cursor The Cursor containing the data.
* @return The created quiz.
*/
private fun createQuizDueToType(cursor: Cursor): Quiz<*> {
// "magic numbers" based on QuizTable#PROJECTION
val type = cursor.getString(2)
val question = cursor.getString(3)
val answer = cursor.getString(4)
val options = cursor.getString(5)
val min = cursor.getInt(6)
val max = cursor.getInt(7)
val step = cursor.getInt(8)
val solved = getBooleanFromDatabase(cursor.getString(11))
return when (type) {
QuizType.ALPHA_PICKER.jsonName ->
AlphaPickerQuiz(question, answer, solved)
QuizType.FILL_BLANK.jsonName ->
createFillBlankQuiz(cursor, question, answer, solved)
QuizType.FILL_TWO_BLANKS.jsonName ->
createFillTwoBlanksQuiz(question, answer, solved)
QuizType.FOUR_QUARTER.jsonName ->
createStringOptionsQuiz(question, answer, options, solved) {
q, a, o, s ->
FourQuarterQuiz(q, a, o, s)
}
QuizType.MULTI_SELECT.jsonName ->
createStringOptionsQuiz(question, answer, options, solved) {
q, a, o, s ->
MultiSelectQuiz(q, a, o, s)
}
QuizType.PICKER.jsonName ->
PickerQuiz(question, Integer.valueOf(answer)!!, min, max, step, solved)
QuizType.SINGLE_SELECT.jsonName, QuizType.SINGLE_SELECT_ITEM.jsonName ->
createStringOptionsQuiz(question, answer, options, solved) {
q, a, o, s ->
SelectItemQuiz(q, a, o, s)
}
QuizType.TOGGLE_TRANSLATE.jsonName ->
createToggleTranslateQuiz(question, answer, options, solved)
QuizType.TRUE_FALSE.jsonName -> TrueFalseQuiz(question, "true" == answer, solved)
else -> throw IllegalArgumentException("Quiz type $type is not supported")
}
}
private fun createFillBlankQuiz(cursor: Cursor,
question: String,
answer: String,
solved: Boolean): Quiz<*> {
val start = cursor.getString(9)
val end = cursor.getString(10)
return FillBlankQuiz(question, answer, start, end, solved)
}
private fun createFillTwoBlanksQuiz(question: String,
answer: String,
solved: Boolean): FillTwoBlanksQuiz {
val answerArray = JSONArray(answer).toStringArray()
return FillTwoBlanksQuiz(question, answerArray, solved)
}
private inline fun <T : OptionsQuiz<String>> createStringOptionsQuiz(
question: String,
answer: String,
options: String,
solved: Boolean,
quizFactory: (String, IntArray, Array<String>, Boolean) -> T): T {
val answerArray = JSONArray(answer).toIntArray()
val optionsArray = JSONArray(options).toStringArray()
return quizFactory(question, answerArray, optionsArray, solved)
}
private fun createToggleTranslateQuiz(question: String,
answer: String,
options: String,
solved: Boolean): Quiz<*> {
val answerArray = JSONArray(answer).toIntArray()
val optionsArrays = extractOptionsArrays(options)
return ToggleTranslateQuiz(question, answerArray, optionsArrays, solved)
}
private fun extractOptionsArrays(options: String): Array<Array<String>> {
val optionsLvlOne = JSONArray(options).toStringArray()
return Array(optionsLvlOne.size) { JSONArray(optionsLvlOne[it]).toStringArray() }
}
/**
* Creates the content values to update a category in the database.
* @param category The category to update.
*
* @return ContentValues containing updatable data.
*/
private fun createContentValuesFor(category: Category) = ContentValues().apply {
put(CategoryTable.COLUMN_SOLVED, category.solved)
put(CategoryTable.COLUMN_SCORES, Arrays.toString(category.scores))
}
companion object {
private var _instance: TopekaDatabaseHelper? = null
fun getInstance(context: Context): TopekaDatabaseHelper {
return _instance ?: synchronized(TopekaDatabaseHelper::class) {
TopekaDatabaseHelper(context).also { _instance = it }
}
}
}
}
inline fun SQLiteDatabase.transact(transaction: SQLiteDatabase.() -> Unit) {
try {
beginTransaction()
transaction()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
| base/src/main/java/com/google/samples/apps/topeka/persistence/TopekaDatabaseHelper.kt | 474810111 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.entity.parameter
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.value.ContextualValueWriter
/**
* Represents a list of parameters of entities.
*/
abstract class ParameterList {
/**
* Gets whether this parameter list is empty.
*/
abstract val isEmpty: Boolean
/**
* Adds a value for the given parameter type to this parameter list.
*/
abstract fun <T> add(type: ParameterType<T>, value: T)
/**
* Writes this [ParameterList] to the [ByteBuffer].
*
* @param buf The byte buffer
*/
protected open fun write(ctx: CodecContext, buf: ByteBuffer) {
buf.writeByte(0xff.toByte())
}
companion object : ContextualValueWriter<ParameterList> {
override fun write(ctx: CodecContext, buf: ByteBuffer, value: ParameterList) = value.write(ctx, buf)
}
}
| src/main/kotlin/org/lanternpowered/server/network/entity/parameter/ParameterList.kt | 3069748033 |
package net.torvald.terranvm.runtime
/**
* Created by minjaesong on 2017-06-03.
*/
interface VMPeripheralHardware {
/**
* @param arg can be a number or a pointer
*/
fun call(arg: Int)
/**
* Returns bootstrapper program in raw machine code, `null` if not available or the device is not bootable.
*/
fun inquireBootstrapper(): ByteArray?
} | src/net/torvald/terranvm/runtime/VMPeripheralHardware.kt | 94114542 |
package it.sephiroth.android.library.uigestures
import android.content.Context
import android.graphics.PointF
import android.os.Message
import android.util.Log
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.ViewConfiguration
/**
* UISwipeGestureRecognizer is a subclass of UIGestureRecognizer that looks for swiping gestures in one or more
* directions. A swipe is a discrete gesture, and thus the associated action message is sent only once per gesture.
*
* @author alessandro crugnola
* @see [
* https://developer.apple.com/reference/uikit/uiswipegesturerecognizer](https://developer.apple.com/reference/uikit/uiswipegesturerecognizer)
*/
@Suppress("MemberVisibilityCanBePrivate", "unused")
open class UISwipeGestureRecognizer(context: Context) : UIGestureRecognizer(context), UIDiscreteGestureRecognizer {
/**
* Minimum fling velocity before the touch can be accepted
* @since 1.0.0
*/
var scaledMinimumFlingVelocity: Int
var scaledMaximumFlingVelocity: Int
/**
* Direction of the swipe gesture. Can be one of RIGHT, LEFT, UP, DOWN
* @since 1.0.0
*/
var direction: Int = RIGHT
/**
* Number of touches required for the gesture to be accepted
* @since 1.0.0
*/
var numberOfTouchesRequired: Int = 1
var scrollX: Float = 0.toFloat()
private set
var scrollY: Float = 0.toFloat()
private set
/**
* @since 1.1.2
*/
val relativeScrollX: Float get() = -scrollX
/**
* @since 1.1.2
*/
val relativeScrollY: Float get() = -scrollY
/**
* @since 1.0.0
*/
var translationX: Float = 0.toFloat()
internal set
/**
* @since 1.0.0
*/
var translationY: Float = 0.toFloat()
internal set
/**
* @since 1.0.0
*/
var yVelocity: Float = 0.toFloat()
private set
/**
* @since 1.0.0
*/
var xVelocity: Float = 0.toFloat()
private set
/**
* Minimum distance in pixel before the touch can be considered
* as a scroll
*/
var scaledTouchSlop: Int
/**
* Minimum total distance before the gesture will begin
* @since 1.0.0
*/
var minimumSwipeDistance: Int = 0
/**
* Maximum amount of time allowed between a touch down and a touch move
* before the gesture will fail
* @since 1.0.0
*/
var maximumTouchSlopTime = MAXIMUM_TOUCH_SLOP_TIME
/**
* During a move event, the maximum time between touches before
* the gesture will fail
* @since 1.0.0
*/
var maximumTouchFlingTime = MAXIMUM_TOUCH_FLING_TIME
private var mDown: Boolean = false
private var mStarted: Boolean = false
private val mLastFocusLocation = PointF()
private val mDownFocusLocation = PointF()
private var mVelocityTracker: VelocityTracker? = null
init {
mStarted = false
val configuration = ViewConfiguration.get(context)
scaledTouchSlop = configuration.scaledTouchSlop
scaledMaximumFlingVelocity = configuration.scaledMaximumFlingVelocity
scaledMinimumFlingVelocity = configuration.scaledMinimumFlingVelocity
minimumSwipeDistance = (scaledTouchSlop * 3f).toInt()
if (logEnabled) {
logMessage(Log.INFO, "scaledTouchSlop: $scaledTouchSlop")
logMessage(Log.INFO, "minimumSwipeDistance: $minimumSwipeDistance")
logMessage(Log.INFO, "scaledMinimumFlingVelocity: $scaledMinimumFlingVelocity")
logMessage(Log.INFO, "scaledMaximumFlingVelocity: $scaledMaximumFlingVelocity")
}
}
override fun handleMessage(msg: Message) {
when (msg.what) {
MESSAGE_RESET -> handleReset()
else -> {
}
}
}
override fun reset() {
super.reset()
handleReset()
}
private fun handleReset() {
mStarted = false
setBeginFiringEvents(false)
state = State.Possible
}
override fun removeMessages() {
removeMessages(MESSAGE_RESET)
}
override fun onStateChanged(recognizer: UIGestureRecognizer) {
if (recognizer.state == State.Failed && state == State.Ended) {
removeMessages()
stopListenForOtherStateChanges()
fireActionEventIfCanRecognizeSimultaneously()
if (!mDown) {
mStarted = false
state = State.Possible
}
} else if (recognizer.inState(State.Began, State.Ended) && mStarted && inState(State.Possible, State.Ended)) {
mStarted = false
setBeginFiringEvents(false)
stopListenForOtherStateChanges()
removeMessages()
state = State.Failed
}
}
private fun fireActionEventIfCanRecognizeSimultaneously() {
if (delegate!!.shouldRecognizeSimultaneouslyWithGestureRecognizer(this)) {
setBeginFiringEvents(true)
fireActionEvent()
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
super.onTouchEvent(event)
if (!isEnabled) {
return false
}
val action = event.actionMasked
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain()
}
mVelocityTracker?.addMovement(event)
when (action) {
MotionEvent.ACTION_POINTER_DOWN -> {
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
if (state == State.Possible && !mStarted) {
if (numberOfTouches > numberOfTouchesRequired) {
state = State.Failed
removeMessages(MESSAGE_RESET)
}
}
}
MotionEvent.ACTION_POINTER_UP -> {
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
mVelocityTracker?.computeCurrentVelocity(1000, scaledMaximumFlingVelocity.toFloat())
val upIndex = event.actionIndex
val id1 = event.getPointerId(upIndex)
val x1 = mVelocityTracker!!.getXVelocity(id1)
val y1 = mVelocityTracker!!.getYVelocity(id1)
for (i in 0 until numberOfTouches) {
if (i == upIndex) {
continue
}
val id2 = event.getPointerId(i)
val x = x1 * mVelocityTracker!!.getXVelocity(id2)
val y = y1 * mVelocityTracker!!.getYVelocity(id2)
val dot = x + y
if (dot < 0) {
mVelocityTracker?.clear()
break
}
}
if (state == State.Possible && !mStarted) {
if (numberOfTouches < numberOfTouchesRequired) {
state = State.Failed
removeMessages(MESSAGE_RESET)
}
}
}
MotionEvent.ACTION_DOWN -> {
if (delegate?.shouldReceiveTouch?.invoke(this)!!) {
mStarted = false
mDown = true
mLastFocusLocation.set(mCurrentLocation)
mDownFocusLocation.set(mCurrentLocation)
mVelocityTracker?.clear()
setBeginFiringEvents(false)
removeMessages(MESSAGE_RESET)
state = State.Possible
}
}
MotionEvent.ACTION_MOVE -> {
scrollX = mLastFocusLocation.x - mCurrentLocation.x
scrollY = mLastFocusLocation.y - mCurrentLocation.y
mVelocityTracker?.computeCurrentVelocity(1000, scaledMaximumFlingVelocity.toFloat())
yVelocity = mVelocityTracker!!.yVelocity
xVelocity = mVelocityTracker!!.xVelocity
if (state == State.Possible) {
val distance = mCurrentLocation.distance(mDownFocusLocation)
logMessage(Log.INFO, "started: $mStarted, distance: $distance, slop: $scaledTouchSlop")
if (!mStarted) {
if (distance > scaledTouchSlop) {
translationX -= scrollX
translationY -= scrollY
mLastFocusLocation.set(mCurrentLocation)
mStarted = true
if (numberOfTouches == numberOfTouchesRequired) {
val time = event.eventTime - event.downTime
logMessage(Log.VERBOSE, "time: $time, maximumTouchSlopTime: $maximumTouchSlopTime")
if (time > maximumTouchSlopTime) {
logMessage(Log.WARN, "passed too much time 1 ($time > $maximumTouchSlopTime)")
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
} else {
val direction =
getTouchDirection(mDownFocusLocation.x, mDownFocusLocation.y, mCurrentLocation.x,
mCurrentLocation.y, xVelocity, yVelocity, 0f)
logMessage(Log.VERBOSE, "(1) direction: $direction")
// this is necessary because sometimes the velocityTracker
// return 0, probably it needs more input events before computing
// correctly the velocities
if (xVelocity != 0f || yVelocity != 0f) {
if (direction == -1 || (this.direction and direction) == 0) {
logMessage(Log.WARN, "invalid direction: $direction")
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
} else {
logMessage(Log.DEBUG, "direction accepted: ${(this.direction and direction)}")
mStarted = true
}
} else {
logMessage(Log.WARN, "velocity is still 0, waiting for the next event...")
mDownFocusLocation.set(mCurrentLocation)
mStarted = false
}
}
} else {
logMessage(Log.WARN, "invalid number of touches ($numberOfTouches != $numberOfTouchesRequired)")
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
}
}
} else {
// touch has been recognized. now let's track the movement
val time = event.eventTime - event.downTime
if (time > maximumTouchFlingTime) {
logMessage(Log.WARN, "passed too much time 2 ($time > $maximumTouchFlingTime)")
mStarted = false
state = State.Failed
} else {
val direction = getTouchDirection(
mDownFocusLocation.x, mDownFocusLocation.y, mCurrentLocation.x, mCurrentLocation.y, xVelocity,
yVelocity, minimumSwipeDistance.toFloat())
if (direction != -1) {
if (this.direction and direction != 0) {
if (delegate?.shouldBegin?.invoke(this)!!) {
state = State.Ended
if (null == requireFailureOf) {
fireActionEventIfCanRecognizeSimultaneously()
} else {
when {
requireFailureOf!!.state == State.Failed -> fireActionEventIfCanRecognizeSimultaneously()
requireFailureOf!!.inState(State.Began, State.Ended, State.Changed) -> {
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
}
else -> {
logMessage(Log.DEBUG, "waiting...")
listenForOtherStateChanges()
setBeginFiringEvents(false)
}
}
}
} else {
state = State.Failed
mStarted = false
setBeginFiringEvents(false)
}
} else {
mStarted = false
setBeginFiringEvents(false)
state = State.Failed
}
}
}
}
}
}
MotionEvent.ACTION_UP -> {
mVelocityTracker?.addMovement(event)
if (mVelocityTracker != null) {
mVelocityTracker!!.recycle()
mVelocityTracker = null
}
// TODO: should we fail if the gesture didn't actually start?
mDown = false
removeMessages(MESSAGE_RESET)
}
MotionEvent.ACTION_CANCEL -> {
if (mVelocityTracker != null) {
mVelocityTracker!!.recycle()
mVelocityTracker = null
}
mDown = false
removeMessages(MESSAGE_RESET)
state = State.Cancelled
mHandler.sendEmptyMessage(MESSAGE_RESET)
}
else -> {
}
}
return cancelsTouchesInView
}
private fun getTouchDirection(
x1: Float, y1: Float, x2: Float, y2: Float, velocityX: Float, velocityY: Float, distanceThreshold: Float): Int {
val diffY = y2 - y1
val diffX = x2 - x1
if (logEnabled) {
logMessage(Log.INFO, "getTouchDirection")
logMessage(Log.VERBOSE, "diff: $diffX, $diffY, distanceThreshold: $distanceThreshold")
logMessage(Log.VERBOSE, "velocity: $velocityX, $velocityY, scaledMinimumFlingVelocity: $scaledMinimumFlingVelocity, " +
"scaledMaximumFlingVelocity: $scaledMaximumFlingVelocity")
}
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > distanceThreshold && Math.abs(velocityX) > scaledMinimumFlingVelocity) {
return if (diffX > 0) {
RIGHT
} else {
LEFT
}
}
} else if (Math.abs(diffY) > distanceThreshold && Math.abs(velocityY) > scaledMinimumFlingVelocity) {
return if (diffY > 0) {
DOWN
} else {
UP
}
}
return -1
}
companion object {
private const val MESSAGE_RESET = 4
const val RIGHT = 1 shl 1
const val LEFT = 1 shl 2
const val UP = 1 shl 3
const val DOWN = 1 shl 4
const val MAXIMUM_TOUCH_SLOP_TIME = 150
const val MAXIMUM_TOUCH_FLING_TIME = 300
}
} | uigesturerecognizer/src/main/java/it/sephiroth/android/library/uigestures/UISwipeGestureRecognizer.kt | 1368985747 |
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.androidstudiopoet.generators.android_modules
import com.google.androidstudiopoet.generators.toApplyPluginExpression
import com.google.androidstudiopoet.generators.toExpression
import com.google.androidstudiopoet.gradle.Closure
import com.google.androidstudiopoet.gradle.Expression
import com.google.androidstudiopoet.gradle.Statement
import com.google.androidstudiopoet.gradle.StringStatement
import com.google.androidstudiopoet.models.*
import com.google.androidstudiopoet.utils.isNullOrEmpty
import com.google.androidstudiopoet.writers.FileWriter
class AndroidModuleBuildGradleGenerator(val fileWriter: FileWriter) {
fun generate(blueprint: AndroidBuildGradleBlueprint) {
val statements = applyPlugins(blueprint.plugins) +
androidClosure(blueprint) +
dependenciesClosure(blueprint) +
additionalTasksClosures(blueprint) +
(blueprint.extraLines?.map { StringStatement(it) } ?: listOf())
val gradleText = statements.joinToString(separator = "\n") { it.toGroovy(0) }
fileWriter.writeToFile(gradleText, blueprint.path)
}
private fun applyPlugins(plugins: Set<String>): List<Statement> {
return plugins.map { it.toApplyPluginExpression() }
}
private fun androidClosure(blueprint: AndroidBuildGradleBlueprint): Closure {
val statements = listOfNotNull(
Expression("compileSdkVersion", "${blueprint.compileSdkVersion}"),
defaultConfigClosure(blueprint),
buildTypesClosure(blueprint),
kotlinOptionsClosure(blueprint),
buildFeaturesClosure(blueprint),
compileOptionsClosure(),
composeOptionsClosure(blueprint)
) + createFlavorsSection(blueprint.productFlavors, blueprint.flavorDimensions)
return Closure("android", statements)
}
private fun defaultConfigClosure(blueprint: AndroidBuildGradleBlueprint): Closure {
val expressions = listOfNotNull(
if (blueprint.isApplication) Expression("applicationId", "\"${blueprint.packageName}\"") else null,
Expression("minSdkVersion", "${blueprint.minSdkVersion}"),
Expression("targetSdkVersion", "${blueprint.targetSdkVersion}"),
Expression("versionCode", "1"),
Expression("versionName", "\"1.0\""),
Expression("multiDexEnabled", "true"),
Expression("testInstrumentationRunner", "\"android.support.test.runner.AndroidJUnitRunner\"")
)
return Closure("defaultConfig", expressions)
}
private fun buildTypesClosure(blueprint: AndroidBuildGradleBlueprint): Statement {
val releaseClosure = Closure("release", listOf(
Expression("minifyEnabled", "false"),
Expression("proguardFiles", "getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'")
))
val buildTypesClosures = blueprint.buildTypes?.map {
Closure(it.name, it.body?.lines()?.map { line -> StringStatement(line) } ?: listOf())
} ?: listOf()
return Closure("buildTypes", listOf(releaseClosure) + buildTypesClosures)
}
private fun createFlavorsSection(productFlavors: Set<Flavor>?, flavorDimensions: Set<String>?): List<Statement> {
if (productFlavors.isNullOrEmpty() && flavorDimensions.isNullOrEmpty()) {
return listOf()
}
val flavorDimensionsExpression = flavorDimensions?.joinToString { "\"$it\"" }?.let { Expression("flavorDimensions", it) }
val flavorsList = productFlavors!!.map {
Closure(it.name, listOfNotNull(
it.dimension?.let { dimensionName -> Expression("dimension", "\"$dimensionName\"") }
))
}
return listOfNotNull(
flavorDimensionsExpression,
Closure("productFlavors", flavorsList)
)
}
private fun buildFeaturesClosure(blueprint: AndroidBuildGradleBlueprint): Closure? {
val statements = mutableListOf<StringStatement>()
when {
blueprint.enableCompose -> statements.add(StringStatement("compose true"))
blueprint.enableDataBinding -> statements.add(StringStatement("dataBinding true"))
blueprint.enableViewBinding -> statements.add(StringStatement("viewBinding true"))
else -> {}
}
return if (statements.isNotEmpty()) Closure("buildFeatures", statements) else null
}
private fun kotlinOptionsClosure(blueprint: AndroidBuildGradleBlueprint): Closure? {
return if (blueprint.enableCompose) {
Closure("kotlinOptions", listOf(
StringStatement("jvmTarget = '1.8'"),
StringStatement("useIR = true")
))
} else {
null
}
}
private fun compileOptionsClosure(): Closure {
val expressions = listOf(
Expression("targetCompatibility", "1.8"),
Expression("sourceCompatibility", "1.8"),
)
return Closure("compileOptions", expressions)
}
private fun composeOptionsClosure(blueprint: AndroidBuildGradleBlueprint): Closure? {
return if (blueprint.enableCompose) {
Closure("composeOptions", listOf(
Expression("kotlinCompilerExtensionVersion", "'1.0.4'"),
Expression("kotlinCompilerVersion", "'1.5.31'"),
))
} else {
null
}
}
private fun dependenciesClosure(blueprint: AndroidBuildGradleBlueprint): Closure {
val dependencyExpressions: Set<Statement> = blueprint.dependencies.mapNotNull { it.toExpression() }.toSet()
val statements = dependencyExpressions.toList()
return Closure("dependencies", statements)
}
private fun additionalTasksClosures(blueprint: AndroidBuildGradleBlueprint): Set<Closure> =
blueprint.additionalTasks.map { task ->
Closure(
task.name,
task.body?.map { StringStatement(it) } ?: listOf())
}.toSet()
}
| aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/android_modules/AndroidModuleBuildGradleGenerator.kt | 2724004955 |
package com.pr0gramm.app.ui.upload
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.pr0gramm.app.R
import com.pr0gramm.app.ui.MenuSheetView
import com.pr0gramm.app.util.catchAll
class UploadTypeDialogFragment : BottomSheetDialogFragment() {
override fun getTheme(): Int = R.style.MyBottomSheetDialog
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val context = requireContext()
val menuSheetView = MenuSheetView(context, R.string.hint_upload) { item ->
dialog?.dismiss()
if (item.itemId == R.id.action_upload_image) {
UploadActivity.openForType(context, UploadMediaType.IMAGE)
}
if (item.itemId == R.id.action_upload_video) {
UploadActivity.openForType(context, UploadMediaType.VIDEO)
}
}
menuSheetView.inflateMenu(R.menu.menu_upload)
return menuSheetView
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply {
setOnShowListener {
val bottomSheet = requireDialog().findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
if (bottomSheet is FrameLayout) {
catchAll {
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED)
}
}
}
}
}
} | app/src/main/java/com/pr0gramm/app/ui/upload/UploadTypeDialogFragment.kt | 1975613993 |
package za.org.grassroot2.view.dialog
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import za.org.grassroot2.R
class NoConnectionDialog : DialogFragment() {
private var dialogType: Int = 0
private val notAuthorizedDialog: Dialog
get() {
val builder = AlertDialog.Builder(activity!!)
val v = LayoutInflater.from(activity).inflate(R.layout.dialog_no_connection_not_authorized, null, false)
v.findViewById<View>(R.id.close).setOnClickListener { v1 -> dismiss() }
v.findViewById<View>(R.id.done).setOnClickListener { v1 -> dismiss() }
builder.setView(v)
val d = builder.create()
d.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return d
}
private val authorizedDialog: Dialog
get() {
val builder = AlertDialog.Builder(activity!!)
val v = LayoutInflater.from(activity).inflate(R.layout.dialog_no_connection_authorized, null, false)
v.findViewById<View>(R.id.continueButton).setOnClickListener { v1 -> dismiss() }
v.findViewById<View>(R.id.retryButton).setOnClickListener { v1 -> dismiss() }
v.findViewById<View>(R.id.close).setOnClickListener { v1 -> dismiss() }
builder.setView(v)
val d = builder.create()
d.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return d
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
dialogType = arguments!!.getInt(EXTRA_TYPE)
when (dialogType) {
TYPE_NOT_AUTHORIZED -> return notAuthorizedDialog
else -> return authorizedDialog
}
}
companion object {
const val TYPE_NOT_AUTHORIZED = 0
const val TYPE_AUTHORIZED = 1
private val EXTRA_TYPE = "type"
fun newInstance(dialogType: Int): DialogFragment {
val dialog = NoConnectionDialog()
val args = Bundle()
args.putInt(EXTRA_TYPE, dialogType)
dialog.arguments = args
return dialog
}
}
}
| app/src/main/java/za/org/grassroot2/view/dialog/NoConnectionDialog.kt | 2555854248 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.reflection
import com.intellij.util.containers.HashMap
import java.beans.Introspector
import java.beans.PropertyDescriptor
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.javaType
import kotlin.reflect.memberProperties
/**
* Tools to fetch properties both from Java and Kotlin code and to copy them from one object to another.
* To be a property container class should have kotlin properties, java bean properties or implement [SimplePropertiesProvider].
*
* Properties should be writable except [DelegationProperty]
* @author Ilya.Kazakevich
*/
interface Property {
fun getName(): String
fun getType(): java.lang.reflect.Type
fun get(): Any?
fun set(value: Any?)
}
private class KotlinProperty(val property: KMutableProperty<*>, val instance: Any?) : Property {
override fun getName() = property.name
override fun getType() = property.returnType.javaType
override fun get() = property.getter.call(instance)
override fun set(value: Any?) = property.setter.call(instance, value)
}
private class JavaProperty(val property: PropertyDescriptor, val instance: Any?) : Property {
override fun getName() = property.name!!
override fun getType() = property.propertyType!!
override fun get() = property.readMethod.invoke(instance)!!
override fun set(value: Any?) {
property.writeMethod.invoke(instance, value)
}
}
private class SimpleProperty(private val propertyName: String,
private val provider: SimplePropertiesProvider) : Property {
override fun getName() = propertyName
override fun getType() = String::class.java
override fun get() = provider.getPropertyValue(propertyName)
override fun set(value: Any?) = provider.setPropertyValue(propertyName, value?.toString())
}
/**
* Implement to handle properties manually
*/
interface SimplePropertiesProvider {
val propertyNames: List<String>
fun setPropertyValue(propertyName: String, propertyValue: String?)
fun getPropertyValue(propertyName: String): String?
}
class Properties(val properties: List<Property>, val instance: Any) {
val propertiesMap: MutableMap<String, Property> = HashMap(properties.map { Pair(it.getName(), it) }.toMap())
init {
if (instance is SimplePropertiesProvider) {
instance.propertyNames.forEach { propertiesMap.put(it, SimpleProperty(it, instance)) }
}
}
fun copyTo(dst: Properties) {
propertiesMap.values.forEach {
val dstProperty = dst.propertiesMap[it.getName()]
if (dstProperty != null) {
val value = it.get()
dstProperty.set(value)
}
}
}
}
private fun KProperty<*>.isAnnotated(annotation: KClass<*>): Boolean {
return this.annotations.find { annotation.java.isAssignableFrom(it.javaClass) } != null
}
/**
* @param instance object with properties (see module doc)
* @param annotationToFilterByClass optional annotation class to fetch only kotlin properties annotated with it. Only supported in Kotlin
* @param usePojoProperties search for java-style properties (kotlin otherwise)
* @return properties of some object
*/
fun getProperties(instance: Any, annotationToFilterByClass: Class<*>? = null, usePojoProperties: Boolean = false): Properties {
val annotationToFilterBy = annotationToFilterByClass?.kotlin
if (usePojoProperties) {
// Java props
val javaProperties = Introspector.getBeanInfo(instance.javaClass).propertyDescriptors
assert(annotationToFilterBy == null, { "Filtering java properties is not supported" })
return Properties(javaProperties.map { JavaProperty(it, instance) }, instance)
}
else {
// Kotlin props
val klass = instance.javaClass.kotlin
val allKotlinProperties = LinkedHashSet(klass.memberProperties.filterIsInstance(KProperty::class.java))
val delegatedProperties = ArrayList<Property>() // See DelegationProperty doc
allKotlinProperties.filter { it.isAnnotated(DelegationProperty::class) }.forEach {
val delegatedInstance = it.getter.call(instance)
if (delegatedInstance != null) {
delegatedProperties.addAll(getProperties(delegatedInstance, annotationToFilterBy?.java, false).properties)
allKotlinProperties.remove(it)
}
}
val firstLevelProperties = allKotlinProperties.filterIsInstance(KMutableProperty::class.java)
if (annotationToFilterBy == null) {
return Properties(firstLevelProperties.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
return Properties(
firstLevelProperties.filter { it.isAnnotated(annotationToFilterBy) }.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
/**
* Property marked with it is not considered to be [Property] by itself, but class with properties instead.
* Following structure is example:
* class User:
* +familyName: String
* +lastName: String
* +credentials: Credentials
*
* class Credentials:
* +login: String
* +password: String
*
* Property credentials here is [DelegationProperty]. It can be val, but all other properties should be var
*/
annotation class DelegationProperty | python/src/com/jetbrains/reflection/ReflectionUtils.kt | 945535119 |
package com.stepstone.stepper.test.runner
import android.os.Build
import com.stepstone.stepper.BuildConfig
import com.stepstone.stepper.test.TestApplication
import org.junit.runners.model.InitializationError
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.lang.reflect.Method
/**
* Test runner with default config for this library.
* Inspired by [Robolectric Bulk Test Configuration](https://medium.com/@andrewlord1990/robolectric-bulk-test-configuration-28ddf82abf4a).
*/
class StepperRobolectricTestRunner @Throws(InitializationError::class) constructor(testClass: Class<*>) : RobolectricTestRunner(testClass) {
companion object {
const val QUALIFIER_LDRTL = "ldrtl"
}
override fun getConfig(method: Method): Config {
val config = super.getConfig(method)
return Config.Builder(config)
.setSdk(*resolveSdk(config.sdk))
.setConstants(resolveBuildConfig(config.constants.java))
.setApplication(TestApplication::class.java)
.build()
}
private fun resolveSdk(sdks: IntArray?): IntArray {
if (sdks == null || sdks.isEmpty()) {
return intArrayOf(Build.VERSION_CODES.LOLLIPOP)
} else {
return sdks
}
}
private fun resolveBuildConfig(constants: Class<*>): Class<*> {
if (constants == Void::class.java) {
return BuildConfig::class.java
} else {
return constants
}
}
}
| material-stepper/src/test/java/com/stepstone/stepper/test/runner/StepperRobolectricTestRunner.kt | 2609788167 |
package org.tasks.preferences.fragments
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import androidx.preference.ListPreference
import androidx.preference.Preference
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.R
import org.tasks.dialogs.MyTimePickerDialog.Companion.newTimePicker
import org.tasks.extensions.Context.toast
import org.tasks.injection.InjectingPreferenceFragment
import org.tasks.preferences.Preferences
import org.tasks.time.DateTime
import org.tasks.ui.TimePreference
import java.time.DayOfWeek
import java.time.format.TextStyle
import java.util.*
import javax.inject.Inject
private const val REQUEST_MORNING = 10007
private const val REQUEST_AFTERNOON = 10008
private const val REQUEST_EVENING = 10009
private const val REQUEST_NIGHT = 10010
@AndroidEntryPoint
class DateAndTime : InjectingPreferenceFragment(), Preference.OnPreferenceChangeListener {
@Inject lateinit var preferences: Preferences
@Inject lateinit var locale: Locale
override fun getPreferenceXml() = R.xml.preferences_date_and_time
override suspend fun setupPreferences(savedInstanceState: Bundle?) {
val startOfWeekPreference: ListPreference = getStartOfWeekPreference()
startOfWeekPreference.entries = getWeekdayEntries()
startOfWeekPreference.onPreferenceChangeListener = this
initializeTimePreference(getMorningPreference(), REQUEST_MORNING)
initializeTimePreference(getAfternoonPreference(), REQUEST_AFTERNOON)
initializeTimePreference(getEveningPreference(), REQUEST_EVENING)
initializeTimePreference(getNightPreference(), REQUEST_NIGHT)
updateStartOfWeek(preferences.getStringValue(R.string.p_start_of_week)!!)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_MORNING) {
if (resultCode == RESULT_OK) {
getMorningPreference().handleTimePickerActivityIntent(data)
}
} else if (requestCode == REQUEST_AFTERNOON) {
if (resultCode == RESULT_OK) {
getAfternoonPreference().handleTimePickerActivityIntent(data)
}
} else if (requestCode == REQUEST_EVENING) {
if (resultCode == RESULT_OK) {
getEveningPreference().handleTimePickerActivityIntent(data)
}
} else if (requestCode == REQUEST_NIGHT) {
if (resultCode == RESULT_OK) {
getNightPreference().handleTimePickerActivityIntent(data)
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun initializeTimePreference(preference: TimePreference, requestCode: Int) {
preference.onPreferenceChangeListener = this
preference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val current = DateTime().withMillisOfDay(preference.millisOfDay)
newTimePicker(this, requestCode, current.millis)
.show(parentFragmentManager, FRAG_TAG_TIME_PICKER)
false
}
}
override fun onPreferenceChange(preference: Preference, newValue: Any?): Boolean {
if (preference == getStartOfWeekPreference()) {
updateStartOfWeek(newValue.toString())
} else {
val millisOfDay = newValue as Int
if (preference == getMorningPreference()) {
if (millisOfDay >= getAfternoonPreference().millisOfDay) {
mustComeBefore(R.string.date_shortcut_morning, R.string.date_shortcut_afternoon)
return false
}
} else if (preference == getAfternoonPreference()) {
if (millisOfDay <= getMorningPreference().millisOfDay) {
mustComeAfter(R.string.date_shortcut_afternoon, R.string.date_shortcut_morning)
return false
} else if (millisOfDay >= getEveningPreference().millisOfDay) {
mustComeBefore(R.string.date_shortcut_afternoon, R.string.date_shortcut_evening)
return false
}
} else if (preference == getEveningPreference()) {
if (millisOfDay <= getAfternoonPreference().millisOfDay) {
mustComeAfter(R.string.date_shortcut_evening, R.string.date_shortcut_afternoon)
return false
} else if (millisOfDay >= getNightPreference().millisOfDay) {
mustComeBefore(R.string.date_shortcut_evening, R.string.date_shortcut_night)
return false
}
} else if (preference == getNightPreference()) {
if (millisOfDay <= getEveningPreference().millisOfDay) {
mustComeAfter(R.string.date_shortcut_night, R.string.date_shortcut_evening)
return false
}
}
}
return true
}
private fun mustComeBefore(settingResId: Int, relativeResId: Int) {
invalidSetting(R.string.date_shortcut_must_come_before, settingResId, relativeResId)
}
private fun mustComeAfter(settingResId: Int, relativeResId: Int) {
invalidSetting(R.string.date_shortcut_must_come_after, settingResId, relativeResId)
}
private fun invalidSetting(errorResId: Int, settingResId: Int, relativeResId: Int) =
context?.toast(errorResId, getString(settingResId), getString(relativeResId))
private fun updateStartOfWeek(value: String) {
val preference = getStartOfWeekPreference()
val index = preference.findIndexOfValue(value)
val summary: String? = getWeekdayEntries().get(index)
preference.summary = summary
}
private fun getStartOfWeekPreference(): ListPreference =
findPreference(R.string.p_start_of_week) as ListPreference
private fun getWeekdayDisplayName(dayOfWeek: DayOfWeek): String =
dayOfWeek.getDisplayName(TextStyle.FULL, locale)
private fun getMorningPreference(): TimePreference =
getTimePreference(R.string.p_date_shortcut_morning)
private fun getAfternoonPreference(): TimePreference =
getTimePreference(R.string.p_date_shortcut_afternoon)
private fun getEveningPreference(): TimePreference =
getTimePreference(R.string.p_date_shortcut_evening)
private fun getNightPreference(): TimePreference =
getTimePreference(R.string.p_date_shortcut_night)
private fun getTimePreference(resId: Int): TimePreference =
findPreference(resId) as TimePreference
private fun getWeekdayEntries(): Array<String?> = arrayOf(
getString(R.string.use_locale_default),
getWeekdayDisplayName(DayOfWeek.SUNDAY),
getWeekdayDisplayName(DayOfWeek.MONDAY),
getWeekdayDisplayName(DayOfWeek.TUESDAY),
getWeekdayDisplayName(DayOfWeek.WEDNESDAY),
getWeekdayDisplayName(DayOfWeek.THURSDAY),
getWeekdayDisplayName(DayOfWeek.FRIDAY),
getWeekdayDisplayName(DayOfWeek.SATURDAY)
)
} | app/src/main/java/org/tasks/preferences/fragments/DateAndTime.kt | 2094516386 |
package com.didichuxing.doraemonkit.kit.test.mock.proxy
import com.didichuxing.doraemonkit.kit.test.utils.DateTime
/**
* didi Create on 2022/3/10 .
*
* Copyright (c) 2022/3/10 by didiglobal.com.
*
* @author <a href="[email protected]">zhangjun</a>
* @version 1.0
* @Date 2022/3/10 7:45 下午
* @Description 用一句话说明文件功能
*/
data class ProxyResponse(
val did: String,
val responseHeaders: String,
val responseContentType: String,
val responseBodyLength: Long,
val responseBody: String,
val responseCode: Int,
val image: Boolean,
val source: String,
val protocol: String,
val responseTime: String = DateTime.nowTime(),
val requestTimeMillis: Long = DateTime.nowTimeMillis()
)
| Android/dokit-test/src/main/java/com/didichuxing/doraemonkit/kit/test/mock/proxy/ProxyResponse.kt | 20996162 |
package com.jospint.droiddevs.architecturecomponents.model
data class Forecast(
val timestamp: Double,
val iconId: String,
val description: String,
val temperature: Double,
val windSpeed: Double,
val prediction: String) | ArchitectureComponents/app/src/main/java/com/jospint/droiddevs/architecturecomponents/model/Forecast.kt | 153764015 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.learning.katas.io.builtinios
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.options.PipelineOptionsFactory
object Task {
@JvmStatic
fun main(args: Array<String>) {
val options = PipelineOptionsFactory.fromArgs(*args).create()
val pipeline = Pipeline.create(options)
pipeline.run()
}
} | learning/katas/kotlin/IO/Built-in IOs/Built-in IOs/src/org/apache/beam/learning/katas/io/builtinios/Task.kt | 3000139836 |
package com.renard.ocr.billing.cache
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class AugmentedSkuDetails(val canPurchase: Boolean, /* Not in SkuDetails; it's the augmentation */
@PrimaryKey val sku: String,
val type: String,
val price: String,
val title: String,
val description: String,
val originalJson: String) | app/src/main/java/com/renard/ocr/billing/cache/AugmentedSkuDetails.kt | 258870456 |
package com.cout970.magneticraft.systems.tilerenderers
import com.cout970.magneticraft.misc.addPostfix
import com.cout970.magneticraft.misc.addPrefix
import com.cout970.magneticraft.misc.logError
import com.cout970.magneticraft.misc.warn
import com.cout970.modelloader.api.*
import com.cout970.modelloader.api.animation.AnimatedModel
import com.cout970.modelloader.api.formats.gltf.GltfAnimationBuilder
import com.cout970.modelloader.api.formats.gltf.GltfStructure
import com.cout970.modelloader.api.formats.mcx.McxModel
import net.minecraft.client.renderer.block.model.ModelResourceLocation
import net.minecraft.client.renderer.texture.TextureMap
/**
* Created by cout970 on 2017/06/16.
*/
object ModelCacheFactory {
fun createModel(loc: ModelResourceLocation, filters: List<ModelSelector>,
useTextures: Boolean, time: () -> Double, createDefault: Boolean = true): Map<String, IRenderCache> {
val models = mutableMapOf<String, IRenderCache>()
val (baked, model) = ModelLoaderApi.getModelEntry(loc) ?: return models
when (model) {
is Model.Mcx -> processMcx(model, filters, useTextures, models, createDefault)
is Model.Gltf -> processGltf(model, filters, useTextures, time, models, createDefault)
is Model.Obj -> {
if (createDefault) {
if (baked != null) {
val cache = ModelCache { ModelUtilities.renderModel(baked) }
models["default"] = if (useTextures) TextureModelCache(TextureMap.LOCATION_BLOCKS_TEXTURE, cache) else cache
} else {
logError("Error: trying to render a obj model that is not backed, this is not supported!")
}
}
}
Model.Missing -> {
warn("Model for $loc not found")
}
}
return models
}
private fun removeTextures(model: AnimatedModel): AnimatedModel {
return AnimatedModel(model.rootNodes.map { removeTextures(it) }, model.channels)
}
private fun removeTextures(node: AnimatedModel.Node): AnimatedModel.Node {
return node.copy(
children = node.children.map { removeTextures(it) },
cache = removeTextures(node.cache)
)
}
private fun removeTextures(renderCache: IRenderCache): IRenderCache {
return when (renderCache) {
is ModelGroupCache -> ModelGroupCache(*renderCache.cache.map { removeTextures(it) }.toTypedArray())
is TextureModelCache -> ModelGroupCache(*renderCache.cache)
else -> renderCache
}
}
private fun processMcx(model: Model.Mcx, filters: List<ModelSelector>, useTextures: Boolean,
models: MutableMap<String, IRenderCache>, createDefault: Boolean) {
val sections = filters.map { (name, filterFunc) ->
val parts = model.data.parts.filter { filterFunc(it.name, FilterTarget.LEAF) }
name to parts
}
val notUsed = if (filters.any { it.animationFilter != IGNORE_ANIMATION }) {
model.data.parts
} else {
val used = sections.flatMap { it.second }.toSet()
model.data.parts.filter { it !in used }
}
fun store(name: String, partList: List<McxModel.Part>) {
partList.groupBy { it.texture }.forEach { tex, parts ->
val cache = ModelCache { ModelUtilities.renderModelParts(model.data, parts) }
val texture = tex.addPrefix("textures/").addPostfix(".png")
val obj = if (useTextures) TextureModelCache(texture, cache) else cache
if (name in models) {
val old = models[name]!!
if (old is ModelGroupCache) {
models[name] = ModelGroupCache(*old.cache, obj)
} else {
models[name] = ModelGroupCache(old, obj)
}
} else {
models[name] = obj
}
}
}
sections.forEach { store(it.first, it.second) }
if (createDefault) store("default", notUsed)
}
private fun processGltf(model: Model.Gltf, filters: List<ModelSelector>, useTextures: Boolean, time: () -> Double, models: MutableMap<String, IRenderCache>,
createDefault: Boolean) {
val scene = model.data.structure.scenes[0]
val namedAnimations = model.data.structure.animations.mapIndexed { index, animation ->
animation.name ?: index.toString()
}
val sections = filters.map { (name, filter, animation) ->
Triple(name, scene.nodes.flatMap { it.recursiveFilter(filter) }.toSet(), animation)
}
val allNodes = (0 until model.data.definition.nodes.size).toSet()
fun store(name: String, nodes: Set<Int>, filter: Filter) {
val exclusions = (0 until model.data.definition.nodes.size).filter { it !in nodes }.toSet()
val validAnimations = namedAnimations.filter { filter(it, FilterTarget.ANIMATION) }
val builder = GltfAnimationBuilder()
.also { it.excludedNodes = exclusions }
.also { it.transformTexture = { tex -> tex.addPrefix("textures/").addPostfix(".png") } }
val newModel = if (validAnimations.isEmpty()) {
builder.buildPlain(model.data)
} else {
builder.build(model.data).first { it.first in validAnimations }.second
}
val obj = if (useTextures) {
AnimationRenderCache(newModel, time)
} else {
AnimationRenderCache(removeTextures(newModel), time)
}
if (name in models) {
val old = models[name]!!
if (old is ModelGroupCache) {
models[name] = ModelGroupCache(*old.cache, obj)
} else {
models[name] = ModelGroupCache(old, obj)
}
} else {
models[name] = obj
}
}
sections.forEach { store(it.first, it.second, it.third) }
if (createDefault) store("default", allNodes, IGNORE_ANIMATION)
}
private fun GltfStructure.Node.recursiveFilter(filter: Filter): Set<Int> {
val children = children.flatMap { it.recursiveFilter(filter) }.toSet()
val all = children + setOf(index)
val name = name ?: return all
val type = if (mesh == null) FilterTarget.BRANCH else FilterTarget.LEAF
return if (filter(name, type)) all else emptySet()
}
}
class AnimationRenderCache(val model: AnimatedModel, val time: () -> Double) : IRenderCache {
override fun render() = model.render(time())
override fun close() = model.rootNodes.close()
private fun List<AnimatedModel.Node>.close(): Unit = forEach {
it.cache.close()
it.children.close()
}
} | src/main/kotlin/com/cout970/magneticraft/systems/tilerenderers/ModelCacheFactory.kt | 1020770004 |
/**
* 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.module.billing.esb
import com.google.common.eventbus.AllowConcurrentEvents
import com.google.common.eventbus.Subscribe
import com.mycollab.common.NotificationType
import com.mycollab.common.i18n.OptionI18nEnum.StatusI18nEnum
import com.mycollab.common.i18n.WikiI18nEnum
import com.mycollab.common.service.OptionValService
import com.mycollab.core.utils.BeanUtility
import com.mycollab.core.utils.StringUtils
import com.mycollab.module.esb.GenericCommand
import com.mycollab.module.file.PathUtils
import com.mycollab.module.page.domain.Folder
import com.mycollab.module.page.domain.Page
import com.mycollab.module.page.service.PageService
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.domain.*
import com.mycollab.module.project.i18n.OptionI18nEnum.*
import com.mycollab.module.project.service.*
import com.mycollab.module.project.domain.BugWithBLOBs
import com.mycollab.module.project.domain.Version
import com.mycollab.module.project.service.TicketRelationService
import com.mycollab.module.project.service.BugService
import com.mycollab.module.project.service.ComponentService
import com.mycollab.module.project.service.VersionService
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
class AccountCreatedCommand(private val optionValService: OptionValService,
private val projectService: ProjectService,
private val messageService: MessageService,
private val milestoneService: MilestoneService,
private val taskService: TaskService,
private val bugService: BugService,
private val bugRelatedService: TicketRelationService,
private val componentService: ComponentService,
private val versionService: VersionService,
private val pageService: PageService,
private val projectNotificationSettingService: ProjectNotificationSettingService) : GenericCommand() {
@AllowConcurrentEvents
@Subscribe
fun execute(event: AccountCreatedEvent) {
createDefaultOptionVals(event.accountId)
if (event.createSampleData != null && event.createSampleData == true) {
createSampleProjectData(event.initialUser, event.accountId)
}
}
private fun createDefaultOptionVals(accountId: Int) {
optionValService.createDefaultOptions(accountId)
}
private fun createSampleProjectData(initialUser: String, accountId: Int) {
val nowDateTime = LocalDateTime.now()
val nowDate = LocalDate.now()
val project = Project()
project.saccountid = accountId
project.description = "Sample project"
project.homepage = "https://www.mycollab.com"
project.name = "Sample project"
project.status = StatusI18nEnum.Open.name
project.shortname = "SP1"
val projectId = projectService.saveWithSession(project, initialUser)
val projectNotificationSetting = ProjectNotificationSetting()
projectNotificationSetting.level = NotificationType.None.name
projectNotificationSetting.projectid = projectId
projectNotificationSetting.saccountid = accountId
projectNotificationSetting.username = initialUser
projectNotificationSettingService.saveWithSession(projectNotificationSetting, initialUser)
val message = Message()
message.isstick = true
message.createduser = initialUser
message.message = "Welcome to MyCollab workspace. I hope you enjoy it!"
message.saccountid = accountId
message.projectid = projectId
message.title = "Thank you for using MyCollab!"
message.createdtime = nowDateTime
messageService.saveWithSession(message, initialUser)
val milestone = Milestone()
milestone.createduser = initialUser
milestone.duedate = nowDate.plusDays(14)
milestone.startdate = nowDate
milestone.enddate = nowDate.plusDays(14)
milestone.name = "Sample milestone"
milestone.assignuser = initialUser
milestone.projectid = projectId
milestone.saccountid = accountId
milestone.status = MilestoneStatus.InProgress.name
val sampleMilestoneId = milestoneService.saveWithSession(milestone, initialUser)
val taskA = Task()
taskA.name = "Task A"
taskA.projectid = projectId
taskA.createduser = initialUser
taskA.percentagecomplete = 0.0
taskA.priority = Priority.Medium.name
taskA.saccountid = accountId
taskA.status = StatusI18nEnum.Open.name
taskA.startdate = nowDate
taskA.enddate = nowDate.plusDays(3)
val taskAId = taskService.saveWithSession(taskA, initialUser)
val taskB = BeanUtility.deepClone(taskA)
taskB.name = "Task B"
taskB.id = null
taskB.milestoneid = sampleMilestoneId
taskB.startdate = nowDate.plusDays(2)
taskB.enddate = nowDate.plusDays(4)
taskService.saveWithSession(taskB, initialUser)
val taskC = BeanUtility.deepClone(taskA)
taskC.id = null
taskC.name = "Task C"
taskC.startdate = nowDate.plusDays(3)
taskC.enddate = nowDate.plusDays(5)
// taskC.parenttaskid = taskAId
taskService.saveWithSession(taskC, initialUser)
val taskD = BeanUtility.deepClone(taskA)
taskD.id = null
taskD.name = "Task D"
taskD.startdate = nowDate
taskD.enddate = nowDate.plusDays(2)
taskService.saveWithSession(taskD, initialUser)
val component = com.mycollab.module.project.domain.Component()
component.name = "Component 1"
component.createduser = initialUser
component.description = "Sample Component 1"
component.status = StatusI18nEnum.Open.name
component.projectid = projectId
component.saccountid = accountId
component.userlead = initialUser
componentService.saveWithSession(component, initialUser)
val version = Version()
version.createduser = initialUser
version.name = "Version 1"
version.description = "Sample version"
version.duedate = nowDate.plusDays(21)
version.projectid = projectId
version.saccountid = accountId
version.status = StatusI18nEnum.Open.name
versionService.saveWithSession(version, initialUser)
val bugA = BugWithBLOBs()
bugA.description = "Sample bug"
bugA.environment = "All platforms"
bugA.assignuser = initialUser
bugA.duedate = nowDate.plusDays(2)
bugA.createduser = initialUser
bugA.milestoneid = sampleMilestoneId
bugA.name = "Bug A"
bugA.status = StatusI18nEnum.Open.name
bugA.priority = Priority.Medium.name
bugA.projectid = projectId
bugA.saccountid = accountId
val bugAId = bugService.saveWithSession(bugA, initialUser)
val bugB = BeanUtility.deepClone(bugA)
bugB.id = null
bugB.name = "Bug B"
bugB.status = StatusI18nEnum.Resolved.name
bugB.resolution = BugResolution.CannotReproduce.name
bugB.priority = Priority.Low.name
bugService.saveWithSession(bugB, initialUser)
bugRelatedService.saveAffectedVersionsOfTicket(bugAId, ProjectTypeConstants.BUG, listOf(version))
bugRelatedService.saveComponentsOfTicket(bugAId, ProjectTypeConstants.BUG, listOf(component))
val page = Page()
page.subject = "Welcome to sample workspace"
page.content = "I hope you enjoy MyCollab!"
page.path = "${PathUtils.getProjectDocumentPath(accountId, projectId)}/${StringUtils.generateSoftUniqueId()}"
page.status = WikiI18nEnum.status_public.name
pageService.savePage(page, initialUser)
val folder = Folder()
folder.name = "Requirements"
folder.description = "Sample folder"
folder.path = "${PathUtils.getProjectDocumentPath(accountId, projectId)}/${StringUtils.generateSoftUniqueId()}"
pageService.createFolder(folder, initialUser)
val timer = Timer("Set member notification")
timer.schedule(object : TimerTask() {
override fun run() {
projectNotificationSetting.level = NotificationType.Default.name
projectNotificationSettingService.updateWithSession(projectNotificationSetting, initialUser)
}
}, 90000)
}
} | mycollab-esb/src/main/java/com/mycollab/module/billing/esb/AccountCreatedCommand.kt | 31728718 |
package com.jraska.github.client.chrome
import android.content.Context
import com.jraska.github.client.WebLinkLauncher
import com.jraska.github.client.core.android.TopActivityProvider
import dagger.Module
import dagger.Provides
@Module
object ChromeCustomTabsModule {
@Provides
fun webLinkLauncher(provider: TopActivityProvider, context: Context): WebLinkLauncher {
return ChromeCustomTabsLauncher(provider, context.packageManager)
}
}
| feature/chrome-custom-tabs/src/main/java/com/jraska/github/client/chrome/ChromeCustomTabsModule.kt | 3645698590 |
/*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.utils
import android.util.Log
import io.mockk.Called
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.mockkStatic
import io.mockk.verify
import org.junit.Assert
import org.junit.Before
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runners.MethodSorters
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class LoggingTest {
@Before
fun setUp() {
mockkStatic(Log::class)
every { Log.e(any(), any()) } returns 0
every { Log.e(any(), any(), any()) } returns 0
every { Log.w(any(), any<String>()) } returns 0
every { Log.i(any(), any()) } returns 0
every { Log.d(any(), any()) } returns 0
every { Log.v(any(), any()) } returns 0
}
@Test
fun `Test_01 Logging TAG`() {
Assert.assertEquals("BOINC_GUI", Logging.TAG)
}
@Test
fun `Test_02 Logging WAKELOCK`() {
Assert.assertEquals("BOINC_GUI:MyPowerLock", Logging.WAKELOCK)
}
@Test
fun `Test_03 Logging Default Log Levels`() {
Assert.assertEquals(-1, Logging.getLogLevel())
Assert.assertFalse(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
Logging.setLogCategory("DEVICE", true)
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_04 Logging setLogLevel(-1)`() {
Logging.setLogLevel(-1)
Assert.assertEquals(-1, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_05 Logging setLogLevel(-10)`() {
Logging.setLogLevel(-10)
Assert.assertEquals(-10, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_06 Logging setLogLevel(-42)`() {
Logging.setLogLevel(-42)
Assert.assertEquals(-42, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_07 Logging setLogLevel(0)`() {
Logging.setLogLevel(0)
Assert.assertEquals(0, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_08 Logging setLogLevel(1)`() {
Logging.setLogLevel(1)
Assert.assertEquals(1, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_09 Logging setLogLevel(2)`() {
Logging.setLogLevel(2)
Assert.assertEquals(2, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_10 Logging setLogLevel(3)`() {
Logging.setLogLevel(3)
Assert.assertEquals(3, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_11 Logging setLogLevel(4)`() {
Logging.setLogLevel(4)
Assert.assertEquals(4, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_12 Logging setLogLevel(5)`() {
Logging.setLogLevel(5)
Assert.assertEquals(5, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_13 Logging setLogLevel(6)`() {
Logging.setLogLevel(6)
Assert.assertEquals(6, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_14 Logging setLogLevel(10)`() {
Logging.setLogLevel(10)
Assert.assertEquals(10, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_15 Logging setLogLevel(42)`() {
Logging.setLogLevel(42)
Assert.assertEquals(42, Logging.getLogLevel())
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertTrue(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test
fun `Test_16 Logging after category remove`() {
Logging.setLogCategory("DEVICE", false)
Assert.assertFalse(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.ERROR, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.WARNING, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.INFO, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.DEBUG, Logging.Category.DEVICE))
Assert.assertFalse(Logging.isLoggable(Logging.Level.VERBOSE, Logging.Category.DEVICE))
}
@Test(expected = Test.None::class)
fun `Test_17 Logging not fail on double add or double remove`() {
Logging.setLogCategory("RPC", true)
Logging.setLogCategory("RPC", true)
Logging.setLogCategory("RPC", false)
Logging.setLogCategory("RPC", false)
}
@Test(expected = Test.None::class)
fun `Test_18 Logging not fail when non existing category is provided`() {
Logging.setLogCategory("TEST_CATEGORY", true)
Logging.setLogCategory("TEST_CATEGORY", false)
}
@Test
fun `Test_19 Logging after categories list set`() {
Logging.setLogCategories(listOf("DEVICE", "RPC"))
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.DEVICE))
Assert.assertTrue(Logging.getLogCategories().contains(Logging.Category.RPC))
Logging.setLogCategory("DEVICE", false)
Logging.setLogCategory("RPC", false)
}
@Test
fun `Test_20 only error and exception are logged when logLevel equals ERROR`() {
Logging.setLogLevel(Logging.Level.ERROR.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 0) { Log.w(any(), any<String>()) }
verify(exactly = 0) { Log.i(any(), any()) }
verify(exactly = 0) { Log.d(any(), any()) }
verify(exactly = 0) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
@Test
fun `Test_21 only warning, error and exception are logged when logLevel equals WARNING`() {
Logging.setLogLevel(Logging.Level.WARNING.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 1) { Log.w(any(), any<String>()) }
verify(exactly = 0) { Log.i(any(), any()) }
verify(exactly = 0) { Log.d(any(), any()) }
verify(exactly = 0) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
@Test
fun `Test_22 only info, warning, error and exception are logged when logLevel equals INFO`() {
Logging.setLogLevel(Logging.Level.INFO.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 1) { Log.w(any(), any<String>()) }
verify(exactly = 1) { Log.i(any(), any()) }
verify(exactly = 0) { Log.d(any(), any()) }
verify(exactly = 0) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
@Test
fun `Test_23 only debug, info, warning, error and exception are logged when logLevel equals DEBUG`() {
Logging.setLogLevel(Logging.Level.DEBUG.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 1) { Log.w(any(), any<String>()) }
verify(exactly = 1) { Log.i(any(), any()) }
verify(exactly = 1) { Log.d(any(), any()) }
verify(exactly = 0) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
@Test
fun `Test_24 verbose, debug, info, warning, error and exception are logged when logLevel equals VERBOSE`() {
Logging.setLogLevel(Logging.Level.VERBOSE.logLevel)
Logging.setLogCategory("DEVICE", true)
Logging.logException(Logging.Category.DEVICE, "TestException", Exception("TestException"))
Logging.logError(Logging.Category.DEVICE, "TestError")
Logging.logWarning(Logging.Category.DEVICE, "TestWarning")
Logging.logInfo(Logging.Category.DEVICE, "TestInfo")
Logging.logDebug(Logging.Category.DEVICE, "TestDebug")
Logging.logVerbose(Logging.Category.DEVICE, "TestVerbose")
verify(exactly = 2) { Log.e(any(), any(), any()) }
verify(exactly = 1) { Log.w(any(), any<String>()) }
verify(exactly = 1) { Log.i(any(), any()) }
verify(exactly = 1) { Log.d(any(), any()) }
verify(exactly = 1) { Log.v(any(), any()) }
Logging.setLogCategory("DEVICE", false)
}
}
| android/BOINC/app/src/test/java/edu/berkeley/boinc/utils/LoggingTest.kt | 239809824 |
package org.rust.ide.surroundWith.expression
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsParenExpr
import org.rust.lang.core.psi.RsPsiFactory
class RsWithParenthesesSurrounder : RsExpressionSurrounderBase<RsParenExpr>() {
override fun getTemplateDescription(): String = "(expr)"
override fun createTemplate(project: Project): RsParenExpr =
RsPsiFactory(project).createExpression("(a)") as RsParenExpr
override fun getWrappedExpression(expression: RsParenExpr): RsExpr =
expression.expr
override fun isApplicable(expression: RsExpr): Boolean = true
override fun doPostprocessAndGetSelectionRange(editor: Editor, expression: PsiElement): TextRange {
val offset = expression.textRange.endOffset
return TextRange.from(offset, 0)
}
}
| src/main/kotlin/org/rust/ide/surroundWith/expression/RsWithParenthesesSurrounder.kt | 3170993308 |
package io.mockk.proxy
interface Cancelable<T> {
fun get(): T
fun cancel()
}
| modules/mockk-agent-api/src/commonMain/kotlin/io/mockk/proxy/Cancelable.kt | 2261929030 |
package com.sinnerschrader.s2b.accounttool.presentation.controller.v2
import com.sinnerschrader.s2b.accounttool.config.WebConstants
import com.sinnerschrader.s2b.accounttool.logic.component.ldap.LdapService
import com.sinnerschrader.s2b.accounttool.logic.component.ldap.v2.LdapServiceV2
import com.sinnerschrader.s2b.accounttool.logic.component.ldap.v2.LdapServiceV2.UserAttributes.FULL
import com.sinnerschrader.s2b.accounttool.logic.component.ldap.v2.LdapServiceV2.UserAttributes.INFO
import com.sinnerschrader.s2b.accounttool.logic.entity.User.State
import com.sinnerschrader.s2b.accounttool.logic.entity.User.State.inactive
import com.sinnerschrader.s2b.accounttool.presentation.controller.v2.DynamicAllowedValues.Companion.COMPANIES
import com.sinnerschrader.s2b.accounttool.presentation.controller.v2.DynamicAllowedValues.Companion.USERTYPE
import com.unboundid.ldap.sdk.LDAPConnection
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.format.annotation.DateTimeFormat
import org.springframework.format.annotation.DateTimeFormat.ISO.DATE
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.*
import springfox.documentation.annotations.ApiIgnore
import java.time.LocalDate
@RestController
@Api(tags = ["Admin"], description = "Provides admin access")
@RequestMapping("/v2")
@PreAuthorize("@authorizationService.ensureUserAdministration()")
class AdminController {
@Autowired
lateinit var ldapServiceV2: LdapServiceV2
@Autowired
lateinit var ldapService: LdapService
@ApiOperation("Retrieve users")
@GetMapping("/admin/user")
fun getUser(@ApiParam("account state")
@RequestParam(required = false) state: State?,
@ApiParam("search multiple fields for a specific keyword")
@RequestParam(required = false) searchTerm: String?,
@ApiParam("earliest entry date")
@RequestParam(required = false) @DateTimeFormat(iso = DATE) entryDateStart: LocalDate?,
@ApiParam("latest entry date")
@RequestParam(required = false) @DateTimeFormat(iso = DATE) entryDateEnd: LocalDate?,
@ApiParam("earliest exit date")
@RequestParam(required = false) @DateTimeFormat(iso = DATE) exitDateStart: LocalDate?,
@ApiParam("latest exit date")
@RequestParam(required = false) @DateTimeFormat(iso = DATE) exitDateEnd: LocalDate?,
@ApiParam(allowableValues = COMPANIES) company: String?,
@ApiParam(allowableValues = USERTYPE) type: String?) =
ldapServiceV2.getUser(state = state,
company = company,
type = type,
searchTerm = searchTerm,
entryDateRange = LdapServiceV2.DateRange.of(entryDateStart, entryDateEnd),
exitDateRange = LdapServiceV2.DateRange.of(exitDateStart, exitDateEnd),
attributes = FULL)
@ApiOperation("Retrieve user by uid")
@GetMapping("/admin/user/{uid}")
fun getUser(@PathVariable uid: String) = ldapServiceV2.getUser(uid = uid, attributes = FULL).single()
@ApiOperation("Retrieve inactive group members")
@GetMapping("/admin/maintenance/group/inactive")
fun getMaintenanceGroupInactive() =
(ldapServiceV2.getUser(state = inactive, attributes = INFO).map { it.uid }).let { inactive ->
ldapServiceV2.getGroups().map {
it.name to it.members.apply { retainAll(inactive) }
}.toMap().filterValues { it.isNotEmpty() }
}
@ApiOperation("Remove inactive group members")
@DeleteMapping("/admin/maintenance/group/inactive")
fun deleteMaintenanceGroupInactive(@ApiIgnore
@RequestAttribute(name = WebConstants.ATTR_CONNECTION)
connection: LDAPConnection) =
// TODO optimise performance (batch change)
ldapServiceV2.getUser(state = inactive, attributes = FULL).forEach {
ldapService.clearGroups(connection, it)
}
}
| src/main/kotlin/com/sinnerschrader/s2b/accounttool/presentation/controller/v2/AdminController.kt | 4263366474 |
package io.gitlab.arturbosch.tinbo.time
import java.time.LocalDate
/**
* @author Artur Bosch
*/
fun weekRange(today: LocalDate): Pair<LocalDate, LocalDate> {
val dayOfWeek = today.dayOfWeek
val from = dayOfWeek.value - 1
val to = 7 - dayOfWeek.value
return today.minusDays(from.toLong()) to today.plusDays(to.toLong())
}
fun TimeEntry.timeAsMinutes(): Int = (hours * 60 + minutes).toInt()
@Throws(IllegalArgumentException::class)
fun Long.validateInHourRange(): Long =
if (this >= 60) throw IllegalArgumentException("Minutes and seconds must be < 60!") else this | tinbo-time/src/main/kotlin/io/gitlab/arturbosch/tinbo/time/TimeExt.kt | 563773408 |
package com.soywiz.korge.input
import com.soywiz.korge.component.*
import com.soywiz.korge.view.*
import com.soywiz.korio.async.*
import com.soywiz.korma.geom.*
class Gestures(override val view: View) : Component {
class Direction(val point: IPointInt) {
constructor(x: Int, y: Int) : this(IPointInt(x, y))
val x get() = point.x
val y get() = point.y
companion object {
val Up = Direction(0, -1)
val Down = Direction(0, +1)
val Left = Direction(-1, 0)
val Right = Direction(+1, 0)
}
}
val onSwipe = Signal<Direction>()
}
val View.gestures get() = this.getOrCreateComponentOther<Gestures> { Gestures(this) }
| korge/src/commonMain/kotlin/com/soywiz/korge/input/Gestures.kt | 3929818599 |
//
// (C) Copyright 2017-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package i.katydid.vdom.elements.interactive
import i.katydid.vdom.builders.details.KatydidDetailsFlowContentBuilderImpl
import i.katydid.vdom.elements.KatydidHtmlElementImpl
import o.katydid.vdom.builders.KatydidFlowContentBuilder
import o.katydid.vdom.builders.KatydidHeadingContentBuilder
import o.katydid.vdom.types.EDirection
//---------------------------------------------------------------------------------------------------------------------
/**
* Virtual node for a <summary> element.
*/
internal class KatydidSummary<Msg> : KatydidHtmlElementImpl<Msg> {
constructor(
detailsContent: KatydidDetailsFlowContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
contenteditable: Boolean?,
dir: EDirection?,
draggable: Boolean?,
hidden: Boolean?,
lang: String?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
defineContent: KatydidFlowContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
detailsContent.detailsContentRestrictions.confirmSummaryAllowedThenDisallow()
detailsContent.withNoAddedRestrictions(this).defineContent()
this.freeze()
}
constructor(
detailsContent: KatydidDetailsFlowContentBuilderImpl<Msg>,
selector: String?,
key: Any?,
accesskey: Char?,
contenteditable: Boolean?,
dir: EDirection?,
draggable: Boolean?,
hidden: Boolean?,
lang: String?,
spellcheck: Boolean?,
style: String?,
tabindex: Int?,
title: String?,
translate: Boolean?,
withHeading: Boolean,
defineContent: KatydidHeadingContentBuilder<Msg>.() -> Unit
) : super(selector, key, accesskey, contenteditable, dir, draggable,
hidden, lang, spellcheck, style, tabindex, title, translate) {
require(withHeading) { "Artificial 'withHeading' parameter not set." }
detailsContent.detailsContentRestrictions.confirmSummaryAllowedThenDisallow()
// TODO: allow only one heading
detailsContent.withNoAddedRestrictions(this).defineContent()
this.freeze()
}
////
override val nodeName = "SUMMARY"
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/interactive/KatydidSummary.kt | 1495991225 |
package com.bennyhuo.github.view.common
import android.animation.ObjectAnimator
import android.support.annotation.LayoutRes
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import com.bennyhuo.github.R
import com.bennyhuo.github.utils.AdapterList
import kotlinx.android.synthetic.main.item_card.view.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.sdk15.listeners.onClick
abstract class CommonListAdapter<T>(@LayoutRes val itemResId: Int) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val CARD_TAP_DURATION = 100L
}
init {
//item有自己的id
setHasStableIds(true)
}
private var oldPosition = -1
val data = AdapterList<T>(this)
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_card, parent, false)
LayoutInflater.from(itemView.context).inflate(itemResId, itemView.contentContainer)
return CommonViewHolder(itemView)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
onBindData(holder, data[position])
holder.itemView.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> ViewCompat.animate(holder.itemView).scaleX(1.03f).scaleY(1.03f).translationZ(holder.itemView.dip(10).toFloat()).duration = CARD_TAP_DURATION
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
ViewCompat.animate(holder.itemView).scaleX(1f).scaleY(1f).translationZ(holder.itemView.dip(0).toFloat()).duration = CARD_TAP_DURATION
}
}
false
}
holder.itemView.onClick {
onItemClicked(holder.itemView, data[position])
}
}
override fun onViewAttachedToWindow(holder: ViewHolder) {
if(holder is CommonViewHolder && holder.layoutPosition > oldPosition){
addItemAnimation(holder.itemView)
oldPosition = holder.layoutPosition
}
}
private fun addItemAnimation(itemView: View) {
ObjectAnimator.ofFloat(itemView, "translationY", 500f, 0f).setDuration(500).start()
}
abstract fun onBindData(viewHolder: ViewHolder, item: T)
abstract fun onItemClicked(itemView: View, item: T)
class CommonViewHolder(itemView: View): ViewHolder(itemView)
} | Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/view/common/CommonListAdapter.kt | 1195861237 |
package com.tamsiree.rxui.view.dialog.wheel
/**
* @author tamsiree
* Wheel scrolled listener interface.
*/
interface OnWheelScrollListener {
/**
* Callback method to be invoked when scrolling started.
* @param wheel the wheel view whose state has changed.
*/
fun onScrollingStarted(wheel: WheelView?)
/**
* Callback method to be invoked when scrolling ended.
* @param wheel the wheel view whose state has changed.
*/
fun onScrollingFinished(wheel: WheelView?)
} | RxUI/src/main/java/com/tamsiree/rxui/view/dialog/wheel/OnWheelScrollListener.kt | 3190489065 |
package com.uchuhimo.konf
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.has
import com.natpryce.hamkrest.throws
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.subject.SubjectSpek
object ConfigSpek : SubjectSpek<Config>({
val spec = NetworkBuffer
val size = NetworkBuffer.size
val maxSize = NetworkBuffer.maxSize
val name = NetworkBuffer.name
val type = NetworkBuffer.type
subject { Config { addSpec(spec) } }
given("a config") {
val invalidItem = ConfigSpec("invalid").run { required<Int>("invalidItem") }
group("addSpec operation") {
on("add orthogonal spec") {
val newSpec = object : ConfigSpec(spec.prefix) {
val minSize = optional("minSize", 1)
}
subject.addSpec(newSpec)
it("should contain items in new spec") {
assertThat(newSpec.minSize in subject, equalTo(true))
assertThat(newSpec.minSize.name in subject, equalTo(true))
}
it("should contain new spec") {
assertThat(newSpec in subject.specs, equalTo(true))
assertThat(spec in subject.specs, equalTo(true))
}
}
on("add repeated item") {
it("should throw RepeatedItemException") {
assertThat({ subject.addSpec(spec) }, throws(has(
RepeatedItemException::name,
equalTo(size.name))))
}
}
on("add repeated name") {
val newSpec = ConfigSpec(spec.prefix).apply { required<Int>("size") }
it("should throw NameConflictException") {
assertThat({ subject.addSpec(newSpec) }, throws<NameConflictException>())
}
}
on("add conflict name, which is prefix of existed name") {
val newSpec = ConfigSpec("network").apply { required<Int>("buffer") }
it("should throw NameConflictException") {
assertThat({ subject.addSpec(newSpec) }, throws<NameConflictException>())
}
}
on("add conflict name, and an existed name is prefix of it") {
val newSpec = ConfigSpec(type.name).apply {
required<Int>("subType")
}
it("should throw NameConflictException") {
assertThat({ subject.addSpec(newSpec) }, throws<NameConflictException>())
}
}
}
on("iterate items in config") {
it("should cover all items in config") {
assertThat(subject.items.toSet(), equalTo(spec.items.toSet()))
}
}
group("get operation") {
on("get with valid item") {
it("should return corresponding value") {
assertThat(subject[name], equalTo("buffer"))
}
}
on("get with invalid item") {
it("should throw NoSuchItemException when using `get`") {
assertThat({ subject[invalidItem] },
throws(has(NoSuchItemException::name, equalTo(invalidItem.name))))
}
it("should return null when using `getOrNull`") {
assertThat(subject.getOrNull(invalidItem), absent())
}
}
on("get with valid name") {
it("should return corresponding value") {
assertThat(subject<String>(spec.qualify("name")), equalTo("buffer"))
}
}
on("get with invalid name") {
it("should throw NoSuchItemException when using `get`") {
assertThat({ subject<String>(spec.qualify("invalid")) }, throws(has(
NoSuchItemException::name, equalTo(spec.qualify("invalid")))))
}
it("should return null when using `getOrNull`") {
assertThat(subject.getOrNull<String>(spec.qualify("invalid")), absent())
}
}
on("get unset item") {
it("should throw UnsetValueException") {
assertThat({ subject[size] }, throws(has(
UnsetValueException::name,
equalTo(size.name))))
assertThat({ subject[maxSize] }, throws(has(
UnsetValueException::name,
equalTo(size.name))))
}
}
}
group("set operation") {
on("set with valid item when corresponding value is unset") {
subject[size] = 1024
it("should contain the specified value") {
assertThat(subject[size], equalTo(1024))
}
}
on("set with valid item when corresponding value exists") {
subject[name] = "newName"
it("should contain the specified value") {
assertThat(subject[name], equalTo("newName"))
}
}
on("set with valid item when corresponding value is lazy") {
test("before set, the item should be lazy; after set," +
" the item should be no longer lazy, and it contains the specified value") {
subject[size] = 1024
assertThat(subject[maxSize], equalTo(subject[size] * 2))
subject[maxSize] = 0
assertThat(subject[maxSize], equalTo(0))
subject[size] = 2048
assertThat(subject[maxSize], !equalTo(subject[size] * 2))
assertThat(subject[maxSize], equalTo(0))
}
}
on("set with invalid item") {
it("should throw NoSuchItemException") {
assertThat({ subject[invalidItem] = 1024 },
throws(has(NoSuchItemException::name, equalTo(invalidItem.name))))
}
}
on("set with valid name") {
subject[spec.qualify("size")] = 1024
it("should contain the specified value") {
assertThat(subject[size], equalTo(1024))
}
}
on("set with invalid name") {
it("should throw NoSuchItemException") {
assertThat({ subject[invalidItem] = 1024 },
throws(has(NoSuchItemException::name, equalTo(invalidItem.name))))
}
}
on("set with incorrect type of value") {
it("should throw ClassCastException") {
assertThat({ subject[size.name] = "1024" }, throws<ClassCastException>())
}
}
on("lazy set with valid item") {
subject.lazySet(maxSize) { it[size] * 4 }
subject[size] = 1024
it("should contain the specified value") {
assertThat(subject[maxSize], equalTo(subject[size] * 4))
}
}
on("lazy set with valid name") {
subject.lazySet(maxSize.name) { it[size] * 4 }
subject[size] = 1024
it("should contain the specified value") {
assertThat(subject[maxSize], equalTo(subject[size] * 4))
}
}
on("lazy set with valid name and invalid value with incompatible type") {
subject.lazySet(maxSize.name) { "string" }
it("should throw InvalidLazySetException when getting") {
assertThat({ subject[maxSize.name] }, throws<InvalidLazySetException>())
}
}
on("unset with valid item") {
subject.unset(type)
it("should contain `null` when using `getOrNull`") {
assertThat(subject.getOrNull(type), absent())
}
}
on("unset with valid name") {
subject.unset(type.name)
it("should contain `null` when using `getOrNull`") {
assertThat(subject.getOrNull(type), absent())
}
}
}
group("item property") {
on("declare a property by item") {
var nameProperty by subject.property(name)
it("should behave same as `get`") {
assertThat(nameProperty, equalTo(subject[name]))
}
it("should support set operation as `set`") {
nameProperty = "newName"
assertThat(nameProperty, equalTo("newName"))
}
}
on("declare a property by name") {
var nameProperty by subject.property<String>(name.name)
it("should behave same as `get`") {
assertThat(nameProperty, equalTo(subject[name]))
}
it("should support set operation as `set`") {
nameProperty = "newName"
assertThat(nameProperty, equalTo("newName"))
}
}
}
}
})
| konf/src/test/kotlin/com/uchuhimo/konf/ConfigSpek.kt | 489576567 |
package OpenSourceProjects_Storybook.buildTypes
import jetbrains.buildServer.configs.kotlin.v2017_2.*
import jetbrains.buildServer.configs.kotlin.v2017_2.buildFeatures.commitStatusPublisher
import jetbrains.buildServer.configs.kotlin.v2017_2.buildSteps.script
import jetbrains.buildServer.configs.kotlin.v2017_2.failureConditions.BuildFailureOnMetric
import jetbrains.buildServer.configs.kotlin.v2017_2.failureConditions.failOnMetricChange
object OpenSourceProjects_Storybook_CRA : BuildType({
uuid = "8cc5f747-4ca7-4f0d-940d-b0c422f501a6-cra"
id = "OpenSourceProjects_Storybook_CRA"
name = "CRA"
artifactRules = "examples/cra-kitchen-sink/storybook-static => cra.zip"
vcs {
root(OpenSourceProjects_Storybook.vcsRoots.OpenSourceProjects_Storybook_HttpsGithubComStorybooksStorybookRefsHeadsMaster)
}
steps {
script {
name = "Bootstrap"
scriptContent = """
yarn
yarn bootstrap --core
""".trimIndent()
dockerImage = "node:latest"
}
script {
name = "build"
scriptContent = """
#!/bin/sh
set -e -x
cd examples/cra-kitchen-sink
yarn build-storybook
""".trimIndent()
dockerImage = "node:latest"
}
}
failureConditions {
failOnMetricChange {
metric = BuildFailureOnMetric.MetricType.ARTIFACT_SIZE
threshold = 50
units = BuildFailureOnMetric.MetricUnit.PERCENTS
comparison = BuildFailureOnMetric.MetricComparison.LESS
compareTo = build {
buildRule = lastSuccessful()
}
}
}
features {
commitStatusPublisher {
publisher = github {
githubUrl = "https://api.github.com"
authType = personalToken {
token = "credentialsJSON:5ffe2d7e-531e-4f6f-b1fc-a41bfea26eaa"
}
}
param("github_oauth_user", "Hypnosphi")
}
}
requirements {
doesNotContain("env.OS", "Windows")
}
})
| .teamcity/OpenSourceProjects_Storybook/buildTypes/OpenSourceProjects_Storybook_CRA.kt | 3417118383 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.util
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.support.customtabs.CustomTabsIntent
import android.support.v4.app.ActivityCompat
import android.support.v4.app.FragmentActivity
import android.text.TextUtils
import org.mariotaku.chameleon.Chameleon
import org.mariotaku.chameleon.ChameleonUtils
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.BuildConfig
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.activity.MediaViewerActivity
import de.vanita5.twittnuker.app.TwittnukerApplication
import de.vanita5.twittnuker.constant.chromeCustomTabKey
import de.vanita5.twittnuker.fragment.SensitiveContentWarningDialogFragment
import de.vanita5.twittnuker.model.*
import de.vanita5.twittnuker.model.util.ParcelableLocationUtils
import de.vanita5.twittnuker.model.util.ParcelableMediaUtils
import de.vanita5.twittnuker.util.LinkCreator.getTwidereUserListRelatedLink
import java.util.*
object IntentUtils {
fun getStatusShareText(context: Context, status: ParcelableStatus): String {
val link = LinkCreator.getStatusWebLink(status)
return context.getString(R.string.status_share_text_format_with_link,
status.text_plain, link.toString())
}
fun getStatusShareSubject(context: Context, status: ParcelableStatus): String {
val timeString = Utils.formatToLongTimeString(context, status.timestamp)
return context.getString(R.string.status_share_subject_format_with_time,
status.user_name, status.user_screen_name, timeString)
}
fun openUserProfile(context: Context, user: ParcelableUser, newDocument: Boolean,
activityOptions: Bundle? = null) {
val intent = userProfile(user)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && newDocument) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
}
ActivityCompat.startActivity(context, intent, activityOptions)
}
fun openUserProfile(context: Context, accountKey: UserKey?,
userKey: UserKey?, screenName: String?, profileUrl: String?,
newDocument: Boolean, activityOptions: Bundle? = null) {
val intent = userProfile(accountKey, userKey, screenName, profileUrl)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && newDocument) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
}
ActivityCompat.startActivity(context, intent, activityOptions)
}
fun userProfile(user: ParcelableUser): Intent {
val uri = LinkCreator.getTwidereUserLink(user.account_key, user.key, user.screen_name)
val intent = uri.intent()
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
intent.putExtra(EXTRA_USER, user)
if (user.extras != null) {
intent.putExtra(EXTRA_PROFILE_URL, user.extras?.statusnet_profile_url)
}
return intent
}
fun userProfile(accountKey: UserKey?, userKey: UserKey?, screenName: String?,
profileUrl: String? = null, accountHost: String? = accountKey?.host ?: userKey?.host): Intent {
val uri = LinkCreator.getTwidereUserLink(accountKey, userKey, screenName)
val intent = uri.intent()
intent.putExtra(EXTRA_PROFILE_URL, profileUrl)
intent.putExtra(EXTRA_ACCOUNT_HOST, accountHost)
return intent
}
fun userTimeline(accountKey: UserKey?, userKey: UserKey?, screenName: String?,
profileUrl: String? = null): Intent {
val uri = LinkCreator.getTwidereUserRelatedLink(AUTHORITY_USER_TIMELINE, accountKey,
userKey, screenName)
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.putExtra(EXTRA_PROFILE_URL, profileUrl)
return intent
}
fun userMediaTimeline(accountKey: UserKey?, userKey: UserKey?, screenName: String?,
profileUrl: String? = null): Intent {
val uri = LinkCreator.getTwidereUserRelatedLink(AUTHORITY_USER_MEDIA_TIMELINE, accountKey,
userKey, screenName)
val intent = uri.intent()
intent.putExtra(EXTRA_PROFILE_URL, profileUrl)
return intent
}
fun userFavorites(accountKey: UserKey?, userKey: UserKey?, screenName: String?,
profileUrl: String? = null): Intent {
val uri = LinkCreator.getTwidereUserRelatedLink(AUTHORITY_USER_FAVORITES, accountKey,
userKey, screenName)
val intent = uri.intent()
intent.putExtra(EXTRA_PROFILE_URL, profileUrl)
return intent
}
fun openItems(context: Context, items: List<Parcelable>?) {
if (items == null) return
val extras = Bundle()
extras.putParcelableArrayList(EXTRA_ITEMS, ArrayList(items))
val builder = UriBuilder(AUTHORITY_ITEMS)
val intent = builder.intent()
intent.putExtras(extras)
context.startActivity(intent)
}
fun openUserMentions(context: Context, accountKey: UserKey?,
screenName: String) {
val builder = UriBuilder(AUTHORITY_USER_MENTIONS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
context.startActivity(builder.intent())
}
fun openMedia(context: Context, status: ParcelableStatus,
current: ParcelableMedia? = null, newDocument: Boolean,
displaySensitiveContents: Boolean, options: Bundle? = null) {
val media = ParcelableMediaUtils.getPrimaryMedia(status) ?: return
openMedia(context, status.account_key, status.is_possibly_sensitive, status, current,
media, newDocument, displaySensitiveContents, options)
}
fun openMedia(context: Context, accountKey: UserKey?, media: Array<ParcelableMedia>,
current: ParcelableMedia? = null, isPossiblySensitive: Boolean,
newDocument: Boolean, displaySensitiveContents: Boolean, options: Bundle? = null) {
openMedia(context, accountKey, isPossiblySensitive, null, current, media, newDocument,
displaySensitiveContents, options)
}
fun openMedia(context: Context, accountKey: UserKey?, isPossiblySensitive: Boolean,
status: ParcelableStatus?, current: ParcelableMedia? = null, media: Array<ParcelableMedia>,
newDocument: Boolean, displaySensitiveContents: Boolean,
options: Bundle? = null) {
if (context is FragmentActivity && isPossiblySensitive && !displaySensitiveContents) {
val fm = context.supportFragmentManager
val fragment = SensitiveContentWarningDialogFragment()
val args = Bundle()
args.putParcelable(EXTRA_ACCOUNT_KEY, accountKey)
args.putParcelable(EXTRA_CURRENT_MEDIA, current)
if (status != null) {
args.putParcelable(EXTRA_STATUS, status)
}
args.putParcelableArray(EXTRA_MEDIA, media)
args.putBundle(EXTRA_ACTIVITY_OPTIONS, options)
args.putBoolean(EXTRA_NEW_DOCUMENT, newDocument)
fragment.arguments = args
fragment.show(fm, "sensitive_content_warning")
} else {
openMediaDirectly(context, accountKey, media, current, options, newDocument, status)
}
}
fun openMediaDirectly(context: Context, accountKey: UserKey?, status: ParcelableStatus,
current: ParcelableMedia, newDocument: Boolean, options: Bundle? = null) {
val media = ParcelableMediaUtils.getPrimaryMedia(status) ?: return
openMediaDirectly(context, accountKey, media, current, options, newDocument, status)
}
fun getDefaultBrowserPackage(context: Context, uri: Uri, checkHandled: Boolean): String? {
if (checkHandled && !isWebLinkHandled(context, uri)) {
return null
}
val intent = Intent(Intent.ACTION_VIEW)
intent.addCategory(Intent.CATEGORY_BROWSABLE)
intent.data = Uri.parse("${uri.scheme}://")
return intent.resolveActivity(context.packageManager)?.takeIf {
it.className != null && it.packageName != "android"
}?.packageName
}
fun isWebLinkHandled(context: Context, uri: Uri): Boolean {
val filter = getWebLinkIntentFilter(context) ?: return false
return filter.match(Intent.ACTION_VIEW, null, uri.scheme, uri,
setOf(Intent.CATEGORY_BROWSABLE), LOGTAG) >= 0
}
fun getWebLinkIntentFilter(context: Context): IntentFilter? {
val testIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/user_name"))
testIntent.addCategory(Intent.CATEGORY_BROWSABLE)
testIntent.`package` = context.packageName
val resolveInfo = context.packageManager.resolveActivity(testIntent,
PackageManager.GET_RESOLVED_FILTER)
return resolveInfo?.filter
}
fun openMediaDirectly(context: Context, accountKey: UserKey?, media: Array<ParcelableMedia>,
current: ParcelableMedia? = null, options: Bundle? = null, newDocument: Boolean,
status: ParcelableStatus? = null, message: ParcelableMessage? = null) {
val intent = Intent(context, MediaViewerActivity::class.java)
intent.putExtra(EXTRA_ACCOUNT_KEY, accountKey)
intent.putExtra(EXTRA_CURRENT_MEDIA, current)
intent.putExtra(EXTRA_MEDIA, media)
if (status != null) {
intent.putExtra(EXTRA_STATUS, status)
intent.data = getMediaViewerUri("status", status.id, accountKey)
}
if (message != null) {
intent.putExtra(EXTRA_MESSAGE, message)
intent.data = getMediaViewerUri("message", message.id, accountKey)
}
if (newDocument && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
}
ActivityCompat.startActivity(context, intent, options)
}
fun getMediaViewerUri(type: String, id: String,
accountKey: UserKey?): Uri {
val builder = Uri.Builder()
builder.scheme(SCHEME_TWITTNUKER)
builder.authority("media")
builder.appendPath(type)
builder.appendPath(id)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
return builder.build()
}
fun openMessageConversation(context: Context, accountKey: UserKey, conversationId: String) {
context.startActivity(messageConversation(accountKey, conversationId))
}
fun messageConversation(accountKey: UserKey, conversationId: String): Intent {
val builder = UriBuilder(AUTHORITY_MESSAGES)
builder.path(PATH_MESSAGES_CONVERSATION)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, conversationId)
return builder.intent()
}
fun messageConversationInfo(accountKey: UserKey, conversationId: String): Intent {
val builder = UriBuilder(AUTHORITY_MESSAGES)
builder.path(PATH_MESSAGES_CONVERSATION_INFO)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, conversationId)
return builder.intent()
}
fun newMessageConversation(accountKey: UserKey): Intent {
val builder = UriBuilder(AUTHORITY_MESSAGES)
builder.path(PATH_MESSAGES_CONVERSATION_NEW)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
return builder.intent()
}
fun openIncomingFriendships(context: Context,
accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_INCOMING_FRIENDSHIPS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openMap(context: Context, latitude: Double, longitude: Double) {
if (!ParcelableLocationUtils.isValidLocation(latitude, longitude)) return
val builder = UriBuilder(AUTHORITY_MAP)
builder.appendQueryParameter(QUERY_PARAM_LAT, latitude.toString())
builder.appendQueryParameter(QUERY_PARAM_LNG, longitude.toString())
context.startActivity(builder.intent())
}
fun openMutesUsers(context: Context,
accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_MUTES_USERS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openSavedSearches(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_SAVED_SEARCHES)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openSearch(context: Context, accountKey: UserKey?, query: String, type: String? = null) {
val builder = UriBuilder(AUTHORITY_SEARCH)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_QUERY, query)
if (!TextUtils.isEmpty(type)) {
builder.appendQueryParameter(QUERY_PARAM_TYPE, type)
}
val intent = builder.intent()
// Some devices cannot process query parameter with hashes well, so add this intent extra
intent.putExtra(EXTRA_QUERY, query)
if (!TextUtils.isEmpty(type)) {
intent.putExtra(EXTRA_TYPE, type)
}
if (accountKey != null) {
intent.putExtra(EXTRA_ACCOUNT_KEY, accountKey)
}
context.startActivity(intent)
}
fun openMastodonSearch(context: Context, accountKey: UserKey?, query: String) {
val builder = UriBuilder(AUTHORITY_MASTODON_SEARCH)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_QUERY, query)
val intent = builder.intent()
// Some devices cannot process query parameter with hashes well, so add this intent extra
intent.putExtra(EXTRA_QUERY, query)
if (accountKey != null) {
intent.putExtra(EXTRA_ACCOUNT_KEY, accountKey)
}
context.startActivity(intent)
}
fun status(accountKey: UserKey?, statusId: String): Intent {
val uri = LinkCreator.getTwidereStatusLink(accountKey, statusId)
return Intent(Intent.ACTION_VIEW, uri).setPackage(BuildConfig.APPLICATION_ID)
}
fun openStatus(context: Context, accountKey: UserKey?, statusId: String) {
context.startActivity(status(accountKey, statusId))
}
fun openStatus(context: Context, status: ParcelableStatus, activityOptions: Bundle? = null) {
val intent = status(status.account_key, status.id)
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
intent.putExtra(EXTRA_STATUS, status)
ActivityCompat.startActivity(context, intent, activityOptions)
}
fun openStatusFavoriters(context: Context, accountKey: UserKey?, statusId: String) {
val builder = UriBuilder(AUTHORITY_STATUS_FAVORITERS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_STATUS_ID, statusId)
ActivityCompat.startActivity(context, builder.intent(), null)
}
fun openStatusRetweeters(context: Context, accountKey: UserKey?, statusId: String) {
val builder = UriBuilder(AUTHORITY_STATUS_RETWEETERS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
builder.appendQueryParameter(QUERY_PARAM_STATUS_ID, statusId)
ActivityCompat.startActivity(context, builder.intent(), null)
}
fun openTweetSearch(context: Context, accountKey: UserKey?, query: String) {
openSearch(context, accountKey, query, QUERY_PARAM_VALUE_TWEETS)
}
fun openUserBlocks(activity: Activity?, accountKey: UserKey) {
if (activity == null) return
val builder = UriBuilder(AUTHORITY_USER_BLOCKS)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
activity.startActivity(builder.intent())
}
fun openUserFavorites(context: Context, accountKey: UserKey?, userKey: UserKey?,
screenName: String?) {
val builder = UriBuilder(AUTHORITY_USER_FAVORITES)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
if (userKey != null) {
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
}
if (screenName != null) {
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
}
context.startActivity(builder.intent())
}
fun openUserFollowers(context: Context, accountKey: UserKey?, userKey: UserKey?,
screenName: String?) {
val intent = LinkCreator.getTwidereUserRelatedLink(AUTHORITY_USER_FOLLOWERS,
accountKey, userKey, screenName)
context.startActivity(Intent(Intent.ACTION_VIEW, intent))
}
fun openUserFriends(context: Context, accountKey: UserKey?, userKey: UserKey?,
screenName: String?) {
val builder = UriBuilder(AUTHORITY_USER_FRIENDS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
if (userKey != null) {
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
}
if (screenName != null) {
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
}
context.startActivity(builder.intent())
}
fun openUserListDetails(context: Context, accountKey: UserKey?, listId: String?,
userKey: UserKey?, screenName: String?, listName: String?) {
context.startActivity(userListDetails(accountKey, listId, userKey, screenName, listName))
}
fun userListDetails(accountKey: UserKey?, listId: String?, userKey: UserKey?,
screenName: String?, listName: String?): Intent {
return getTwidereUserListRelatedLink(AUTHORITY_USER_LIST, accountKey, listId, userKey,
screenName, listName).intent()
}
fun userListTimeline(accountKey: UserKey?, listId: String?, userKey: UserKey?,
screenName: String?, listName: String?): Intent {
return getTwidereUserListRelatedLink(AUTHORITY_USER_LIST_TIMELINE, accountKey, listId,
userKey, screenName, listName).intent()
}
fun openUserListDetails(context: Context, userList: ParcelableUserList) {
context.startActivity(userListDetails(userList))
}
fun userListDetails(userList: ParcelableUserList): Intent {
val userKey = userList.user_key
val listId = userList.id
val builder = UriBuilder(AUTHORITY_USER_LIST)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, userList.account_key.toString())
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
builder.appendQueryParameter(QUERY_PARAM_LIST_ID, listId)
val intent = builder.intent()
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
intent.putExtra(EXTRA_USER_LIST, userList)
return intent
}
fun openGroupDetails(context: Context, group: ParcelableGroup) {
val builder = UriBuilder(AUTHORITY_GROUP)
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, group.account_key.toString())
builder.appendQueryParameter(QUERY_PARAM_GROUP_ID, group.id)
builder.appendQueryParameter(QUERY_PARAM_GROUP_NAME, group.nickname)
val intent = builder.intent()
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
intent.putExtra(EXTRA_GROUP, group)
context.startActivity(intent)
}
fun openUserLists(context: Context, accountKey: UserKey?, userKey: UserKey?, screenName: String?) {
val builder = Uri.Builder()
builder.scheme(SCHEME_TWITTNUKER)
builder.authority(AUTHORITY_USER_LISTS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
if (userKey != null) {
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
}
if (screenName != null) {
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
}
context.startActivity(builder.intent())
}
fun openUserGroups(context: Context, accountKey: UserKey?, userKey: UserKey?, screenName: String?) {
val builder = UriBuilder(AUTHORITY_USER_GROUPS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
if (userKey != null) {
builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString())
}
if (screenName != null) {
builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName)
}
context.startActivity(builder.intent())
}
fun openDirectMessages(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_MESSAGES)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openInteractions(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_INTERACTIONS)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openPublicTimeline(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_PUBLIC_TIMELINE)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openNetworkPublicTimeline(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_NETWORK_PUBLIC_TIMELINE)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openAccountsManager(context: Context) {
val builder = UriBuilder(AUTHORITY_ACCOUNTS)
context.startActivity(builder.intent())
}
fun openDrafts(context: Context) {
val builder = UriBuilder(AUTHORITY_DRAFTS)
context.startActivity(builder.intent())
}
fun settings(initialTag: String? = null): Intent {
val builder = Uri.Builder()
builder.scheme(SCHEME_TWITTNUKER_SETTINGS)
builder.authority(initialTag.orEmpty())
return builder.intent(Intent.ACTION_MAIN)
}
fun openProfileEditor(context: Context, accountKey: UserKey?) {
val builder = UriBuilder(AUTHORITY_PROFILE_EDITOR)
if (accountKey != null) {
builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_KEY, accountKey.toString())
}
context.startActivity(builder.intent())
}
fun openFilters(context: Context, initialTab: String? = null) {
val builder = UriBuilder(AUTHORITY_FILTERS)
val intent = builder.intent()
intent.putExtra(EXTRA_INITIAL_TAB, initialTab)
context.startActivity(intent)
}
fun browse(context: Context, preferences: SharedPreferences,
theme: Chameleon.Theme? = Chameleon.getOverrideTheme(context, ChameleonUtils.getActivity(context)),
uri: Uri, forceBrowser: Boolean = true): Pair<Intent, Bundle?> {
if (!preferences[chromeCustomTabKey]) {
val viewIntent = Intent(Intent.ACTION_VIEW, uri)
viewIntent.addCategory(Intent.CATEGORY_BROWSABLE)
return Pair(viewIntent, null)
}
val builder = CustomTabsIntent.Builder()
builder.addDefaultShareMenuItem()
theme?.let { t ->
builder.setToolbarColor(t.colorToolbar)
}
val customTabsIntent = builder.build()
val intent = customTabsIntent.intent
intent.data = uri
if (forceBrowser) {
intent.`package` = getDefaultBrowserPackage(context, uri, false)
}
return Pair(intent, customTabsIntent.startAnimationBundle)
}
fun applyNewDocument(intent: Intent, enable: Boolean) {
if (enable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
}
}
fun UriBuilder(authority: String): Uri.Builder {
return Uri.Builder().scheme(SCHEME_TWITTNUKER).authority(authority)
}
private fun Uri.intent(action: String = Intent.ACTION_VIEW): Intent {
return Intent(action, this).setPackage(BuildConfig.APPLICATION_ID)
}
private fun Uri.Builder.intent(action: String = Intent.ACTION_VIEW): Intent {
return build().intent(action)
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/IntentUtils.kt | 2338311734 |
package com.matejdro.wearmusiccenter.watch
import android.content.pm.ApplicationInfo
import android.preference.PreferenceManager
import com.matejdro.wearmusiccenter.watch.config.PreferencesBus
import com.matejdro.wearutils.logging.FileLogger
import com.matejdro.wearutils.logging.TimberExceptionWear
import dagger.hilt.android.HiltAndroidApp
import pl.tajchert.exceptionwear.ExceptionWear
import timber.log.Timber
@HiltAndroidApp
class WearMusicCenter : android.app.Application() {
override fun onCreate() {
super.onCreate()
val isDebuggable = applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
Timber.setAppTag("WearMusicCenter")
Timber.plant(Timber.AndroidDebugTree(isDebuggable))
if (!isDebuggable) {
ExceptionWear.initialize(this)
Timber.plant(TimberExceptionWear(this))
}
val fileLogger = FileLogger.getInstance(this)
fileLogger.activate()
Timber.plant(fileLogger)
PreferencesBus.value = PreferenceManager.getDefaultSharedPreferences(this)
}
} | wear/src/main/java/com/matejdro/wearmusiccenter/watch/WearMusicCenter.kt | 3016346099 |
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.cupcake
import android.content.Context
import android.content.Intent
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.cupcake.data.DataSource.flavors
import com.example.cupcake.data.DataSource.quantityOptions
import com.example.cupcake.data.OrderUiState
import com.example.cupcake.ui.OrderSummaryScreen
import com.example.cupcake.ui.OrderViewModel
import com.example.cupcake.ui.SelectOptionScreen
import com.example.cupcake.ui.StartOrderScreen
/**
* enum values that represent the screens in the app
*/
enum class CupcakeScreen(@StringRes val title: Int) {
Start(title = R.string.app_name),
Flavor(title = R.string.choose_flavor),
Pickup(title = R.string.choose_pickup_date),
Summary(title = R.string.order_summary)
}
/**
* Composable that displays the topBar and displays back button if back navigation is possible.
*/
@Composable
fun CupcakeAppBar(
currentScreen: CupcakeScreen,
canNavigateBack: Boolean,
navigateUp: () -> Unit,
modifier: Modifier = Modifier
) {
TopAppBar(
title = { Text(stringResource(currentScreen.title)) },
modifier = modifier,
navigationIcon = {
if (canNavigateBack) {
IconButton(onClick = navigateUp) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = stringResource(R.string.back_button)
)
}
}
}
)
}
@Composable
fun CupcakeApp(
modifier: Modifier = Modifier,
viewModel: OrderViewModel = viewModel(),
navController: NavHostController = rememberNavController()
) {
// Get current back stack entry
val backStackEntry by navController.currentBackStackEntryAsState()
// Get the name of the current screen
val currentScreen = CupcakeScreen.valueOf(
backStackEntry?.destination?.route ?: CupcakeScreen.Start.name
)
Scaffold(
topBar = {
CupcakeAppBar(
currentScreen = currentScreen,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() }
)
}
) { innerPadding ->
val uiState by viewModel.uiState.collectAsState()
NavHost(
navController = navController,
startDestination = CupcakeScreen.Start.name,
modifier = modifier.padding(innerPadding)
) {
composable(route = CupcakeScreen.Start.name) {
StartOrderScreen(
quantityOptions = quantityOptions,
onNextButtonClicked = {
viewModel.setQuantity(it)
navController.navigate(CupcakeScreen.Flavor.name)
}
)
}
composable(route = CupcakeScreen.Flavor.name) {
val context = LocalContext.current
SelectOptionScreen(
subtotal = uiState.price,
onNextButtonClicked = { navController.navigate(CupcakeScreen.Pickup.name) },
onCancelButtonClicked = {
cancelOrderAndNavigateToStart(viewModel, navController)
},
options = flavors.map { id -> context.resources.getString(id) },
onSelectionChanged = { viewModel.setFlavor(it) }
)
}
composable(route = CupcakeScreen.Pickup.name) {
SelectOptionScreen(
subtotal = uiState.price,
onNextButtonClicked = { navController.navigate(CupcakeScreen.Summary.name) },
onCancelButtonClicked = {
cancelOrderAndNavigateToStart(viewModel, navController)
},
options = uiState.pickupOptions,
onSelectionChanged = { viewModel.setDate(it) }
)
}
composable(route = CupcakeScreen.Summary.name) {
val context = LocalContext.current
OrderSummaryScreen(
orderUiState = uiState,
onCancelButtonClicked = {
cancelOrderAndNavigateToStart(viewModel, navController)
},
onSendButtonClicked = { subject: String, summary: String ->
shareOrder(context, subject = subject, summary = summary)
}
)
}
}
}
}
/**
* Resets the [OrderUiState] and pops up to [CupcakeScreen.Start]
*/
private fun cancelOrderAndNavigateToStart(
viewModel: OrderViewModel,
navController: NavHostController
) {
viewModel.resetOrder()
navController.popBackStack(CupcakeScreen.Start.name, inclusive = false)
}
/**
* Creates an intent to share order details
*/
private fun shareOrder(context: Context, subject: String, summary: String) {
// Create an ACTION_SEND implicit intent with order details in the intent extras
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_SUBJECT, subject)
putExtra(Intent.EXTRA_TEXT, summary)
}
context.startActivity(
Intent.createChooser(
intent,
context.getString(R.string.new_cupcake_order)
)
)
}
| app/src/main/java/com/example/cupcake/CupcakeScreen.kt | 2762077916 |
package versioned.host.exp.exponent.modules.universal.sensors
import expo.modules.core.interfaces.InternalModule
import expo.modules.interfaces.sensors.services.MagnetometerUncalibratedServiceInterface
import host.exp.exponent.kernel.ExperienceKey
import host.exp.exponent.kernel.services.sensors.SubscribableSensorKernelService
class ScopedMagnetometerUncalibratedService(experienceKey: ExperienceKey) : BaseSensorService(experienceKey), InternalModule, MagnetometerUncalibratedServiceInterface {
override val sensorKernelService: SubscribableSensorKernelService
get() = kernelServiceRegistry.magnetometerUncalibratedKernelService
override fun getExportedInterfaces(): List<Class<*>> {
return listOf(MagnetometerUncalibratedServiceInterface::class.java)
}
}
| android/expoview/src/main/java/versioned/host/exp/exponent/modules/universal/sensors/ScopedMagnetometerUncalibratedService.kt | 317187575 |
// Copyright 2015-present 650 Industries. All rights reserved.
package versioned.host.exp.exponent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import com.facebook.common.logging.FLog
import com.facebook.hermes.reactexecutor.HermesExecutorFactory
import com.facebook.react.ReactInstanceManager
import com.facebook.react.ReactInstanceManagerBuilder
import com.facebook.react.bridge.JavaScriptContextHolder
import com.facebook.react.bridge.JavaScriptExecutorFactory
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.common.LifecycleState
import com.facebook.react.common.ReactConstants
import com.facebook.react.jscexecutor.JSCExecutorFactory
import com.facebook.react.modules.systeminfo.AndroidInfoHelpers
import com.facebook.react.packagerconnection.NotificationOnlyHandler
import com.facebook.react.packagerconnection.RequestHandler
import com.facebook.react.shell.MainReactPackage
import expo.modules.jsonutils.getNullable
import host.exp.exponent.Constants
import host.exp.exponent.RNObject
import host.exp.exponent.experience.ExperienceActivity
import host.exp.exponent.experience.ReactNativeActivity
import host.exp.exponent.kernel.KernelProvider
import host.exp.expoview.Exponent
import host.exp.expoview.Exponent.InstanceManagerBuilderProperties
import org.json.JSONObject
import versioned.host.exp.exponent.modules.api.reanimated.ReanimatedJSIModulePackage
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*
object VersionedUtils {
// Update this value when hermes-engine getting updated.
// Currently there is no way to retrieve Hermes bytecode version from Java,
// as an alternative, we maintain the version by hand.
private const val HERMES_BYTECODE_VERSION = 76
private fun toggleExpoDevMenu() {
val currentActivity = Exponent.instance.currentActivity
if (currentActivity is ExperienceActivity) {
currentActivity.toggleDevMenu()
} else {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the Expo dev menu because the current activity could not be found."
)
}
}
private fun reloadExpoApp() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to reload the app because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
devSupportManager.callRecursive("reloadExpoApp")
}
private fun toggleElementInspector() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the element inspector because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
devSupportManager.callRecursive("toggleElementInspector")
}
private fun requestOverlayPermission(context: Context) {
// From the unexposed DebugOverlayController static helper
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Get permission to show debug overlay in dev builds.
if (!Settings.canDrawOverlays(context)) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + context.packageName)
).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
FLog.w(
ReactConstants.TAG,
"Overlay permissions needs to be granted in order for React Native apps to run in development mode"
)
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
}
}
}
}
private fun togglePerformanceMonitor() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the performance monitor because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
if (devSettings != null) {
val isFpsDebugEnabled = devSettings.call("isFpsDebugEnabled") as Boolean
if (!isFpsDebugEnabled) {
// Request overlay permission if needed when "Show Perf Monitor" option is selected
requestOverlayPermission(currentActivity)
}
devSettings.call("setFpsDebugEnabled", !isFpsDebugEnabled)
}
}
private fun toggleRemoteJSDebugging() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle remote JS debugging because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
if (devSettings != null) {
val isRemoteJSDebugEnabled = devSettings.call("isRemoteJSDebugEnabled") as Boolean
devSettings.call("setRemoteJSDebugEnabled", !isRemoteJSDebugEnabled)
}
}
private fun createPackagerCommandHelpers(): Map<String, RequestHandler> {
// Attach listeners to the bundler's dev server web socket connection.
// This enables tools to automatically reload the client remotely (i.e. in expo-cli).
val packagerCommandHandlers = mutableMapOf<String, RequestHandler>()
// Enable a lot of tools under the same command namespace
packagerCommandHandlers["sendDevCommand"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
if (params != null && params is JSONObject) {
when (params.getNullable<String>("name")) {
"reload" -> reloadExpoApp()
"toggleDevMenu" -> toggleExpoDevMenu()
"toggleRemoteDebugging" -> {
toggleRemoteJSDebugging()
// Reload the app after toggling debugging, this is based on what we do in DevSupportManagerBase.
reloadExpoApp()
}
"toggleElementInspector" -> toggleElementInspector()
"togglePerformanceMonitor" -> togglePerformanceMonitor()
}
}
}
}
// These commands (reload and devMenu) are here to match RN dev tooling.
// Reload the app on "reload"
packagerCommandHandlers["reload"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
reloadExpoApp()
}
}
// Open the dev menu on "devMenu"
packagerCommandHandlers["devMenu"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
toggleExpoDevMenu()
}
}
return packagerCommandHandlers
}
@JvmStatic fun getReactInstanceManagerBuilder(instanceManagerBuilderProperties: InstanceManagerBuilderProperties): ReactInstanceManagerBuilder {
// Build the instance manager
var builder = ReactInstanceManager.builder()
.setApplication(instanceManagerBuilderProperties.application)
.setJSIModulesPackage { reactApplicationContext: ReactApplicationContext, jsContext: JavaScriptContextHolder? ->
val devSupportManager = getDevSupportManager(reactApplicationContext)
if (devSupportManager == null) {
Log.e(
"Exponent",
"Couldn't get the `DevSupportManager`. JSI modules won't be initialized."
)
return@setJSIModulesPackage emptyList()
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
val isRemoteJSDebugEnabled = devSettings != null && devSettings.call("isRemoteJSDebugEnabled") as Boolean
if (!isRemoteJSDebugEnabled) {
return@setJSIModulesPackage ReanimatedJSIModulePackage().getJSIModules(
reactApplicationContext,
jsContext
)
}
emptyList()
}
.addPackage(MainReactPackage())
.addPackage(
ExponentPackage(
instanceManagerBuilderProperties.experienceProperties,
instanceManagerBuilderProperties.manifest,
// DO NOT EDIT THIS COMMENT - used by versioning scripts
// When distributing change the following two arguments to nulls
instanceManagerBuilderProperties.expoPackages,
instanceManagerBuilderProperties.exponentPackageDelegate,
instanceManagerBuilderProperties.singletonModules
)
)
.addPackage(
ExpoTurboPackage(
instanceManagerBuilderProperties.experienceProperties,
instanceManagerBuilderProperties.manifest
)
)
.setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
.setCustomPackagerCommandHandlers(createPackagerCommandHelpers())
.setJavaScriptExecutorFactory(createJSExecutorFactory(instanceManagerBuilderProperties))
if (instanceManagerBuilderProperties.jsBundlePath != null && instanceManagerBuilderProperties.jsBundlePath!!.isNotEmpty()) {
builder = builder.setJSBundleFile(instanceManagerBuilderProperties.jsBundlePath)
}
return builder
}
private fun getDevSupportManager(reactApplicationContext: ReactApplicationContext): RNObject? {
val currentActivity = Exponent.instance.currentActivity
return if (currentActivity != null) {
if (currentActivity is ReactNativeActivity) {
currentActivity.devSupportManager
} else {
null
}
} else try {
val devSettingsModule = reactApplicationContext.catalystInstance.getNativeModule("DevSettings")
val devSupportManagerField = devSettingsModule!!.javaClass.getDeclaredField("mDevSupportManager")
devSupportManagerField.isAccessible = true
RNObject.wrap(devSupportManagerField[devSettingsModule]!!)
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
private fun createJSExecutorFactory(
instanceManagerBuilderProperties: InstanceManagerBuilderProperties
): JavaScriptExecutorFactory? {
val appName = instanceManagerBuilderProperties.manifest.getName() ?: ""
val deviceName = AndroidInfoHelpers.getFriendlyDeviceName()
if (Constants.isStandaloneApp()) {
return JSCExecutorFactory(appName, deviceName)
}
val hermesBundlePair = parseHermesBundleHeader(instanceManagerBuilderProperties.jsBundlePath)
if (hermesBundlePair.first && hermesBundlePair.second != HERMES_BYTECODE_VERSION) {
val message = String.format(
Locale.US,
"Unable to load unsupported Hermes bundle.\n\tsupportedBytecodeVersion: %d\n\ttargetBytecodeVersion: %d",
HERMES_BYTECODE_VERSION, hermesBundlePair.second
)
KernelProvider.instance.handleError(RuntimeException(message))
return null
}
val jsEngineFromManifest = instanceManagerBuilderProperties.manifest.getAndroidJsEngine()
return if (jsEngineFromManifest == "hermes") HermesExecutorFactory() else JSCExecutorFactory(
appName,
deviceName
)
}
private fun parseHermesBundleHeader(jsBundlePath: String?): Pair<Boolean, Int> {
if (jsBundlePath == null || jsBundlePath.isEmpty()) {
return Pair(false, 0)
}
// https://github.com/facebook/hermes/blob/release-v0.5/include/hermes/BCGen/HBC/BytecodeFileFormat.h#L24-L25
val HERMES_MAGIC_HEADER = byteArrayOf(
0xc6.toByte(), 0x1f.toByte(), 0xbc.toByte(), 0x03.toByte(),
0xc1.toByte(), 0x03.toByte(), 0x19.toByte(), 0x1f.toByte()
)
val file = File(jsBundlePath)
try {
FileInputStream(file).use { inputStream ->
val bytes = ByteArray(12)
inputStream.read(bytes, 0, bytes.size)
// Magic header
for (i in HERMES_MAGIC_HEADER.indices) {
if (bytes[i] != HERMES_MAGIC_HEADER[i]) {
return Pair(false, 0)
}
}
// Bytecode version
val bundleBytecodeVersion: Int =
(bytes[11].toInt() shl 24) or (bytes[10].toInt() shl 16) or (bytes[9].toInt() shl 8) or bytes[8].toInt()
return Pair(true, bundleBytecodeVersion)
}
} catch (e: FileNotFoundException) {
} catch (e: IOException) {
}
return Pair(false, 0)
}
internal fun isHermesBundle(jsBundlePath: String?): Boolean {
return parseHermesBundleHeader(jsBundlePath).first
}
internal fun getHermesBundleBytecodeVersion(jsBundlePath: String?): Int {
return parseHermesBundleHeader(jsBundlePath).second
}
}
| android/expoview/src/main/java/versioned/host/exp/exponent/VersionedUtils.kt | 843155716 |
/*
* Copyright (C) 2016 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.sqlite.db
/**
* An interface to map the behavior of [android.database.sqlite.SQLiteStatement].
*/
interface SupportSQLiteStatement : SupportSQLiteProgram {
/**
* Execute this SQL statement, if it is not a SELECT / INSERT / DELETE / UPDATE, for example
* CREATE / DROP table, view, trigger, index etc.
*
* @throws [android.database.SQLException] If the SQL string is invalid for
* some reason
*/
fun execute()
/**
* Execute this SQL statement, if the the number of rows affected by execution of this SQL
* statement is of any importance to the caller - for example, UPDATE / DELETE SQL statements.
*
* @return the number of rows affected by this SQL statement execution.
* @throws [android.database.SQLException] If the SQL string is invalid for
* some reason
*/
fun executeUpdateDelete(): Int
/**
* Execute this SQL statement and return the ID of the row inserted due to this call.
* The SQL statement should be an INSERT for this to be a useful call.
*
* @return the row ID of the last row inserted, if this insert is successful. -1 otherwise.
*
* @throws [android.database.SQLException] If the SQL string is invalid for
* some reason
*/
fun executeInsert(): Long
/**
* Execute a statement that returns a 1 by 1 table with a numeric value.
* For example, SELECT COUNT(*) FROM table;
*
* @return The result of the query.
*
* @throws [android.database.sqlite.SQLiteDoneException] if the query returns zero rows
*/
fun simpleQueryForLong(): Long
/**
* Execute a statement that returns a 1 by 1 table with a text value.
* For example, SELECT COUNT(*) FROM table;
*
* @return The result of the query.
*
* @throws [android.database.sqlite.SQLiteDoneException] if the query returns zero rows
*/
fun simpleQueryForString(): String?
} | sqlite/sqlite/src/main/java/androidx/sqlite/db/SupportSQLiteStatement.kt | 2979486677 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig.buildtool
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolderEx
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.runconfig.RsExecutableRunner.Companion.artifacts
import org.rust.cargo.runconfig.buildtool.CargoBuildManager.showBuildNotification
import org.rust.cargo.runconfig.command.workingDirectory
import org.rust.cargo.toolchain.impl.CompilerArtifactMessage
import java.nio.file.Path
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
abstract class CargoBuildContextBase(
val cargoProject: CargoProject,
val progressTitle: String,
val isTestBuild: Boolean,
val buildId: Any,
val parentId: Any
) {
val project: Project get() = cargoProject.project
val workingDirectory: Path get() = cargoProject.workingDirectory
@Volatile
var indicator: ProgressIndicator? = null
val errors: AtomicInteger = AtomicInteger()
val warnings: AtomicInteger = AtomicInteger()
@Volatile
var artifacts: List<CompilerArtifactMessage> = emptyList()
}
class CargoBuildContext(
cargoProject: CargoProject,
val environment: ExecutionEnvironment,
val taskName: String,
progressTitle: String,
isTestBuild: Boolean,
buildId: Any,
parentId: Any
) : CargoBuildContextBase(cargoProject, progressTitle, isTestBuild, buildId, parentId) {
@Volatile
var processHandler: ProcessHandler? = null
private val buildSemaphore: Semaphore = project.getUserData(BUILD_SEMAPHORE_KEY)
?: (project as UserDataHolderEx).putUserDataIfAbsent(BUILD_SEMAPHORE_KEY, Semaphore(1))
val result: CompletableFuture<CargoBuildResult> = CompletableFuture()
val started: Long = System.currentTimeMillis()
@Volatile
var finished: Long = started
private val duration: Long get() = finished - started
fun waitAndStart(): Boolean {
indicator?.pushState()
try {
indicator?.text = "Waiting for the current build to finish..."
indicator?.text2 = ""
while (true) {
indicator?.checkCanceled()
try {
if (buildSemaphore.tryAcquire(100, TimeUnit.MILLISECONDS)) break
} catch (e: InterruptedException) {
throw ProcessCanceledException()
}
}
} catch (e: ProcessCanceledException) {
canceled()
return false
} finally {
indicator?.popState()
}
return true
}
fun finished(isSuccess: Boolean) {
val isCanceled = indicator?.isCanceled ?: false
environment.artifacts = artifacts.takeIf { isSuccess && !isCanceled }
finished = System.currentTimeMillis()
buildSemaphore.release()
val finishMessage: String
val finishDetails: String?
val errors = errors.get()
val warnings = warnings.get()
// We report successful builds with errors or warnings correspondingly
val messageType = if (isCanceled) {
finishMessage = "$taskName canceled"
finishDetails = null
MessageType.INFO
} else {
val hasWarningsOrErrors = errors > 0 || warnings > 0
finishMessage = if (isSuccess) "$taskName finished" else "$taskName failed"
finishDetails = if (hasWarningsOrErrors) {
val errorsString = if (errors == 1) "error" else "errors"
val warningsString = if (warnings == 1) "warning" else "warnings"
"$errors $errorsString and $warnings $warningsString"
} else {
null
}
when {
!isSuccess -> MessageType.ERROR
hasWarningsOrErrors -> MessageType.WARNING
else -> MessageType.INFO
}
}
result.complete(CargoBuildResult(
succeeded = isSuccess,
canceled = isCanceled,
started = started,
duration = duration,
errors = errors,
warnings = warnings,
message = finishMessage
))
showBuildNotification(project, messageType, finishMessage, finishDetails, duration)
}
fun canceled() {
finished = System.currentTimeMillis()
result.complete(CargoBuildResult(
succeeded = false,
canceled = true,
started = started,
duration = duration,
errors = errors.get(),
warnings = warnings.get(),
message = "$taskName canceled"
))
environment.notifyProcessNotStarted()
}
companion object {
private val BUILD_SEMAPHORE_KEY: Key<Semaphore> = Key.create("BUILD_SEMAPHORE_KEY")
}
}
| src/main/kotlin/org/rust/cargo/runconfig/buildtool/CargoBuildContext.kt | 2739155716 |
package com.teamwizardry.librarianlib.testcore.junit
import com.teamwizardry.librarianlib.core.util.kotlin.unmodifiableView
import net.fabricmc.fabric.api.event.registry.FabricRegistryBuilder
import net.minecraft.util.Identifier
import net.minecraft.util.registry.Registry
public class UnitTestSuite {
private val _tests = mutableListOf<Class<*>>()
public val tests: List<Class<*>> = _tests.unmodifiableView()
public var description: String? = null
public constructor() {}
public constructor(block: UnitTestSuite.() -> Unit) {
this.apply(block)
}
public fun addTests(vararg testClasses: Class<*>): UnitTestSuite {
this._tests.addAll(testClasses)
return this
}
public fun addTests(testClasses: List<Class<*>>): UnitTestSuite {
this._tests.addAll(testClasses)
return this
}
public inline fun<reified T> add(): UnitTestSuite {
this.addTests(T::class.java)
return this
}
public companion object {
@JvmField
public val REGISTRY_ID: Identifier = Identifier("testcore:unit_tests")
@JvmField
public val REGISTRY: Registry<UnitTestSuite> = FabricRegistryBuilder
.createSimple(UnitTestSuite::class.java, REGISTRY_ID)
.buildAndRegister()
}
} | testcore/src/main/kotlin/com/teamwizardry/librarianlib/testcore/junit/UnitTestSuite.kt | 4421657 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve.ref
import com.intellij.psi.PsiPolyVariantReference
import org.rust.lang.core.psi.ext.RsElement
interface RsReference : PsiPolyVariantReference {
override fun getElement(): RsElement
override fun resolve(): RsElement?
fun multiResolve(): List<RsElement>
}
| src/main/kotlin/org/rust/lang/core/resolve/ref/RsReference.kt | 1582229152 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.debugger.runconfig
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessTerminatedListener
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.ui.RunContentDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts.Button
import com.intellij.openapi.util.NlsContexts.DialogMessage
import com.intellij.openapi.util.SystemInfo
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugProcessStarter
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.XDebuggerManager
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.BuildResult
import org.rust.cargo.runconfig.CargoRunStateBase
import org.rust.cargo.runconfig.CargoTestRunState
import org.rust.cargo.toolchain.wsl.RsWslToolchain
import org.rust.debugger.RsDebuggerToolchainService
import org.rust.debugger.settings.RsDebuggerSettings
object RsDebugRunnerUtils {
// TODO: move into bundle
const val ERROR_MESSAGE_TITLE: String = "Unable to run debugger"
fun showRunContent(
state: CargoRunStateBase,
environment: ExecutionEnvironment,
runExecutable: GeneralCommandLine
): RunContentDescriptor {
val runParameters = RsDebugRunParameters(
environment.project,
runExecutable,
state.cargoProject,
// TODO: always pass `withSudo` when `com.intellij.execution.process.ElevationService` supports error stream redirection
// https://github.com/intellij-rust/intellij-rust/issues/7320
if (state is CargoTestRunState) false else state.runConfiguration.withSudo
)
return XDebuggerManager.getInstance(environment.project)
.startSession(environment, object : XDebugProcessStarter() {
override fun start(session: XDebugSession): XDebugProcess =
RsLocalDebugProcess(runParameters, session, state.consoleBuilder).apply {
ProcessTerminatedListener.attach(processHandler, environment.project)
start()
}
})
.runContentDescriptor
}
fun checkToolchainSupported(project: Project, host: String): BuildResult.ToolchainError? {
if (SystemInfo.isWindows) {
if (project.toolchain is RsWslToolchain) {
return BuildResult.ToolchainError.UnsupportedWSL
}
val isGNURustToolchain = "gnu" in host
if (isGNURustToolchain) {
return BuildResult.ToolchainError.UnsupportedGNU
}
}
return null
}
fun checkToolchainConfigured(project: Project): Boolean {
val lldbStatus = RsDebuggerToolchainService.getInstance().getLLDBStatus()
val (message, action) = when (lldbStatus) {
RsDebuggerToolchainService.LLDBStatus.Unavailable -> return false
RsDebuggerToolchainService.LLDBStatus.NeedToDownload -> "Debugger is not loaded yet" to "Download"
RsDebuggerToolchainService.LLDBStatus.NeedToUpdate -> "Debugger is outdated" to "Update"
RsDebuggerToolchainService.LLDBStatus.Bundled,
is RsDebuggerToolchainService.LLDBStatus.Binaries -> return true
}
val option = if (!RsDebuggerSettings.getInstance().downloadAutomatically) {
showDialog(project, message, action)
} else {
Messages.OK
}
if (option == Messages.OK) {
val result = RsDebuggerToolchainService.getInstance().downloadDebugger(project)
if (result is RsDebuggerToolchainService.DownloadResult.Ok) {
RsDebuggerSettings.getInstance().lldbPath = result.lldbDir.absolutePath
return true
}
}
return false
}
private fun showDialog(
project: Project,
@Suppress("UnstableApiUsage") @DialogMessage message: String,
@Suppress("UnstableApiUsage") @Button action: String
): Int {
return Messages.showDialog(
project,
message,
ERROR_MESSAGE_TITLE,
arrayOf(action),
Messages.OK,
Messages.getErrorIcon(),
object : DialogWrapper.DoNotAskOption.Adapter() {
override fun rememberChoice(isSelected: Boolean, exitCode: Int) {
if (exitCode == Messages.OK) {
RsDebuggerSettings.getInstance().downloadAutomatically = isSelected
}
}
}
)
}
}
| debugger/src/main/kotlin/org/rust/debugger/runconfig/RsDebugRunnerUtils.kt | 659119760 |
/*
* Copyright 2002-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.session
/**
* Marker annotation indicating that the annotated class is part of the session security DSL.
*
* @author Eleftheria Stein
* @since 5.4
*/
@DslMarker
annotation class SessionSecurityMarker
| config/src/main/kotlin/org/springframework/security/config/annotation/web/session/SessionSecurityMarker.kt | 2995284450 |
package io.erva.sample
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.annotation.DrawableRes
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class DividerItemDecoration : RecyclerView.ItemDecoration {
private var divider: Drawable? = null
constructor(context: Context) {
val a = context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider))
divider = a.getDrawable(0)
a.recycle()
}
constructor(divider: Drawable) {
this.divider = divider
}
constructor(context: Context, @DrawableRes drawableId: Int) {
divider = ResourcesCompat.getDrawable(context.resources, drawableId, null)
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
if (divider == null) return
if (parent.getChildAdapterPosition(view) < 1) return
if (getOrientation(parent) == LinearLayoutManager.VERTICAL)
outRect.top = divider!!.intrinsicHeight
else
outRect.left = divider!!.intrinsicWidth
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (divider == null) {
super.onDrawOver(c, parent, state)
return
}
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 1..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val size = divider!!.intrinsicHeight
val top = child.top - params.topMargin
val bottom = top + size
divider!!.setBounds(left, top, right, bottom)
divider!!.draw(c)
}
} else { //horizontal
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val childCount = parent.childCount
for (i in 1..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val size = divider!!.intrinsicWidth
val left = child.left - params.leftMargin
val right = left + size
divider!!.setBounds(left, top, right, bottom)
divider!!.draw(c)
}
}
}
private fun getOrientation(parent: RecyclerView): Int {
if (parent.layoutManager is LinearLayoutManager) {
val layoutManager = parent.layoutManager as LinearLayoutManager
return layoutManager.orientation
} else
throw IllegalStateException("DividerItemDecoration can only be used with a LinearLayoutManager.")
}
} | sample-x-kotlin/src/main/kotlin/io/erva/sample/DividerItemDecoration.kt | 1539573669 |
package com.quijotelui.model
import org.hibernate.annotations.Immutable
import java.io.Serializable
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Immutable
@Table(name = "v_ele_informaciones")
class Informacion : Serializable {
@Id
@Column(name = "id")
var id : Long? = null
@Column(name = "documento")
var documento : String? = null
@Column(name = "nombre")
var nombre : String? = null
@Column(name = "valor")
var valor : String? = null
} | src/main/kotlin/com/quijotelui/model/Informacion.kt | 1721569705 |
package com.habitrpg.android.habitica.ui.fragments.social.guilds
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.MainNavDirections
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ChallengeRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.databinding.FragmentGuildDetailBinding
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.modules.AppModule
import com.habitrpg.android.habitica.ui.activities.GroupInviteActivity
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.helpers.setMarkdown
import com.habitrpg.android.habitica.ui.viewmodels.GroupViewModel
import com.habitrpg.android.habitica.ui.views.HabiticaIcons
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.SnackbarActivity
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Named
class GuildDetailFragment : BaseFragment<FragmentGuildDetailBinding>() {
@Inject
lateinit var configManager: AppConfigManager
override var binding: FragmentGuildDetailBinding? = null
@Inject
lateinit var challengeRepository: ChallengeRepository
@Inject
lateinit var userRepository: UserRepository
@field:[Inject Named(AppModule.NAMED_USER_ID)]
lateinit var userId: String
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentGuildDetailBinding {
return FragmentGuildDetailBinding.inflate(inflater, container, false)
}
var viewModel: GroupViewModel? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.refreshLayout?.setOnRefreshListener { this.refresh() }
viewModel?.getGroupData()?.observe(viewLifecycleOwner, { updateGuild(it) })
viewModel?.getLeaderData()?.observe(viewLifecycleOwner, { setLeader(it) })
viewModel?.getIsMemberData()?.observe(viewLifecycleOwner, { updateMembership(it) })
binding?.guildDescription?.movementMethod = LinkMovementMethod.getInstance()
binding?.guildBankIcon?.setImageBitmap(HabiticaIconsHelper.imageOfGem())
binding?.leaveButton?.setOnClickListener {
leaveGuild()
}
binding?.joinButton?.setOnClickListener {
viewModel?.joinGroup {
(this.activity as? SnackbarActivity)?.showSnackbar(title = getString(R.string.joined_guild))
}
}
binding?.inviteButton?.setOnClickListener {
val intent = Intent(activity, GroupInviteActivity::class.java)
sendInvitesResult.launch(intent)
}
binding?.leaderWrapper?.setOnClickListener {
viewModel?.leaderID?.let { leaderID ->
val profileDirections = MainNavDirections.openProfileActivity(leaderID)
MainNavigationController.navigate(profileDirections)
}
}
}
private fun setLeader(leader: Member?) {
if (leader == null) {
return
}
binding?.leaderAvatarView?.setAvatar(leader)
binding?.leaderProfileName?.username = leader.displayName
binding?.leaderProfileName?.tier = leader.contributor?.level ?: 0
binding?.leaderUsername?.text = leader.formattedUsername
}
private fun updateMembership(isMember: Boolean?) {
binding?.joinButton?.visibility = if (isMember == true) View.GONE else View.VISIBLE
binding?.leaveButton?.visibility = if (isMember == true) View.VISIBLE else View.GONE
}
private val sendInvitesResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
val inviteData = HashMap<String, Any>()
inviteData["inviter"] = viewModel?.user?.value?.profile?.name ?: ""
val emails = it.data?.getStringArrayExtra(GroupInviteActivity.EMAILS_KEY)
if (emails != null && emails.isNotEmpty()) {
val invites = ArrayList<HashMap<String, String>>()
emails.forEach { email ->
val invite = HashMap<String, String>()
invite["name"] = ""
invite["email"] = email
invites.add(invite)
}
inviteData["emails"] = invites
}
val userIDs = it.data?.getStringArrayExtra(GroupInviteActivity.USER_IDS_KEY)
if (userIDs != null && userIDs.isNotEmpty()) {
val invites = ArrayList<String>()
userIDs.forEach { invites.add(it) }
inviteData["usernames"] = invites
}
viewModel?.inviteToGroup(inviteData)
}
}
private fun refresh() {
viewModel?.retrieveGroup {
binding?.refreshLayout?.isRefreshing = false
}
}
private fun getGroupChallenges(): List<Challenge> {
val groupChallenges = mutableListOf<Challenge>()
userRepository.getUser(userId).forEach {
it.challenges?.forEach {
challengeRepository.getChallenge(it.challengeID).forEach {
if (it.groupId.equals(viewModel?.groupID)) {
groupChallenges.add(it)
}
}
}
}
return groupChallenges
}
internal fun leaveGuild() {
val context = context
if (context != null) {
val groupChallenges = getGroupChallenges()
lifecycleScope.launch(Dispatchers.Main) {
delay(500)
if (groupChallenges.isNotEmpty()) {
val alert = HabiticaAlertDialog(context)
alert.setTitle(R.string.guild_challenges)
alert.setMessage(R.string.leave_guild_challenges_confirmation)
alert.addButton(R.string.keep_challenges, true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, true) { showLeaveSnackbar() }
}
alert.addButton(R.string.leave_challenges_delete_tasks, isPrimary = false, isDestructive = true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, false) { showLeaveSnackbar() }
}
alert.setExtraCloseButtonVisibility(View.VISIBLE)
alert.show()
} else {
val alert = HabiticaAlertDialog(context)
alert.setTitle(R.string.leave_guild_confirmation)
alert.setMessage(R.string.rejoin_guild)
alert.addButton(R.string.leave, isPrimary = true, isDestructive = true) { _, _ ->
viewModel?.leaveGroup(groupChallenges, false) {
showLeaveSnackbar()
}
}
alert.setExtraCloseButtonVisibility(View.VISIBLE)
alert.show()
}
}
}
}
private fun showLeaveSnackbar() {
(this.activity as? MainActivity)?.showSnackbar(title = getString(R.string.left_guild))
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun updateGuild(guild: Group?) {
binding?.titleView?.text = guild?.name
binding?.guildMembersIcon?.setImageBitmap(HabiticaIcons.imageOfGuildCrestMedium((guild?.memberCount ?: 0).toFloat()))
binding?.guildMembersText?.text = guild?.memberCount.toString()
binding?.guildBankText?.text = guild?.gemCount.toString()
binding?.guildSummary?.setMarkdown(guild?.summary)
binding?.guildDescription?.setMarkdown(guild?.description)
}
companion object {
fun newInstance(viewModel: GroupViewModel?): GuildDetailFragment {
val args = Bundle()
val fragment = GuildDetailFragment()
fragment.arguments = args
fragment.viewModel = viewModel
return fragment
}
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/guilds/GuildDetailFragment.kt | 1194841535 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.util
import androidx.room.compiler.processing.XProcessingEnvConfig
import androidx.room.compiler.processing.XProcessingEnvironmentTestConfigProvider
class TestDefaultEnvironmentConfigProvider : XProcessingEnvironmentTestConfigProvider {
init {
initialized = true
}
override fun configure(options: Map<String, String>): XProcessingEnvConfig {
invoked = true
return XProcessingEnvConfig.DEFAULT
}
companion object {
/**
* Used in test to assert it is used
*/
internal var initialized: Boolean = false
private set
internal var invoked: Boolean = false
private set
}
} | room/room-compiler-processing-testing/src/test/java/androidx/room/compiler/processing/util/TestDefaultEnvironmentConfigProvider.kt | 2670834828 |
package org.thoughtcrime.securesms.components.settings.conversation
import android.content.Context
import android.database.Cursor
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.signal.core.util.concurrent.SignalExecutors
import org.signal.core.util.logging.Log
import org.signal.storageservice.protos.groups.local.DecryptedGroup
import org.signal.storageservice.protos.groups.local.DecryptedPendingMember
import org.thoughtcrime.securesms.contacts.sync.ContactDiscovery
import org.thoughtcrime.securesms.database.GroupDatabase
import org.thoughtcrime.securesms.database.MediaDatabase
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.model.IdentityRecord
import org.thoughtcrime.securesms.database.model.StoryViewState
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.groups.GroupId
import org.thoughtcrime.securesms.groups.GroupProtoUtil
import org.thoughtcrime.securesms.groups.LiveGroup
import org.thoughtcrime.securesms.groups.v2.GroupAddMembersResult
import org.thoughtcrime.securesms.groups.v2.GroupManagementRepository
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.recipients.RecipientUtil
import org.thoughtcrime.securesms.util.FeatureFlags
import java.io.IOException
import java.util.Optional
private val TAG = Log.tag(ConversationSettingsRepository::class.java)
class ConversationSettingsRepository(
private val context: Context,
private val groupManagementRepository: GroupManagementRepository = GroupManagementRepository(context)
) {
@WorkerThread
fun getThreadMedia(threadId: Long): Optional<Cursor> {
return if (threadId <= 0) {
Optional.empty()
} else {
Optional.of(SignalDatabase.media.getGalleryMediaForThread(threadId, MediaDatabase.Sorting.Newest))
}
}
fun getStoryViewState(groupId: GroupId): Observable<StoryViewState> {
return Observable.fromCallable {
SignalDatabase.recipients.getByGroupId(groupId)
}.flatMap {
StoryViewState.getForRecipientId(it.get())
}.observeOn(Schedulers.io())
}
fun getThreadId(recipientId: RecipientId, consumer: (Long) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(SignalDatabase.threads.getThreadIdIfExistsFor(recipientId))
}
}
fun getThreadId(groupId: GroupId, consumer: (Long) -> Unit) {
SignalExecutors.BOUNDED.execute {
val recipientId = Recipient.externalGroupExact(groupId).id
consumer(SignalDatabase.threads.getThreadIdIfExistsFor(recipientId))
}
}
fun isInternalRecipientDetailsEnabled(): Boolean = SignalStore.internalValues().recipientDetails()
fun hasGroups(consumer: (Boolean) -> Unit) {
SignalExecutors.BOUNDED.execute { consumer(SignalDatabase.groups.activeGroupCount > 0) }
}
fun getIdentity(recipientId: RecipientId, consumer: (IdentityRecord?) -> Unit) {
SignalExecutors.BOUNDED.execute {
if (SignalStore.account().aci != null && SignalStore.account().pni != null) {
consumer(ApplicationDependencies.getProtocolStore().aci().identities().getIdentityRecord(recipientId).orElse(null))
} else {
consumer(null)
}
}
}
fun getGroupsInCommon(recipientId: RecipientId, consumer: (List<Recipient>) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(
SignalDatabase
.groups
.getPushGroupsContainingMember(recipientId)
.asSequence()
.filter { it.members.contains(Recipient.self().id) }
.map(GroupDatabase.GroupRecord::getRecipientId)
.map(Recipient::resolved)
.sortedBy { gr -> gr.getDisplayName(context) }
.toList()
)
}
}
fun getGroupMembership(recipientId: RecipientId, consumer: (List<RecipientId>) -> Unit) {
SignalExecutors.BOUNDED.execute {
val groupDatabase = SignalDatabase.groups
val groupRecords = groupDatabase.getPushGroupsContainingMember(recipientId)
val groupRecipients = ArrayList<RecipientId>(groupRecords.size)
for (groupRecord in groupRecords) {
groupRecipients.add(groupRecord.recipientId)
}
consumer(groupRecipients)
}
}
fun refreshRecipient(recipientId: RecipientId) {
SignalExecutors.UNBOUNDED.execute {
try {
ContactDiscovery.refresh(context, Recipient.resolved(recipientId), false)
} catch (e: IOException) {
Log.w(TAG, "Failed to refresh user after adding to contacts.")
}
}
}
fun setMuteUntil(recipientId: RecipientId, until: Long) {
SignalExecutors.BOUNDED.execute {
SignalDatabase.recipients.setMuted(recipientId, until)
}
}
fun getGroupCapacity(groupId: GroupId, consumer: (GroupCapacityResult) -> Unit) {
SignalExecutors.BOUNDED.execute {
val groupRecord: GroupDatabase.GroupRecord = SignalDatabase.groups.getGroup(groupId).get()
consumer(
if (groupRecord.isV2Group) {
val decryptedGroup: DecryptedGroup = groupRecord.requireV2GroupProperties().decryptedGroup
val pendingMembers: List<RecipientId> = decryptedGroup.pendingMembersList
.map(DecryptedPendingMember::getUuid)
.map(GroupProtoUtil::uuidByteStringToRecipientId)
val members = mutableListOf<RecipientId>()
members.addAll(groupRecord.members)
members.addAll(pendingMembers)
GroupCapacityResult(Recipient.self().id, members, FeatureFlags.groupLimits(), groupRecord.isAnnouncementGroup)
} else {
GroupCapacityResult(Recipient.self().id, groupRecord.members, FeatureFlags.groupLimits(), false)
}
)
}
}
fun addMembers(groupId: GroupId, selected: List<RecipientId>, consumer: (GroupAddMembersResult) -> Unit) {
groupManagementRepository.addMembers(groupId, selected, consumer)
}
fun setMuteUntil(groupId: GroupId, until: Long) {
SignalExecutors.BOUNDED.execute {
val recipientId = Recipient.externalGroupExact(groupId).id
SignalDatabase.recipients.setMuted(recipientId, until)
}
}
fun block(recipientId: RecipientId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.resolved(recipientId)
if (recipient.isGroup) {
RecipientUtil.block(context, recipient)
} else {
RecipientUtil.blockNonGroup(context, recipient)
}
}
}
fun unblock(recipientId: RecipientId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.resolved(recipientId)
RecipientUtil.unblock(recipient)
}
}
fun block(groupId: GroupId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.externalGroupExact(groupId)
RecipientUtil.block(context, recipient)
}
}
fun unblock(groupId: GroupId) {
SignalExecutors.BOUNDED.execute {
val recipient = Recipient.externalGroupExact(groupId)
RecipientUtil.unblock(recipient)
}
}
@WorkerThread
fun isMessageRequestAccepted(recipient: Recipient): Boolean {
return RecipientUtil.isMessageRequestAccepted(context, recipient)
}
fun getMembershipCountDescription(liveGroup: LiveGroup): LiveData<String> {
return liveGroup.getMembershipCountDescription(context.resources)
}
fun getExternalPossiblyMigratedGroupRecipientId(groupId: GroupId, consumer: (RecipientId) -> Unit) {
SignalExecutors.BOUNDED.execute {
consumer(Recipient.externalPossiblyMigratedGroup(groupId).id)
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/ConversationSettingsRepository.kt | 3780823742 |
package com.simplemobiletools.notes.pro.helpers
import android.text.Selection
import android.text.Spannable
import android.text.method.ArrowKeyMovementMethod
import android.text.style.ClickableSpan
import android.view.MotionEvent
import android.widget.TextView
class MyMovementMethod : ArrowKeyMovementMethod() {
companion object {
private var sInstance: MyMovementMethod? = null
fun getInstance(): MyMovementMethod {
if (sInstance == null) {
sInstance = MyMovementMethod()
}
return sInstance!!
}
}
override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean {
val action = event.action
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
var x = event.x.toInt()
var y = event.y.toInt()
x -= widget.totalPaddingLeft
y -= widget.totalPaddingTop
x += widget.scrollX
y += widget.scrollY
val layout = widget.layout
val line = layout.getLineForVertical(y)
val off = layout.getOffsetForHorizontal(line, x.toFloat())
val links = buffer.getSpans(off, off, ClickableSpan::class.java)
if (links.isNotEmpty()) {
if (action == MotionEvent.ACTION_UP) {
links[0].onClick(widget)
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer,
buffer.getSpanStart(links[0]),
buffer.getSpanEnd(links[0]))
}
return true
}
}
return super.onTouchEvent(widget, buffer, event)
}
}
| app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/MyMovementMethod.kt | 1649079096 |
package org.thoughtcrime.securesms.stories.settings.my
import org.thoughtcrime.securesms.database.model.DistributionListPrivacyMode
data class MyStoryPrivacyState(val privacyMode: DistributionListPrivacyMode? = null, val connectionCount: Int = 0)
| app/src/main/java/org/thoughtcrime/securesms/stories/settings/my/MyStoryPrivacyState.kt | 3412010800 |
/*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.overrideImplement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.SmartList
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds
import org.eclipse.jdt.ui.actions.SelectionDispatchAction
import org.eclipse.jface.text.ITextSelection
import org.eclipse.jface.window.Window
import org.eclipse.ui.PlatformUI
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.ui.editors.KotlinCommonEditor
import org.jetbrains.kotlin.ui.editors.quickassist.KotlinImplementMethodsProposal
import org.jetbrains.kotlin.ui.editors.quickassist.resolveToDescriptor
import java.util.LinkedHashMap
import java.util.LinkedHashSet
public class KotlinOverrideMembersAction(
val editor: KotlinCommonEditor,
val filterMembersFromAny: Boolean = false) : SelectionDispatchAction(editor.getSite()) {
init {
setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS)
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION)
val overrideImplementText = "Override/Implement Members"
setText(overrideImplementText)
setDescription("Override or implement members declared in supertypes")
setToolTipText(overrideImplementText)
}
val membersFromAny = listOf("equals", "hashCode", "toString")
companion object {
val ACTION_ID = "OverrideMethods"
}
override fun run(selection: ITextSelection) {
val jetClassOrObject = getKtClassOrObject(selection)
if (jetClassOrObject == null) return
val generatedMembers = collectMembersToGenerate(jetClassOrObject)
val selectedMembers = if (filterMembersFromAny) {
generatedMembers.filterNot { it.getName().asString() in membersFromAny }
} else {
showDialog(generatedMembers)
}
if (selectedMembers.isEmpty()) return
KotlinImplementMethodsProposal(editor).generateMethods(editor.document, jetClassOrObject, selectedMembers.toSet())
}
private fun getKtClassOrObject(selection: ITextSelection): KtClassOrObject? {
val psiElement = EditorUtil.getPsiElement(editor, selection.getOffset())
return if (psiElement != null) {
PsiTreeUtil.getNonStrictParentOfType(psiElement, KtClassOrObject::class.java)
} else {
null
}
}
private fun showDialog(descriptors: Set<CallableMemberDescriptor>): Set<CallableMemberDescriptor> {
val shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()
val types = descriptors.map { it.getContainingDeclaration() as ClassDescriptor }.toSet()
val dialog = CheckedTreeSelectionDialog(shell,
KotlinCallableLabelProvider(),
KotlinCallableContentProvider(descriptors, types))
dialog.setTitle("Override/Implement members")
dialog.setContainerMode(true)
dialog.setExpandedElements(types.toTypedArray())
dialog.setInput(Any()) // Initialize input
if (dialog.open() != Window.OK) {
return emptySet()
}
val selected = dialog.getResult()?.filterIsInstance(CallableMemberDescriptor::class.java)
return selected?.toSet() ?: emptySet()
}
private fun collectMembersToGenerate(classOrObject: KtClassOrObject): Set<CallableMemberDescriptor> {
val descriptor = classOrObject.resolveToDescriptor()
if (descriptor !is ClassDescriptor) return emptySet()
val result = LinkedHashSet<CallableMemberDescriptor>()
for (member in descriptor.unsubstitutedMemberScope.getContributedDescriptors()) {
if (member is CallableMemberDescriptor
&& (member.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE || member.kind == CallableMemberDescriptor.Kind.DELEGATION)) {
val overridden = member.overriddenDescriptors
if (overridden.any { it.modality == Modality.FINAL || Visibilities.isPrivate(it.visibility.normalize()) }) continue
class Data(
val realSuper: CallableMemberDescriptor,
val immediateSupers: MutableList<CallableMemberDescriptor> = SmartList()
)
val byOriginalRealSupers = LinkedHashMap<CallableMemberDescriptor, Data>()
for (immediateSuper in overridden) {
for (realSuper in toRealSupers(immediateSuper)) {
byOriginalRealSupers.getOrPut(realSuper.original) { Data(realSuper) }.immediateSupers.add(immediateSuper)
}
}
val realSupers = byOriginalRealSupers.values.map { it.realSuper }
val nonAbstractRealSupers = realSupers.filter { it.modality != Modality.ABSTRACT }
val realSupersToUse = if (nonAbstractRealSupers.isNotEmpty()) {
nonAbstractRealSupers
}
else {
listOf(realSupers.first())
}
for (realSuper in realSupersToUse) {
val immediateSupers = byOriginalRealSupers[realSuper.original]!!.immediateSupers
assert(immediateSupers.isNotEmpty())
val immediateSuperToUse = if (immediateSupers.size == 1) {
immediateSupers.single()
}
else {
immediateSupers.singleOrNull { (it.containingDeclaration as? ClassDescriptor)?.kind == ClassKind.CLASS } ?: immediateSupers.first()
}
result.add(immediateSuperToUse)
}
}
}
return result
}
private fun toRealSupers(immediateSuper: CallableMemberDescriptor): Collection<CallableMemberDescriptor> {
if (immediateSuper.kind != CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
return listOf(immediateSuper)
}
val overridden = immediateSuper.overriddenDescriptors
assert(overridden.isNotEmpty())
return overridden.flatMap { toRealSupers(it) }.distinctBy { it.original }
}
} | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/overrideImplement/KotlinOverrideMembersAction.kt | 2611111984 |
package com.baeldung.springreactivekotlin
import org.springframework.http.MediaType
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody
import reactor.core.publisher.Flux
@Controller
class Controller {
@GetMapping(path = ["/numbers"], produces = [MediaType.APPLICATION_STREAM_JSON_VALUE])
@ResponseBody
fun getNumbers(): Flux<Int> {
return Flux.range(1, 100)
}
}
| projects/tutorials-master/tutorials-master/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt | 3689196982 |
/*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.commands.ResponseBuilder
import com.demonwav.statcraft.querydsl.QKills
import com.demonwav.statcraft.querydsl.QPlayers
import org.bukkit.command.CommandSender
import java.sql.Connection
class SCKills(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("kills", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.kills")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Kills" }
stats["Total"] = "0"
}
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val k = QKills.kills
val result = query.from(k).where(k.id.eq(id)).uniqueResult(k.amount.sum()) ?: 0
return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Kills" }
stats["Total"] = df.format(result)
}
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String {
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val k = QKills.kills
val p = QPlayers.players
val list = query
.from(k)
.innerJoin(p)
.on(k.id.eq(p.id))
.groupBy(p.name)
.orderBy(k.amount.sum().desc())
.limit(num)
.list(p.name, k.amount.sum())
return topListResponse("Kills", list)
}
}
| src/main/kotlin/com/demonwav/statcraft/commands/sc/SCKills.kt | 1900236552 |
/*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.debug.commands
import org.eclipse.core.commands.AbstractHandler
import org.eclipse.core.commands.ExecutionEvent
import org.eclipse.ui.handlers.HandlerUtil
import org.jetbrains.kotlin.ui.editors.KotlinFileEditor
import org.eclipse.jface.text.ITextSelection
import org.eclipse.jdt.internal.debug.ui.EvaluationContextManager
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil
import org.jetbrains.kotlin.core.references.getReferenceExpression
import org.jetbrains.kotlin.core.references.resolveToSourceElements
import org.jetbrains.kotlin.core.references.createReferences
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.core.resolve.lang.java.resolver.EclipseJavaSourceElement
import org.jetbrains.kotlin.core.model.sourceElementsToLightElements
import org.eclipse.jdt.core.IJavaElement
import org.eclipse.jdt.debug.core.IJavaStackFrame
import org.eclipse.jdt.internal.debug.ui.actions.StepIntoSelectionHandler
import org.eclipse.jdt.debug.core.IJavaThread
import org.eclipse.jdt.core.IMethod
import org.jetbrains.kotlin.ui.debug.findTopmostType
import org.eclipse.jdt.internal.debug.ui.actions.StepIntoSelectionUtils
import org.eclipse.ui.IEditorPart
import org.eclipse.debug.core.model.IThread
import org.jetbrains.kotlin.core.log.KotlinLogger
import org.eclipse.jdt.core.IType
public class KotlinStepIntoSelectionHandler : AbstractHandler() {
override fun execute(event: ExecutionEvent): Any? {
val editor = HandlerUtil.getActiveEditor(event) as KotlinFileEditor
val selection = editor.getEditorSite().getSelectionProvider().getSelection()
if (selection is ITextSelection) {
stepIntoSelection(editor, selection)
}
return null
}
}
private fun stepIntoSelection(editor: KotlinFileEditor, selection: ITextSelection) {
val frame = EvaluationContextManager.getEvaluationContext(editor)
if (frame == null || !frame.isSuspended()) return
val psiElement = EditorUtil.getPsiElement(editor, selection.getOffset())
if (psiElement == null) return
val expression = getReferenceExpression(psiElement)
if (expression == null) return
val sourceElements = createReferences(expression).resolveToSourceElements()
val javaElements = sourceElementsToLightElements(sourceElements)
if (javaElements.size > 1) {
KotlinLogger.logWarning("There are more than one java element for $sourceElements")
return
}
val element = javaElements.first()
val method = when (element) {
is IMethod -> element
is IType -> element.getMethod(element.elementName, emptyArray())
else -> null
} ?: return
stepIntoElement(method, frame, selection, editor)
}
private fun stepIntoElement(method: IMethod, frame: IJavaStackFrame, selection: ITextSelection, editor: KotlinFileEditor) {
if (selection.getStartLine() + 1 == frame.getLineNumber()) {
val handler = StepIntoSelectionHandler(frame.getThread() as IJavaThread, frame, method)
handler.step()
} else {
val refMethod = StepIntoSelectionUtils::class.java.getDeclaredMethod(
"runToLineBeforeStepIn",
IEditorPart::class.java,
String::class.java,
ITextSelection::class.java,
IThread::class.java,
IMethod::class.java)
refMethod.setAccessible(true)
refMethod.invoke(null, editor, frame.getReceivingTypeName(), selection, frame.getThread(), method)
}
} | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/debug/commands/KotlinStepIntoSelectionHandler.kt | 2789918006 |
package org.elm.ide.color
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import org.elm.ide.highlight.ElmSyntaxHighlighter
import org.elm.ide.icons.ElmIcons
class ElmColorSettingsPage : ColorSettingsPage {
private val ATTRS = ElmColor.values().map { it.attributesDescriptor }.toTypedArray()
override fun getDisplayName() =
"Elm"
override fun getIcon() =
ElmIcons.FILE
override fun getAttributeDescriptors() =
ATTRS
override fun getColorDescriptors(): Array<ColorDescriptor> =
ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter() =
ElmSyntaxHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap() =
// special tags in [demoText] for semantic highlighting
mapOf(
"type" to ElmColor.TYPE_EXPR,
"variant" to ElmColor.UNION_VARIANT,
"accessor" to ElmColor.RECORD_FIELD_ACCESSOR,
"field" to ElmColor.RECORD_FIELD,
"func_decl" to ElmColor.DEFINITION_NAME
).mapValues { it.value.textAttributesKey }
override fun getDemoText() =
demoCodeText
}
private const val demoCodeText = """
module Todo exposing (..)
import Html exposing (div, h1, ul, li, text)
-- a single line comment
type alias Model =
{ <field>page</field> : <type>Int</type>
, <field>title</field> : <type>String</type>
, <field>stepper</field> : <type>Int</type> -> <type>Int</type>
}
type Msg <type>a</type>
= <variant>ModeA</variant>
| <variant>ModeB</variant> <type>Maybe a</type>
<func_decl>update</func_decl> : <type>Msg</type> -> <type>Model</type> -> ( <type>Model</type>, <type>Cmd Msg</type> )
<func_decl>update</func_decl> msg model =
case msg of
<variant>ModeA</variant> ->
{ model
| <field>page</field> = 0
, <field>title</field> = "Mode A"
, <field>stepper</field> = (\k -> k + 1)
}
! []
<func_decl>view</func_decl> : <type>Model</type> -> <type>Html.Html Msg</type>
<func_decl>view</func_decl> model =
let
<func_decl>itemify</func_decl> label =
li [] [ text label ]
in
div []
[ h1 [] [ text "Chapter One" ]
, ul []
(List.map <accessor>.value</accessor> model.<field>items</field>)
]
"""
| src/main/kotlin/org/elm/ide/color/ElmColorSettingsPage.kt | 2588426578 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge.creator
import com.demonwav.mcdev.creator.BaseProjectCreator
import com.demonwav.mcdev.creator.BasicJavaClassStep
import com.demonwav.mcdev.creator.CreateDirectoriesStep
import com.demonwav.mcdev.creator.CreatorStep
import com.demonwav.mcdev.creator.buildsystem.BuildSystem
import com.demonwav.mcdev.creator.buildsystem.gradle.BasicGradleFinalizerStep
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleBuildSystem
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleFiles
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleGitignoreStep
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleSetupStep
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleWrapperStep
import com.demonwav.mcdev.creator.buildsystem.maven.BasicMavenFinalizerStep
import com.demonwav.mcdev.creator.buildsystem.maven.BasicMavenStep
import com.demonwav.mcdev.creator.buildsystem.maven.MavenBuildSystem
import com.demonwav.mcdev.creator.buildsystem.maven.MavenGitignoreStep
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import java.nio.file.Path
sealed class Sponge8ProjectCreator<T : BuildSystem>(
protected val rootDirectory: Path,
protected val rootModule: Module,
protected val buildSystem: T,
protected val config: SpongeProjectConfig
) : BaseProjectCreator(rootModule, buildSystem) {
protected fun setupDependencyStep(): SpongeDependenciesSetup {
val spongeApiVersion = config.spongeApiVersion
return SpongeDependenciesSetup(buildSystem, spongeApiVersion, false)
}
protected fun setupMainClassStep(): BasicJavaClassStep {
return createJavaClassStep(config.mainClass) { packageName, className ->
val pluginId = (buildSystem.parent ?: buildSystem).artifactId
Sponge8Template.applyMainClass(project, pluginId, packageName, className)
}
}
}
class Sponge8MavenCreator(
rootDirectory: Path,
rootModule: Module,
buildSystem: MavenBuildSystem,
config: SpongeProjectConfig
) : Sponge8ProjectCreator<MavenBuildSystem>(rootDirectory, rootModule, buildSystem, config) {
override fun getSteps(): Iterable<CreatorStep> {
val mainClassStep = setupMainClassStep()
val pluginsJsonStep = CreatePluginsJsonStep(project, buildSystem, config)
val pomText = SpongeTemplate.applyPom(project, config)
return listOf(
setupDependencyStep(),
BasicMavenStep(project, rootDirectory, buildSystem, config, pomText),
mainClassStep,
pluginsJsonStep,
MavenGitignoreStep(project, rootDirectory),
BasicMavenFinalizerStep(rootModule, rootDirectory),
)
}
}
class CreatePluginsJsonStep(
private val project: Project,
private val buildSystem: BuildSystem,
private val config: SpongeProjectConfig
) : CreatorStep {
override fun runStep(indicator: ProgressIndicator) {
val pluginsJsonPath = buildSystem.dirsOrError.resourceDirectory.resolve("META-INF")
val pluginsJsonText = Sponge8Template.applyPluginsJson(project, buildSystem, config)
CreatorStep.writeTextToFile(project, pluginsJsonPath, "sponge_plugins.json", pluginsJsonText)
}
}
class Sponge8GradleCreator(
rootDirectory: Path,
rootModule: Module,
buildSystem: GradleBuildSystem,
config: SpongeProjectConfig
) : Sponge8ProjectCreator<GradleBuildSystem>(rootDirectory, rootModule, buildSystem, config) {
override fun getSteps(): Iterable<CreatorStep> {
val mainClassStep = setupMainClassStep()
val buildText = Sponge8Template.applyBuildGradle(
project,
buildSystem,
config
)
val propText = Sponge8Template.applyGradleProp(project)
val settingsText = Sponge8Template.applySettingsGradle(project, buildSystem.artifactId)
val files = GradleFiles(buildText, propText, settingsText)
return listOf(
CreateDirectoriesStep(buildSystem, rootDirectory),
GradleSetupStep(project, rootDirectory, buildSystem, files, true),
mainClassStep,
GradleWrapperStep(project, rootDirectory, buildSystem),
GradleGitignoreStep(project, rootDirectory),
BasicGradleFinalizerStep(rootModule, rootDirectory, buildSystem, "runServer")
)
}
}
| src/main/kotlin/platform/sponge/creator/Sponge8ProjectCreator.kt | 3450039487 |
package io.kri.anotherViewPager
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.runner.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("io.kri.anotherViewPager", appContext.packageName)
}
}
| anotherViewPager/src/androidTest/java/io/kri/anotherViewPager/ExampleInstrumentedTest.kt | 3892265506 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.intentions
import com.demonwav.mcdev.translations.Translation
import com.demonwav.mcdev.translations.TranslationFiles
import com.demonwav.mcdev.translations.index.TranslationInverseIndex
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
class RemoveDuplicatesIntention(private val translation: Translation) : PsiElementBaseIntentionAction() {
override fun getText() = "Remove duplicates (keep this translation)"
override fun getFamilyName() = "Minecraft localization"
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement) = true
override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
val keep = TranslationFiles.seekTranslation(element) ?: return
val entries = TranslationInverseIndex.findElements(
translation.key,
GlobalSearchScope.fileScope(element.containingFile)
)
for (other in entries) {
if (other !== keep) {
TranslationFiles.remove(other)
}
}
}
}
| src/main/kotlin/translations/intentions/RemoveDuplicatesIntention.kt | 1106305496 |
package com.tomer.draw.utils
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.view.animation.FastOutSlowInInterpolator
import android.view.View
import android.view.ViewAnimationUtils
import android.widget.Toast
import com.tomer.draw.R
/**
* DrawEverywhere
* Created by Tomer Rosenfeld on 7/28/17.
*/
fun Context.isAndroidNewerThan(version: Int): Boolean = Build.VERSION.SDK_INT >= version
fun Context.hasPermissions(vararg permissions: String): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return true
return permissions.none { checkSelfPermission(it) == PackageManager.PERMISSION_DENIED }
}
fun View.circularRevealHide(cx: Int = width / 2, cy: Int = height / 2, radius: Float = -1f, action: Runnable? = null) {
if (context.isAndroidNewerThan(Build.VERSION_CODES.LOLLIPOP)) {
val finalRadius =
if (radius == -1f)
Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
else
radius
val anim = ViewAnimationUtils
.createCircularReveal(this, cx, cy, finalRadius, 0f)
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
action?.run()
}
})
anim.interpolator = FastOutSlowInInterpolator()
anim.start()
} else {
val fadeOut = ObjectAnimator.ofFloat(this, "alpha", 1f, .1f)
fadeOut.duration = 300
fadeOut.addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationEnd(animation: Animator?) {
action?.run()
}
override fun onAnimationCancel(animation: Animator?) {
}
override fun onAnimationStart(animation: Animator?) {
}
})
fadeOut.start()
}
}
fun View.circularRevealShow(cx: Int = width / 2, cy: Int = height / 2, radius: Float = -1f) {
post {
if (context.isAndroidNewerThan(Build.VERSION_CODES.LOLLIPOP)) {
val finalRadius =
if (radius == -1f)
Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
else
radius
val anim = ViewAnimationUtils.createCircularReveal(this, cx, cy, 0f, finalRadius)
anim.interpolator = FastOutSlowInInterpolator()
anim.start()
} else {
val fadeIn = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f)
fadeIn.duration = 300
fadeIn.start()
}
}
}
fun Activity.askPermissionNoCallBack(vararg permissions: String) {
ActivityCompat.requestPermissions(this, permissions, 22)
}
fun Activity.askDrawOverPermission() {
val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + packageName))
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (doesIntentExist(intent)) {
startActivity(intent)
} else {
Toast.makeText(this, R.string.error_1_open_draw_over, Toast.LENGTH_LONG).show()
}
}
fun Context.doesIntentExist(intent: Intent): Boolean {
val mgr = packageManager
val list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.size > 0
}
fun Context.canDrawOverlaysCompat(): Boolean {
if (isAndroidNewerThan(Build.VERSION_CODES.M))
return Settings.canDrawOverlays(this)
return true
}
fun Context.safeUnregisterReceiver(receiver: BroadcastReceiver) {
try {
unregisterReceiver(receiver)
} catch (ignored: IllegalArgumentException) {
}
}
| app/src/main/java/com/tomer/draw/utils/AndroidMethods.kt | 3009087543 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.sponge
import com.demonwav.mcdev.creator.getText
import com.demonwav.mcdev.util.fromJson
import com.google.gson.Gson
import javax.swing.JComboBox
data class SpongeVersion(var versions: LinkedHashMap<String, String>, var selectedIndex: Int) {
fun set(combo: JComboBox<String>) {
combo.removeAllItems()
for ((key, _) in this.versions) {
combo.addItem(key)
}
combo.selectedIndex = this.selectedIndex
}
companion object {
suspend fun downloadData(): SpongeVersion? {
return try {
val text = getText("sponge_v2.json")
Gson().fromJson(text, SpongeVersion::class)
} catch (e: Exception) {
null
}
}
}
}
| src/main/kotlin/platform/sponge/SpongeVersion.kt | 3936842105 |
package ru.fantlab.android.ui.modules.plans.pubnews
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import ru.fantlab.android.data.dao.model.Pubnews
import ru.fantlab.android.helper.FantlabHelper
import ru.fantlab.android.provider.rest.PubnewsSortOption
import ru.fantlab.android.provider.rest.loadmore.OnLoadMore
import ru.fantlab.android.ui.base.mvp.BaseMvp
import ru.fantlab.android.ui.widgets.dialog.ContextMenuDialogView
import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder
interface PubnewsMvp {
interface View : BaseMvp.View,
SwipeRefreshLayout.OnRefreshListener,
android.view.View.OnClickListener,
ContextMenuDialogView.ListDialogViewActionCallback {
fun onNotifyAdapter(items: ArrayList<Pubnews.Object>, page: Int)
fun getLoadMore(): OnLoadMore<Int>
fun onItemClicked(item: Pubnews.Object)
fun onItemLongClicked(position: Int, v: android.view.View?, item: Pubnews.Object)
}
interface Presenter : BaseMvp.Presenter,
BaseViewHolder.OnItemClickListener<Pubnews.Object>,
BaseMvp.PaginationListener<Int> {
fun getPubnews(page: Int, force: Boolean)
fun setCurrentSort(sortBy: PubnewsSortOption?, filterLang: String?, filterPublisher: String?)
fun getCurrentSort(): FantlabHelper.PubnewsSort<PubnewsSortOption, Int, Int>
}
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/plans/pubnews/PubnewsMvp.kt | 3843355378 |
/*
* Copyright 2016 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 pm.hhp.core.model.users
import org.junit.Assert.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class UserFactoryTest {
private lateinit var userFactory: UserFactory
@BeforeEach
fun setUp() {
userFactory = UserFactory()
}
@Test
fun shouldBePossibleToGenerateAnUserEntityGivenAnUserId() {
val userId = "8fba4e27-5a93-4d6a-96ad-9d1c9e198a67"
assertEquals(
userFactory.getUserEntity(
userId,
"name",
"[email protected]"
).userId.toString(),
userId
)
}
@Test
fun shouldBePossibleToGenerateAnUserEntityWithoutGivenAnUserId() {
val name = "name"
assertEquals(
userFactory.getUserEntity(
name,
"[email protected]"
).name,
name
)
}
} | src/test/kotlin/pm/hhp/core/model/users/UserFactoryTest.kt | 2418569931 |
package pl.shockah.godwit.android
import android.app.Activity
open class AndroidProvider(
val activity: Activity
) | android/src/pl/shockah/godwit/android/AndroidProvider.kt | 2265309518 |
package ktx.assets
import com.badlogic.gdx.utils.Pool
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertSame
import org.junit.Test
/**
* Tests [Pool] extensions.
*/
class PoolsTest {
@Test
fun `should invoke pool as no parameter function to provide instances`() {
// Given:
val pool = MockPool()
// When: Pool is called as a function.
val instance = pool()
// Then: Should work as "obtain":
assertNotNull(instance)
pool.free(instance)
assertSame(instance, pool()) // Since the object was freed, pool should return the same instance.
}
@Test
fun `should invoke pool as one parameter function to return instances`() {
// Given:
val pool = MockPool()
val instance = pool.obtain()
// When: Pool is called as a function with object parameter.
pool(instance)
// Then: Should work as "free".
assertEquals(1, pool.free)
assertSame(instance, pool.obtain()) // Since the object was freed, pool should return the same instance.
}
@Test
fun `should create new pools with custom providers`() {
// Given: A pool that always returns the same instance:
val provided = "10"
val pool = pool { provided }
// When:
val obtained = pool()
// Then:
assertSame(provided, obtained)
}
@Test
fun `should honor max setting`() {
// Given:
val pool = pool(max = 5) { "Mock." }
// When:
for (index in 1..10) pool.free("Value.")
// Then:
assertEquals(5, pool.free)
}
@Test
fun `should create new pools with a custom discard function`() {
// Given: A pool that adds discarded objects to a list:
val discarded = mutableListOf<String>()
val pool = pool(max = 5, discard = { discarded.add(it) }) { "Mock." }
// When:
for (index in 1..10) pool.free("Value$index")
// Then:
assertEquals(listOf("Value6", "Value7", "Value8", "Value9", "Value10"), discarded)
}
/**
* Provides new [Any] instances.
*/
private class MockPool : Pool<Any>() {
override fun newObject(): Any = Any()
}
}
| assets/src/test/kotlin/ktx/assets/PoolsTest.kt | 2458844475 |
/*
* StatCraft Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands
import java.sql.Connection
/**
* TODO - this will very likely change, I haven't looked at Sponge to see what will carry over
*/
interface StatCraftTemplate {
/**
* TODO
*/
fun hasPermission(sender: Any, args: Array<out String>?): Boolean
/**
* TODO
*/
fun playerStatResponse(name: String, args: List<String>, connection: Connection): String?
/**
* TODO
*/
fun serverStatResponse(num: Long, args: List<String>, connection: Connection): String?
}
| statcraft-api/src/main/kotlin/com/demonwav/statcraft/commands/StatCraftTemplate.kt | 172438680 |
/*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpm.lang.diagnostics
import com.intellij.psi.PsiElement
interface XpmDiagnostics {
fun error(element: PsiElement, code: String, description: String)
fun warning(element: PsiElement, code: String, description: String)
companion object {
// It is a *static error* if an expression is not a valid instance of the grammar.
const val XPST0003: String = "XPST0003"
}
}
| src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/lang/diagnostics/XpmDiagnostics.kt | 4043489999 |
/*
* Copyright (C) 2016-2017, 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.ast.plugin
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathPrimaryExpr
import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression
/**
* A MarkLogic 8.0 `NumberConstructor` node in the XQuery AST.
*/
interface PluginNumberConstructor : XPathPrimaryExpr, XpmExpression
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/plugin/PluginNumberConstructor.kt | 2324365447 |
package org.worldcubeassociation.tnoodle.server.webscrambles.zip.folder
import org.worldcubeassociation.tnoodle.server.webscrambles.Translate
import org.worldcubeassociation.tnoodle.server.webscrambles.exceptions.ScheduleMatchingException
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.StringUtil.toFileSafeString
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.CompetitionDrawingData
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.WCIFDataBuilder
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model.Schedule
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.folder
import org.worldcubeassociation.tnoodle.server.webscrambles.zip.model.Folder
import java.time.LocalDate
import java.time.Period
import java.time.ZonedDateTime
data class OrderedScramblesFolder(val globalTitle: String, val scrambleDrawingData: CompetitionDrawingData) {
fun assemble(wcifSchedule: Schedule, generationDate: LocalDate, versionTag: String): Folder {
val wcifBindings = wcifSchedule.allActivities
// scrambleSetId as assigned by WCIFScrambleMatcher#matchActivity
.filter { it.scrambleSetId != null }
.associateWith { act ->
scrambleDrawingData.scrambleSheets.filter { it.scrambleSet.id == act.scrambleSetId }.unlessEmpty()
?: ScheduleMatchingException.error("Ordered Scrambles: Could not find ScrambleSet ${act.scrambleSetId} associated with Activity $act")
}.mapValues { (act, scrs) ->
scrs.filter { act.activityCode.isParentOf(it.activityCode) }.unlessEmpty()
?: ScheduleMatchingException.error("Ordered Scrambles: Could not find any activity for scramble sheets affiliated with ScrambleSet ${act.scrambleSetId}")
}
val activityDays = wcifSchedule.activitiesWithLocalStartTimes
.map { it.value.dayOfYear }
.distinct()
// hasMultipleDays gets a variable assigned on the competition creation using the website's form.
// Online schedule fit to it and the user should not be able to put events outside it, but we double check here.
// The next assignment fix possible mistakes (eg. a competition is assigned with 1 day, but events are spread among 2 days).
val hasMultipleDays = wcifSchedule.hasMultipleDays || activityDays.size > 1
val hasMultipleVenues = wcifSchedule.hasMultipleVenues
// We consider the competition start date as the earlier activity from the schedule.
// This prevents miscalculation of dates for multiple timezones.
val competitionStartActivity = wcifSchedule.earliestActivity
return folder("Ordered Scrambles") {
for (venue in wcifSchedule.venues) {
val venueName = venue.fileSafeName
val hasMultipleRooms = venue.hasMultipleRooms
val timezone = venue.dateTimeZone
val competitionStartDate = competitionStartActivity.getLocalStartTime(timezone)
for (room in venue.rooms) {
val roomName = room.fileSafeName
val activitiesPerDay = room.activities
.flatMap { it.leafChildActivities }
.groupBy {
Period.between(
competitionStartDate.atLocalStartOfDay(),
it.getLocalStartTime(timezone).atLocalStartOfDay()
).days
}
for ((nthDay, activities) in activitiesPerDay) {
val scrambles = activities.associateWith(wcifBindings::get)
.filterValuesNotNull()
val activitiesHaveScrambles = scrambles.values.flatten().isNotEmpty()
if (activitiesHaveScrambles) {
val filenameDay = nthDay + 1
val parts = listOfNotNull(
"$venueName/".takeIf { hasMultipleVenues },
"Day $filenameDay/".takeIf { hasMultipleDays },
"Ordered Scrambles",
" - $venueName".takeIf { hasMultipleVenues },
" - Day $filenameDay".takeIf { hasMultipleDays },
" - $roomName".takeIf { hasMultipleRooms },
".pdf"
)
if (hasMultipleVenues || hasMultipleDays || hasMultipleRooms) {
// In addition to different folders, we stamp venue, day and room in the PDF's name
// to prevent different files with the same name.
val pdfFileName = parts.joinToString("")
val sortedScrambles = scrambles.entries
.sortedBy { it.key.getLocalStartTime(timezone) }
.flatMap { it.value }
val sheetData = scrambleDrawingData.copy(scrambleSheets = sortedScrambles)
val sheet = WCIFDataBuilder.requestsToCompletePdf(sheetData, generationDate, versionTag, Translate.DEFAULT_LOCALE)
file(pdfFileName, sheet.render())
}
}
}
}
}
// Generate all scrambles ordered
val allScramblesOrdered = wcifSchedule.activitiesWithLocalStartTimes.entries
.sortedBy { it.value }
// the notNull will effectively never happen, because we guarantee that all relevant activities are indexed
.mapNotNull { wcifBindings[it.key] }
.flatten()
.distinct()
val allScramblesData = scrambleDrawingData.copy(scrambleSheets = allScramblesOrdered)
val completeOrderedPdf = WCIFDataBuilder.requestsToCompletePdf(allScramblesData, generationDate, versionTag, Translate.DEFAULT_LOCALE)
val safeGlobalTitle = globalTitle.toFileSafeString()
file("Ordered $safeGlobalTitle - All Scrambles.pdf", completeOrderedPdf.render())
}
}
companion object {
fun ZonedDateTime.atLocalStartOfDay() = toLocalDate().atStartOfDay(zone).toLocalDate()
fun <K, V> Map<K, V?>.filterValuesNotNull(): Map<K, V> = mapNotNull { (k, v) -> v?.let { k to it } }.toMap()
fun <T, C : Collection<T>> C.unlessEmpty(): C? = takeIf { it.isNotEmpty() }
}
}
| webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/zip/folder/OrderedScramblesFolder.kt | 3158641957 |
/*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xqdoc.documentation
import uk.co.reecedunn.intellij.plugin.xqdoc.resources.XQDocBundle
val XQDocDocumentation.sections: String
get() {
val sections = sequenceOf(
XQDocBundle.message("section.summary") to summary,
XQDocBundle.message("section.operator-mapping") to (this as? XQDocFunctionDocumentation)?.operatorMapping,
XQDocBundle.message("section.signatures") to (this as? XQDocFunctionDocumentation)?.signatures,
XQDocBundle.message("section.parameters") to (this as? XQDocFunctionDocumentation)?.parameters,
XQDocBundle.message("section.properties") to (this as? XQDocFunctionDocumentation)?.properties,
XQDocBundle.message("section.required-privileges") to (this as? XQDocFunctionDocumentation)?.privileges,
XQDocBundle.message("section.rules") to (this as? XQDocFunctionDocumentation)?.rules,
XQDocBundle.message("section.error-conditions") to (this as? XQDocFunctionDocumentation)?.errorConditions,
XQDocBundle.message("section.notes") to notes,
XQDocBundle.message("section.examples") to examples
).filter { it.second != null }
return "<dl>${sections.joinToString("") { "<dt>${it.first}</dt><dd>${it.second}</dd>" }}</dl>"
}
| src/lang-xqdoc/main/uk/co/reecedunn/intellij/plugin/xqdoc/documentation/Documentation.kt | 4211568043 |
package org.stepik.android.view.step_quiz_fill_blanks.ui.delegate
import android.view.View
import androidx.fragment.app.FragmentManager
import com.google.android.flexbox.FlexboxLayoutManager
import kotlinx.android.synthetic.main.fragment_step_quiz.view.*
import kotlinx.android.synthetic.main.layout_step_quiz_fill_blanks.view.*
import org.stepic.droid.R
import ru.nobird.android.core.model.mutate
import org.stepik.android.model.Reply
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz.model.ReplyResult
import org.stepik.android.view.step_quiz.resolver.StepQuizFormResolver
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate
import org.stepik.android.view.step_quiz_fill_blanks.ui.adapter.delegate.FillBlanksItemInputAdapterDelegate
import org.stepik.android.view.step_quiz_fill_blanks.ui.adapter.delegate.FillBlanksItemSelectAdapterDelegate
import org.stepik.android.view.step_quiz_fill_blanks.ui.adapter.delegate.FillBlanksItemTextAdapterDelegate
import org.stepik.android.view.step_quiz_fill_blanks.ui.fragment.FillBlanksInputBottomSheetDialogFragment
import org.stepik.android.view.step_quiz_fill_blanks.ui.mapper.FillBlanksItemMapper
import org.stepik.android.view.step_quiz_fill_blanks.ui.model.FillBlanksItem
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
import ru.nobird.android.view.base.ui.extension.showIfNotExists
class FillBlanksStepQuizFormDelegate(
private val containerView: View,
private val fragmentManager: FragmentManager,
private val onQuizChanged: (ReplyResult) -> Unit
) : StepQuizFormDelegate {
private val quizDescription = containerView.stepQuizDescription
private val itemsAdapter = DefaultDelegateAdapter<FillBlanksItem>()
private val fillBlanksItemMapper = FillBlanksItemMapper()
init {
quizDescription.setText(R.string.step_quiz_fill_blanks_description)
itemsAdapter += FillBlanksItemTextAdapterDelegate()
itemsAdapter += FillBlanksItemInputAdapterDelegate(onItemClicked = ::inputItemAction)
itemsAdapter += FillBlanksItemSelectAdapterDelegate(onItemClicked = ::selectItemAction)
with(containerView.fillBlanksRecycler) {
itemAnimator = null
adapter = itemsAdapter
isNestedScrollingEnabled = false
layoutManager = FlexboxLayoutManager(context)
}
}
fun updateInputItem(index: Int, text: String) {
itemsAdapter.items = itemsAdapter.items.mutate {
val inputItem = get(index) as FillBlanksItem.Input
set(index, inputItem.copy(text = text))
}
itemsAdapter.notifyItemChanged(index)
onQuizChanged(createReply())
}
private fun selectItemAction(index: Int, text: String) {
itemsAdapter.items = itemsAdapter.items.mutate {
val selectItem = get(index) as FillBlanksItem.Select
set(index, selectItem.copy(text = text))
}
onQuizChanged(createReply())
}
private fun inputItemAction(index: Int, text: String) {
FillBlanksInputBottomSheetDialogFragment
.newInstance(index, text)
.showIfNotExists(fragmentManager, FillBlanksInputBottomSheetDialogFragment.TAG)
}
override fun setState(state: StepQuizFeature.State.AttemptLoaded) {
val submission = (state.submissionState as? StepQuizFeature.SubmissionState.Loaded)
?.submission
itemsAdapter.items = fillBlanksItemMapper.mapToFillBlanksItems(state.attempt, submission, StepQuizFormResolver.isQuizEnabled(state))
containerView.post { containerView.fillBlanksRecycler.requestLayout() }
}
override fun createReply(): ReplyResult =
ReplyResult(
Reply(
blanks = itemsAdapter
.items
.mapNotNull { item ->
when (item) {
is FillBlanksItem.Text ->
null
is FillBlanksItem.Input ->
item.text
is FillBlanksItem.Select ->
item.text
}
}
),
ReplyResult.Validation.Success
)
} | app/src/main/java/org/stepik/android/view/step_quiz_fill_blanks/ui/delegate/FillBlanksStepQuizFormDelegate.kt | 3375452474 |
package org.stepik.android.data.certificate.source
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.android.core.model.PagedList
import org.stepik.android.model.Certificate
interface CertificateRemoteDataSource {
fun getCertificate(userId: Long, courseId: Long): Maybe<Certificate>
fun getCertificates(userId: Long, page: Int = 1): Single<PagedList<Certificate>>
} | app/src/main/java/org/stepik/android/data/certificate/source/CertificateRemoteDataSource.kt | 3032043087 |
package app.test
import org.springframework.data.repository.CrudRepository
/**
* Created by michal on 19/05/2017.
*/
interface AnswerRepository : CrudRepository<Answer, Long> {
}
| backend/src/main/kotlin/app/test/AnswerRepository.kt | 412102818 |
package com.github.skuznets0v.metro.services
import com.github.skuznets0v.metro.model.entities.Station
interface StationService {
fun getAllForScheme(schemeUrn: String): List<Station>
}
| src/main/kotlin/com/github/skuznets0v/metro/services/StationService.kt | 857352203 |
package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.DefaultBow
import nl.sugcube.dirtyarrows.util.fuzz
import org.bukkit.Material
import org.bukkit.entity.Arrow
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.event.entity.ProjectileHitEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
import kotlin.random.Random
/**
* Paralyzes the target, which is a random cocktail of:
* - Confusion
* - Slowness
* - Weakness
* - Blindness
*
* @author SugarCaney
*/
open class ParalyzeBow(plugin: DirtyArrows) : BowAbility(
plugin = plugin,
type = DefaultBow.PARALYZE,
canShootInProtectedRegions = true,
costRequirements = listOf(ItemStack(Material.NETHER_WART, 1)),
removeArrow = false,
description = "Paralyzes the target."
) {
/**
* How long the effects last in ticks.
*/
val effectTime = config.getInt("$node.effect-time")
/**
* How much variance there is in the effect time, in ticks.
*/
val effectTimeFuzzing = config.getInt("$node.effect-time-fuzzing")
/**
* How much chance the target has to be applied a certain effect in `[0,1]`.
*/
val effectChance = config.getDouble("$node.effect-chance")
/**
* How much chance the target has to be confused in `[0,1]`.
*/
val confusionChance = config.getDouble("$node.confusion-chance")
init {
check(effectTime >= 0) { "$node.effect-time must not be negative, got <$effectTime>" }
check(effectTimeFuzzing >= 0) { "$node.effect-time-fuzzing must not be negative, got <$effectTimeFuzzing>" }
check(effectChance in 0.0..1.0) { "$node.effect-chance must be between 0 and 1, got <$effectChance>" }
check(confusionChance in 0.0..1.0) { "$node.confusion-chance must be between 0 and 1, got <$confusionChance>" }
}
override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) {
val target = event.hitEntity as? LivingEntity ?: return
if (Random.nextDouble() < confusionChance) {
target.giveEffect(PotionEffectType.CONFUSION)
}
if (Random.nextDouble() < effectChance) {
target.giveEffect(PotionEffectType.SLOW)
}
if (Random.nextDouble() < effectChance) {
target.giveEffect(PotionEffectType.WEAKNESS)
}
if (Random.nextDouble() < effectChance) {
target.giveEffect(PotionEffectType.BLINDNESS)
}
}
/**
* Applies the given potion/paralyze effect for a random time.
*/
private fun LivingEntity.giveEffect(type: PotionEffectType) {
val time = effectTime.fuzz(effectTimeFuzzing) + if (type == PotionEffectType.CONFUSION) 60 else 0
val level = if (type == PotionEffectType.CONFUSION) 1.fuzz(1) else 20
addPotionEffect(PotionEffect(type, time, level))
}
} | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/ParalyzeBow.kt | 2210630825 |
package com.vmenon.mpo.api.pact
import au.com.dius.pact.consumer.dsl.LambdaDsl
import au.com.dius.pact.consumer.dsl.LambdaDslObject
import au.com.dius.pact.consumer.dsl.PactDslJsonRootValue
import au.com.dius.pact.consumer.dsl.PactDslWithProvider
import au.com.dius.pact.consumer.junit.PactProviderRule
import au.com.dius.pact.consumer.junit.PactVerification
import au.com.dius.pact.core.model.RequestResponsePact
import au.com.dius.pact.core.model.annotations.Pact
import com.vmenon.mpo.api.model.RegisterUserRequest
import com.vmenon.mpo.common.framework.di.dagger.ApiModule
import okhttp3.OkHttpClient
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
class MpoApiPactTest {
@Rule
@JvmField
val provider = PactProviderRule("mpo-api", this)
@Pact(consumer = "consumer-mpo-api")
fun createSearchPact(builder: PactDslWithProvider): RequestResponsePact {
return builder
.given("default")
.uponReceiving("Search for shows")
.path("/podcasts")
.query("keyword=$SEARCH_KEYWORD")
.method("GET")
.willRespondWith()
.status(200)
.body(LambdaDsl.newJsonArray { array ->
array.`object` { item ->
item.stringType(
"name",
"artworkUrl",
"feedUrl",
"smallArtworkUrl",
"author"
)
item.eachLike("genres", PactDslJsonRootValue.stringType())
}
}.build()).toPact()
}
@Pact(consumer = "consumer-mpo-api")
fun createShowDetailsPact(builder: PactDslWithProvider): RequestResponsePact {
return builder
.given("default")
.uponReceiving("Get Show Details")
.path("/podcastdetails")
.query("maxEpisodes=$MAX_EPISODES&feedUrl=$FEED_URL")
.method("GET")
.willRespondWith()
.status(200)
.body(LambdaDsl.newJsonBody { root ->
root.stringType(
"name",
"description",
"imageUrl"
)
root.eachLike("episodes") { item: LambdaDslObject ->
item.stringType(
"name",
"artworkUrl",
"feedUrl",
"smallArtworkUrl",
"author"
)
item.eachLike("genres", PactDslJsonRootValue.stringType())
}
}.build()).toPact()
}
@Pact(consumer = "consumer-mpo-api")
fun createShowUpdatePact(builder: PactDslWithProvider): RequestResponsePact {
return builder
.given("default")
.uponReceiving("Get Show update")
.path("/podcastupdate")
.query("feedUrl=$FEED_URL&publishTimestamp=$PUBLISH_TIMESTAMP")
.method("GET")
.willRespondWith()
.status(200)
.body(LambdaDsl.newJsonBody { root ->
root.stringType(
"name",
"artworkUrl",
"description",
"type",
"artworkUrl"
)
root.numberType(
"published",
"length"
)
}.build()).toPact()
}
@Pact(consumer = "consumer-mpo-api")
fun registerUserPact(builder: PactDslWithProvider): RequestResponsePact {
return builder
.given("default")
.uponReceiving("Register a User")
.path("/register_user")
.method("POST")
.body(LambdaDsl.newJsonBody { body ->
body.stringType(
"firstName",
"lastName",
"email",
"password"
)
}.build())
.willRespondWith()
.status(200)
.body(LambdaDsl.newJsonBody { body ->
body.stringType(
"firstName",
"lastName",
"email"
)
}.build()).toPact()
}
@Test
@PactVerification(fragment = "createSearchPact")
fun `should fetch shows from provider`() {
val response = client().searchPodcasts(SEARCH_KEYWORD).blockingGet()
Assert.assertFalse(response.isEmpty())
}
@Test
@PactVerification(fragment = "createShowDetailsPact")
fun `should fetch show details from provider`() {
val response = client().getPodcastDetails(FEED_URL, MAX_EPISODES).blockingGet()
Assert.assertNotNull(response)
}
@Test
@PactVerification(fragment = "createShowUpdatePact")
fun `should fetch show update from provider`() {
val response = client().getPodcastUpdate(FEED_URL, PUBLISH_TIMESTAMP).blockingGet()
Assert.assertNotNull(response)
}
@Test
@PactVerification(fragment = "registerUserPact")
fun `should register a User`() {
val response = client().registerUser(
RegisterUserRequest(
firstName = "User First Name",
lastName = "User Last Name",
email = "User email",
password = "User password"
)
).blockingGet()
Assert.assertNotNull(response)
}
private fun client() =
ApiModule.provideMediaPlayerRetrofitApi(provider.url, OkHttpClient.Builder().build())
companion object {
private const val SEARCH_KEYWORD = "Game Scoop! TV (Video)"
private const val MAX_EPISODES = 10
private const val FEED_URL = "http://feeds.ign.com/ignfeeds/podcasts/video/gamescoop"
private const val PUBLISH_TIMESTAMP = 1507661400000
}
} | api_pact/src/test/java/com/vmenon/mpo/api/pact/MpoApiPactTest.kt | 1860009939 |
package nl.shadowlink.tools.shadowmapper.gui.checklist
import java.awt.event.*
import javax.swing.*
import javax.swing.event.ListSelectionEvent
import javax.swing.event.ListSelectionListener
// @author Santhosh Kumar T - [email protected]
class CheckListManager<T>(
private val list: JList<T>,
private val onSelectionToggled: (index: Int, isSelected: Boolean) -> Unit,
) : MouseAdapter(), ListSelectionListener, ActionListener {
private val selectionModel: ListSelectionModel = DefaultListSelectionModel()
var hotspot = JCheckBox().preferredSize.width
init {
list.cellRenderer = CheckListCellRenderer(list.cellRenderer, selectionModel)
list.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_FOCUSED)
list.addMouseListener(this)
selectionModel.addListSelectionListener(this)
}
private fun toggleSelection(index: Int) {
if (index < 0) return
if (selectionModel.isSelectedIndex(index)) {
selectionModel.removeSelectionInterval(index, index)
onSelectionToggled(index, false)
} else {
selectionModel.addSelectionInterval(index, index)
onSelectionToggled(index, true)
}
}
override fun mouseClicked(me: MouseEvent) {
val index = list.locationToIndex(me.point)
if (index < 0) return
if (me.x > list.getCellBounds(index, index).x + hotspot) return
toggleSelection(index)
}
override fun valueChanged(e: ListSelectionEvent) {
list.repaint(list.getCellBounds(e.firstIndex, e.lastIndex))
}
override fun actionPerformed(e: ActionEvent) {
toggleSelection(list.selectedIndex)
}
} | src/main/java/nl/shadowlink/tools/shadowmapper/gui/checklist/CheckListManager.kt | 3320519043 |
package com.msc.serverbrowser.gui.controllers.implementations
import com.github.plushaze.traynotification.animations.Animations
import com.github.plushaze.traynotification.notification.NotificationTypeImplementations
import com.github.plushaze.traynotification.notification.TrayNotificationBuilder
import com.msc.serverbrowser.Client
import com.msc.serverbrowser.constants.PathConstants
import com.msc.serverbrowser.data.properties.ClientPropertiesController
import com.msc.serverbrowser.data.properties.UseDarkThemeProperty
import com.msc.serverbrowser.gui.controllers.interfaces.ViewController
import com.msc.serverbrowser.gui.views.FilesView
import com.msc.serverbrowser.info
import com.msc.serverbrowser.severe
import com.msc.serverbrowser.util.basic.FileUtility
import com.msc.serverbrowser.util.basic.StringUtility
import com.msc.serverbrowser.warn
import javafx.event.EventHandler
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.util.function.Predicate
import java.util.regex.Pattern
/**
* Controls the Files view which allows you to look at your taken screenshots, your chatlogs and
* your saved positions.
*
* @author Marcel
* @since 08.07.2017
*
* @property filesView the view to be used by this controller
*/
class FilesController(private val filesView: FilesView) : ViewController {
init {
filesView.setLoadChatLogsButtonAction(EventHandler { loadChatLog() })
filesView.setClearChatLogsButtonAction(EventHandler { clearChatLog() })
filesView.showColorsProperty.addListener { _ -> loadChatLog() }
filesView.showColorsAsTextProperty.addListener { _ -> loadChatLog() }
filesView.showTimesIfAvailableProperty.addListener { _ -> loadChatLog() }
filesView.lineFilterProperty.addListener { _ -> loadChatLog() }
loadChatLog()
}
private fun loadChatLog() {
val darkThemeInUse = ClientPropertiesController.getProperty(UseDarkThemeProperty)
val gray = "#333131"
val white = "#FFFFFF"
val newContent = StringBuilder("<html><body style='background-color: ")
.append(if (darkThemeInUse) gray else white)
.append("; color: ")
.append(if (darkThemeInUse) white else gray)
.append("';")
.append(">")
try {
val path = Paths.get(PathConstants.SAMP_CHATLOG)
val filterProperty = filesView.lineFilterProperty.valueSafe.toLowerCase()
FileUtility.readAllLinesTryEncodings(path, StandardCharsets.ISO_8859_1, StandardCharsets.UTF_8, StandardCharsets.US_ASCII)
.stream()
.filter(Predicate<String> { it.isEmpty() }.negate())
.filter { line -> line.toLowerCase().contains(filterProperty) }
.map { StringUtility.escapeHTML(it) }
.map { this.processSampChatlogTimestamps(it) }
.map { this.processSampColorCodes(it) }
.map { line -> "$line<br/>" }
.forEach { newContent.append(it) }
} catch (exception: FileNotFoundException) {
info("Chatlog file doesn't exist.")
} catch (exception: IOException) {
severe("Error loading chatlog.", exception)
}
filesView.setChatLogTextAreaContent(newContent.toString())
}
private fun processSampChatlogTimestamps(line: String): String {
if (filesView.showTimesIfAvailableProperty.get()) {
return line
}
val timeRegex = "\\[(?:(?:([01]?\\d|2[0-3]):)?([0-5]?\\d):)?([0-5]?\\d)]"
return if (line.length >= 10 && line.substring(0, 10).matches(timeRegex.toRegex())) {
line.replaceFirst(timeRegex.toRegex(), "")
} else line
}
private fun processSampColorCodes(line: String): String {
val showColorsAsText = filesView.showColorsAsTextProperty.get()
val showColors = filesView.showColorsProperty.get()
if (showColorsAsText && !showColors) {
return line
}
val colorRegex = "([{](.{6})[}])"
if (showColors) {
var fixedLine = "<span>" + line.replace("{000000}", "{FFFFFF}")
val colorCodeMatcher = Pattern.compile(colorRegex).matcher(fixedLine)
while (colorCodeMatcher.find()) {
val replacementColorCode = "#" + colorCodeMatcher.group(2)
val replacement = StringBuilder("</span><span style='color:")
.append(replacementColorCode)
.append(";'>")
val color = colorCodeMatcher.group(1)
if (showColorsAsText) {
replacement.append(color)
}
fixedLine = fixedLine.replace(color, replacement.toString())
}
return "$fixedLine</span>"
}
return line.replace(colorRegex.toRegex(), "")
}
private fun clearChatLog() {
try {
Files.deleteIfExists(Paths.get(PathConstants.SAMP_CHATLOG))
loadChatLog()
} catch (exception: IOException) {
TrayNotificationBuilder()
.type(NotificationTypeImplementations.ERROR)
.animation(Animations.POPUP)
.title(Client.getString("couldntClearChatLog"))
.message(Client.getString("checkLogsForMoreInformation")).build().showAndDismiss(Client.DEFAULT_TRAY_DISMISS_TIME)
warn("Couldn't clear chatlog", exception)
}
}
}
| src/main/kotlin/com/msc/serverbrowser/gui/controllers/implementations/FilesController.kt | 2284410265 |
package com.grenzfrequence.showmycar.car_types.data.repos
import com.grenzfrequence.githubviewerkotlin.webservice.WebServiceConfig
import com.grenzfrequence.showmycar.car_types.data.model.MainTypesModel
import com.grenzfrequence.showmycar.webservice.ShowMyCarApi
import io.reactivex.Observable
import retrofit2.Response
import javax.inject.Inject
import kotlin.collections.Map.Entry
/**
* Created by grenzfrequence on 18.08.17.
*/
class MainTypesRepository
@Inject
constructor(val showMyCarApi: ShowMyCarApi) : Repository<MainTypesModel>() {
lateinit var manufacturer: Entry<String, String>
override fun nextPage(): Observable<Response<MainTypesModel>> {
return showMyCarApi.getMainTypes(manufacturer.key, ++currentPageNr, WebServiceConfig.CARTYPES_PAGE_SIZE)
}
}
| app/src/main/java/com/grenzfrequence/showmycar/car_types/data/repos/MainTypesRepository.kt | 2575812489 |
package com.mindera.skeletoid.analytics
import android.app.Activity
import android.content.Context
import android.os.Bundle
import com.mindera.skeletoid.analytics.appenders.interfaces.IAnalyticsAppender
import com.mindera.skeletoid.utils.extensions.mock
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import java.util.ArrayList
import java.util.HashMap
import java.util.HashSet
class AnalyticsUnitTest {
private lateinit var context: Context
@Before
fun setUp() {
context = Mockito.mock(Context::class.java)
}
@After
fun cleanUp() {
Analytics.deinit()
}
@Test
fun testInit() {
Analytics.init(context)
}
@Test
fun testInitWithParams() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
//Must have logger initialized for this test
Analytics.init(context, appenders)
Assert.assertTrue(Analytics.isInitialized)
}
@Test
fun testIsInitialized() {
Assert.assertFalse(Analytics.isInitialized)
Analytics.init(context)
Assert.assertTrue(Analytics.isInitialized)
}
@Test
fun testDeinit() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
//Must have logger initialized for this test
Analytics.init(context, appenders)
Analytics.deinit()
Mockito.verify(appenderA, Mockito.times(1)).disableAppender()
Mockito.verify(appenderB, Mockito.times(1)).disableAppender()
Mockito.verify(appenderC, Mockito.times(1)).disableAppender()
}
@Test
fun testAddAppenders() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
val appendersIds = Analytics.init(context, appenders)
Mockito.verify(appenderA, Mockito.times(1)).enableAppender(context)
Mockito.verify(appenderB, Mockito.times(1)).enableAppender(context)
Mockito.verify(appenderC, Mockito.times(1)).enableAppender(context)
Assert.assertNotNull(appendersIds)
Assert.assertEquals(3, appendersIds.size)
Assert.assertTrue(appendersIds.contains("A"))
Assert.assertTrue(appendersIds.contains("B"))
Assert.assertTrue(appendersIds.contains("C"))
}
@Test
fun testAddAppendersRepeated() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB1 = mockAppender("B")
val appenderB2 = mockAppender("B")
appenders.add(appenderA)
appenders.add(appenderB1)
appenders.add(appenderB2)
Analytics.init(context)
val appendersIds = Analytics.init(context, appenders)
Assert.assertNotNull(appendersIds)
Assert.assertEquals(2, appendersIds.size)
Assert.assertTrue(appendersIds.contains("A"))
Assert.assertTrue(appendersIds.contains("B"))
}
@Test
fun testDisableAppendersEmpty() {
Analytics.removeAppenders(context, HashSet())
}
@Test
fun testRemoveAppenders() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
Analytics.init(context)
val appendersIds = Analytics.addAppenders(context, appenders)
Analytics.removeAppenders(context, appendersIds)
Mockito.verify(appenderA, Mockito.times(1)).disableAppender()
Mockito.verify(appenderB, Mockito.times(1)).disableAppender()
Mockito.verify(appenderC, Mockito.times(1)).disableAppender()
}
@Test
fun testRemoveAllAppenders() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
Analytics.init(context)
Analytics.addAppenders(context, appenders)
Analytics.removeAllAppenders()
Mockito.verify(appenderA, Mockito.times(1)).disableAppender()
Mockito.verify(appenderB, Mockito.times(1)).disableAppender()
Mockito.verify(appenderC, Mockito.times(1)).disableAppender()
}
@Test
fun testTrackEvent() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
Analytics.init(context, appenders)
val analyticsPayload: MutableMap<String, Any> = HashMap()
analyticsPayload["A"] = "A1"
analyticsPayload["B"] = "B1"
analyticsPayload["C"] = "C1"
Analytics.trackEvent("test", analyticsPayload)
Mockito.verify(appenderA, Mockito.times(1))
.trackEvent("test", analyticsPayload)
Mockito.verify(appenderB, Mockito.times(1))
.trackEvent("test", analyticsPayload)
Mockito.verify(appenderC, Mockito.times(1))
.trackEvent("test", analyticsPayload)
}
@Test
fun testTrackEventWithBundle() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
Analytics.init(context, appenders)
val analyticsPayload = Bundle()
analyticsPayload.putString("A", "A1")
analyticsPayload.putString("B", "B1")
analyticsPayload.putString("C", "C1")
Analytics.trackEvent("test", analyticsPayload)
Mockito.verify(appenderA, Mockito.times(1))
.trackEvent("test", analyticsPayload)
Mockito.verify(appenderB, Mockito.times(1))
.trackEvent("test", analyticsPayload)
Mockito.verify(appenderC, Mockito.times(1))
.trackEvent("test", analyticsPayload)
}
@Test
fun testTrackPageHit() {
val activity : Activity = mock()
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
Analytics.init(context, appenders)
Analytics.trackPageHit(activity, "test", "screen class")
Mockito.verify(appenderA, Mockito.times(1))
.trackPageHit(activity, "test", "screen class")
Mockito.verify(appenderB, Mockito.times(1))
.trackPageHit(activity, "test", "screen class")
Mockito.verify(appenderC, Mockito.times(1))
.trackPageHit(activity, "test", "screen class")
Analytics.trackPageHit("test", "screen class")
Mockito.verify(appenderA, Mockito.times(1))
.trackPageHit("test", "screen class")
Mockito.verify(appenderB, Mockito.times(1))
.trackPageHit("test", "screen class")
Mockito.verify(appenderC, Mockito.times(1))
.trackPageHit("test", "screen class")
}
@Test
fun testSetUserID() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
Analytics.init(context, appenders)
Analytics.setUserID("1234")
Mockito.verify(appenderA, Mockito.times(1)).setUserId("1234")
Mockito.verify(appenderB, Mockito.times(1)).setUserId("1234")
Mockito.verify(appenderC, Mockito.times(1)).setUserId("1234")
}
@Test
fun testSetUserProperty() {
val appenders: MutableList<IAnalyticsAppender> = ArrayList()
val appenderA = mockAppender("A")
val appenderB = mockAppender("B")
val appenderC = mockAppender("C")
appenders.add(appenderA)
appenders.add(appenderB)
appenders.add(appenderC)
Analytics.init(context, appenders)
Analytics.setUserProperty("name", "banana")
Analytics.setUserProperty("age", "30")
Mockito.verify(appenderA, Mockito.times(1))
.setUserProperty("name", "banana")
Mockito.verify(appenderB, Mockito.times(1))
.setUserProperty("name", "banana")
Mockito.verify(appenderC, Mockito.times(1))
.setUserProperty("name", "banana")
Mockito.verify(appenderA, Mockito.times(1)).setUserProperty("age", "30")
Mockito.verify(appenderB, Mockito.times(1)).setUserProperty("age", "30")
Mockito.verify(appenderC, Mockito.times(1)).setUserProperty("age", "30")
}
private fun mockAppender(analyticsId: String): IAnalyticsAppender {
val appender: IAnalyticsAppender = mock()
Mockito.`when`(appender.analyticsId).thenReturn(analyticsId)
return appender
}
} | base/src/test/java/com/mindera/skeletoid/analytics/AnalyticsUnitTest.kt | 2623899277 |
package nebula.plugin.compile.provider
import org.gradle.api.JavaVersion
interface JDKPathProvider {
fun provide(javaVersion: JavaVersion): String?
} | src/main/kotlin/nebula/plugin/compile/provider/JDKPathProvider.kt | 1353122387 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.test
import com.intellij.configurationStore.SchemeManagerImpl
import com.intellij.configurationStore.TestScheme
import com.intellij.configurationStore.TestSchemesProcessor
import com.intellij.configurationStore.save
import com.intellij.testFramework.ProjectRule
import com.intellij.util.xmlb.serialize
import com.intellij.util.xmlb.toByteArray
import org.assertj.core.api.Assertions.assertThat
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.ReadonlySource
import org.jetbrains.settingsRepository.git.GitRepositoryManager
import org.jetbrains.settingsRepository.git.cloneBare
import org.jetbrains.settingsRepository.git.commit
import org.junit.ClassRule
import org.junit.Test
private val dirName = "keymaps"
class LoadTest : IcsTestCase() {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
private fun createSchemeManager(dirPath: String) = SchemeManagerImpl(dirPath, TestSchemesProcessor(), provider, tempDirManager.newPath("schemes"))
@Test fun `load scheme`() {
val localScheme = TestScheme("local")
provider.write("$dirName/local.xml", localScheme.serialize().toByteArray())
val schemeManager = createSchemeManager(dirName)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(localScheme)
schemeManager.save()
val dirPath = (icsManager.repositoryManager as GitRepositoryManager).repository.workTree.toPath().resolve(dirName)
assertThat(dirPath).isDirectory()
schemeManager.removeScheme(localScheme)
schemeManager.save()
assertThat(dirPath).doesNotExist()
provider.write("$dirName/local1.xml", TestScheme("local1").serialize().toByteArray())
provider.write("$dirName/local2.xml", TestScheme("local2").serialize().toByteArray())
assertThat(dirPath.resolve("local1.xml")).isRegularFile()
assertThat(dirPath.resolve("local2.xml")).isRegularFile()
schemeManager.loadSchemes()
schemeManager.removeScheme("local1")
schemeManager.save()
assertThat(dirPath.resolve("local1.xml")).doesNotExist()
assertThat(dirPath.resolve("local2.xml")).isRegularFile()
}
@Test fun `load scheme with the same names`() {
val localScheme = TestScheme("local")
val data = localScheme.serialize().toByteArray()
provider.write("$dirName/local.xml", data)
provider.write("$dirName/local2.xml", data)
val schemeManager = createSchemeManager(dirName)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(localScheme)
}
@Test fun `load scheme from repo and read-only repo`() {
val localScheme = TestScheme("local")
provider.write("$dirName/local.xml", localScheme.serialize().toByteArray())
val remoteScheme = TestScheme("remote")
val remoteRepository = tempDirManager.createRepository()
remoteRepository
.add("$dirName/Mac OS X from RubyMine.xml", remoteScheme.serialize().toByteArray())
.commit("")
remoteRepository.useAsReadOnlySource {
val schemesManager = createSchemeManager(dirName)
schemesManager.loadSchemes()
assertThat(schemesManager.allSchemes).containsOnly(remoteScheme, localScheme)
assertThat(schemesManager.isMetadataEditable(localScheme)).isTrue()
assertThat(schemesManager.isMetadataEditable(remoteScheme)).isFalse()
}
}
@Test fun `scheme overrides read-only`() {
val schemeName = "Emacs"
val localScheme = TestScheme(schemeName, "local")
provider.write("$dirName/$schemeName.xml", localScheme.serialize().toByteArray())
val remoteScheme = TestScheme(schemeName, "remote")
val remoteRepository = tempDirManager.createRepository("remote")
remoteRepository
.add("$dirName/$schemeName.xml", remoteScheme.serialize().toByteArray())
.commit("")
remoteRepository.useAsReadOnlySource {
val schemeManager = createSchemeManager(dirName)
schemeManager.loadSchemes()
assertThat(schemeManager.allSchemes).containsOnly(localScheme)
assertThat(schemeManager.isMetadataEditable(localScheme)).isFalse()
}
}
inline fun Repository.useAsReadOnlySource(runnable: () -> Unit) {
createAndRegisterReadOnlySource()
try {
runnable()
}
finally {
icsManager.readOnlySourcesManager.setSources(emptyList())
}
}
fun Repository.createAndRegisterReadOnlySource(): ReadonlySource {
val source = ReadonlySource(workTree.absolutePath)
assertThat(cloneBare(source.url!!, icsManager.readOnlySourcesManager.rootDir.resolve(source.path!!)).objectDatabase.exists()).isTrue()
icsManager.readOnlySourcesManager.setSources(listOf(source))
return source
}
} | plugins/settings-repository/testSrc/LoadTest.kt | 696667858 |
package xxx.jq.controller
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import xxx.jq.consts.Authorizes
import xxx.jq.entity.Account
import xxx.jq.form.SignInForm
import xxx.jq.form.SignUpForm
import xxx.jq.service.AccountService
import xxx.jq.service.AuthenticationService
import javax.servlet.http.HttpServletRequest
/**
* @author rinp
* @since 2015/10/08
*/
@RestController
@RequestMapping(value = "/v1/accounts")
open class AccountController {
@Autowired
lateinit private var service: AccountService
@Autowired
lateinit private var auth: AuthenticationService
@RequestMapping(value = "/signup", method = arrayOf(RequestMethod.POST), consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE))
open fun signUp(@RequestBody @Validated form: SignUpForm, request: HttpServletRequest): Account {
val account = service.save(form.toAccount())
auth.setAuthentication(account, form.password, request)
return account
}
@RequestMapping(value = "/signin", method = arrayOf(RequestMethod.POST), consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE))
open fun signIn(@RequestBody @Validated form: SignInForm, request: HttpServletRequest): Account {
val account = service.findByAccountId(form.accountId)
val rawPass = form.password
auth.setAuthentication(account, rawPass, request)
return account
}
//TODO これもMypageか別途コントローラーを切り出したい
@RequestMapping(value = "/in", method = arrayOf(RequestMethod.GET))
open fun isSignIn(): Boolean {
return auth.currentAccount.accountId != "system"
}
//TODO これもMypageか別途コントローラーを切り出したい
@RequestMapping(value = "/admin", method = arrayOf(RequestMethod.GET))
open fun isAdmin(): Boolean {
return auth.currentAccount.isAdmin
}
@PreAuthorize(Authorizes.ADMIN)
@RequestMapping(value = "/users", method = arrayOf(RequestMethod.GET))
open fun get(): List<Account> {
return service.findAll()
}
}
| src/main/kotlin/xxx/jq/controller/AccountController.kt | 1368354933 |
// 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.base.analysis
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.ide.scratch.ScratchUtil
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindMatcher
import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager
import org.jetbrains.kotlin.idea.base.projectStructure.isKotlinBinary
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import kotlin.script.experimental.api.ScriptAcceptedLocation
import kotlin.script.experimental.api.ScriptCompilationConfiguration
import kotlin.script.experimental.api.acceptedLocations
import kotlin.script.experimental.api.ide
internal class RootKindMatcherImpl(private val project: Project) : RootKindMatcher {
private val fileIndex by lazy { ProjectRootManager.getInstance(project).fileIndex }
override fun matches(filter: RootKindFilter, virtualFile: VirtualFile): Boolean {
ProgressManager.checkCanceled()
val fileType = FileTypeManager.getInstance().getFileTypeByFileName(virtualFile.nameSequence)
val kotlinExcludeLibrarySources = fileType == KotlinFileType.INSTANCE
&& !filter.includeLibrarySourceFiles
&& !filter.includeScriptsOutsideSourceRoots
if (kotlinExcludeLibrarySources && !filter.includeProjectSourceFiles) {
return false
}
if (virtualFile !is VirtualFileWindow && fileIndex.isInSourceContent(virtualFile)) {
return filter.includeProjectSourceFiles
}
if (kotlinExcludeLibrarySources) {
return false
}
val scriptConfiguration = (@Suppress("DEPRECATION") virtualFile.findScriptDefinition(project))?.compilationConfiguration
val scriptScope = scriptConfiguration?.get(ScriptCompilationConfiguration.ide.acceptedLocations)
val correctedFilter = if (scriptScope != null) {
val includeEverything = scriptScope.containsAllowedLocations() || ScratchUtil.isScratch(virtualFile)
val includeLibrariesForScripts = includeEverything || scriptScope.contains(ScriptAcceptedLocation.Libraries)
val includeProjectSourceFilesForScripts = includeEverything
|| scriptScope.contains(ScriptAcceptedLocation.Sources)
|| scriptScope.contains(ScriptAcceptedLocation.Tests)
filter.copy(
includeProjectSourceFiles = filter.includeProjectSourceFiles && includeProjectSourceFilesForScripts,
includeLibrarySourceFiles = filter.includeLibrarySourceFiles && includeLibrariesForScripts,
includeLibraryClassFiles = filter.includeLibraryClassFiles && includeLibrariesForScripts,
includeScriptDependencies = filter.includeScriptDependencies && includeLibrariesForScripts,
includeScriptsOutsideSourceRoots = filter.includeScriptsOutsideSourceRoots && includeEverything
)
} else {
filter.copy(includeScriptsOutsideSourceRoots = false)
}
if (correctedFilter.includeScriptsOutsideSourceRoots) {
if (ProjectRootManager.getInstance(project).fileIndex.isInContent(virtualFile) || ScratchUtil.isScratch(virtualFile)) {
return true
}
return scriptConfiguration?.get(ScriptCompilationConfiguration.ide.acceptedLocations)?.containsAllowedLocations() == true
}
if (!correctedFilter.includeLibraryClassFiles && !correctedFilter.includeLibrarySourceFiles) {
return false
}
// NOTE: the following is a workaround for cases when class files are under library source roots and source files are under class roots
val canContainClassFiles = fileType == ArchiveFileType.INSTANCE || virtualFile.isDirectory
val isBinary = fileType.isKotlinBinary
val scriptConfigurationManager = when {
correctedFilter.includeScriptDependencies -> ScriptConfigurationManager.getInstance(project)
else -> null
}
if (correctedFilter.includeLibraryClassFiles && (isBinary || canContainClassFiles)) {
if (fileIndex.isInLibraryClasses(virtualFile)) {
return true
}
val classFileScope = scriptConfigurationManager?.getAllScriptsDependenciesClassFilesScope()
if (classFileScope != null && classFileScope.contains(virtualFile)) {
return true
}
}
if (correctedFilter.includeLibrarySourceFiles && !isBinary) {
if (fileIndex.isInLibrarySource(virtualFile)) {
return true
}
val sourceFileScope = scriptConfigurationManager?.getAllScriptDependenciesSourcesScope()
if (sourceFileScope != null && sourceFileScope.contains(virtualFile) && !(virtualFile !is VirtualFileWindow && fileIndex.isInSourceContent(
virtualFile
))
) {
return true
}
}
return false
}
private fun List<ScriptAcceptedLocation>.containsAllowedLocations(): Boolean {
return any { it == ScriptAcceptedLocation.Everywhere || it == ScriptAcceptedLocation.Project }
}
} | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/base/analysis/RootKindMatcherImpl.kt | 1971306868 |
package org.ligi.passandroid.functions
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import org.ligi.passandroid.R
fun checkThatHelpIsThere() {
onView(withId(R.id.help_text)).check(matches(isDisplayed()))
}
| android/src/androidTest/java/org/ligi/passandroid/functions/HelpChecks.kt | 1630940951 |
/*
* 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
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.textarea.TextComponentEditorImpl
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimScriptExecutorBase
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.ex.FinishException
import com.maddyhome.idea.vim.history.HistoryConstants
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.register.RegisterConstants.LAST_COMMAND_REGISTER
import com.maddyhome.idea.vim.vimscript.model.CommandLineVimLContext
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
import com.maddyhome.idea.vim.vimscript.model.VimLContext
import com.maddyhome.idea.vim.vimscript.model.commands.Command
import com.maddyhome.idea.vim.vimscript.model.commands.RepeatCommand
import com.maddyhome.idea.vim.vimscript.parser.VimscriptParser
import java.io.File
import java.io.IOException
import javax.swing.JTextArea
@Service
class Executor : VimScriptExecutorBase() {
private val logger = logger<Executor>()
override var executingVimscript = false
@Throws(ExException::class)
override fun execute(script: String, editor: VimEditor, context: ExecutionContext, skipHistory: Boolean, indicateErrors: Boolean, vimContext: VimLContext?): ExecutionResult {
var finalResult: ExecutionResult = ExecutionResult.Success
val myScript = VimscriptParser.parse(script)
myScript.units.forEach { it.vimContext = vimContext ?: myScript }
for (unit in myScript.units) {
try {
val result = unit.execute(editor, context)
if (result is ExecutionResult.Error) {
finalResult = ExecutionResult.Error
if (indicateErrors) {
VimPlugin.indicateError()
}
}
} catch (e: ExException) {
if (e is FinishException) {
break
}
finalResult = ExecutionResult.Error
if (indicateErrors) {
VimPlugin.showMessage(e.message)
VimPlugin.indicateError()
} else {
logger.warn("Failed while executing $unit. " + e.message)
}
} catch (e: NotImplementedError) {
if (indicateErrors) {
VimPlugin.showMessage("Not implemented yet :(")
VimPlugin.indicateError()
}
} catch (e: Exception) {
logger.warn("Caught: ${e.message}")
logger.warn(e.stackTrace.toString())
if (injector.application.isUnitTest()) {
throw e
}
}
}
if (!skipHistory) {
VimPlugin.getHistory().addEntry(HistoryConstants.COMMAND, script)
if (myScript.units.size == 1 && myScript.units[0] is Command && myScript.units[0] !is RepeatCommand) {
VimPlugin.getRegister().storeTextSpecial(LAST_COMMAND_REGISTER, script)
}
}
return finalResult
}
override fun execute(script: String, skipHistory: Boolean) {
val editor = TextComponentEditorImpl(null, JTextArea()).vim
val context = DataContext.EMPTY_CONTEXT.vim
execute(script, editor, context, skipHistory, indicateErrors = true, CommandLineVimLContext)
}
override fun executeFile(file: File, indicateErrors: Boolean) {
val editor = TextComponentEditorImpl(null, JTextArea()).vim
val context = DataContext.EMPTY_CONTEXT.vim
try {
execute(file.readText(), editor, context, skipHistory = true, indicateErrors)
} catch (ignored: IOException) { }
}
@Throws(ExException::class)
override fun executeLastCommand(editor: VimEditor, context: ExecutionContext): Boolean {
val reg = VimPlugin.getRegister().getRegister(':') ?: return false
val text = reg.text ?: return false
execute(text, editor, context, skipHistory = false, indicateErrors = true, CommandLineVimLContext)
return true
}
}
| src/main/java/com/maddyhome/idea/vim/vimscript/Executor.kt | 3338873755 |
package org.hexworks.zircon.internal.component.impl
import org.hexworks.cobalt.databinding.api.extension.orElseGet
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.cobalt.events.api.Subscription
import org.hexworks.zircon.api.Components
import org.hexworks.zircon.api.component.AttachedComponent
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.RadioButton
import org.hexworks.zircon.api.component.RadioButtonGroup
import org.hexworks.zircon.api.dsl.component.buildRadioButton
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.internal.component.InternalComponent
import org.hexworks.zircon.internal.component.InternalGroup
import kotlin.jvm.Synchronized
class DefaultRadioButtonGroup internal constructor(
initialIsDisabled: Boolean,
initialIsHidden: Boolean,
initialTheme: ColorTheme,
initialTileset: TilesetResource,
private val groupDelegate: InternalGroup<RadioButton> = Components.group<RadioButton>()
.withIsDisabled(initialIsDisabled)
.withIsHidden(initialIsHidden)
.withTheme(initialTheme)
.withTileset(initialTileset)
.build() as InternalGroup<RadioButton>
) : RadioButtonGroup, InternalGroup<RadioButton> by groupDelegate {
private val buttons = mutableMapOf<String, Pair<GroupAttachedComponent, Subscription>>()
override var selectedButtonProperty: Property<RadioButton?> = null.toProperty()
override var selectedButton: RadioButton? by selectedButtonProperty.asDelegate()
@Synchronized
override fun addComponent(component: RadioButton): AttachedComponent {
require(component is InternalComponent) {
"The supplied component does not implement required interface: InternalComponent."
}
require(buttons.containsKey(component.key).not()) {
"There is already a Radio Button in this Radio Button Group with the key '${component.key}'."
}
val handle = GroupAttachedComponent(component, this)
buttons[component.key] = handle to component.selectedProperty.onChange { (_, newlySelected) ->
selectedButton?.let { previousSelected ->
if (newlySelected && previousSelected !== component) {
previousSelected.isSelected = false
selectedButton = component
}
}.orElseGet {
selectedButton = component
}
}
if (component.isSelected) {
selectedButton?.let { oldSelection ->
oldSelection.isSelected = false
}
selectedButton = component
}
groupDelegate.addComponent(component)
return handle
}
override fun addComponents(vararg components: RadioButton) = components.map(::addComponent)
}
| zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/DefaultRadioButtonGroup.kt | 2337918661 |
package com.example.andrej.mit_lab_8
import android.app.*
import android.content.Context
import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.NotificationCompat
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.andrej.mit_lab_8.SqlHelper.Companion.COLUMN_NAME
import com.example.andrej.mit_lab_8.SqlHelper.Companion.TABLE_NAME
import java.util.*
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
val editTextTitle by lazy {
findViewById(R.id.editTextTitle) as EditText
}
val editTextMessage by lazy {
findViewById(R.id.editTextMessage) as EditText
}
val editTextTime by lazy {
findViewById(R.id.editTextTime) as EditText
}
val editTextDate by lazy {
findViewById(R.id.editTextDate) as EditText
}
val buttonAddNotification by lazy {
findViewById(R.id.buttonAddNotification) as Button
}
val buttonShowNotifications by lazy {
findViewById(R.id.buttonShowNotifications) as Button
}
val buttonRemove by lazy {
findViewById(R.id.buttonRemove) as Button
}
val calendar = Calendar.getInstance()
val sqlDB by lazy { SqlHelper(this@MainActivity) }
val newNotification = mutableListOf<NotificationData>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
PushNotification(this).execute(sqlDB.getAllRecords().toMutableList())
buttonRemove.setOnClickListener { sqlDB.removeOldNotification() }
buttonShowNotifications.setOnClickListener {
Intent(this@MainActivity, TableViewActivity::class.java)
.let(this@MainActivity::startActivity)
}
buttonAddNotification.setOnClickListener {
NotificationData(
title = editTextTitle.text.toString(),
message = editTextMessage.text.toString(),
date = calendar.let {
Date(it[Calendar.YEAR],
it[Calendar.MONTH],
it[Calendar.DAY_OF_MONTH],
it[Calendar.HOUR_OF_DAY],
it[Calendar.MINUTE]
)
}
).let {
sqlDB.insert(it)
synchronized(newNotification, { newNotification.add(it) })
}
Toast.makeText(this@MainActivity, "Уведомление добавлено", Toast.LENGTH_LONG)
.show()
}
editTextDate.setOnClickListener {
DatePickerDialog(this@MainActivity,
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
editTextDate.text.let {
calendar.set(year, month, dayOfMonth)
it.clear()
it.append("$year-$month-$dayOfMonth")
}
},
calendar[Calendar.YEAR],
calendar[Calendar.MONTH],
calendar[Calendar.DAY_OF_MONTH]
).show()
}
editTextTime.setOnClickListener {
TimePickerDialog(this@MainActivity,
TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
editTextTime.text.let {
with(calendar) {
set(get(Calendar.YEAR),
get(Calendar.MONTH),
get(Calendar.DAY_OF_MONTH),
hourOfDay, minute)
}
it.clear()
it.append("$hourOfDay:$minute")
}
},
calendar[Calendar.HOUR_OF_DAY],
calendar[Calendar.MINUTE],
true
).show()
}
}
var notificationId = 0
fun NotificationData.addNotification() {
val builder = NotificationCompat.Builder(this@MainActivity).apply {
setSmallIcon(R.drawable.kotlin)
setContentTitle(title)
setContentText(message)
}
Intent(this@MainActivity, MainActivity::class.java)
.let {
TaskStackBuilder.create(this@MainActivity).apply {
addParentStack(MainActivity::class.java)
addNextIntent(it)
builder.setContentIntent(getPendingIntent(notificationId, PendingIntent.FLAG_UPDATE_CURRENT))
}
}
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.notify(notificationId, builder.build())
notificationId++
}
}
class PushNotification(val main: MainActivity) : AsyncTask<MutableList<NotificationData>, Unit, Unit>() {
override fun doInBackground(vararg params: MutableList<NotificationData>?) {
val mutableList = params[0]!!
while (true) {
val currentTime = Date().let { Date(it.year, it.month, it.date, it.hours, it.minutes) }
mutableList += synchronized(main.newNotification, { main.newNotification })
mutableList
.filter { it.date == currentTime }
.forEach {
main.apply { it.addNotification() }
mutableList.remove(it)
}
synchronized(main.newNotification, { main.newNotification.clear() })
TimeUnit.SECONDS.sleep(2)
}
}
}
data class NotificationData(val id: Int = -1,
val title: String,
val message: String,
val date: Date)
class SqlHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 2) {
companion object {
const val DATABASE_NAME = "MIT_lab_8_DB"
const val TABLE_NAME = "NotificationData"
val COLUMN_NAME = arrayOf("_id", "title", "message", "date")
val DEFAULT = arrayOf("", "заголовок не установлин", "сообщение не установлено", "давно")
}
override fun onCreate(db: SQLiteDatabase?) {
db!!.execSQL("CREATE TABLE $TABLE_NAME(" +
"${COLUMN_NAME[0]} INTEGER PRIMARY KEY AUTOINCREMENT," +
"${COLUMN_NAME[1]} TEXT DEFAULT '${DEFAULT[1]}'," +
"${COLUMN_NAME[2]} TEXT DEFAULT '${DEFAULT[2]}'," +
"${COLUMN_NAME[3]} TEXT DEFAULT '${DEFAULT[3]}');")
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db!!.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
db.version = newVersion
onCreate(db)
}
fun insert(radio: NotificationData) = with(radio) {
writableDatabase.execSQL("INSERT INTO $TABLE_NAME" +
"(${COLUMN_NAME[1]}, ${COLUMN_NAME[2]}, ${COLUMN_NAME[3]}) " +
"VALUES('$title', '$message', '${date.apply { year -= 1900 }}');")
}
fun getAllRecords(): List<NotificationData> {
val cursor = writableDatabase.rawQuery("SELECT ${COLUMN_NAME.joinToString(",")} FROM $TABLE_NAME;", null)
cursor.moveToFirst()
return (0..cursor.count - 1).map {
with(cursor) {
NotificationData(
getInt(0),
getString(1),
getString(2),
Date(getString(3))
).apply { moveToNext() }
}
}
}
}
fun SqlHelper.removeOldNotification(date: Date = Date()) = writableDatabase
.execSQL("DELETE FROM $TABLE_NAME WHERE ${COLUMN_NAME[3]} <= '$date'") | MIT/MIT_lab_8/app/src/main/java/com/example/andrej/mit_lab_8/MainActivity.kt | 723921458 |
/*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.ui.internal.about
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.pyamsoft.pydroid.bootstrap.libraries.OssLibraries
import com.pyamsoft.pydroid.bootstrap.libraries.OssLibrary
import com.pyamsoft.pydroid.theme.keylines
import com.pyamsoft.pydroid.ui.R
import com.pyamsoft.pydroid.ui.defaults.CardDefaults
@Composable
internal fun AboutListItem(
modifier: Modifier = Modifier,
library: OssLibrary,
onViewHomePage: () -> Unit,
onViewLicense: () -> Unit
) {
Card(
modifier = modifier,
shape = MaterialTheme.shapes.medium,
elevation = CardDefaults.Elevation,
) {
Column(
modifier = Modifier.padding(MaterialTheme.keylines.baseline),
) {
Name(
library = library,
)
License(
library = library,
)
Description(
library = library,
)
Row(
modifier = Modifier.padding(top = MaterialTheme.keylines.baseline),
) {
ViewLicense(
onClick = onViewLicense,
)
VisitHomepage(
onClick = onViewHomePage,
)
}
}
}
}
@Composable
private fun Name(library: OssLibrary) {
Text(
style = MaterialTheme.typography.body1.copy(fontWeight = FontWeight.W700),
text = library.name,
)
}
@Composable
private fun License(library: OssLibrary) {
Text(
style = MaterialTheme.typography.caption,
text = stringResource(R.string.license_name, library.licenseName),
)
}
@Composable
private fun Description(library: OssLibrary) {
val description = library.description
AnimatedVisibility(visible = description.isNotBlank()) {
Box(
modifier = Modifier.padding(vertical = MaterialTheme.keylines.baseline),
) {
Text(
style = MaterialTheme.typography.body2,
text = description,
)
}
}
}
@Composable
private fun ViewLicense(onClick: () -> Unit) {
TextButton(
onClick = onClick,
) {
Text(
text = stringResource(R.string.view_license),
)
}
}
@Composable
private fun VisitHomepage(onClick: () -> Unit) {
Box(
modifier = Modifier.padding(start = MaterialTheme.keylines.baseline),
) {
TextButton(
onClick = onClick,
) {
Text(
text = stringResource(R.string.visit_homepage),
)
}
}
}
@Preview
@Composable
private fun PreviewAboutListItem() {
Surface {
AboutListItem(
library = OssLibraries.libraries().first(),
onViewLicense = {},
onViewHomePage = {},
)
}
}
| ui/src/main/java/com/pyamsoft/pydroid/ui/internal/about/AboutListItem.kt | 1668594099 |
package org.wordpress.android.ui.pages
import android.os.Bundle
import org.wordpress.android.databinding.PagesParentActivityBinding
import org.wordpress.android.ui.LocaleAwareActivity
class PageParentActivity : LocaleAwareActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = PagesParentActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar.toolbarMain)
supportActionBar?.let {
it.setHomeButtonEnabled(true)
it.setDisplayHomeAsUpEnabled(true)
}
}
}
| WordPress/src/main/java/org/wordpress/android/ui/pages/PageParentActivity.kt | 131296237 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.arrays
import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer
import com.kotlinnlp.simplednn.core.functionalities.updatemethods.UpdaterSupportStructure
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import com.kotlinnlp.simplednn.simplemath.ndarray.sparse.SparseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.sparse.SparseNDArrayFactory
import java.io.Serializable
import java.util.UUID
/**
* The [ParamsArray] is a wrapper of a [DenseNDArray] extending it with an unique identifier [uuid],
* with an [updaterSupportStructure] and with methods to build the params [Errors].
*
* @property values the values of the parameters
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*/
class ParamsArray(
val values: DenseNDArray,
private val defaultErrorsType: ErrorsType = ErrorsType.Dense
) : Serializable {
companion object {
/**
* Private val used to serialize the class (needed from [Serializable])
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
}
/**
* Build a new [ParamsArray] with the given [values].
*
* @param values the values
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(values: DoubleArray,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.arrayOf(values),
defaultErrorsType = defaultErrorsType
)
/**
* Build a new [ParamsArray] with the given [values].
*
* @param values the values
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(values: List<DoubleArray>,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.arrayOf(values),
defaultErrorsType = defaultErrorsType
)
/**
* Build a new [ParamsArray] with the given dimensions.
*
* @param dim1 the first dimension of the array
* @param dim2 the second dimension of the array
* @param initializer the initializer of the values (can be null)
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(dim1: Int,
dim2: Int,
initializer: Initializer? = null,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.zeros(Shape(dim1, dim2)).apply { initializer?.initialize(this) },
defaultErrorsType = defaultErrorsType
)
/**
* Build a new [ParamsArray] with the given [shape].
*
* @param shape the shape
* @param initializer the initializer of the values (can be null)
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(shape: Shape,
initializer: Initializer? = null,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.zeros(shape).apply { initializer?.initialize(this) },
defaultErrorsType = defaultErrorsType
)
/**
* Build a new [ParamsArray] with the given [size].
*
* @param size the size
* @param initializer the initializer of the values (can be null)
* @param defaultErrorsType the type of the errors generated by the [buildDefaultErrors] method (default Dense)
*
* @return a new params array
*/
constructor(size: Int,
initializer: Initializer? = null,
defaultErrorsType: ErrorsType = ErrorsType.Dense) : this(
values = DenseNDArrayFactory.zeros(Shape(size)).apply { initializer?.initialize(this) },
defaultErrorsType = defaultErrorsType
)
/**
* The errors type.
*/
enum class ErrorsType { Dense, Sparse }
/**
* ParamsErrors.
*
* @property values the error of the parameters
*/
inner class Errors<T: NDArray<T>>(val values: T) {
/**
* Reference parameters.
*
* The instance of the [ParamsArray] from witch the [Errors] has been created.
*/
val refParams: ParamsArray = this@ParamsArray
/**
* @return a copy of this params errors (the copy share the same [refParams])
*/
fun copy() = Errors(this.values.copy())
/**
* @return the hash code for this object
*/
override fun hashCode(): Int = this.refParams.uuid.hashCode()
/**
* @param other an object
*
* @return `true` if the other object is equal to this one, otherwise `false`
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Errors<*>
if (refParams.uuid != other.refParams.uuid) return false
return true
}
}
/**
* The unique identifier of this [ParamsArray].
*/
val uuid = UUID.randomUUID().toString()
/**
* The updater support structure used by [com.kotlinnlp.simplednn.core.functionalities.updatemethods].
*/
var updaterSupportStructure: UpdaterSupportStructure? = null
/**
* Return the [updaterSupportStructure].
*
* If the [updaterSupportStructure] is null, set it with a new [StructureType].
* If the [updaterSupportStructure] has already been initialized, it must be compatible with the required
* [StructureType].
*
* @return the [updaterSupportStructure]
*/
inline fun <reified StructureType: UpdaterSupportStructure>getOrSetSupportStructure(): StructureType {
if (this.updaterSupportStructure == null) {
this.updaterSupportStructure = StructureType::class.constructors.first().call(this.values.shape)
}
require(this.updaterSupportStructure is StructureType) { "Incompatible support structure" }
@Suppress("UNCHECKED_CAST")
return this.updaterSupportStructure as StructureType
}
/**
* Return a new instance of [Errors] initialized to zeros or with the given [values] if not null.
*
* @param values the values used to initialize the errors (can be null)
*
* @return a new instance of errors parameters
*/
fun buildDenseErrors(values: DenseNDArray? = null) =
Errors(values ?: DenseNDArrayFactory.zeros(this.values.shape))
/**
* Return a new instance of [Errors] initialized to zeros or with the given [values] if not null.
*
* @param values the values used to initialize the errors (can be null)
*
* @return a new instance of errors parameters
*/
fun buildSparseErrors(values: SparseNDArray? = null) =
Errors(values ?: SparseNDArrayFactory.zeros(this.values.shape))
/**
* Return a new instance of [Errors] initialized to zeros.
*
* If the [defaultErrorsType] is [ErrorsType.Sparse], build sparse errors.
* If the [defaultErrorsType] is [ErrorsType.Dense], build dense errors.
*
* @return a new instance of errors parameters
*/
fun buildDefaultErrors() = when (defaultErrorsType) {
ErrorsType.Dense -> this.buildDenseErrors()
ErrorsType.Sparse -> this.buildSparseErrors()
}
}
| src/main/kotlin/com/kotlinnlp/simplednn/core/arrays/ParamsArray.kt | 2064604741 |
/*
* ImportHelper.kt
* Implements the ImportHelper object
* A ImportHelper provides methods for integrating station files from Transistor v3
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor.helpers
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import org.y20k.transistor.Keys
import org.y20k.transistor.core.Collection
import org.y20k.transistor.core.Station
import java.io.File
import java.util.*
/*
* ImportHelper object
*/
object ImportHelper {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(ImportHelper::class.java)
/* Converts older station of type .m3u */
fun convertOldStations(context: Context): Boolean {
val oldStations: ArrayList<Station> = arrayListOf()
val oldCollectionFolder: File? = context.getExternalFilesDir(Keys.TRANSISTOR_LEGACY_FOLDER_COLLECTION)
if (oldCollectionFolder != null && shouldStartImport(oldCollectionFolder)) {
CoroutineScope(IO).launch {
var success: Boolean = false
// start import
oldCollectionFolder.listFiles()?.forEach { file ->
// look for station files from Transistor v3
if (file.name.endsWith(Keys.TRANSISTOR_LEGACY_STATION_FILE_EXTENSION)) {
// read stream uri and name
val station: Station = FileHelper.readStationPlaylist(file.inputStream())
station.nameManuallySet = true
// detect stream content
station.streamContent = NetworkHelper.detectContentType(station.getStreamUri()).type
// try to also import station image
val sourceImageUri: String = getLegacyStationImageFileUri(context, station)
if (sourceImageUri != Keys.LOCATION_DEFAULT_STATION_IMAGE) {
// create and add image and small image + get main color
station.image = FileHelper.saveStationImage(context, station.uuid, sourceImageUri, Keys.SIZE_STATION_IMAGE_CARD, Keys.STATION_SMALL_IMAGE_FILE).toString()
station.smallImage = FileHelper.saveStationImage(context, station.uuid, sourceImageUri, Keys.SIZE_STATION_IMAGE_MAXIMUM, Keys.STATION_IMAGE_FILE).toString()
station.imageColor = ImageHelper.getMainColor(context, sourceImageUri)
station.imageManuallySet = true
}
// improvise a name if empty
if (station.name.isEmpty()) {
station.name = file.name.substring(0, file.name.lastIndexOf("."))
station.nameManuallySet = false
}
station.modificationDate = GregorianCalendar.getInstance().time
// add station
oldStations.add(station)
success = true
}
}
// check for success (= at least one station was found)
if (success) {
// delete files from Transistor v3
oldCollectionFolder.deleteRecursively()
// sort and save collection
val newCollection: Collection = CollectionHelper.sortCollection(Collection(stations = oldStations))
CollectionHelper.saveCollection(context, newCollection)
}
}
// import has been started
return true
} else {
// import has NOT been started
return false
}
}
/* Checks if conditions for a station import are met */
private fun shouldStartImport(oldCollectionFolder: File): Boolean {
return oldCollectionFolder.exists() &&
oldCollectionFolder.isDirectory &&
oldCollectionFolder.listFiles()?.isNotEmpty()!! &&
!FileHelper.checkForCollectionFile(oldCollectionFolder)
}
/* Gets Uri for station images created by older Transistor versions */
private fun getLegacyStationImageFileUri(context: Context, station: Station): String {
val collectionFolder: File? = context.getExternalFilesDir(Keys.TRANSISTOR_LEGACY_FOLDER_COLLECTION)
if (collectionFolder != null && collectionFolder.exists() && collectionFolder.isDirectory) {
val stationNameCleaned: String = station.name.replace(Regex("[:/]"), "_")
val legacyStationImage = File("$collectionFolder/$stationNameCleaned.png")
if (legacyStationImage.exists()) {
return legacyStationImage.toString()
} else {
return Keys.LOCATION_DEFAULT_STATION_IMAGE
}
} else {
return Keys.LOCATION_DEFAULT_STATION_IMAGE
}
}
}
| app/src/main/java/org/y20k/transistor/helpers/ImportHelper.kt | 523875543 |
package com.edwardharker.aircraftrecognition.filter.picker
import com.edwardharker.aircraftrecognition.filter.FakeSelectedFilterOptions
import com.edwardharker.aircraftrecognition.filter.SelectedFilterOptions
import org.junit.Test
import org.mockito.Mockito
import rx.Observable
import rx.schedulers.Schedulers
class FilterPickerResetPresenterTest {
@Test
fun `shows reset`() {
val mockedView = Mockito.mock(FilterPickerResetView::class.java)
val presenter = FilterPickerResetPresenter(
mainScheduler = Schedulers.immediate(),
shouldShowResetUseCase = { Observable.just(true) },
selectedFilterOptions = FakeSelectedFilterOptions()
)
presenter.startPresenting(mockedView)
Mockito.verify(mockedView).showReset()
}
@Test
fun `hides reset`() {
val mockedView = Mockito.mock(FilterPickerResetView::class.java)
val presenter = FilterPickerResetPresenter(
mainScheduler = Schedulers.immediate(),
shouldShowResetUseCase = { Observable.just(false) },
selectedFilterOptions = FakeSelectedFilterOptions()
)
presenter.startPresenting(mockedView)
Mockito.verify(mockedView).hideReset()
}
@Test
fun `resets filter options`() {
val mockedSelectedFilterOptions = Mockito.mock(SelectedFilterOptions::class.java)
val presenter = FilterPickerResetPresenter(
mainScheduler = Schedulers.immediate(),
shouldShowResetUseCase = { Observable.just(true) },
selectedFilterOptions = mockedSelectedFilterOptions
)
presenter.resetFilters()
Mockito.verify(mockedSelectedFilterOptions).deselectAll()
}
}
| recognition/src/test/kotlin/com/edwardharker/aircraftrecognition/filter/picker/FilterPickerResetPresenterTest.kt | 1325710611 |
package com.sheepsgohome.shared
import com.badlogic.gdx.Application.ApplicationType.Desktop
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Preferences
import com.badlogic.gdx.utils.I18NBundle
import com.sheepsgohome.android.Android
import com.sheepsgohome.google.GoogleLeaderboard
import java.util.*
object GameData {
private val gamePreferences: Preferences by lazy { Gdx.app.getPreferences("gamePreferences") }
val loc: I18NBundle by lazy {
val baseFileHandle = Gdx.files.internal("loc/Language")
val locale = Locale.getDefault()
I18NBundle.createBundle(baseFileHandle, locale)
}
//----------------ANDROID BRIDGE-----------------
var android: Android? = null
var leaderboard: GoogleLeaderboard? = null
//----------------CONSTANTS----------------------
val VERSION_STRING = "1.0.3"
val codeX = "oiaewj023897rvoiuwanvoiune0v9128n09r2898v7q3342089"
val CAMERA_HEIGHT = 160f
val CAMERA_WIDTH = 90f
val SETTINGS_TITLE_FONT_SCALE = 0.35f
val SETTINGS_ITEM_FONT_SCALE = 0.5f
//----------------PREFERENCES----------------------
var VIRTUAL_JOYSTICK = 0
var VIRTUAL_JOYSTICK_NONE = 0
var VIRTUAL_JOYSTICK_LEFT = 1
var VIRTUAL_JOYSTICK_RIGHT = 2
var SOUND_ENABLED = true
var SOUND_VOLUME = 0.7f
var MUSIC_ENABLED = true
//----------------GAME-DATA----------------------
var LEVEL = 1
var PLAYER_NAME = ""
fun loadPreferences() {
with(gamePreferences) {
LEVEL = getInteger("LEVEL", 1)
MUSIC_ENABLED = getBoolean("MUSICENABLED", true)
SOUND_ENABLED = getBoolean("SOUNDENABLED", true)
SOUND_VOLUME = getFloat("SOUNDVOLUME", 0.5f)
PLAYER_NAME = getString("PLAYERNAME", "")
val preferredJoystick = when (Gdx.app.type) {
Desktop -> VIRTUAL_JOYSTICK_NONE
else -> VIRTUAL_JOYSTICK_RIGHT
}
VIRTUAL_JOYSTICK = getInteger("VIRTUALJOYSTICK", preferredJoystick)
}
}
fun savePreferences() {
with(gamePreferences) {
putInteger("LEVEL", LEVEL)
putInteger("VIRTUALJOYSTICK", VIRTUAL_JOYSTICK)
putBoolean("SOUNDENABLED", SOUND_ENABLED)
putBoolean("MUSICENABLED", MUSIC_ENABLED)
putFloat("SOUNDVOLUME", SOUND_VOLUME)
putString("PLAYERNAME", PLAYER_NAME)
flush()
}
}
fun levelUp() {
LEVEL++
gamePreferences.putInteger("LEVEL", GameData.LEVEL)
gamePreferences.flush()
}
}
| core/src/com/sheepsgohome/shared/GameData.kt | 272157028 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("PluginsAdvertiser")
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginNode
import com.intellij.ide.plugins.RepositoryHelper
import com.intellij.ide.plugins.advertiser.PluginData
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationGroupManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.PlatformUtils.isIdeaUltimate
import org.jetbrains.annotations.ApiStatus
import java.io.IOException
private const val IGNORE_ULTIMATE_EDITION = "ignoreUltimateEdition"
@get:JvmName("getLog")
internal val LOG = Logger.getInstance("#PluginsAdvertiser")
private val propertiesComponent
get() = PropertiesComponent.getInstance()
var isIgnoreIdeSuggestion: Boolean
get() = propertiesComponent.isTrueValue(IGNORE_ULTIMATE_EDITION)
set(value) = propertiesComponent.setValue(IGNORE_ULTIMATE_EDITION, value)
@JvmField
@ApiStatus.ScheduledForRemoval
@Deprecated("Use `notificationGroup` property")
val NOTIFICATION_GROUP = notificationGroup
val notificationGroup: NotificationGroup
get() = NotificationGroupManager.getInstance().getNotificationGroup("Plugins Suggestion")
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use `installAndEnable(Project, Set, Boolean, Runnable)`")
fun installAndEnablePlugins(
pluginIds: Set<String>,
onSuccess: Runnable,
) {
installAndEnable(
LinkedHashSet(pluginIds.map { PluginId.getId(it) }),
onSuccess,
)
}
@Deprecated("Use `installAndEnable(Project, Set, Boolean, Runnable)`")
fun installAndEnable(
pluginIds: Set<PluginId>,
onSuccess: Runnable,
) = installAndEnable(null, pluginIds, true, false, null, onSuccess)
@JvmOverloads
fun installAndEnable(
project: Project?,
pluginIds: Set<PluginId>,
showDialog: Boolean = false,
selectAlInDialog: Boolean = false,
modalityState: ModalityState? = null,
onSuccess: Runnable,
) {
require(!showDialog || modalityState == null) {
"`modalityState` can be not null only if plugin installation won't show the dialog"
}
ProgressManager.getInstance().run(InstallAndEnableTask(project, pluginIds, showDialog, selectAlInDialog, modalityState, onSuccess))
}
internal fun getBundledPluginToInstall(
plugins: Collection<PluginData>,
descriptorsById: Map<PluginId, IdeaPluginDescriptor> = PluginManagerCore.buildPluginIdMap(),
): List<String> {
return if (isIdeaUltimate()) {
emptyList()
}
else {
plugins.filter { it.isBundled }
.filterNot { descriptorsById.containsKey(it.pluginId) }
.map { it.pluginName }
}
}
/**
* Loads list of plugins, compatible with a current build, from all configured repositories
*/
@JvmOverloads
internal fun loadPluginsFromCustomRepositories(indicator: ProgressIndicator? = null): List<PluginNode> {
return RepositoryHelper
.getPluginHosts()
.filterNot {
it == null
&& ApplicationInfoEx.getInstanceEx().usesJetBrainsPluginRepository()
}.flatMap {
try {
RepositoryHelper.loadPlugins(it, null, indicator)
}
catch (e: IOException) {
LOG.info("Couldn't load plugins from $it: $e")
LOG.debug(e)
emptyList<PluginNode>()
}
}.distinctBy { it.pluginId }
}
| platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.kt | 2601724666 |
package cz.sazel.android.serverlesswebrtcandroid.adapters
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Context.CLIPBOARD_SERVICE
import android.os.Build
import android.support.v7.widget.RecyclerView
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import cz.sazel.android.serverlesswebrtcandroid.R
import org.jetbrains.anko.find
/**
* This is just to do the printing into the RecyclerView.
*/
class ConsoleAdapter(val items: List<String>) : RecyclerView.Adapter<ConsoleAdapter.ConsoleVH>() {
@Suppress("DEPRECATION")
override fun onBindViewHolder(holder: ConsoleVH, position: Int) {
holder.tvText.text = Html.fromHtml(items[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConsoleVH {
val view = LayoutInflater.from(parent.context).inflate(R.layout.l_item, parent, false)
return ConsoleVH(view)
}
override fun getItemCount(): Int = items.count()
class ConsoleVH(view: View) : RecyclerView.ViewHolder(view) {
var tvText: TextView = view.find(R.id.tvText)
init {
tvText.setOnLongClickListener {
//clipboard on long touch
val text = tvText.text.toString()
val clipboard = tvText.context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
clipboard.primaryClip = ClipData.newPlainText("text", text)
Toast.makeText(tvText.context, R.string.clipboard_copy, LENGTH_SHORT).show()
true
}
}
}
}
| app/src/main/kotlin/cz/sazel/android/serverlesswebrtcandroid/adapters/ConsoleAdapter.kt | 3351884581 |
package org.snakeskin.init
import org.snakeskin.runtime.SnakeskinModules
import org.snakeskin.runtime.SnakeskinRuntime
class CtreInit: Initializer {
override fun preStartup() {
SnakeskinRuntime.registerModule(SnakeskinModules.CTRE)
}
override fun postStartup() {
}
} | SnakeSkin-CTRE/src/main/kotlin/org/snakeskin/init/CtreInit.kt | 2699838677 |
package <%= appPackage %>.presentation
/**
* Interface class to act as a base for any class that is to take the role of the BaseView in the Model-
* BaseView-Presenter pattern.
*/
interface BaseView<in T : BasePresenter> {
fun setPresenter(presenter: T)
} | templates/buffer-clean-kotlin/presentation/src/main/java/org/buffer/android/boilerplate/presentation/BaseView.kt | 586360031 |
package com.helpchoice.kotlin.urlet
/**
* Holds a single substitution placeholder with leading literal in front of it
*
*
*/
abstract class Expression(private val prefix: String, placeholder: String?) {
val type: Char?
var names: Collection<Triple<String, Int?, Char?>> = listOf()
init {
if (placeholder == null) {
type = null
} else {
var holder = placeholder
if (holder[0] in "/?&@+#;.") {
type = holder[0]
holder = placeholder.substring(1)
} else {
type = null
}
holder.split(',').map { variable: String ->
val multiplier = if (variable.last() == '*') '*' else null
val name =
multiplier?.let {
variable.dropLast(1)
} ?: variable
val splits = name.split(':')
if (splits.size > 1) {
names += Triple(splits[0], splits[1].toInt(), multiplier)
} else {
names += Triple(splits[0], null, multiplier)
}
}
}
}
fun appendTo(buffer: StringBuilder, with: Map<String, Any?>) {
buffer.append(prefix)
var separator = """${type ?: ""}"""
var preparator = separator
when (type) {
null -> {
separator = ","
preparator = ""
}
'?' -> {
separator = "&"
preparator = if (buffer.toString().contains('?')) "&" else "?"
}
'+' -> {
separator = ","
preparator = ""
}
'#' -> {
separator = ","
}
}
for (varDeclaration in names) {
val variable = with[varDeclaration.first]
fun incode(value: String, limit: Int?): String {
var str = value
str = str.substring(0, minOf(str.length, limit ?: str.length))
str = if (type == null || !"+#".contains(type)) {
encode(str).replace("+", "%20")
} else {
str.replace(" ", "%20")
}
return str
}
when {
variable is Collection<*> -> {
if (variable.isNotEmpty()) {
var prefix = "$type"
var infix: String
when (type) {
null, '+' -> {
prefix = ""
infix = ","
}
'#' -> {
infix = ","
}
';', '&' -> {
prefix = "$type${varDeclaration.first}="
infix = prefix
}
'?' -> {
prefix = "?${varDeclaration.first}="
infix = "&${varDeclaration.first}="
}
else -> {
infix = prefix
}
}
if (varDeclaration.third != '*') {
infix = ","
}
variable.mapNotNull {
incode(it.toString(), varDeclaration.second)
}.joinTo(buffer, infix, prefix)
}
}
variable is Map<*, *> -> {
if (variable.isNotEmpty()) {
val mapped = variable.mapNotNull {
val str = incode(it.value.toString(), varDeclaration.second)
"${it.key}${if (varDeclaration.third == '*') "=" else ","}$str"
}
if (varDeclaration.third == '*') {
mapped.joinTo(buffer, separator, preparator)
} else {
mapped.joinTo(buffer, ","
, preparator + if (type != null && ";?&".contains(type)) "${varDeclaration.first}=" else "")
}
}
}
variable != null -> {
var str = incode(variable.toString(), varDeclaration.second)
buffer.append(preparator)
type?.let {
if (";?&".contains(type)) {
buffer.append(varDeclaration.first)
if (type != ';' || str.isNotEmpty()) {
buffer.append(if (varDeclaration.third == '*') separator else "=")
}
}
}
buffer.append(str)
}
}
if (type == null || "+#?".contains(type)) {
preparator = if (variable != null) separator else preparator
}
}
}
fun getNames(): Iterable<String> {
return names.map { name: Triple<String, Int?, Char?> ->
name.first
}
}
abstract fun encode(str: String): String
} | src/main/kotlin/com/helpchoice/kotlin/urlet/Expression.kt | 2330821294 |
/*
* French Revolutionary Calendar Android Widget
* Copyright (C) 2016-2017 Carmen Alvarez
*
* 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 ca.rmen.android.frccommon.compat
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.support.annotation.ColorInt
import android.support.annotation.DrawableRes
import android.util.Log
import ca.rmen.android.frccommon.Action
import ca.rmen.android.frccommon.Constants
import ca.rmen.android.frenchcalendar.R
import java.lang.reflect.InvocationTargetException
object NotificationCompat {
private val TAG = Constants.TAG + NotificationCompat::class.java.simpleName
fun getNotificationPriority(priority: String): Int =
if (ApiHelper.apiLevel < 16) {
0
} else {
Api16Helper.getNotificationPriority(priority)
}
fun createNotification(context: Context,
priority: Int,
@ColorInt color: Int,
tickerText: String,
contentText: String,
bigText: String,
defaultIntent: PendingIntent,
vararg actions: Action): Notification {
@DrawableRes val iconId: Int = R.drawable.ic_notif
when {
ApiHelper.apiLevel < 11 -> {
val notification = Notification()
notification.tickerText = tickerText
notification.`when` = System.currentTimeMillis()
@Suppress("DEPRECATION")
notification.icon = iconId
notification.contentIntent = defaultIntent
notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL
// Google removed setLatestEventInfo in sdk 23.
try {
val method = Notification::class.java.getMethod("setLatestEventInfo", Context::class.java, CharSequence::class.java, CharSequence::class.java, PendingIntent::class.java)
method.invoke(notification, context, tickerText, contentText, defaultIntent)
} catch (e: NoSuchMethodException) {
Log.v(TAG, "Error creating notification", e)
} catch (e: IllegalAccessException) {
Log.v(TAG, "Error creating notification", e)
} catch (e: InvocationTargetException) {
Log.v(TAG, "Error creating notification", e)
}
return notification
}
ApiHelper.apiLevel < 16 -> return Api11Helper.createNotification(context, iconId, tickerText, contentText, defaultIntent)
// convoluted way to pass actions. We have to convert from vararg to array, because the spread operator (*) crashes on cupcake.
// Arrays.copyOf() is used by the spread operator, and this doesn't exist on cupcake.
ApiHelper.apiLevel < 20 -> return Api16Helper.createNotification(context, priority, iconId, tickerText, contentText, bigText, defaultIntent, Array(actions.size) { actions[it] })
ApiHelper.apiLevel < 23 -> return Api20Helper.createNotification(context, priority, iconId, color, tickerText, contentText, bigText, defaultIntent, Array(actions.size) { actions[it] })
ApiHelper.apiLevel < 26 -> return Api23Helper.createNotification(context, priority, iconId, color, tickerText, contentText, bigText, defaultIntent, Array(actions.size) { actions[it] })
else -> return Api26Helper.createNotification(context, iconId, color, tickerText, contentText, bigText, defaultIntent, Array(actions.size) { actions[it] })
}
}
}
| app/src/main/kotlin/ca/rmen/android/frccommon/compat/NotificationCompat.kt | 382949585 |
/*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.gemoji
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "gemoji")
internal data class Gemoji(
@PrimaryKey
@ColumnInfo(name = "alias")
var alias: String,
@ColumnInfo(name = "emoji")
var emoji: String?
)
| libraries/gemoji/src/main/kotlin/io/sweers/catchup/gemoji/Gemoji.kt | 1373088017 |
package me.aberrantfox.hotbot.permissions
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import kotlinx.coroutines.experimental.runBlocking
import me.aberrantfox.hotbot.dsls.command.Command
import me.aberrantfox.hotbot.dsls.command.CommandsContainer
import me.aberrantfox.hotbot.services.Configuration
import me.aberrantfox.hotbot.services.ServerInformation
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.entities.Guild
import net.dv8tion.jda.core.entities.Member
import net.dv8tion.jda.core.entities.Role
import net.dv8tion.jda.core.entities.User
import org.junit.*
import java.io.File
import java.nio.file.Files
private const val commandName = "test-command"
private const val permsFilePath = "fake-path"
class PermissionTests {
companion object {
@BeforeClass
@JvmStatic
fun beforeAll() = cleanupFiles()
@AfterClass
@JvmStatic
fun afterAll() = cleanupFiles()
}
private lateinit var manager: PermissionManager
@Before
fun beforeEach() { manager = produceManager() }
@Test
fun correctPermissionIsStored() = assert(manager.roleRequired(commandName) == PermissionLevel.JrMod)
@Test
fun permissionStoredIsNotEqualToOtherPermissions() = assert(manager.roleRequired(commandName) != PermissionLevel.Moderator)
@Test
fun unknownCommandIsOfLevelOwner() = assert(manager.roleRequired("unknown-cmd-test") == PermissionLevel.Owner)
}
private fun produceManager(): PermissionManager {
val userMock = mock<User> {
on { id } doReturn "non-blank"
}
val memberMock = mock<Member> {
on { roles } doReturn listOf<Role>()
}
val guildMock = mock<Guild> {
on { getMember(userMock) } doReturn memberMock
}
val commandMock = mock<Command> {
on { name } doReturn commandName
}
val containerMock = mock<CommandsContainer> {
on { commands } doReturn hashMapOf(commandName to commandMock)
}
val serverInformationMock = mock<ServerInformation> {
on { ownerID } doReturn ""
on { guildid } doReturn "guildid"
}
val config = mock<Configuration> {
on { serverInformation } doReturn serverInformationMock
}
val jdaMock = mock<JDA> {
on { getGuildById(config.serverInformation.guildid) } doReturn guildMock
}
val manager = PermissionManager(jdaMock, containerMock, config, permsFilePath)
runBlocking { manager.setPermission(commandName, PermissionLevel.JrMod).join() }
return manager
}
private fun cleanupFiles() {
val permsFile = File(permsFilePath)
Files.deleteIfExists(permsFile.toPath())
} | src/test/kotlin/me/aberrantfox/hotbot/permissions/RoleRequiredTest.kt | 2852066092 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.