repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | platform/testFramework/junit5/src/impl/TestDisposableExtension.kt | 5 | 2097 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.testFramework.junit5.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.CheckedDisposable
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.junit5.TestDisposable
import org.jetbrains.annotations.TestOnly
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.ParameterContext
import org.junit.jupiter.api.extension.ParameterResolver
import org.junit.platform.commons.util.AnnotationUtils.findAnnotatedFields
import org.junit.platform.commons.util.ReflectionUtils
@TestOnly
internal class TestDisposableExtension
: BeforeEachCallback,
ParameterResolver {
override fun beforeEach(context: ExtensionContext) {
val instance = context.requiredTestInstance
for (field in findAnnotatedFields(instance.javaClass, TestDisposable::class.java, ReflectionUtils::isNotStatic)) {
ReflectionUtils.makeAccessible(field)[instance] = context.testDisposable()
}
}
override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean {
return parameterContext.parameter.type === Disposable::class.java && parameterContext.isAnnotated(TestDisposable::class.java)
}
override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any {
return extensionContext.testDisposable()
}
}
private fun ExtensionContext.testDisposable(): Disposable {
return getStore(ExtensionContext.Namespace.GLOBAL)
.computeIfAbsent("test disposable") {
DisposableResource(Disposer.newCheckedDisposable(uniqueId))
}
.disposable
}
private class DisposableResource(val disposable: CheckedDisposable) : ExtensionContext.Store.CloseableResource {
override fun close() {
Assertions.assertFalse(disposable.isDisposed)
Disposer.dispose(disposable)
}
}
| apache-2.0 | 3416085cb72581d0e719552717034e12 | 39.326923 | 129 | 0.812589 | 4.842956 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/externalCodeProcessing/ExternalUsagesFixer.kt | 1 | 4840 | // 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.nj2k.externalCodeProcessing
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.psi.isConstructorDeclaredProperty
import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation
import org.jetbrains.kotlin.j2k.AccessorKind.GETTER
import org.jetbrains.kotlin.j2k.AccessorKind.SETTER
import org.jetbrains.kotlin.lexer.KtTokens.*
import org.jetbrains.kotlin.load.java.JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
internal class ExternalUsagesFixer(private val usages: List<JKMemberInfoWithUsages>) {
private val conversions = mutableListOf<JKExternalConversion>()
fun fix() {
usages.forEach { it.fix() }
conversions.sort()
conversions.forEach(JKExternalConversion::apply)
}
private fun JKMemberInfoWithUsages.fix() {
when (member) {
is JKFieldDataFromJava -> member.fix(javaUsages, kotlinUsages)
is JKMethodData -> member.fix(javaUsages, kotlinUsages)
}
}
private fun JKFieldDataFromJava.fix(javaUsages: List<PsiElement>, kotlinUsages: List<KtElement>) {
run {
val ktProperty = kotlinElement ?: return@run
when {
javaUsages.isNotEmpty() && ktProperty.canBeAnnotatedWithJvmField() ->
ktProperty.addAnnotationIfThereAreNoJvmOnes(JVM_FIELD_ANNOTATION_FQ_NAME)
javaUsages.isNotEmpty() && isStatic && !ktProperty.hasModifier(CONST_KEYWORD) ->
ktProperty.addAnnotationIfThereAreNoJvmOnes(JVM_STATIC_FQ_NAME)
}
}
if (wasRenamed) {
javaUsages.forEach { usage ->
conversions += PropertyRenamedJavaExternalUsageConversion(name, usage)
}
kotlinUsages.forEach { usage ->
conversions += PropertyRenamedKotlinExternalUsageConversion(name, usage)
}
}
}
private fun JKMethodData.fix(javaUsages: List<PsiElement>, kotlinUsages: List<KtElement>) {
val member = usedAsAccessorOfProperty ?: this
val element = member.kotlinElement
when {
javaUsages.isNotEmpty() && element.canBeAnnotatedWithJvmField() ->
element?.addAnnotationIfThereAreNoJvmOnes(JVM_FIELD_ANNOTATION_FQ_NAME)
javaUsages.isNotEmpty() && isStatic && !element.isConstProperty() ->
element?.addAnnotationIfThereAreNoJvmOnes(JVM_STATIC_FQ_NAME)
}
if (element.isSimpleProperty()) {
val accessorKind = if (javaElement.name.startsWith("set")) SETTER else GETTER
if (element?.hasJvmFieldAnnotation() == true) {
javaUsages.forEach { usage ->
conversions += AccessorToPropertyJavaExternalConversion(member.name, accessorKind, usage)
}
}
kotlinUsages.forEach { usage ->
conversions += AccessorToPropertyKotlinExternalConversion(member.name, accessorKind, usage)
}
}
}
private fun KtNamedDeclaration?.isConstProperty(): Boolean =
this is KtProperty && hasModifier(CONST_KEYWORD)
private fun KtNamedDeclaration?.canBeAnnotatedWithJvmField(): Boolean {
if (this == null) return false
if (hasModifier(OVERRIDE_KEYWORD) || hasModifier(OPEN_KEYWORD) || hasModifier(CONST_KEYWORD)) return false
return isSimpleProperty()
}
private fun KtNamedDeclaration?.isSimpleProperty(): Boolean =
this?.isConstructorDeclaredProperty() == true ||
(this is KtProperty && getter == null && setter == null)
private fun KtNamedDeclaration.addAnnotationIfThereAreNoJvmOnes(fqName: FqName) {
// we don't want to resolve here and as we are working with fqNames, just by-text comparing is OK
if (annotationEntries.any { entry ->
USED_JVM_ANNOTATIONS.any { jvmAnnotation ->
entry.typeReference?.textMatches(jvmAnnotation.asString()) == true
}
}
) return
addAnnotationEntry(KtPsiFactory(this).createAnnotationEntry("@${fqName.asString()}"))
}
internal data class JKMemberInfoWithUsages(
val member: JKMemberData,
val javaUsages: List<PsiElement>,
val kotlinUsages: List<KtElement>
)
companion object {
private val JVM_STATIC_FQ_NAME = FqName("kotlin.jvm.JvmStatic")
val USED_JVM_ANNOTATIONS = listOf(JVM_STATIC_FQ_NAME, JVM_FIELD_ANNOTATION_FQ_NAME)
}
}
| apache-2.0 | 8eb6e5e68482ffca95786c5b8ea73ca3 | 40.367521 | 120 | 0.669421 | 4.801587 | false | false | false | false |
android/storage-samples | ScopedStorage/app/src/main/java/com/samples/storage/scopedstorage/mediastore/AddMediaFileScreen.kt | 1 | 3997 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.samples.storage.scopedstorage.mediastore
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.material.Button
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.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.samples.storage.scopedstorage.Demos
import com.samples.storage.scopedstorage.HomeRoute
import com.samples.storage.scopedstorage.R
import com.samples.storage.scopedstorage.common.MediaFilePreviewCard
@ExperimentalFoundationApi
@Composable
fun AddMediaFileScreen(
navController: NavController,
viewModel: AddMediaFileViewModel = viewModel()
) {
val scaffoldState = rememberScaffoldState()
val error by viewModel.errorFlow.collectAsState(null)
val addedMedia by viewModel.addedMedia.observeAsState()
LaunchedEffect(error) {
error?.let { scaffoldState.snackbarHostState.showSnackbar(it) }
}
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = { Text(stringResource(Demos.AddMediaFile.name)) },
navigationIcon = {
IconButton(onClick = { navController.popBackStack(HomeRoute, false) }) {
Icon(
Icons.Filled.ArrowBack,
contentDescription = stringResource(R.string.back_button_label)
)
}
}
)
},
content = { paddingValues ->
Column(Modifier.padding(paddingValues)) {
if (addedMedia != null) {
MediaFilePreviewCard(addedMedia!!)
} else {
IntroCard()
}
LazyVerticalGrid(cells = GridCells.Fixed(2)) {
item {
Button(
modifier = Modifier.padding(16.dp),
onClick = { viewModel.addImage() }) {
Text(stringResource(R.string.demo_add_image_label))
}
}
item {
Button(
modifier = Modifier.padding(16.dp),
onClick = { viewModel.addVideo() }) {
Text(stringResource(R.string.demo_add_video_label))
}
}
}
}
}
)
}
| apache-2.0 | 93c6c1e042c478414528ce1496b0d6bf | 37.432692 | 92 | 0.648486 | 5.144144 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/dfa/Math.kt | 9 | 3645 | // WITH_STDLIB
fun basicMath(x: Int, y: Int) {
if (x == 12 && y == 2) {
if (<warning descr="Condition 'x + y == 14' is always true">x + y == 14</warning>) {}
if (<warning descr="Condition 'x - y == 10' is always true">x - y == 10</warning>) {}
if (<warning descr="Condition 'x * y == 24' is always true">x * y == 24</warning>) {}
if (<warning descr="Condition 'x / y == 6' is always true">x / y == 6</warning>) {}
if (<warning descr="Condition 'x % y == 0' is always true"><warning descr="Value of 'x % y' is always zero">x % y</warning> == 0</warning>) {}
if (<warning descr="Condition 'x shl y == 48' is always true">x shl y == 48</warning>) {}
if (<warning descr="Condition 'x shr y == 3' is always true">x shr y == 3</warning>) {}
if (<warning descr="Condition 'x ushr y == 3' is always true">x ushr y == 3</warning>) {}
}
}
fun basicMathLong(x: Long, y: Long) {
if (x == 12L && y == 2L) {
if (<warning descr="Condition 'x + y == 14L' is always true">x + y == 14L</warning>) {}
if (<warning descr="Condition 'x - y == 10L' is always true">x - y == 10L</warning>) {}
if (<warning descr="Condition 'x * y == 24L' is always true">x * y == 24L</warning>) {}
if (<warning descr="Condition 'x / y == 6L' is always true">x / y == 6L</warning>) {}
if (<warning descr="Condition 'x % y == 0L' is always true"><warning descr="Value of 'x % y' is always zero">x % y</warning> == 0L</warning>) {}
}
}
fun test(x : Int) {
var a : Int
a = 3
if (x > 0) {
a += 2
} else {
a *= 3
}
if (<warning descr="Condition 'a == 5 || a == 9' is always true">a == 5 || <warning descr="Condition 'a == 9' is always true when reached">a == 9</warning></warning>) {}
}
fun divByZero(x : Int) {
val y = 100 / x
if (<warning descr="Condition 'x == 0' is always false">x == 0</warning>) {
}
if (x == 1) {}
println(y)
}
fun percLongInt(x: Long, y: Int) {
val z = 0
x % y
if (<warning descr="Condition 'z == 0' is always true">z == 0</warning>) {}
}
fun backPropagation(x : Int) {
if (x + 1 > 5) {
if (<warning descr="Condition 'x < 3' is always false">x < 3</warning>) {
}
}
}
fun decrement() {
var x = 10
if (<warning descr="Condition 'x-- == 10' is always true">x-- == 10</warning>) { }
if (<warning descr="Condition 'x == 9' is always true">x == 9</warning>) {}
if (<warning descr="Condition '--x == 8' is always true">--x == 8</warning>) {}
if (<warning descr="Condition 'x == 8' is always true">x == 8</warning>) {}
}
fun increment() {
var x = 10
if (<warning descr="Condition 'x++ == 10' is always true">x++ == 10</warning>) { }
if (<warning descr="Condition 'x == 11' is always true">x == 11</warning>) {}
if (<warning descr="Condition '++x == 12' is always true">++x == 12</warning>) {}
if (<warning descr="Condition 'x == 12' is always true">x == 12</warning>) {}
}
fun increment(x: Int) {
if (x < 0) return
var y = x
++y
if (<warning descr="Condition 'y == 0' is always false">y == 0</warning>) {}
}
fun oddity(x : Int) : Boolean {
if (x % 2 == 0) {
return true;
}
return <warning descr="Condition 'x == 10' is always false">x == 10</warning>;
}
fun shiftLeft(x: Int) {
val y = x shl 2
if (<warning descr="Condition 'y % 4 == 2' is always false"><warning descr="Value of 'y % 4' is always zero">y % 4</warning> == 2</warning>) {}
}
fun unaryMinus() {
val x = 10
val y = -x
if (<warning descr="Condition 'y == -10' is always true">y == -10</warning>) {}
} | apache-2.0 | 90c0a5b22afc53750cbe29df89519086 | 41.395349 | 173 | 0.536351 | 3.211454 | false | false | false | false |
clumsy/intellij-community | platform/script-debugger/protocol/protocol-reader-runtime/src/annotations.kt | 2 | 1610 | /*
* 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.jsonProtocol
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FUNCTION)
annotation class JsonField(
val allowAnyPrimitiveValue: Boolean = false, // read any primitive value as String (true as true, number as string - don't try to parse)
val allowAnyPrimitiveValueAndMap: Boolean = false,
val primitiveValue: String = "")
@Target(AnnotationTarget.CLASS)
annotation class JsonType(val allowsOtherProperties: Boolean = false)
@Target(AnnotationTarget.FUNCTION)
annotation class JsonSubtypeCasting(val reinterpret: Boolean = false)
@Target(AnnotationTarget.FUNCTION)
annotation class JsonParseMethod
/**
* For field-reading method specifies that the field is optional and may safely be absent in
* JSON object. By default fields are not optional.
*/
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FUNCTION)
annotation class Optional(val default: String = "")
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FUNCTION)
annotation class ProtocolName(val name: String) | apache-2.0 | bf9f03e98a8bdeb0778405d548414c96 | 38.292683 | 138 | 0.781988 | 4.375 | false | false | false | false |
7449/Album | wechat/src/main/java/com/gallery/ui/wechat/extension/Extensions.kt | 1 | 3119 | package com.gallery.ui.wechat.extension
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.view.animation.Animation
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.gallery.compat.extensions.getObjExpand
import com.gallery.ui.wechat.args.WeChatGalleryBundle
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.concurrent.TimeUnit
@SuppressLint("SimpleDateFormat")
private val formatter = SimpleDateFormat("yyyy/MM")
internal val Parcelable?.weChatGalleryArgOrDefault: WeChatGalleryBundle
get() = this as? WeChatGalleryBundle ?: WeChatGalleryBundle()
fun Bundle?.getBooleanExpand(key: String): Boolean = getObjExpand(key) { false }
fun Int.colorExpand(activity: Context): Int = activity.colorExpand(this)
fun Context.colorExpand(@ColorRes id: Int): Int = ContextCompat.getColor(this, id)
fun Long.formatTimeVideo(): String {
if (toInt() == 0) {
return "--:--"
}
val format: String = String.format(
"%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(this),
TimeUnit.MILLISECONDS.toSeconds(this) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(this))
)
if (!format.startsWith("0")) {
return format
}
return format.substring(1)
}
fun Long.formatTime(): String {
if (toInt() == 0) {
return "--/--"
}
return formatter.format(this * 1000)
}
fun Long.toFileSize(): String {
return when {
this < 1024 -> DecimalFormat().format(this) + " B"
this < 1048576 -> DecimalFormat().format(this / 1024) + " KB"
this < 1073741824 -> DecimalFormat().format(this / 1048576) + " MB"
else -> DecimalFormat().format(this / 1073741824) + " GB"
}
}
fun Animation.doOnAnimationStartExpand(action: (animation: Animation) -> Unit): Animation =
setAnimationListenerExpand(onAnimationStart = action)
fun Animation.doOnAnimationEndExpand(action: (animation: Animation) -> Unit): Animation =
setAnimationListenerExpand(onAnimationEnd = action)
fun Animation.doOnAnimationRepeatExpand(action: (animation: Animation) -> Unit): Animation =
setAnimationListenerExpand(onAnimationRepeat = action)
fun Animation.setAnimationListenerExpand(
onAnimationRepeat: (animation: Animation) -> Unit = {},
onAnimationEnd: (animation: Animation) -> Unit = {},
onAnimationStart: (animation: Animation) -> Unit = {},
): Animation {
val listener = object : Animation.AnimationListener {
override fun onAnimationRepeat(animation: Animation) {
onAnimationRepeat.invoke(animation)
}
override fun onAnimationEnd(animation: Animation) {
onAnimationEnd.invoke(animation)
}
override fun onAnimationStart(animation: Animation) {
onAnimationStart.invoke(animation)
}
}
setAnimationListener(listener)
return this
} | mpl-2.0 | fc806d194d141eaec44e7f5b06bfbf51 | 33.465909 | 92 | 0.681629 | 4.468481 | false | false | false | false |
batagliao/onebible.android | app/src/main/java/com/claraboia/bibleandroid/activities/SelectBooksActivity.kt | 1 | 5965 | package com.claraboia.bibleandroid.activities
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.view.MenuItemCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.SearchView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.Log
import android.util.TypedValue
import android.view.Menu
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.claraboia.bibleandroid.R
import com.claraboia.bibleandroid.adapters.BookSelectionAdapter
import com.claraboia.bibleandroid.bibleApplication
import com.claraboia.bibleandroid.views.BooksSelectDisplay
import com.claraboia.bibleandroid.views.BooksSelectSortType
import com.claraboia.bibleandroid.views.decorators.DividerItemDecoration
import com.claraboia.bibleandroid.views.decorators.GridSpacingItemDecoration
import kotlinx.android.synthetic.main.activity_select_books.*
class SelectBooksActivity : AppCompatActivity() {
lateinit var bookAdapter: BookSelectionAdapter
lateinit var gridItemDecoration: GridSpacingItemDecoration
val dividerItemDecoration by lazy { DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_select_books)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayShowTitleEnabled(true)
supportActionBar?.setDisplayShowCustomEnabled(false)
// Calculate ActionBar height
val tv = TypedValue()
if (theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
val params = barBellowToolbar.layoutParams
params.height = actionBarHeight * 2 - 44
barBellowToolbar.layoutParams = params
}
//grid item decoration
val metrics = this.resources.displayMetrics
val space = (metrics.density * 12).toInt()
gridItemDecoration = GridSpacingItemDecoration(2, space, true, 0)
//click
bookAdapter = BookSelectionAdapter(bibleApplication.booksForSelection, click = { b ->
bibleApplication.currentBook = b.bookOrder
val i = Intent(this, SelectChapterActivity::class.java)
startActivity(i)
})
bookList.setHasFixedSize(true)
bookList.itemAnimator = DefaultItemAnimator()
setRecyclerLayout()
setRecyclerSort()
groupSelectDisplayType.onChangeDisplayType += {
setRecyclerLayout()
}
groupSelectSortType.onChangeSortType += {
setRecyclerSort()
}
groupSelectSortOrder.onChangeSortOrder += {
setRecyclerSort()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search, menu)
//TODO: make search work
// Associate searchable configuration with the SearchView
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView = MenuItemCompat.getActionView(menu?.findItem(R.id.action_search)) as SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.queryHint = resources.getString(R.string.book_search_hint)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(newText: String?): Boolean {
Log.d("newText = ", newText)
bookAdapter.filter(newText)
return true
}
override fun onQueryTextSubmit(query: String?): Boolean {
Log.d("query = ", query)
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(searchView.windowToken, 0)
searchView.clearFocus()
return true
}
})
searchView.setOnSearchClickListener {
val view = currentFocus
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(searchView.windowToken, 0)
searchView.clearFocus()
}
//searchView.setOnQueryTextListener(this)
return super.onCreateOptionsMenu(menu)
}
private fun setRecyclerLayout() {
bookList.removeItemDecoration(dividerItemDecoration)
bookList.removeItemDecoration(gridItemDecoration)
if (groupSelectDisplayType.currentDisplayType == BooksSelectDisplay.BookLayoutDisplayType.GRID) {
//GRID
bookAdapter.displayType = BooksSelectDisplay.BookLayoutDisplayType.GRID
bookList.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
bookList.addItemDecoration(gridItemDecoration)
} else {
//LIST
bookAdapter.displayType = BooksSelectDisplay.BookLayoutDisplayType.LIST
bookList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
bookList.addItemDecoration(dividerItemDecoration)
}
bookList.adapter = bookAdapter
}
private fun setRecyclerSort() {
if (groupSelectSortType.currentSortType == BooksSelectSortType.BookSortType.NORMAL) {
bookAdapter.sortNormal(groupSelectSortOrder.currentSortOrder)
} else {
bookAdapter.sortAlpha(groupSelectSortOrder.currentSortOrder)
}
}
}
| apache-2.0 | e6893088183ac1aab1c498756c3b73a8 | 38.766667 | 107 | 0.714837 | 5.417802 | false | false | false | false |
deltadak/plep | src/main/kotlin/nl/deltadak/plep/database/tables/Colors.kt | 1 | 1659 | package nl.deltadak.plep.database.tables
import nl.deltadak.plep.database.regularTransaction
import org.jetbrains.exposed.sql.*
/**
* Describes the Colors table for the database, and implements operations on this table.
*/
object Colors : Table() {
/** ID of the color. */
val id = integer("id").uniqueIndex()
/** String value of the hex code of the color, e.g. #ff6688*/
val hex = varchar("hex", length = 10)
/**
* Insert a color in the database if its id is not in the database yet.
*
* @param id of the color.
* @param hex string of the color.
*/
fun insert(id: Int, hex: String) = regularTransaction {
insertIgnore {
it[this.id] = id
it[this.hex] = hex
}
}
/**
* Edit color, i.e., updateOrInsert its hex value in the database.
*
* @param id of the color to be updated.
* @param value the new value to be stored in the database.
*/
fun update(id: Int, value: String) = regularTransaction {
update({ Colors.id eq id + 1 }) { it[hex] = value }
}
/**
* Request all the colors in the database.
*
* @return all the hex values that are in the database.
*/
fun getAll(): List<String> = regularTransaction { selectAll().toList().map { it[Colors.hex] } }
/**
* Request the value of a color. Takes the first of all the colors with this id. Since the id is unique, this gives
* the only result.
*
* @return the hex of the requested color.
*/
fun get(id: Int): String = regularTransaction {
select { Colors.id eq id + 1 }.map { it[hex] }.first()
}
} | mit | adc892147fa9c7bd03531ed0c0a35ec0 | 29.740741 | 119 | 0.601567 | 3.849188 | false | false | false | false |
rjhdby/motocitizen | Motocitizen/src/motocitizen/utils/ParseUtils.kt | 1 | 1373 | package motocitizen.utils
import com.google.android.gms.maps.model.LatLng
import motocitizen.dictionary.Dictionary
import motocitizen.geo.geocoder.AccidentLocation
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.*
fun JSONObject.getTimeFromSeconds() = Date(getLong("ut") * 1000)
fun JSONObject.getAccidentLocation() = AccidentLocation(getString("a"), LatLng(getDouble("y"), getDouble("x")))
inline fun <reified T : Enum<T>> JSONObject.getEnumOr(code: String, default: T): T = enumValues<T>().firstOrNull {
val el = it as Dictionary<Any>
el.code == when (el.code) {
is Int -> getInt(code)
else -> getString(code)
}
} ?: default
fun JSONArray.asList(): List<JSONObject> = (0 until length()).map { getJSONObject(it) }.toList()
fun JSONObject.getStringOr(key: String, default: String): String = getOr(key, default) { getString(key) }
fun JSONObject.getIntOr(key: String, default: Int): Int = getOr(key, default) { getInt(key) }
fun JSONObject.getArrayOrEmpty(key: String): JSONArray = getOr(key, JSONArray()) { getJSONArray(key) }
fun JSONObject.getObjectOrEmpty(key: String): JSONObject = getOr(key, JSONObject()) { getJSONObject(key) }
private fun <T> getOr(key: String, default: T, getter: (String) -> T?): T = try {
getter(key) ?: default
} catch (e: JSONException) {
default
} | mit | cb052938cef2aa234366438dfe0a7e50 | 40.636364 | 114 | 0.718135 | 3.69086 | false | false | false | false |
SpaceFox/kotlinquarium | src/fr/spacefox/kotlinquarium/Aquarium.kt | 1 | 3030 | package fr.spacefox.kotlinquarium
import java.util.*
/**
* Created by spacefox on 20/12/16.
*/
class Aquarium {
val algae = mutableListOf<Alga>()
val fishes = mutableListOf<Fish>()
private var age = 0
fun addAlga(alga: Alga) {
algae.add(alga)
}
fun addFish(fish: Fish) {
fishes.add(fish)
}
fun newTurn() {
age++
algae.forEach(Alga::ages)
val iterator = algae.listIterator()
while (iterator.hasNext()) {
val alga = iterator.next()
if (alga.isAlive()) {
if (alga.hp > 10) {
iterator.add(alga.reproduces())
}
} else {
println("$alga is dead")
iterator.remove()
}
}
val survivorFishes: MutableList<Fish> = mutableListOf()
survivorFishes.addAll(fishes)
fishes
.asSequence() // Indispensable pour éviter le traitement de poissons mangés
.filter { it in survivorFishes }
.forEach {
it.ages()
if (!it.isAlive()) {
println("✝ $it is dead ✝")
survivorFishes.remove(it)
}
// Les poissons qui viennent de naître ne se reproduisent pas
else if (it.age > 0 && !it.isHungry()) {
val partner = survivorFishes.filter { it.age > 0 }.getRandom()
val child = partner?.reproducesWith(it)
if (child != null) {
survivorFishes.add(child)
}
}
else if (it.isHungry()) when (it) {
is Carnivore -> {
val prey = survivorFishes.getRandom()
if (prey != null && it.eat(prey) && !prey.isAlive()) {
println("✝ $prey is dead ✝")
survivorFishes.remove(prey)
}
}
is Herbivore -> {
val alga = algae.getRandom()
if (alga != null && it.eat(alga) && !alga.isAlive()) {
println("An alga is dead.")
algae.remove(alga)
}
}
}
}
fishes.clear()
fishes.addAll(survivorFishes)
print(this)
}
override fun toString(): String {
var out = "Turn $age. This aquarium contains ${algae.size} algae and ${fishes.size} fishes :"
fishes.forEach { out += "\n- $it" }
algae.forEach { out += "\n- $it" }
return out
}
}
private val random = Random()
fun <E> List<E>.getRandom(): E? {
return if (this.isNotEmpty()) this[random.nextInt(this.size)] else null
}
| mit | bd220af7525cc12af21e70805dc2aff8 | 30.113402 | 101 | 0.431743 | 4.191667 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/AdBlock.kt | 1 | 3996 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.adblock
import android.net.Uri
import android.webkit.WebResourceRequest
import androidx.core.util.PatternsCompat
import jp.hazuki.yuzubrowser.adblock.core.ContentRequest
import jp.hazuki.yuzubrowser.core.utility.utils.getMimeTypeFromExtension
import okhttp3.internal.publicsuffix.PublicSuffix
import java.util.*
const val BROADCAST_ACTION_UPDATE_AD_BLOCK_DATA = "jp.hazuki.yuzubrowser.adblock.broadcast.update.adblock"
fun WebResourceRequest.isThirdParty(pageUri: Uri): Boolean {
val hostName = url.host ?: return true
val pageHost = pageUri.host ?: return true
if (hostName == pageHost) return false
val ipPattern = PatternsCompat.IP_ADDRESS
if (ipPattern.matcher(hostName).matches() || ipPattern.matcher(pageHost).matches()) {
return true
}
val db = PublicSuffix.get()
return db.getEffectiveTldPlusOne(hostName) != db.getEffectiveTldPlusOne(pageHost)
}
fun WebResourceRequest.getContentRequest(pageUri: Uri) =
ContentRequest(url, pageUri, getContentType(pageUri), isThirdParty(pageUri))
private fun WebResourceRequest.getContentType(pageUri: Uri): Int {
var type = 0
val scheme = url.scheme
var isPage = false
if (isForMainFrame) {
if (url == pageUri) {
isPage = true
type = ContentRequest.TYPE_DOCUMENT
}
} else {
type = ContentRequest.TYPE_SUB_DOCUMENT
}
if (scheme == "ws" || scheme == "wss") {
type = type or ContentRequest.TYPE_WEB_SOCKET
}
if (requestHeaders["X-Requested-With"] == "XMLHttpRequest") {
type = type or ContentRequest.TYPE_XHR
}
val path = url.path ?: url.toString()
val lastDot = path.lastIndexOf('.')
if (lastDot >= 0) {
when (val extension = path.substring(lastDot + 1).toLowerCase(Locale.ENGLISH)) {
"js" -> return type or ContentRequest.TYPE_SCRIPT
"css" -> return type or ContentRequest.TYPE_STYLE_SHEET
"otf", "ttf", "ttc", "woff", "woff2" -> return type or ContentRequest.TYPE_FONT
"php" -> Unit
else -> {
val mimeType = getMimeTypeFromExtension(extension)
if (mimeType != "application/octet-stream") {
return type or mimeType.getFilterType()
}
}
}
}
if (isPage) {
return type or ContentRequest.TYPE_OTHER
}
val accept = requestHeaders["Accept"]
return if (accept != null && accept != "*/*") {
val mimeType = accept.split(',')[0]
type or mimeType.getFilterType()
} else {
type or ContentRequest.TYPE_OTHER or ContentRequest.TYPE_MEDIA or ContentRequest.TYPE_IMAGE or
ContentRequest.TYPE_FONT or ContentRequest.TYPE_STYLE_SHEET or ContentRequest.TYPE_SCRIPT
}
}
private fun String.getFilterType(): Int {
return when (this) {
"application/javascript",
"application/x-javascript",
"text/javascript",
"application/json" -> ContentRequest.TYPE_SCRIPT
"text/css" -> ContentRequest.TYPE_STYLE_SHEET
else -> when {
startsWith("image/") -> ContentRequest.TYPE_IMAGE
startsWith("video/") || startsWith("audio/") -> ContentRequest.TYPE_MEDIA
startsWith("font/") -> ContentRequest.TYPE_FONT
else -> ContentRequest.TYPE_OTHER
}
}
}
| apache-2.0 | 34f30e7a64f65b75beabd0f04db09e4e | 33.448276 | 106 | 0.658158 | 4.219641 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/main/MainActivityViewModel.kt | 1 | 5216 | package com.orgzly.android.ui.main
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.App
import com.orgzly.android.data.DataRepository
import com.orgzly.android.db.dao.NoteDao
import com.orgzly.android.db.entity.Book
import com.orgzly.android.db.entity.BookView
import com.orgzly.android.db.entity.SavedSearch
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.ui.CommonViewModel
import com.orgzly.android.ui.SingleLiveEvent
import com.orgzly.android.usecase.*
import com.orgzly.android.util.LogUtils
import java.io.File
class MainActivityViewModel(private val dataRepository: DataRepository) : CommonViewModel() {
private val booksParams = MutableLiveData<String>()
private val booksSubject: LiveData<List<BookView>> = Transformations.switchMap(booksParams) {
dataRepository.getBooksLiveData()
}
private val savedSearches: LiveData<List<SavedSearch>> by lazy {
dataRepository.getSavedSearchesLiveData()
}
val savedSearchedExportEvent: SingleLiveEvent<Int> = SingleLiveEvent()
val savedSearchedImportEvent: SingleLiveEvent<Int> = SingleLiveEvent()
val navigationActions: SingleLiveEvent<MainNavigationAction> = SingleLiveEvent()
/* Triggers querying only if parameters changed. */
fun refresh(sortOrder: String) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, sortOrder)
booksParams.value = sortOrder
}
fun books(): LiveData<List<BookView>> {
return booksSubject
}
fun savedSearches(): LiveData<List<SavedSearch>> {
return savedSearches
}
fun followLinkToFile(path: String) {
App.EXECUTORS.diskIO().execute {
catchAndPostError {
val result = UseCaseRunner.run(LinkFindTarget(path)).userData
if (result is File) {
navigationActions.postValue(MainNavigationAction.OpenFile(result))
} else if (result is Book) {
navigationActions.postValue(MainNavigationAction.OpenBook(result.id))
}
}
}
}
fun displayQuery(query: String) {
navigationActions.postValue(MainNavigationAction.DisplayQuery(query))
}
fun followLinkToNoteWithProperty(name: String, value: String) {
App.EXECUTORS.diskIO().execute {
val useCase = NoteFindWithProperty(name, value)
catchAndPostError {
val result = UseCaseRunner.run(useCase)
if (result.userData == null) {
val msg = App.getAppContext().getString(R.string.no_such_link_target, name, value)
errorEvent.postValue(Throwable(msg))
} else {
val noteIdBookId = result.userData as NoteDao.NoteIdBookId
when (AppPreferences.linkTarget(App.getAppContext())) {
"note_details" ->
navigationActions.postValue(
MainNavigationAction.OpenNote(noteIdBookId.bookId, noteIdBookId.noteId))
"book_and_sparse_tree" ->
UseCaseRunner.run(BookSparseTreeForNote(noteIdBookId.noteId))
"book_and_scroll" ->
UseCaseRunner.run(BookScrollToNote(noteIdBookId.noteId))
}
}
}
}
}
fun openNote(noteId: Long) {
App.EXECUTORS.diskIO().execute {
dataRepository.getNote(noteId)?.let { note ->
navigationActions.postValue(
MainNavigationAction.OpenNote(note.position.bookId, note.id))
}
}
}
fun exportSavedSearches(uri: Uri) {
App.EXECUTORS.diskIO().execute {
catchAndPostError {
val result = UseCaseRunner.run(SavedSearchExport(uri))
savedSearchedExportEvent.postValue(result.userData as Int)
}
}
}
fun importSavedSearches(uri: Uri) {
App.EXECUTORS.diskIO().execute {
catchAndPostError {
val result = UseCaseRunner.run(SavedSearchImport(uri))
savedSearchedImportEvent.postValue(result.userData as Int)
}
}
}
fun clockingUpdateRequest(noteIds: Set<Long>, type: Int) {
App.EXECUTORS.diskIO().execute {
catchAndPostError {
UseCaseRunner.run(NoteUpdateClockingState(noteIds, type))
}
}
}
companion object {
private val TAG = MainActivityViewModel::class.java.name
}
}
sealed class MainNavigationAction {
data class OpenBook(val bookId: Long) : MainNavigationAction()
data class OpenBookFocusNote(val bookId: Long, val noteId: Long, val foldRest: Boolean) : MainNavigationAction()
data class OpenNote(val bookId: Long, val noteId: Long) : MainNavigationAction()
data class OpenFile(val file: File) : MainNavigationAction()
data class DisplayQuery(val query: String) : MainNavigationAction()
} | gpl-3.0 | 9942b2b76e481cdb3bcc4b69155f3f89 | 34.489796 | 116 | 0.643405 | 4.794118 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/AppSnackbar.kt | 1 | 2531 | @file:JvmName("AppSnackbarUtils")
package com.orgzly.android.ui
import android.app.Activity
import android.content.Context
import android.view.View
import androidx.annotation.StringRes
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.snackbar.Snackbar
import com.orgzly.R
import com.orgzly.android.ui.util.styledAttributes
@JvmOverloads
fun Activity.showSnackbar(@StringRes resId: Int, @StringRes actionResId: Int? = null, action: (() -> Unit)? = null) {
showSnackbar(getString(resId), actionResId, action)
}
@JvmOverloads
fun Activity.showSnackbar(msg: String?, @StringRes actionResId: Int? = null, action: (() -> Unit)? = null) {
AppSnackbar.showSnackbar(this, msg, actionResId, action)
}
object AppSnackbar {
private var snackbar: Snackbar? = null
fun showSnackbar(activity: Activity, msg: String?, @StringRes actionResId: Int? = null, action: (() -> Unit)? = null) {
if (msg != null) {
val view = activity.findViewById<View>(R.id.main_content) ?: return
val snack = Snackbar.make(view, msg, Snackbar.LENGTH_LONG)
if (actionResId != null && action != null) {
snack.setAction(actionResId) {
action()
}
}
snack.anchorView = anchorView(activity)
showSnackbar(activity, snack)
}
}
private fun anchorView(activity: Activity): View? {
activity.findViewById<View>(R.id.fab)?.run {
if (visibility == View.VISIBLE) {
return this
}
}
activity.findViewById<View>(R.id.bottom_toolbar)?.run {
if (visibility == View.VISIBLE) {
return this
}
}
return null
}
private fun showSnackbar(activity: Activity, snack: Snackbar) {
// Dismiss previous snackbar
dismiss()
// Close drawer before displaying snackbar
activity.findViewById<DrawerLayout>(R.id.drawer_layout)?.closeDrawer(GravityCompat.START)
// On dismiss
snack.addCallback(object : Snackbar.Callback() {
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
super.onDismissed(transientBottomBar, event)
snackbar = null
}
})
// Show the snackbar
snackbar = snack.apply {
show()
}
}
fun dismiss() {
snackbar?.dismiss()
}
} | gpl-3.0 | e9c8258592a8cc10bbf71ac6f018b102 | 28.44186 | 123 | 0.615962 | 4.56036 | false | false | false | false |
stream1984/vertx-kotlin-coroutine | src/main/kotlin/example/Example.kt | 1 | 2976 | package example
import io.vertx.core.CompositeFuture
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.eventbus.Message
import io.vertx.core.http.HttpServer
import io.vertx.kotlin.coroutines.*
/**
* Created by stream.
*/
fun main(args: Array<String>) {
val vertx = Vertx.vertx()
vertx.deployVerticle(ExampleVerticle())
//embed style with out extends CoroutineVerticle, working on Main method directly.
attachVertxToCoroutine(vertx)
runVertxCoroutine {
asyncEvent<Long> { h -> vertx.setTimer(1000L, h) }.await()
println("fired by embed vert.x")
}
}
class ExampleVerticle : CoroutineVerticle() {
override fun start() {
//make all the handler under coroutine.
runVertxCoroutine {
syncEventExample()
syncResultExample()
streamExample()
coroutineHandlerExample()
futureToAwait()
}
}
//asyncEvent
private suspend fun syncEventExample() {
asyncEvent<Long> { h -> vertx.setTimer(2000L, h) }.await()
println("This would be fire in 2s.")
}
//asyncResult
private suspend fun syncResultExample() {
val consumer = vertx.eventBus().localConsumer<String>("someAddressA")
consumer.handler { message ->
println("consumer receive message ${message.body()}")
message.reply("pong")
}
//wait consumer to complete register synchronously
asyncResult<Void> { h -> consumer.completionHandler(h) }.await()
//send message and wait reply synchronously
val reply = asyncResult<Message<String>> { h -> vertx.eventBus().send("someAddressA", "ping", h) }.await()
println("Receive reply ${reply.body()}")
}
//streamAdaptor
private suspend fun streamExample() {
val adaptor = streamAdaptor<Message<Int>>()
vertx.eventBus().localConsumer<Int>("someAddress").handler(adaptor)
//send 10 message to consumer
for (i in 0..10) vertx.eventBus().send("someAddress", i)
//Receive 10 message from the consumer
for (i in 0..10) {
val message = adaptor.receive()
println("got message: ${message.body()}")
}
}
//Convert future to await
private suspend fun futureToAwait() {
val httpServerFuture = Future.future<HttpServer>()
vertx.createHttpServer().requestHandler({ _ -> }).listen(8000, httpServerFuture.completer())
//we can get httpServer by await on future instance.
val httpServer = httpServerFuture.await()
//await composite future.
val result = CompositeFuture.all(httpServerFuture, httpServerFuture).await()
if (result.succeeded()) {
println("all have start up.")
} else {
result.cause().printStackTrace()
}
}
//run coroutine in requestHandler
private fun coroutineHandlerExample() {
vertx.createHttpServer().requestHandler { req ->
runVertxCoroutine {
val timerID = asyncEvent<Long> { h -> vertx.setTimer(2000L, h) }.await()
req.response().end("Hello, this is timerID $timerID")
}
}.listen(8081)
}
}
| apache-2.0 | a8e02c05c0a2915ccaa063153f562d95 | 29.060606 | 110 | 0.681116 | 4.127601 | false | false | false | false |
basion/androidTraining | PermissionsDispatcher-master/processor/src/main/kotlin/permissions/dispatcher/processor/util/Extensions.kt | 1 | 2329 | package permissions.dispatcher.processor.util
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.OnNeverAskAgain
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.OnShowRationale
import permissions.dispatcher.processor.TYPE_UTILS
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeMirror
/**
* Returns the package name of a TypeElement.
*/
fun TypeElement.packageName(): String {
val qn = this.qualifiedName.toString()
return qn.substring(0, qn.lastIndexOf('.'))
}
/**
* Returns the simple name of an Element as a string.
*/
fun Element.simpleString(): String = this.simpleName.toString()
/**
* Returns the simple name of a TypeMirror as a string.
*/
fun TypeMirror.simpleString(): String {
val toString: String = this.toString()
val indexOfDot: Int = toString.lastIndexOf('.')
return if (indexOfDot == -1) toString else toString.substring(indexOfDot + 1)
}
/**
* Returns whether or not an Element is annotated with the provided Annotation class.
*/
fun <A : Annotation> Element.hasAnnotation(annotationType: Class<A>): Boolean =
this.getAnnotation(annotationType) != null
/**
* Returns the inherent value() of a permission Annotation.
* <p>
* If this is invoked on an Annotation that's not defined by PermissionsDispatcher, this returns an empty list.
*/
fun Annotation.permissionValue(): List<String> {
when (this) {
is NeedsPermission -> return this.value.asList()
is OnShowRationale -> return this.value.asList()
is OnPermissionDenied -> return this.value.asList()
is OnNeverAskAgain -> return this.value.asList()
}
return emptyList()
}
/**
* Returns a list of enclosed elements annotated with the provided Annotations.
*/
fun <A : Annotation> Element.childElementsAnnotatedWith(annotationClass: Class<A>): List<ExecutableElement> =
this.enclosedElements
.filter { it.hasAnnotation(annotationClass) }
.map { it as ExecutableElement }
/**
* Returns whether or not a TypeMirror is a subtype of the provided other TypeMirror.
*/
fun TypeMirror.isSubtypeOf(ofType: TypeMirror): Boolean = TYPE_UTILS.isSubtype(this, ofType)
| apache-2.0 | 34e325a80ff0d98e0e5b9e27939101e0 | 33.761194 | 111 | 0.735938 | 4.419355 | false | false | false | false |
thomasnield/kotlin-statistics | src/main/kotlin/org/nield/kotlinstatistics/DoubleStatistics.kt | 1 | 10728 | package org.nield.kotlinstatistics
import org.apache.commons.math3.stat.StatUtils
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics
import org.nield.kotlinstatistics.range.Range
import org.nield.kotlinstatistics.range.until
import java.math.BigDecimal
val DoubleArray.descriptiveStatistics: Descriptives get() = DescriptiveStatistics().apply { forEach { addValue(it) } }.let(::ApacheDescriptives)
fun DoubleArray.geometricMean() = StatUtils.geometricMean(this)
fun DoubleArray.median() = percentile(50.0)
fun DoubleArray.percentile(percentile: Double) = StatUtils.percentile(this, percentile)
fun DoubleArray.variance() = StatUtils.variance(this)
fun DoubleArray.sumOfSquares() = StatUtils.sumSq(this)
fun DoubleArray.standardDeviation() = descriptiveStatistics.standardDeviation
fun DoubleArray.normalize() = StatUtils.normalize(this)
val DoubleArray.kurtosis get() = descriptiveStatistics.kurtosis
val DoubleArray.skewness get() = descriptiveStatistics.skewness
// AGGREGATION OPERATORS
inline fun <T,K> Sequence<T>.sumBy(crossinline keySelector: (T) -> K, crossinline doubleSelector: (T) -> Double) =
groupApply(keySelector, doubleSelector) { it.sum() }
fun <K> Sequence<Pair<K,Double>>.sumBy() =
groupApply({it.first}, {it.second}) { it.sum() }
inline fun <T,K> Iterable<T>.sumBy(crossinline keySelector: (T) -> K, crossinline doubleSelector: (T) -> Double) =
asSequence().sumBy(keySelector, doubleSelector)
fun <K> Iterable<Pair<K,Double>>.sumBy() = asSequence().sumBy()
inline fun <T,K> Sequence<T>.averageBy(crossinline keySelector: (T) -> K, crossinline doubleSelector: (T) -> Double) =
groupApply(keySelector, doubleSelector) { it.average() }
inline fun <T,K> Iterable<T>.averageBy(crossinline keySelector: (T) -> K, crossinline doubleSelector: (T) -> Double) =
asSequence().groupApply(keySelector, doubleSelector) { it.average() }
fun <K> Sequence<Pair<K,Double>>.averageBy() =
groupApply({it.first}, {it.second}) { it.average() }
fun <K> Iterable<Pair<K,Double>>.averageBy() = asSequence().averageBy()
fun Sequence<Double>.doubleRange() = toList().doubleRange()
fun Iterable<Double>.doubleRange() = toList().let { (it.min()?:throw Exception("At least one element must be present"))..(it.max()?:throw Exception("At least one element must be present")) }
inline fun <T,K> Sequence<T>.doubleRangeBy(crossinline keySelector: (T) -> K, crossinline doubleSelector: (T) -> Double) =
groupApply(keySelector, doubleSelector) { it.range() }
inline fun <T,K> Iterable<T>.doubleRangeBy(crossinline keySelector: (T) -> K, crossinline doubleSelector: (T) -> Double) =
asSequence().rangeBy(keySelector, doubleSelector)
// Bin Operators
inline fun <T> Iterable<T>.binByDouble(binSize: Double,
crossinline valueSelector: (T) -> Double,
rangeStart: Double? = null
): BinModel<List<T>, Double> = toList().binByDouble(binSize, valueSelector, { it }, rangeStart)
inline fun <T, G> Iterable<T>.binByDouble(binSize: Double,
crossinline valueSelector: (T) -> Double,
crossinline groupOp: (List<T>) -> G,
rangeStart: Double? = null
) = toList().binByDouble(binSize, valueSelector, groupOp, rangeStart)
inline fun <T> Sequence<T>.binByDouble(binSize: Double,
crossinline valueSelector: (T) -> Double,
rangeStart: Double? = null
): BinModel<List<T>, Double> = toList().binByDouble(binSize, valueSelector, { it }, rangeStart)
inline fun <T, G> Sequence<T>.binByDouble(binSize: Double,
crossinline valueSelector: (T) -> Double,
crossinline groupOp: (List<T>) -> G,
rangeStart: Double? = null
) = toList().binByDouble(binSize, valueSelector, groupOp, rangeStart)
inline fun <T> List<T>.binByDouble(binSize: Double,
crossinline valueSelector: (T) -> Double,
rangeStart: Double? = null
): BinModel<List<T>, Double> = binByDouble(binSize, valueSelector, { it }, rangeStart)
inline fun <T, G> List<T>.binByDouble(binSize: Double,
crossinline valueSelector: (T) -> Double,
crossinline groupOp: (List<T>) -> G,
rangeStart: Double? = null
): BinModel<G, Double> {
val groupedByC = asSequence().groupBy { BigDecimal.valueOf(valueSelector(it)) }
val minC = rangeStart?.let(BigDecimal::valueOf)?:groupedByC.keys.min()!!
val maxC = groupedByC.keys.max()!!
val bins = mutableListOf<Range<Double>>().apply {
var currentRangeStart = minC
var currentRangeEnd = minC
val binSizeBigDecimal = BigDecimal.valueOf(binSize)
while (currentRangeEnd < maxC) {
currentRangeEnd = currentRangeStart + binSizeBigDecimal
add(currentRangeStart.toDouble() until currentRangeEnd.toDouble())
currentRangeStart = currentRangeEnd
}
}
return bins.asSequence()
.map { it to mutableListOf<T>() }
.map { binWithList ->
groupedByC.entries.asSequence()
.filter { it.key.toDouble() in binWithList.first }
.forEach { binWithList.second.addAll(it.value) }
binWithList
}.map { Bin(it.first, groupOp(it.second)) }
.toList()
.let(::BinModel)
}
fun <T, C : Comparable<C>> BinModel<List<T>, C>.sumByDouble(selector: (T) -> Double): BinModel<Double, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).sum()) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.averageByDouble(selector: (T) -> Double): BinModel<Double, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).average()) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.doubleRangeBy(selector: (T) -> Double): BinModel<ClosedFloatingPointRange<Double>, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).doubleRange()) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.geometricMeanByDouble(selector: (T) -> Double): BinModel<Double, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).geometricMean()) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.medianByDouble(selector: (T) -> Double): BinModel<Double, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).median()) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.percentileByDouble(selector: (T) -> Double, percentile: Double): BinModel<Double, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).percentile(percentile)) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.varianceByDouble(selector: (T) -> Double): BinModel<Double, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).variance()) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.sumOfSquaresByDouble(selector: (T) -> Double): BinModel<Double, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).sumOfSquares()) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.normalizeByDouble(selector: (T) -> Double): BinModel<DoubleArray, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).normalize()) })
fun <T, C : Comparable<C>> BinModel<List<T>, C>.descriptiveStatisticsByDouble(selector: (T) -> Double): BinModel<Descriptives, C> =
BinModel(bins.map { Bin(it.range, it.value.map(selector).descriptiveStatistics) })
fun <K> Map<K, List<Double>>.sum(): Map<K, Double> = entries.map { it.key to it.value.sum() }.toMap()
fun <K> Map<K, List<Double>>.average(): Map<K, Double> = entries.map { it.key to it.value.average() }.toMap()
fun <K> Map<K, List<Double>>.intRange(): Map<K, ClosedFloatingPointRange<Double>> = entries.map { it.key to it.value.doubleRange() }.toMap()
fun <K> Map<K, List<Double>>.geometricMean(): Map<K, Double> = entries.map { it.key to it.value.geometricMean() }.toMap()
fun <K> Map<K, List<Double>>.median(): Map<K, Double> = entries.map { it.key to it.value.median() }.toMap()
fun <K> Map<K, List<Double>>.percentile(percentile: Double): Map<K, Double> = entries.map { it.key to it.value.percentile(percentile) }.toMap()
fun <K> Map<K, List<Double>>.variance(): Map<K, Double> = entries.map { it.key to it.value.variance() }.toMap()
fun <K> Map<K, List<Double>>.sumOfSquares(): Map<K, Double> = entries.map { it.key to it.value.sumOfSquares() }.toMap()
fun <K> Map<K, List<Double>>.normalize(): Map<K, DoubleArray> = entries.map { it.key to it.value.normalize() }.toMap()
fun <K> Map<K, List<Double>>.descriptiveStatistics(): Map<K, Descriptives> = entries.map { it.key to it.value.descriptiveStatistics }.toMap()
fun <K, V> Map<K, List<V>>.sumByDouble(selector: (V) -> Double): Map<K, Double> =
entries.map { it.key to it.value.map(selector).sum() }.toMap()
fun <K, V> Map<K, List<V>>.averageByDouble(selector: (V) -> Double): Map<K, Double> =
entries.map { it.key to it.value.map(selector).average() }.toMap()
fun <K, V> Map<K, List<V>>.doubleRangeBy(selector: (V) -> Double): Map<K, ClosedFloatingPointRange<Double>> =
entries.map { it.key to it.value.map(selector).doubleRange() }.toMap()
fun <K, V> Map<K, List<V>>.geometricMeanByDouble(selector: (V) -> Double): Map<K, Double> =
entries.map { it.key to it.value.map(selector).geometricMean() }.toMap()
fun <K, V> Map<K, List<V>>.medianByDouble(selector: (V) -> Double): Map<K, Double> =
entries.map { it.key to it.value.map(selector).median() }.toMap()
fun <K, V> Map<K, List<V>>.percentileByDouble(selector: (V) -> Double, percentile: Double): Map<K, Double> =
entries.map { it.key to it.value.map(selector).percentile(percentile) }.toMap()
fun <K, V> Map<K, List<V>>.varianceByDouble(selector: (V) -> Double): Map<K, Double> =
entries.map { it.key to it.value.map(selector).variance() }.toMap()
fun <K, V> Map<K, List<V>>.sumOfSquaresByDouble(selector: (V) -> Double): Map<K, Double> =
entries.map { it.key to it.value.map(selector).sumOfSquares() }.toMap()
fun <K, V> Map<K, List<V>>.normalizeByDouble(selector: (V) -> Double): Map<K, DoubleArray> =
entries.map { it.key to it.value.map(selector).normalize() }.toMap()
fun <K, V> Map<K, List<V>>.descriptiveStatisticsByDouble(selector: (V) -> Double): Map<K, Descriptives> =
entries.map { it.key to it.value.map(selector).descriptiveStatistics }.toMap()
| apache-2.0 | 4b92a6d0954dd40ace7797edd76ec459 | 52.373134 | 190 | 0.646066 | 3.562936 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/exceptions/exceptions.kt | 1 | 2982 | package edu.kit.iti.formal.automation.exceptions
import edu.kit.iti.formal.automation.IEC61131Facade
import edu.kit.iti.formal.automation.datatypes.AnyDt
import edu.kit.iti.formal.automation.scope.Scope
import edu.kit.iti.formal.automation.st.ast.Expression
import edu.kit.iti.formal.automation.st.ast.Invocation
import edu.kit.iti.formal.automation.st.ast.SymbolicReference
import edu.kit.iti.formal.automation.st.ast.Top
import java.util.*
/**
* Top class of exceptions.
*
* @author weigl
* @version 1
* @since 27.11.16.
*/
abstract class IECException : RuntimeException {
constructor() : super()
constructor(message: String?) : super(message)
constructor(message: String?, cause: Throwable?) : super(message, cause)
constructor(cause: Throwable?) : super(cause)
constructor(message: String?, cause: Throwable?, enableSuppression: Boolean, writableStackTrace: Boolean) : super(message, cause, enableSuppression, writableStackTrace)
}
/**
* @author weigl
* @since 25.11.16
*/
class DataTypeNotDefinedException : RuntimeException {
constructor() : super() {}
constructor(message: String) : super(message) {}
constructor(message: String, cause: Throwable) : super(message, cause) {}
constructor(cause: Throwable) : super(cause) {}
protected constructor(message: String, cause: Throwable, enableSuppression: Boolean, writableStackTrace: Boolean) : super(message, cause, enableSuppression, writableStackTrace) {}
}
/**
* Created by weigl on 24.11.16.
*
* @author weigl
*/
class VariableNotDefinedException(message: String) : IECException(message) {
var scope: Scope? = null
var reference: SymbolicReference? = null
constructor(scope: Scope, reference: SymbolicReference)
: this("Variable: $reference not defined in the given localScope $scope") {
this.scope = scope
this.reference = reference
}
constructor(scope: Scope, reference: String)
: this("Variable: $reference not defined in the given localScope $scope") {
this.scope = scope
}
}
class DataTypeNotResolvedException(message: String) : IECException(message) {
val expr: Top? = null
}
class FunctionInvocationArgumentNumberException : IECException()
/**
* FunctionUndefinedException isType thrown if
* a function isType used but not in the list of toplevel elements.
*
* @author weigl
* @since 27.11.16.
*/
class FunctionUndefinedException(val invocation: Invocation) : IECException()
class TypeConformityException(
val expression: Expression,
val expectedDataTypes: Array<AnyDt>,
vararg actual: AnyDt?) : IECException() {
val actualDatatypes: Array<out AnyDt?> = actual
override val message: String?
get() = String.format("Type(s) violated in %s %nExpected:%s %nGot:%s %n ",
IEC61131Facade.print(expression),
Arrays.toString(this.expectedDataTypes),
Arrays.toString(this.actualDatatypes))
}
| gpl-3.0 | 1eab6f56522ca2eb4f9e3a0ad43eadb4 | 32.505618 | 183 | 0.71328 | 4.046133 | false | false | false | false |
NLPIE/BioMedICUS | biomedicus-core/src/main/kotlin/edu/umn/biomedicus/measures/TimeUnits.kt | 1 | 2851 | /*
* Copyright (c) 2018 Regents of the University of Minnesota.
*
* 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 edu.umn.biomedicus.measures
import edu.umn.biomedicus.annotations.Setting
import edu.umn.biomedicus.tokenization.ParseToken
import edu.umn.nlpengine.*
import java.io.File
import java.nio.charset.StandardCharsets
import javax.inject.Inject
/**
* Some kind of time unit: days, months, years, hours
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class TimeUnit(
override val startIndex: Int,
override val endIndex: Int
) : Label() {
constructor(textRange: TextRange) : this(textRange.startIndex, textRange.endIndex)
}
/**
* A time frequency: hourly, daily, weekly, yearly.
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class TimeFrequencyUnit(override val startIndex: Int, override val endIndex: Int) : Label() {
constructor(textRange: TextRange): this(textRange.startIndex, textRange.endIndex)
}
class TimeUnitDetector(val words: List<String>) : DocumentsProcessor {
@Inject constructor(
@Setting("measures.timeUnits.asDataPath") timeUnitsPath: String
): this(File(timeUnitsPath).readLines(StandardCharsets.UTF_8))
override fun process(document: Document) {
val parseTokens = document.labelIndex<ParseToken>()
val labeler = document.labeler<TimeUnit>()
parseTokens
.filter {
words.indexOfFirst { tu ->
it.text.compareTo(tu, true) == 0
} != -1
}
.forEach { labeler.add(TimeUnit(it)) }
}
}
data class TimeFrequencyUnitDetector(val units: List<String>) : DocumentsProcessor {
@Inject constructor(
@Setting("measures.timeFrequencyUnits.asDataPath") path: String
) : this(File(path).readLines(StandardCharsets.UTF_8))
override fun process(document: Document) {
val parseTokens = document.labelIndex<ParseToken>()
val labeler = document.labeler<TimeFrequencyUnit>()
parseTokens
.filter {
units.indexOfFirst { tu ->
it.text.compareTo(tu, true) == 0
} != -1
}
.forEach { labeler.add(TimeFrequencyUnit(it)) }
}
}
| apache-2.0 | e529d5d3a02ca41d17f9cf1a1618ddd5 | 32.940476 | 98 | 0.662925 | 4.352672 | false | false | false | false |
sxend/FrameworkBenchmarks | frameworks/Kotlin/ktor/ktor-asyncdb/src/main/kotlin/main.kt | 23 | 7041 | import com.github.jasync.sql.db.ConnectionPoolConfiguration
import com.github.jasync.sql.db.SuspendingConnection
import com.github.jasync.sql.db.asSuspending
import com.github.jasync.sql.db.postgresql.PostgreSQLConnectionBuilder
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.features.DefaultHeaders
import io.ktor.html.Placeholder
import io.ktor.html.Template
import io.ktor.html.insert
import io.ktor.html.respondHtmlTemplate
import io.ktor.http.ContentType
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.reactiverse.kotlin.pgclient.getConnectionAwait
import io.reactiverse.kotlin.pgclient.preparedBatchAwait
import io.reactiverse.kotlin.pgclient.preparedQueryAwait
import io.reactiverse.pgclient.*
import kotlinx.html.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JSON
import kotlinx.serialization.list
import java.lang.IllegalArgumentException
import kotlin.random.Random
import kotlin.random.nextInt
@Serializable
data class Message(val message: String)
@Serializable
data class World(val id: Int, val randomNumber: Int)
data class Fortune(val id: Int, val message: String)
val rand = Random(1)
interface Repository {
suspend fun getWorld(): World
suspend fun getFortunes(): List<Fortune>
suspend fun updateWorlds(worlds: List<World>)
}
class JasyncRepository() : Repository {
private val dbConfig: ConnectionPoolConfiguration
private val db: SuspendingConnection
init {
dbConfig = ConnectionPoolConfiguration(
"tfb-database",
database = "hello_world",
username = "benchmarkdbuser",
password = "benchmarkdbpass",
maxActiveConnections = 64
)
db = PostgreSQLConnectionBuilder.createConnectionPool(dbConfig).asSuspending
}
override suspend fun getWorld(): World {
val worldId = rand.nextInt(1, 10000)
val result = db.sendPreparedStatement("select id, randomNumber from world where id = ?", listOf(worldId))
val row = result.rows.first()
return World(row.getInt(0)!!, row.getInt(1)!!)
}
override suspend fun getFortunes(): List<Fortune> {
val results = db.sendPreparedStatement("select id, message from fortune")
return results.rows.map { Fortune(it.getInt(0)!!, it.getString(1)!!) }
}
override suspend fun updateWorlds(worlds: List<World>) {
worlds.forEach { world ->
db.sendPreparedStatement(
"update world set randomNumber = ? where id = ?",
listOf(world.randomNumber, world.id)
)
}
}
}
class ReactivePGRepository : Repository {
private val db: PgPool
init {
val poolOptions = PgPoolOptions()
poolOptions.apply {
host = "tfb-database"
database = "hello_world"
user = "benchmarkdbuser"
password = "benchmarkdbpass"
maxSize = 64
cachePreparedStatements = true
}
db = PgClient.pool(poolOptions)
}
override suspend fun getFortunes(): List<Fortune> {
val results = db.preparedQueryAwait("select id, message from fortune")
return results.map { Fortune(it.getInteger(0), it.getString(1)) }
}
override suspend fun getWorld(): World {
val worldId = rand.nextInt(1, 10000)
val result = db.preparedQueryAwait("select id, randomNumber from world where id = $1", Tuple.of(worldId))
val row = result.first()
return World(row.getInteger(0), row.getInteger(1)!!)
}
override suspend fun updateWorlds(worlds: List<World>) {
val batch = worlds.map { Tuple.of(it.id, it.randomNumber) }
db.preparedBatchAwait("update world set randomNumber = $1 where id = $2", batch)
}
}
fun String.toBoxedInt(range: IntRange): Int = try {
this.toInt().coerceIn(range)
} catch (e: NumberFormatException) {
1
}
class MainTemplate : Template<HTML> {
val content = Placeholder<HtmlBlockTag>()
override fun HTML.apply() {
head {
title { +"Fortunes" }
}
body {
insert(content)
}
}
}
class FortuneTemplate(val fortunes: List<Fortune>, val main: MainTemplate = MainTemplate()) : Template<HTML> {
override fun HTML.apply() {
insert(main) {
content {
table {
tr {
th { +"id" }
th { +"message" }
}
fortunes.forEach { fortune ->
tr {
td { +fortune.id.toString() }
td { +fortune.message }
}
}
}
}
}
}
}
fun main(args: Array<String>) {
val db = when(args.firstOrNull()) {
"jasync-sql" -> JasyncRepository()
"reactive-pg" -> ReactivePGRepository()
else -> throw IllegalArgumentException("Must specify a postgres client")
}
val messageSerializer = Message.serializer()
val worldSerializer = World.serializer()
val server = embeddedServer(Netty, 8080, configure = {
shareWorkGroup = true
}) {
install(DefaultHeaders)
routing {
get("/plaintext") {
call.respondText("Hello, World!")
}
get("/json") {
call.respondText(
JSON.stringify(messageSerializer, Message("Hello, World!")),
ContentType.Application.Json
)
}
get("/db") {
call.respondText(JSON.stringify(worldSerializer, db.getWorld()), ContentType.Application.Json)
}
get("/query/") {
val queries = call.parameters["queries"]?.toBoxedInt(1..500) ?: 1
val worlds = (1..queries).map { db.getWorld() }
call.respondText(JSON.stringify(worldSerializer.list, worlds), ContentType.Application.Json)
}
get("/fortunes") {
val newFortune = Fortune(0, "Additional fortune added at request time.")
val fortunes = db.getFortunes().toMutableList()
fortunes.add(newFortune)
fortunes.sortBy { it.message }
call.respondHtmlTemplate(FortuneTemplate(fortunes)) { }
}
get("/updates") {
val queries = call.parameters["queries"]?.toBoxedInt(1..500) ?: 1
val worlds = (1..queries).map { db.getWorld() }
val newWorlds = worlds.map { it.copy(randomNumber = rand.nextInt(1..10000)) }
db.updateWorlds(newWorlds)
call.respondText(JSON.stringify(worldSerializer.list, newWorlds), ContentType.Application.Json)
}
}
}
server.start(wait = true)
}
| bsd-3-clause | 2166e5ba8b590c466eb759e2094c7371 | 32.056338 | 113 | 0.610709 | 4.447884 | false | false | false | false |
android/user-interface-samples | DownloadableFonts/app/src/main/java/com/example/android/downloadablefonts/QueryBuilder.kt | 1 | 1577 | /*
* Copyright (C) 2017 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.android.downloadablefonts
/**
* Builder class for constructing a query for downloading a font.
*/
internal class QueryBuilder(val familyName: String,
val width: Float? = null,
val weight: Int? = null,
val italic: Float? = null,
val bestEffort: Boolean? = null) {
fun build(): String {
if (weight == null && width == null && italic == null && bestEffort == null) {
return familyName
}
val builder = StringBuilder()
builder.append("name=").append(familyName)
weight?.let { builder.append("&weight=").append(weight) }
width?.let { builder.append("&width=").append(width) }
italic?.let { builder.append("&italic=").append(italic) }
bestEffort?.let { builder.append("&besteffort=").append(bestEffort) }
return builder.toString()
}
}
| apache-2.0 | eb6143d3ed5a88bbddd0224b2c4419b4 | 38.425 | 86 | 0.627774 | 4.454802 | false | false | false | false |
ryugoo/conference-app-2017 | app/src/test/java/io/github/droidkaigi/confsched2017/viewmodel/SponsorshipsViewModelTest.kt | 5 | 3437 | package io.github.droidkaigi.confsched2017.viewmodel
import com.google.gson.Gson
import com.sys1yagi.kmockito.any
import com.sys1yagi.kmockito.mock
import com.sys1yagi.kmockito.verify
import com.taroid.knit.should
import io.github.droidkaigi.confsched2017.model.Sponsor
import io.github.droidkaigi.confsched2017.model.Sponsorship
import io.github.droidkaigi.confsched2017.util.RxTestSchedulerRule
import io.github.droidkaigi.confsched2017.view.helper.ResourceResolver
import io.reactivex.disposables.CompositeDisposable
import org.junit.After
import org.junit.Before
import org.junit.ClassRule
import org.junit.Test
import org.mockito.Mockito.never
class SponsorshipsViewModelTest {
companion object {
@ClassRule
@JvmField
val schedulerRule = RxTestSchedulerRule
private val EXPECTED_SPONSORSHIPS = listOf(
Sponsorship().apply {
category = "Category A"
sponsors = listOf(
createDummySponsor("a"),
createDummySponsor("b")
)
},
Sponsorship().apply {
category = "Category B"
sponsors = listOf(
createDummySponsor("c")
)
}
)
private fun createDummySponsor(name: String) = Sponsor().apply {
imageUrl = "imageUrl_$name"
url = "url_$name"
}
}
private val resourceResolver = object : ResourceResolver(null) {
override fun getString(resId: Int): String = "dummy"
override fun loadJSONFromAsset(jsonFileName: String?): String = Gson().toJson(EXPECTED_SPONSORSHIPS)
}
private lateinit var viewModel: SponsorshipsViewModel
@Before
fun setUp() {
viewModel = SponsorshipsViewModel(resourceResolver, CompositeDisposable())
}
@After
fun tearDown() {
viewModel.destroy()
}
@Test
@Throws(Exception::class)
fun start() {
viewModel.start()
schedulerRule.testScheduler.triggerActions()
assertSponsorShipEq(viewModel.sponsorShipViewModels, EXPECTED_SPONSORSHIPS)
}
@Test
@Throws(Exception::class)
fun onSponsorClick() {
val callback = mock<SponsorViewModel.Callback>()
viewModel.start()
schedulerRule.testScheduler.triggerActions()
val targetSponsor = viewModel.sponsorShipViewModels[0].sponsorViewModels[0]
targetSponsor.setCallback(callback)
callback.verify(never()).onClickSponsor(any())
targetSponsor.onClickSponsor(null)
callback.verify().onClickSponsor("url_a")
}
private fun assertSponsorShipEq(actual: List<SponsorshipViewModel>, expected: List<Sponsorship>) {
actual.size.should be expected.size
actual.map { it.category }.should be expected.map { it.category }
actual.zip(expected).forEach {
val actualSponsors = it.first.sponsorship.sponsors
val expectedSponsors = it.second.sponsors
assertSponsorEq(actualSponsors, expectedSponsors)
}
}
private fun assertSponsorEq(actual: List<Sponsor>, expected: List<Sponsor>) {
actual.size.should be expected.size
actual.map { it.imageUrl }.should be expected.map { it.imageUrl }
actual.map { it.url }.should be expected.map { it.url }
}
}
| apache-2.0 | 856e31b560f96d943e15956e14f671fb | 31.424528 | 108 | 0.64824 | 4.657182 | false | true | false | false |
owntracks/android | project/app/src/test/java/org/owntracks/android/ui/preferences/load/LoadViewModelTest.kt | 1 | 1768 | package org.owntracks.android.ui.preferences.load
import android.content.Context
import android.content.res.Resources
import org.greenrobot.eventbus.EventBus
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.owntracks.android.support.InMemoryPreferencesStore
import org.owntracks.android.support.Parser
import org.owntracks.android.support.Preferences
import org.owntracks.android.support.PreferencesGettersAndSetters
import org.owntracks.android.support.preferences.PreferencesStore
import org.owntracks.android.ui.NoopAppShortcuts
import java.net.URI
class LoadViewModelTest {
private lateinit var mockResources: Resources
private lateinit var mockContext: Context
private lateinit var preferencesStore: PreferencesStore
private val eventBus: EventBus = mock {}
@Before
fun createMocks() {
mockResources = PreferencesGettersAndSetters.getMockResources()
mockContext = mock {
on { resources } doReturn mockResources
on { packageName } doReturn javaClass.canonicalName
}
preferencesStore = InMemoryPreferencesStore()
}
@Test
fun `When invalid JSON on an inline owntracks config URL, then the error is correctly set`() {
val parser = Parser(null)
val preferences = Preferences(mockContext, null, preferencesStore, NoopAppShortcuts())
val vm = LoadViewModel(preferences, parser, InMemoryWaypointsRepo(eventBus))
vm.extractPreferences(URI("owntracks:///config?inline=e30k"))
assertEquals(
"""Import failed: Message is not a valid configuration message""",
vm.displayedConfiguration
)
}
}
| epl-1.0 | 3e96ae7283150f8098a8581a63e4e10f | 36.617021 | 98 | 0.751131 | 4.830601 | false | true | false | false |
Nagarajj/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandlerSpec.kt | 1 | 19075 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.TaskResult
import com.netflix.spinnaker.orca.batch.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.pipeline.model.Execution.PausedDetails
import com.netflix.spinnaker.orca.pipeline.model.Pipeline
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.*
import com.netflix.spinnaker.orca.time.fixedClock
import com.netflix.spinnaker.spek.and
import com.netflix.spinnaker.spek.shouldEqual
import com.nhaarman.mockito_kotlin.*
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.threeten.extra.Minutes
import java.lang.RuntimeException
import java.time.Duration
object RunTaskHandlerSpec : SubjectSpek<RunTaskHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
val task: DummyTask = mock()
val exceptionHandler: ExceptionHandler<in Exception> = mock()
val clock = fixedClock()
subject {
RunTaskHandler(queue, repository, listOf(task), clock, listOf(exceptionHandler))
}
fun resetMocks() = reset(queue, repository, task, exceptionHandler)
describe("running a task") {
describe("that completes successfully") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
startTime = clock.instant().toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
val taskResult = TaskResult(SUCCEEDED)
beforeGroup {
whenever(task.execute(any<Stage<*>>())) doReturn taskResult
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("executes the task") {
verify(task).execute(pipeline.stages.first())
}
it("completes the task") {
verify(queue).push(check<CompleteTask> {
it.status shouldEqual SUCCEEDED
})
}
}
describe("that is not yet complete") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
startTime = clock.instant().toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
val taskResult = TaskResult(RUNNING)
val taskBackoffMs = 30_000L
beforeGroup {
whenever(task.execute(any())) doReturn taskResult
whenever(task.backoffPeriod) doReturn taskBackoffMs
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("re-queues the command") {
verify(queue).push(message, Duration.ofMillis(taskBackoffMs))
}
}
describe("that fails") {
val pipeline = pipeline {
stage {
refId = "1"
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
startTime = clock.instant().toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
val taskResult = TaskResult(TERMINAL)
and("no overrides are in place") {
beforeGroup {
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task TERMINAL") {
verify(queue).push(check<CompleteTask> {
it.status shouldEqual TERMINAL
})
}
}
and("the task should not fail the whole pipeline, only the branch") {
beforeGroup {
pipeline.stageByRef("1").apply {
context["failPipeline"] = false
context["continuePipeline"] = false
}
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
afterGroup { pipeline.stages.first().context.clear() }
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task STOPPED") {
verify(queue).push(check<CompleteTask> {
it.status shouldEqual STOPPED
})
}
}
and("the task should allow the pipeline to proceed") {
beforeGroup {
pipeline.stageByRef("1").apply {
context["failPipeline"] = false
context["continuePipeline"] = true
}
whenever(task.execute(any())) doReturn taskResult
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
afterGroup { pipeline.stages.first().context.clear() }
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task FAILED_CONTINUE") {
verify(queue).push(check<CompleteTask> {
it.status shouldEqual FAILED_CONTINUE
})
}
}
}
describe("that throws an exception") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
startTime = clock.instant().toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
context("that is not recoverable") {
val exceptionDetails = ExceptionHandler.Response(
RuntimeException::class.qualifiedName,
"o noes",
ExceptionHandler.ResponseDetails("o noes"),
false
)
beforeGroup {
whenever(task.execute(any())) doThrow RuntimeException("o noes")
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as terminal") {
verify(queue).push(check<CompleteTask> {
it.status shouldEqual TERMINAL
})
}
it("attaches the exception to the stage context") {
verify(repository).storeStage(check {
it.getContext()["exception"] shouldEqual exceptionDetails
})
}
}
context("that is recoverable") {
val taskBackoffMs = 30_000L
val exceptionDetails = ExceptionHandler.Response(
RuntimeException::class.qualifiedName,
"o noes",
ExceptionHandler.ResponseDetails("o noes"),
true
)
beforeGroup {
whenever(task.backoffPeriod) doReturn taskBackoffMs
whenever(task.execute(any())) doThrow RuntimeException("o noes")
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
whenever(exceptionHandler.handles(any())) doReturn true
whenever(exceptionHandler.handle(anyOrNull(), any())) doReturn exceptionDetails
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("re-runs the task") {
verify(queue).push(eq(message), eq(Duration.ofMillis(taskBackoffMs)))
}
}
}
describe("when the execution has stopped") {
val pipeline = pipeline {
status = TERMINAL
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
startTime = clock.instant().toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("emits an event indicating that the task was canceled") {
verify(queue).push(CompleteTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
message.taskId,
CANCELED
))
}
it("does not execute the task") {
verifyZeroInteractions(task)
}
}
describe("when the execution has been canceled") {
val pipeline = pipeline {
status = RUNNING
isCanceled = true
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
startTime = clock.instant().toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as canceled") {
verify(queue).push(CompleteTask(
message.executionType,
message.executionId,
"foo",
message.stageId,
message.taskId,
CANCELED
))
}
it("does not execute the task") {
verifyZeroInteractions(task)
}
}
describe("when the execution has been paused") {
val pipeline = pipeline {
status = PAUSED
stage {
type = "whatever"
status = RUNNING
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
startTime = clock.instant().toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("marks the task as paused") {
verify(queue).push(PauseTask(message))
}
it("does not execute the task") {
verifyZeroInteractions(task)
}
}
describe("when the task has exceeded its timeout") {
context("the execution was never paused") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
whenever(task.timeout) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
context("the execution had been paused") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli()
}
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
whenever(task.timeout) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("executes the task") {
verify(task).execute(any())
}
}
context("the execution had been paused but is timed out anyway") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(3)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(2)).toEpochMilli()
}
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
status = RUNNING
startTime = clock.instant().minusMillis(timeout.plusMinutes(1).toMillis() + 1).toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
whenever(task.timeout) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
context("the execution had been paused but only before this task started running") {
val timeout = Duration.ofMinutes(5)
val pipeline = pipeline {
paused = PausedDetails().apply {
pauseTime = clock.instant().minus(Minutes.of(10)).toEpochMilli()
resumeTime = clock.instant().minus(Minutes.of(9)).toEpochMilli()
}
stage {
type = "whatever"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
status = RUNNING
startTime = clock.instant().minusMillis(timeout.toMillis() + 1).toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
whenever(task.timeout) doReturn timeout.toMillis()
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("fails the task") {
verify(queue).push(CompleteTask(message, TERMINAL))
}
it("does not execute the task") {
verify(task, never()).execute(any())
}
}
}
describe("the context passed to the task") {
val pipeline = pipeline {
context["global"] = "foo"
context["override"] = "global"
stage {
type = "whatever"
context["stage"] = "foo"
context["override"] = "stage"
task {
id = "1"
implementingClass = DummyTask::class.qualifiedName
startTime = clock.instant().toEpochMilli()
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", DummyTask::class.java)
val taskResult = TaskResult(SUCCEEDED)
beforeGroup {
whenever(task.execute(any<Stage<*>>())) doReturn taskResult
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("merges stage and global contexts") {
verify(task).execute(check {
it.getContext() shouldEqual mapOf(
"global" to "foo",
"stage" to "foo",
"override" to "stage"
)
})
}
}
}
describe("no such task") {
val pipeline = pipeline {
stage {
type = "whatever"
task {
id = "1"
implementingClass = InvalidTask::class.qualifiedName
}
}
}
val message = RunTask(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id, "1", InvalidTask::class.java)
beforeGroup {
whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("does not run any tasks") {
verifyZeroInteractions(task)
}
it("emits an error event") {
verify(queue).push(isA<InvalidTaskType>())
}
}
})
| apache-2.0 | 4a0a3aa3b1641907c3389133594c7e02 | 29.766129 | 127 | 0.595334 | 4.82667 | false | false | false | false |
eugeis/ee | ee-lang/src/main/kotlin/ee/lang/gen/kt/KotlinPojos.kt | 1 | 8155 | package ee.lang.gen.kt
import ee.common.ext.*
import ee.lang.*
fun LiteralI<*>.toKotlin(): String = name().toUnderscoredUpperCase()
fun LiteralI<*>.toKotlinIsMethod(): String {
return "is${name().toCamelCase().capitalize()}()"
}
fun LiteralI<*>.toKotlinIsMethodDef(): String {
return """
fun ${toKotlinIsMethod()}: Boolean = this == ${toKotlin()}"""
}
fun <T : EnumTypeI<*>> T.toKotlinEnum(
c: GenerationContext, derived: String = LangDerivedKind.API,
api: String = LangDerivedKind.API): String {
val externalNameNeeded = isKotlinExternalNameNeeded()
val externalNameProp = propExternalName()
val enumConst = if (externalNameNeeded) {
Constructor {
name("Full")
primary()
parent(this)
params(externalNameProp, *propsAllNoMeta().toTypedArray())
namespace(namespace())
}.init()
} else {
primaryOrFirstConstructorOrFull().init()
}
val name = c.n(this, derived)
val typePrefix = """enum class $name"""
return """${toKotlinDoc()}
$typePrefix${enumConst.toKotlinEnum(c, derived, api)} {
${literals().joinToString(",$nL ") { lit ->
"${lit.toKotlin()}${
if (externalNameNeeded) {
val paramsWithExternalName = mutableListOf(p(externalNameProp) {
value(lit.externalName() ?: lit.name())
})
paramsWithExternalName.addAll(lit.params())
lit.toKotlinCallValue(c, derived, paramsWithExternalName)
} else {
lit.toKotlinCallValue(c, derived)
}}"
}};${propsExceptPrimaryConstructor().joinToString(nL) {
it.toKotlinMember(c, derived, api)
}}${operationsWithoutDataTypeOperations().joinToString(nL) {
it.toKotlinImpl(c, derived, api, isNonBlock(it))
}}${
literals().joinToString("", nL) { it.toKotlinIsMethodDef() }}
companion object {${
toKotlinEnumFindByMethods(c, derived)}
}
}
${toKotlinEnumParseMethods(c, derived)}
"""
}
fun <T : EnumTypeI<*>> T.toKotlinEnumFindByMethods(
c: GenerationContext, derived: String = LangDerivedKind.API): String {
val externalNameParse = if (isKotlinExternalNameNeeded()) {
"$nL$nL${toKotlinEnumFindByMethod(c, derived, propExternalName())}"
} else ""
return """$nL${toKotlinEnumFindByMethod(c, derived, p("name").init())}${
externalNameParse}${props().joinSurroundIfNotEmptyToString(nL, "$nL$nL") {
toKotlinEnumFindByMethod(c, derived, it)
}}"""
}
fun <T : EnumTypeI<*>> T.toKotlinEnumFindByMethod(
c: GenerationContext, derived: String = LangDerivedKind.API, prop: AttributeI<*>): String {
val name = c.n(this, derived)
val byName = prop.toByName()
val propName = prop.name()
return """ fun findBy$byName($propName: ${
prop.type().toKotlin(c, derived)}?, orInstance: $name = ${literals().first().toKotlin()}): $name {
return $propName.to${name}$byName(orInstance)
}"""
}
fun <T : EnumTypeI<*>> T.toKotlinEnumParseMethods(
c: GenerationContext, derived: String = LangDerivedKind.API): String {
val externalNameParse = if (isKotlinExternalNameNeeded()) {
"$nL$nL${toKotlinEnumParseMethodByProp(c, derived, propExternalName())}"
} else ""
return """${toKotlinEnumParseMethodByProp(c, derived, p("name").init())}${
externalNameParse}${props().joinSurroundIfNotEmptyToString(nL, "$nL$nL") {
toKotlinEnumParseMethodByProp(c, derived, it)
}}"""
}
fun <T : EnumTypeI<*>> T.toKotlinEnumParseMethodByProp(
c: GenerationContext, derived: String = LangDerivedKind.API, prop: AttributeI<*>): String {
val name = c.n(this, derived)
return """fun ${prop.type().toKotlin(c, derived)}?.to${name}${
prop.toByName()}(orInstance: $name = $name.${literals().first().toKotlin()}): $name {
val found = $name.values().find {
this != null && it.${prop.name()}${(prop.type()==n.String).ifElse(".equals(this, true)", " == this")}
}
return found ?: orInstance
}"""
}
fun propExternalName() = p("externalName").key().init()
fun <T : EnumTypeI<*>> T.isKotlinExternalNameNeeded(): Boolean {
val atLeastOneWithExternalNameNeeded = literals().find {
val literName = it.toKotlin()
val externalName = it.externalName()
if (externalName != null) {
externalName != literName
} else {
literName != it.name()
}
}
return atLeastOneWithExternalNameNeeded != null
}
fun AttributeI<*>.toByName() = """By${name().capitalize()}"""
fun <T : CompilationUnitI<*>> T.toKotlinIfc(
c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API,
itemName: String = c.n(this, api), nonBlock: Boolean? = null): String {
return """${toKotlinDoc()}
interface $itemName${toKotlinGenerics(c, derived)}${toKotlinExtends(c, derived, api)}${
operationsWithoutDataTypeOperations()
.joinSurroundIfNotEmptyToString(nL, prefix = " {$nL", postfix = "$nL}") {
it.toKotlinIfc(c, derived, api, nonBlock.notNullValueElse(isNonBlock(it)))
}}"""
}
fun <T : CompilationUnitI<*>> T.toKotlinEMPTY(
c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API,
itemName: String = c.n(this, derived), nonBlock: Boolean? = null): String {
val generics = toKotlinGenerics(c, derived)
val extendsEMPTY = if (generics.isNotEmpty()) toKotlinExtendsEMPTY(c, derived, api) else ""
val allOperations = generics.isNotEmpty().ifElse(operations(), operationsWithInherited())
return """${generics.isEmpty().ifElse("object", "open class")} ${itemName}EMPTY$generics$extendsEMPTY${
extendsEMPTY.isEmpty().ifElse(" : ", ", ")}$itemName$generics${
allOperations.joinSurroundIfNotEmptyToString(nL, prefix = " {$nL", postfix = "$nL}") {
it.toKotlinEMPTY(c, derived, api, nonBlock.notNullValueElse(isNonBlock(it)))
}}"""
}
fun <T : CompilationUnitI<*>> T.toKotlinBlockingWrapper(
c: GenerationContext, derived: String = LangDerivedKind.IMPL, api: String = LangDerivedKind.API): String {
val itemName = c.n(this, derived)
return """${toKotlinDoc()}
${generics().isEmpty().ifElse({ "class ${itemName}BlockingWrapper" }) {
"class ${itemName}BlockingWrapper${toKotlinGenerics(c, derived)}"
}}(
val api: $itemName${toKotlinGenerics(c, derived)},
val scope: ${c.n(k.coroutines.CoroutineScope)} = ${c.n(k.coroutines.GlobalScope)})
: ${itemName}Blocking${toKotlinGenerics(c, derived)}, ${c.n(k.coroutines.CoroutineScope)} {
override val coroutineContext: ${c.n(k.coroutines.CoroutineContext)}
get() = scope.coroutineContext${operationsWithInherited()
.joinSurroundIfNotEmptyToString(nL, prefix = nL, postfix = nL) {
it.toKotlinBlockingWrapper(c, derived, api, isNonBlock(it))
}}
}"""
}
fun <T : CompilationUnitI<*>> T.toKotlinImpl(
c: GenerationContext, derived: String = LangDerivedKind.IMPL,
api: String = LangDerivedKind.API,
itemName: String = c.n(this, derived),
dataClass: Boolean = this is BasicI<*> && superUnits().isEmpty() && superUnitFor().isEmpty()): String {
val typePrefix = """${(isOpen() && !dataClass).then("open ")}${dataClass.then("data ")}class $itemName${
toKotlinGenerics(c, derived)}"""
return """${toKotlinDoc()}
$typePrefix${
primaryConstructor().toKotlinPrimaryAndExtends(c, derived, api, this)} {${
propsWithoutParamsOfPrimaryConstructor().joinSurroundIfNotEmptyToString(nL, prefix = nL, postfix = nL) {
it.toKotlinMember(c, derived, api, false)
}}${otherConstructors().joinSurroundIfNotEmptyToString(nL, prefix = nL, postfix = nL) {
it.toKotlin(c, derived, api)
}}${operationsWithoutDataTypeOperations().joinSurroundIfNotEmptyToString(nL, prefix = nL, postfix = nL) {
it.toKotlinImpl(c, derived, api, isNonBlock(it))
}}${toKotlinEqualsHashcode(c, derived)}${toKotlinToString()}${toKotlinEmptyObject(c, derived)}
}"""
} | apache-2.0 | 07528e3495bc8a8c09b86dd9644b5117 | 39.376238 | 114 | 0.645616 | 4.073427 | false | false | false | false |
YounesRahimi/java-utils | src/main/java/ir/iais/utilities/javautils/time/PersianDateUtils.kt | 2 | 1358 | package ir.iais.utilities.javautils.time
import ir.iais.utilities.javautils.utils.DEFAULT_DATE_FORMAT
import ir.iais.utilities.javautils.utils.dateOf
import ir.iais.utilities.javautils.utils.toDate
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.Period
import java.time.ZoneId
import java.util.*
/**
* Today in Persian Date
*/
val EMROUZ: PersianDate get() = PersianDate.now()
infix operator fun PersianDate.minus(other: PersianDate): Period = this.until(other)
val String.toPersianDate: PersianDate get() = PersianDate.parse(this)
val String.persianToDate: Date get() = PersianDate.parse(this).toDate
val String.persianToLocal: LocalDate get() = PersianDate.parse(this).toGregorian()
fun String.toPersianDate(pattern: String = DEFAULT_DATE_FORMAT): PersianDate = PersianDate.parse(this, pattern)
val PersianDate.toDate: Date get() = this.toGregorian().toDate
fun PersianDate.toDate(zoneId: ZoneId = ZoneId.systemDefault()): Date = dateOf(this.toGregorian(), zoneId = zoneId)
val PersianDate.isFuture: Boolean get() = this > PersianDate.now()
val PersianDate.isFriday: Boolean get() = this.dayOfWeek == DayOfWeek.FRIDAY
/**
* Checks if a date is today.
*
* @return true if the date is today.
* @throws IllegalArgumentException if the date is `null`
*/
val PersianDate.isToday: Boolean get() = this == PersianDate.now()
| gpl-3.0 | e70ee703c792d6954188557e38cea2b0 | 34.736842 | 115 | 0.769514 | 3.836158 | false | false | false | false |
mitchwongho/GDS-Material-Kotlin-Kata | app/src/main/java/com/mitchwongho/example/apkotlin/MainActivity.kt | 1 | 1914 | package com.mitchwongho.example.apkotlin
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.view.GravityCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.graphics.Palette
import android.support.v7.widget.LinearLayoutManager
import kotlinx.android.synthetic.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bmp: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
Palette.from(bmp).generate {
val mutedColour = it.getMutedColor(R.attr.colorPrimary)
collapsing_toolbar.setContentScrimColor(mutedColour)
footer_toolbar.setBackgroundColor(mutedColour)
}
super.setSupportActionBar(header_toolbar)
header_toolbar.setNavigationIcon(R.mipmap.ic_menu_24dp)
// on nav item click
header_toolbar.setNavigationOnClickListener {
drawer.openDrawer(GravityCompat.START)
}
//
// onItemSelected
nav_drawer.setNavigationItemSelectedListener {
it.setChecked(true)
drawer.closeDrawers()
true
}
footer_toolbar.inflateMenu(R.menu.menu_footer)
val dow = resources.getStringArray(R.array.days_of_week)
val adapter = SimpleAdapter(dow)
main_recyclerview.setHasFixedSize(true)
main_recyclerview.layoutManager = LinearLayoutManager(this)
main_recyclerview.adapter = adapter
// F.A.B
fab.setOnClickListener {
Snackbar.make(it, R.string.salutation, Snackbar.LENGTH_LONG).show()
}
}
override fun onResume() {
super.onResume()
}
}
| mit | 33e5dfced01a0a6153e8e19f53dd03ec | 32.578947 | 83 | 0.693835 | 4.656934 | false | false | false | false |
StefanOltmann/Kaesekaestchen | app/src/main/java/de/stefan_oltmann/kaesekaestchen/ui/fragments/SpielViewModel.kt | 1 | 2134 | /*
* Kaesekaestchen
* A simple Dots'n'Boxes Game for Android
*
* Copyright (C) Stefan Oltmann
*
* Contact : [email protected]
* Homepage: https://github.com/StefanOltmann/Kaesekaestchen
*
* This file is part of Kaesekaestchen.
*
* Kaesekaestchen 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.
*
* Kaesekaestchen 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 Kaesekaestchen. If not, see <http://www.gnu.org/licenses/>.
*/
package de.stefan_oltmann.kaesekaestchen.ui.fragments
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import de.stefan_oltmann.kaesekaestchen.controller.SpielLogik
import de.stefan_oltmann.kaesekaestchen.model.Spieler
import de.stefan_oltmann.kaesekaestchen.model.Spielfeld
class SpielViewModel : ViewModel() {
val spielfeld = MutableLiveData<Spielfeld>()
val spielLogik = MutableLiveData<SpielLogik>()
val aktuellerSpieler = MutableLiveData<Spieler>()
val spielKaeseImageViewAlpha = Transformations.map(aktuellerSpieler) {
if (it == Spieler.KAESE) AUSGEGRAUT_ALPHA else AUSGEWAEHLT_ALPHA
}
val spielMausImageViewAlpha = Transformations.map(aktuellerSpieler) {
if (it == Spieler.MAUS) AUSGEGRAUT_ALPHA else AUSGEWAEHLT_ALPHA
}
/**
* Wenn das ViewModel vernichtet wird müssen wir die
* Logik darüber informieren, damit der Courotines Job
* sauber entfernt werden kann.
*/
override fun onCleared() {
spielLogik.value?.onCleared()
}
companion object {
private const val AUSGEWAEHLT_ALPHA = 1.0f
private const val AUSGEGRAUT_ALPHA = 0.1f
}
}
| gpl-3.0 | 1205d2ea2b4f048f874920b6388ebc78 | 33.387097 | 74 | 0.742495 | 3.714286 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/integration/crafttweaker/Refinery.kt | 1 | 2341 | package com.cout970.magneticraft.systems.integration.crafttweaker
import com.cout970.magneticraft.api.MagneticraftApi
import com.cout970.magneticraft.api.internal.registries.machines.refinery.RefineryRecipeManager
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.liquid.ILiquidStack
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@Suppress("UNUSED")
@ZenClass("mods.magneticraft.Refinery")
@ZenRegister
object Refinery {
@ZenMethod
@JvmStatic
fun addRecipe(input: ILiquidStack, output0: ILiquidStack?, output1: ILiquidStack?, output2: ILiquidStack?, duration: Float) {
CraftTweakerPlugin.delayExecution {
val inFluid = input.toStack() ?: run {
ctLogError("[Refinery] Invalid input value: $input")
return@delayExecution
}
val outFluid0 = output0?.toStack()
val outFluid1 = output1?.toStack()
val outFluid2 = output2?.toStack()
if (duration <= 0) {
ctLogError("[Refinery] Invalid duration value: $duration")
return@delayExecution
}
if (outFluid0 == null && outFluid1 == null && outFluid2 == null) {
ctLogError("[Refinery] Error: All outputs null")
return@delayExecution
}
val recipe = RefineryRecipeManager.createRecipe(inFluid, outFluid0, outFluid1, outFluid2, duration)
applyAction("Adding $recipe") {
RefineryRecipeManager.registerRecipe(recipe)
}
}
}
@ZenMethod
@JvmStatic
fun removeRecipe(input: ILiquidStack) {
CraftTweakerPlugin.delayExecution {
val a = input.toStack()
if (a == null) {
ctLogError("[Refinery] Invalid input stack: $input")
return@delayExecution
}
val man = MagneticraftApi.getRefineryRecipeManager()
val recipe = man.findRecipe(a)
if (recipe != null) {
applyAction("Removing $recipe") {
man.removeRecipe(recipe)
}
} else {
ctLogError("[Refinery] Error removing recipe: Unable to find recipe with input = $input")
}
}
}
} | gpl-2.0 | 6e1ceea9e312c129fca896823e610fce | 32.942029 | 129 | 0.610423 | 4.682 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-android/src/androidTest/java/reactivecircus/flowbinding/android/view/ViewFocusChangedFlowTest.kt | 1 | 3150 | package reactivecircus.flowbinding.android.view
import android.widget.EditText
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import reactivecircus.blueprint.testing.action.clickView
import reactivecircus.flowbinding.android.fixtures.view.AndroidViewFragment
import reactivecircus.flowbinding.android.test.R
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
@LargeTest
class ViewFocusChangedFlowTest {
@Test
fun viewFocusChanges() {
launchTest<AndroidViewFragment> {
val recorder = FlowRecorder<Boolean>(testScope)
val editText = getViewById<EditText>(R.id.editText1)
editText.focusChanges().recordWith(recorder)
assertThat(recorder.takeValue())
.isFalse()
recorder.assertNoMoreValues()
clickView(R.id.editText1)
assertThat(recorder.takeValue())
.isTrue()
recorder.assertNoMoreValues()
clickView(R.id.editText2)
assertThat(recorder.takeValue())
.isFalse()
recorder.assertNoMoreValues()
cancelTestScope()
clickView(R.id.editText1)
recorder.assertNoMoreValues()
}
}
@Test
fun viewFocusChanges_programmatic() {
launchTest<AndroidViewFragment> {
val recorder = FlowRecorder<Boolean>(testScope)
val editText1 = getViewById<EditText>(R.id.editText1)
val editText2 = getViewById<EditText>(R.id.editText2)
editText1.focusChanges().recordWith(recorder)
assertThat(recorder.takeValue())
.isFalse()
recorder.assertNoMoreValues()
runOnUiThread { editText1.requestFocus() }
assertThat(recorder.takeValue())
.isTrue()
recorder.assertNoMoreValues()
runOnUiThread { editText2.requestFocus() }
assertThat(recorder.takeValue())
.isFalse()
recorder.assertNoMoreValues()
cancelTestScope()
runOnUiThread { editText1.requestFocus() }
recorder.assertNoMoreValues()
}
}
@Test
fun viewFocusChanges_skipInitialValue() {
launchTest<AndroidViewFragment> {
val recorder = FlowRecorder<Boolean>(testScope)
val editText = getViewById<EditText>(R.id.editText1).apply {
runOnUiThread { requestFocus() }
}
editText.focusChanges()
.skipInitialValue()
.recordWith(recorder)
recorder.assertNoMoreValues()
clickView(R.id.editText2)
assertThat(recorder.takeValue())
.isFalse()
recorder.assertNoMoreValues()
cancelTestScope()
clickView(R.id.editText1)
recorder.assertNoMoreValues()
}
}
}
| apache-2.0 | 91cf43503f2ee1c3a0f399ba67b33891 | 30.818182 | 85 | 0.632698 | 5.545775 | false | true | false | false |
facebook/litho | litho-core-kotlin/src/main/kotlin/com/facebook/litho/animated/DynamicValueStyles.kt | 1 | 4461 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.animated
import android.graphics.drawable.Drawable
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.DynamicPropsManager.KEY_ALPHA
import com.facebook.litho.DynamicPropsManager.KEY_BACKGROUND_COLOR
import com.facebook.litho.DynamicPropsManager.KEY_BACKGROUND_DRAWABLE
import com.facebook.litho.DynamicPropsManager.KEY_ELEVATION
import com.facebook.litho.DynamicPropsManager.KEY_FOREGROUND_COLOR
import com.facebook.litho.DynamicPropsManager.KEY_ROTATION
import com.facebook.litho.DynamicPropsManager.KEY_SCALE_X
import com.facebook.litho.DynamicPropsManager.KEY_SCALE_Y
import com.facebook.litho.DynamicPropsManager.KEY_TRANSLATION_X
import com.facebook.litho.DynamicPropsManager.KEY_TRANSLATION_Y
import com.facebook.litho.DynamicValue
import com.facebook.litho.Style
import com.facebook.litho.StyleItem
import com.facebook.litho.StyleItemField
import com.facebook.litho.exhaustive
import com.facebook.litho.getOrCreateCommonDynamicPropsHolder
/** Enums for [DynamicStyleItem]. */
@PublishedApi
internal enum class DynamicField : StyleItemField {
ALPHA,
BACKGROUND_COLOR,
BACKGROUND_DRAWABLE,
ELEVATION,
FOREGROUND,
ROTATION,
SCALE_X,
SCALE_Y,
TRANSLATION_X,
TRANSLATION_Y,
}
/**
* Common style item for all dynamic value styles. See note on [DynamicField] about this pattern.
*/
@PublishedApi
internal data class DynamicStyleItem(
override val field: DynamicField,
override val value: DynamicValue<*>
) : StyleItem<DynamicValue<*>> {
override fun applyToComponent(context: ComponentContext, component: Component) {
val dynamicProps = component.getOrCreateCommonDynamicPropsHolder()
when (field) {
DynamicField.ALPHA -> dynamicProps.put(KEY_ALPHA, value)
DynamicField.BACKGROUND_COLOR -> dynamicProps.put(KEY_BACKGROUND_COLOR, value)
DynamicField.BACKGROUND_DRAWABLE -> dynamicProps.put(KEY_BACKGROUND_DRAWABLE, value)
DynamicField.ELEVATION -> dynamicProps.put(KEY_ELEVATION, value)
DynamicField.FOREGROUND -> dynamicProps.put(KEY_FOREGROUND_COLOR, value)
DynamicField.ROTATION -> dynamicProps.put(KEY_ROTATION, value)
DynamicField.SCALE_X -> dynamicProps.put(KEY_SCALE_X, value)
DynamicField.SCALE_Y -> dynamicProps.put(KEY_SCALE_Y, value)
DynamicField.TRANSLATION_X -> dynamicProps.put(KEY_TRANSLATION_X, value)
DynamicField.TRANSLATION_Y -> dynamicProps.put(KEY_TRANSLATION_Y, value)
}.exhaustive
}
}
inline fun Style.alpha(alpha: DynamicValue<Float>): Style =
this + DynamicStyleItem(DynamicField.ALPHA, alpha)
inline fun Style.background(background: DynamicValue<out Drawable>): Style =
this + DynamicStyleItem(DynamicField.BACKGROUND_DRAWABLE, background)
inline fun Style.backgroundColor(background: DynamicValue<Int>): Style =
this + DynamicStyleItem(DynamicField.BACKGROUND_COLOR, background)
inline fun Style.foregroundColor(foreground: DynamicValue<Int>): Style =
this + DynamicStyleItem(DynamicField.FOREGROUND, foreground)
inline fun Style.elevation(elevation: DynamicValue<Float>): Style =
this + DynamicStyleItem(DynamicField.ELEVATION, elevation)
inline fun Style.rotation(rotation: DynamicValue<Float>): Style =
this + DynamicStyleItem(DynamicField.ROTATION, rotation)
inline fun Style.scaleX(scaleX: DynamicValue<Float>): Style =
this + DynamicStyleItem(DynamicField.SCALE_X, scaleX)
inline fun Style.scaleY(scaleY: DynamicValue<Float>): Style =
this + DynamicStyleItem(DynamicField.SCALE_Y, scaleY)
inline fun Style.translationX(translationX: DynamicValue<Float>): Style =
this + DynamicStyleItem(DynamicField.TRANSLATION_X, translationX)
inline fun Style.translationY(translationY: DynamicValue<Float>): Style =
this + DynamicStyleItem(DynamicField.TRANSLATION_Y, translationY)
| apache-2.0 | f74f28693c3653e7db90ab7e79a13695 | 40.691589 | 97 | 0.783008 | 4.066545 | false | false | false | false |
square/leakcanary | shark/src/test/java/shark/HeapDumps.kt | 2 | 4428 | package shark
import shark.GcRoot.JavaFrame
import shark.GcRoot.ThreadObject
import shark.ValueHolder.BooleanHolder
import shark.ValueHolder.ReferenceHolder
import java.io.File
fun File.writeWeakReferenceCleared() {
dump {
keyedWeakReference(ReferenceHolder(0))
}
}
fun File.writeNoPathToInstance() {
dump {
keyedWeakReference(instance(clazz("Leaking")))
}
}
fun File.writeSinglePathToInstance() {
dump {
val leaking = instance(clazz("Leaking"))
keyedWeakReference(leaking)
clazz(
"GcRoot", staticFields = listOf(
"shortestPath" to leaking
)
)
}
}
fun File.writeSinglePathToString(value: String = "Hi") {
dump {
val leaking = string(value)
keyedWeakReference(leaking)
clazz(
"GcRoot", staticFields = listOf(
"shortestPath" to leaking
)
)
}
}
fun File.writeSinglePathsToCharArrays(values: List<String>) {
dump {
val arrays = mutableListOf<Long>()
values.forEach {
val leaking = it.charArrayDump
keyedWeakReference(leaking)
arrays.add(leaking.value)
}
clazz(
className = "GcRoot",
staticFields = listOf(
"arrays" to ReferenceHolder(
objectArray(clazz("char[][]"), arrays.toLongArray())
)
)
)
}
}
fun File.writeTwoPathsToInstance() {
dump {
val leaking = instance(clazz("Leaking"))
keyedWeakReference(leaking)
val hasLeaking = instance(
clazz("HasLeaking", fields = listOf("leaking" to ReferenceHolder::class)),
fields = listOf(leaking)
)
clazz(
"GcRoot", staticFields = listOf(
"shortestPath" to leaking,
"longestPath" to hasLeaking
)
)
}
}
fun File.writeMultipleActivityLeaks(leakCount: Int) {
dump {
val activityClassId = clazz(
className = "android.app.Activity",
fields = listOf("mDestroyed" to BooleanHolder::class)
)
val exampleActivityClassId = clazz(
superclassId = activityClassId,
className = "com.example.ExampleActivity"
)
val activityArrayClassId = arrayClass("com.example.ExampleActivity")
val destroyedActivities = mutableListOf<ReferenceHolder>()
for (i in 1..leakCount) {
destroyedActivities.add(instance(exampleActivityClassId, listOf(BooleanHolder(true))))
}
clazz(
className = "com.example.ActivityHolder",
staticFields = listOf(
"activities" to
objectArrayOf(
activityArrayClassId, *destroyedActivities.toTypedArray()
)
)
)
destroyedActivities.forEach { instanceId ->
keyedWeakReference(instanceId)
}
}
}
fun File.writeJavaLocalLeak(
threadClass: String? = null,
threadName: String? = null
) {
dump {
val threadClassId =
clazz(
className = Thread::class.java.name,
fields = if (threadName != null) listOf("name" to ReferenceHolder::class) else emptyList()
)
val myThreadClassId = if (threadClass == null) {
threadClassId
} else {
clazz(className = threadClass, superclassId = threadClassId)
}
val threadInstance = instance(
myThreadClassId, if (threadName != null) {
listOf(string(threadName))
} else {
emptyList()
}
)
gcRoot(
ThreadObject(
id = threadInstance.value, threadSerialNumber = 42, stackTraceSerialNumber = 0
)
)
val leaking = "Leaking" watchedInstance {}
gcRoot(JavaFrame(id = leaking.value, threadSerialNumber = 42, frameNumber = 0))
}
}
fun File.writeTwoPathJavaLocalShorterLeak(
threadClass: String,
threadName: String
) {
dump {
val threadClassId =
clazz(className = "java.lang.Thread", fields = listOf("name" to ReferenceHolder::class))
val myThreadClassId = clazz(className = threadClass, superclassId = threadClassId)
val threadInstance = instance(myThreadClassId, listOf(string(threadName)))
gcRoot(
ThreadObject(
id = threadInstance.value, threadSerialNumber = 42, stackTraceSerialNumber = 0
)
)
val leaking = "Leaking" watchedInstance {}
gcRoot(JavaFrame(id = leaking.value, threadSerialNumber = 42, frameNumber = 0))
val hasLeaking = instance(
clazz("HasLeaking", fields = listOf("leaking" to ReferenceHolder::class)),
fields = listOf(leaking)
)
clazz(
"GcRoot", staticFields = listOf(
"longestPath" to hasLeaking
)
)
}
}
| apache-2.0 | caecebd91e63d5b6ded28f50ffed7969 | 24.302857 | 98 | 0.653117 | 4.278261 | false | false | false | false |
moxi/weather-app-demo | weather-library/src/main/java/org/rcgonzalezf/weather/openweather/model/ForecastData.kt | 1 | 803 | package org.rcgonzalezf.weather.openweather.model
import com.google.gson.annotations.SerializedName
import org.rcgonzalezf.weather.common.models.converter.Data
import java.util.ArrayList
open // open for Mockito
class ForecastData(@SerializedName("city") var city: City, count: Int) : Data {
@SerializedName("cnt")
var count = 0
@SerializedName("list")
private val weatherList: MutableList<WeatherData>
override fun toString(): String {
return "ForecastData [name=" + city.name + ", count=" + count + ""
}
fun getWeatherList(): List<WeatherData> {
return weatherList
}
fun addWeatherItem(weatherData: WeatherData) {
weatherList.add(weatherData)
}
init {
this.count = count
weatherList = ArrayList(count)
}
}
| mit | 86a5e1046dce0263f40c1a8250a3ee95 | 24.903226 | 79 | 0.681196 | 4.204188 | false | false | false | false |
consp1racy/android-commons | commons-base/src/main/java/net/xpece/android/content/BaseResources.kt | 1 | 1249 | @file:JvmName("XpBaseResources")
package net.xpece.android.content
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.TypedArray
import android.support.annotation.AttrRes
import android.support.annotation.StyleRes
import android.support.v7.widget.TintTypedArray
private val TEMP_ARRAY = object : ThreadLocal<IntArray>() {
override fun initialValue(): IntArray = intArrayOf(0)
}
fun Context.resolveResourceId(@AttrRes attr: Int, fallback: Int): Int =
resolveResourceId(0, attr, fallback)
fun Context.resolveResourceId(@StyleRes style: Int, @AttrRes attr: Int, fallback: Int): Int {
val ta = obtainTypedArray(style, attr)
try {
return ta.getResourceId(0, fallback)
} finally {
ta.recycle()
}
}
fun Context.obtainTypedArray(@StyleRes style: Int, @AttrRes attr: Int): TypedArray {
val tempArray = TEMP_ARRAY.get()
tempArray[0] = attr
return obtainStyledAttributes(style, tempArray)
}
@SuppressLint("RestrictedApi")
fun Context.obtainTintTypedArray(@StyleRes style: Int, @AttrRes attr: Int): TintTypedArray {
val tempArray = TEMP_ARRAY.get()
tempArray[0] = attr
return TintTypedArray.obtainStyledAttributes(this, style, tempArray)
}
| apache-2.0 | c74ce7445f766adfe207ad1c9e195bff | 31.025641 | 93 | 0.745396 | 4.042071 | false | false | false | false |
google/horologist | base-ui/src/debug/java/com/google/android/horologist/base/ui/components/SecondaryButtonPreview.kt | 1 | 2468 | /*
* 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
*
* 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.
*/
@file:OptIn(ExperimentalHorologistBaseUiApi::class)
package com.google.android.horologist.base.ui.components
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.runtime.Composable
import com.google.android.horologist.base.ui.ExperimentalHorologistBaseUiApi
import com.google.android.horologist.compose.tools.WearPreview
@WearPreview
@Composable
fun SecondaryButtonPreview() {
StandardButton(
imageVector = Icons.Default.Check,
contentDescription = "contentDescription",
onClick = { },
buttonType = StandardButtonType.Secondary
)
}
@WearPreview
@Composable
fun SecondaryButtonPreviewLarge() {
StandardButton(
imageVector = Icons.Default.Check,
contentDescription = "contentDescription",
onClick = { },
buttonType = StandardButtonType.Secondary,
buttonSize = StandardButtonSize.Large
)
}
@WearPreview
@Composable
fun SecondaryButtonPreviewSmall() {
StandardButton(
imageVector = Icons.Default.Check,
contentDescription = "contentDescription",
onClick = { },
buttonType = StandardButtonType.Secondary,
buttonSize = StandardButtonSize.Small
)
}
@WearPreview
@Composable
fun SecondaryButtonPreviewExtraSmall() {
StandardButton(
imageVector = Icons.Default.Check,
contentDescription = "contentDescription",
onClick = { },
buttonType = StandardButtonType.Secondary,
buttonSize = StandardButtonSize.ExtraSmall
)
}
@WearPreview
@Composable
fun SecondaryButtonPreviewDisabled() {
StandardButton(
imageVector = Icons.Default.Check,
contentDescription = "contentDescription",
onClick = { },
buttonType = StandardButtonType.Secondary,
enabled = false
)
}
| apache-2.0 | 6b3087da94d59b15a97a6c50f934f89e | 28.380952 | 76 | 0.721637 | 4.792233 | false | false | false | false |
sswierczek/Helix-Movie-Guide-Android | core-android/src/main/kotlin/com/androidmess/helix/core/data/api/ApiMovieVideo.kt | 1 | 475 | package com.androidmess.helix.core.data.api
import com.google.gson.annotations.SerializedName
/**
* Movie video model. More information here https://developers.themoviedb.org/3/movies/get-movie-videos
*/
data class ApiMovieVideo(
@SerializedName("key")
val videoKey: String,
@SerializedName("site")
val site: String,
@SerializedName("type")
val type: String
) {
fun isTrailer() = type == "Trailer"
fun isFromYouTube() = site == "YouTube"
} | apache-2.0 | 313bf1dddc0e55a888ebd95b7defe01b | 25.444444 | 103 | 0.698947 | 3.710938 | false | false | false | false |
ajmirB/Messaging | app/src/main/java/com/xception/messaging/core/manager/ChannelsManager.kt | 1 | 2080 | package com.xception.messaging.core.manager
import com.sendbird.android.OpenChannel
import io.reactivex.Completable
import io.reactivex.Single
object ChannelsManager {
/**
* Get channel identified by its url
* @parem channelUrl the url of the channel
*/
fun getOpenChannel(channelUrl: String): Single<OpenChannel> {
return Single.create<OpenChannel> { subscriber ->
OpenChannel.getChannel(channelUrl, { channel, e ->
if (e != null) {
subscriber.onError(e)
} else {
subscriber.onSuccess(channel)
}
})
}
}
/**
* Get all open channels
*/
fun getOpenChannels(): Single<List<OpenChannel>> {
return Single.create<List<OpenChannel>> { subscriber ->
val channelListQuery = OpenChannel.createOpenChannelListQuery()
channelListQuery.next({ channels, error ->
if (error != null) {
subscriber.onError(error)
} else {
subscriber.onSuccess(channels)
}
})
}
}
/**
* Enter in an open channel if not already entered
* @param channelUrl the channel url
*/
fun enterChannel(channel: OpenChannel): Completable {
// Request to enter in the channel
return Completable.create { subscriber ->
channel.enter({ e ->
if (e != null) {
subscriber.onError(e)
} else {
subscriber.onComplete()
}
})
}
}
fun createOpenChannel(name: String): Single<OpenChannel> {
return Single.create { subcriber ->
OpenChannel.createChannel(name, null, null, null, { openChannel, e ->
if (e != null) {
subcriber.onError(e)
} else {
subcriber.onSuccess(openChannel)
}
})
}
}
} | apache-2.0 | 53db61dc21f4e5f68ac44e9640eaa73b | 29.15942 | 81 | 0.508173 | 4.976077 | false | false | false | false |
Ekito/koin | koin-projects/koin-android-scope/src/main/java/org/koin/android/scope/LifecycleOwnerExt.kt | 1 | 1603 | /*
* Copyright 2017-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.koin.android.scope
import android.arch.lifecycle.LifecycleOwner
import org.koin.core.scope.Scope
@Deprecated("Use ScopeActivity or ScopeFragment instead", replaceWith = ReplaceWith("lifecycleScope"),
level = DeprecationLevel.ERROR)
val LifecycleOwner.lifecycleScope: Scope
get() = kotlin.error("Don't use scope on a lifecycle component. Use ScopeActivity or ScopeFragment instead")
@Deprecated("Use ScopeActivity or ScopeFragment instead", replaceWith = ReplaceWith("lifecycleScope"),
level = DeprecationLevel.ERROR)
val LifecycleOwner.scope: Scope
get() = kotlin.error("Don't use scope on a lifecycle component. Use ScopeActivity or ScopeFragment instead")
@Deprecated("Use ScopeActivity or ScopeFragment instead", replaceWith = ReplaceWith("lifecycleScope"),
level = DeprecationLevel.ERROR)
val LifecycleOwner.currentScope: Scope
get() = kotlin.error("Don't use scope on a lifecycle component. Use ScopeActivity or ScopeFragment instead") | apache-2.0 | 3be502b00b147b01aa399fefe78c057b | 43.555556 | 112 | 0.769807 | 4.646377 | false | false | false | false |
bachhuberdesign/deck-builder-gwent | app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/shared/base/BasePresenter.kt | 1 | 626 | package com.bachhuberdesign.deckbuildergwent.features.shared.base
/**
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
open class BasePresenter<T : MvpContract> : Presenter<T> {
var view: T? = null
override fun attach(view: T) {
this.view = view
}
override fun detach() {
view = null
}
override fun isViewAttached(): Boolean = view != null
override fun getViewOrThrow(): T {
if (view == null) {
throw UnsupportedOperationException("Tried to get view for presenter but was null.")
} else {
return view!!
}
}
} | apache-2.0 | 3144a1481098a4a2050b0f3d5bec4804 | 19.9 | 96 | 0.592652 | 4.173333 | false | false | false | false |
Shynixn/BlockBall | blockball-bukkit-plugin/src/main/java/com/github/shynixn/blockball/bukkit/logic/business/extension/ExtensionMethod.kt | 1 | 1944 | @file:Suppress("DEPRECATION")
package com.github.shynixn.blockball.bukkit.logic.business.extension
import com.github.shynixn.blockball.api.BlockBallApi
import com.github.shynixn.blockball.api.business.enumeration.Permission
import com.github.shynixn.blockball.api.business.proxy.PluginProxy
import com.github.shynixn.blockball.api.persistence.entity.Position
import com.github.shynixn.blockball.core.logic.persistence.entity.PositionEntity
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.entity.Player
import org.bukkit.util.Vector
/**
* Returns if the given [player] has got this [Permission].
*/
internal fun Permission.hasPermission(player: Player): Boolean {
return player.hasPermission(this.permission)
}
/**
* Converts the given Location to a position.
*/
internal fun Location.toPosition(): Position {
val position = PositionEntity()
if (this.world != null) {
position.worldName = this.world!!.name
}
position.x = this.x
position.y = this.y
position.z = this.z
position.yaw = this.yaw.toDouble()
position.pitch = this.pitch.toDouble()
return position
}
/**
* Finds the version compatible NMS class.
*/
fun findClazz(name: String): Class<*> {
return Class.forName(
name.replace(
"VERSION",
BlockBallApi.resolve(PluginProxy::class.java).getServerVersion().bukkitId
)
)
}
/**
* Converts the given position to a bukkit Location.
*/
internal fun Position.toLocation(): Location {
return Location(Bukkit.getWorld(this.worldName!!), this.x, this.y, this.z, this.yaw.toFloat(), this.pitch.toFloat())
}
/**
* Converts the given position to a bukkit vector.
*/
internal fun Position.toVector(): Vector {
return Vector(this.x, this.y, this.z)
}
/**
* Converts the given bukkit vector to a position.
*/
internal fun Vector.toPosition(): Position {
return PositionEntity(this.x, this.y, this.z)
}
| apache-2.0 | e31ec12c8c7bb91809cf0a9b21184571 | 26 | 120 | 0.718107 | 3.811765 | false | false | false | false |
reime005/splintersweets | core/src/de/reimerm/splintersweets/actors/scene2d/HighScoreTable.kt | 1 | 1995 | package de.reimerm.splintersweets.actors.scene2d
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import de.reimerm.splintersweets.utils.AssetsManager
import de.reimerm.splintersweets.utils.GameSettings
import de.reimerm.splintersweets.utils.Resources
/**
* Created by mariu on 04.11.2016.
*/
class HighScoreTable(scores: Map<String, String>?) : Table() {
val pane: ScrollPane
init {
val paneStyle = ScrollPane.ScrollPaneStyle()
paneStyle.background = TextureRegionDrawable(AssetsManager.textureMap[Resources.RegionNames.HIGHSCORE_PANE.name])
pane = ScrollPane(this, paneStyle)
pane.setScrollingDisabled(true, false)
pane.setFadeScrollBars(false)
var labelStyle = Label.LabelStyle(AssetsManager.highscoreTextFont, Color.WHITE)
if (scores == null) {
add(Label("Loading data...", labelStyle)).expand().colspan(3)
} else if (scores.isEmpty()) {
add(Label("No data available", labelStyle)).expand().colspan(3)
} else {
labelStyle = Label.LabelStyle(AssetsManager.highscoreTextFont, Color.WHITE)
var i = 1
for ((key, value) in scores) {
row().padBottom(GameSettings.WIDTH * 0.015f)
add(Label("" + i, labelStyle)).expand().colspan(1)
add(Label(key, labelStyle)).expand().colspan(1)
add(Label(value, labelStyle)).expand().colspan(1)
i++
}
for (k in 0..5) {
row().padBottom(GameSettings.WIDTH * 0.015f)
add(Label("", labelStyle)).expand().colspan(1)
add(Label("", labelStyle)).expand().colspan(1)
add(Label("", labelStyle)).expand().colspan(1)
}
}
}
}
| apache-2.0 | 29584d4d82085d3003d4830b5bbc1bb6 | 35.272727 | 121 | 0.63609 | 4.022177 | false | false | false | false |
aldoram5/SimpleHTMLTesterAndroid | app/src/main/java/com/crimsonrgames/titanium/htmltester/MainActivity.kt | 1 | 16556 | /***
*
* MainActivity.java
*
* Copyright 2016 Aldo Pedro Rangel Montiel
*
* 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.crimsonrgames.titanium.htmltester
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.tabs.TabLayout
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
class MainActivity : AppCompatActivity(), AddTagDialogFragment.OnAddTagDialogFragmentInteractionListener {
/**
* The [android.support.v4.view.PagerAdapter] that will provide
* fragments for each of the sections. We use a
* [FragmentPagerAdapter] derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* [android.support.v4.app.FragmentStatePagerAdapter].
*/
private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
/**
* The [ViewPager] that will host the section contents.
*/
private var mViewPager: ViewPager? = null
/**
* The EditorFragment that will be used to edit the source code
*/
private var mEditorFragment: EditorFragment? = null
/**
* The PreviewFragment that will be used to show the WebView with the contents of the source
* code
*/
private var mPreviewFragment: PreviewFragment? = null
private var mSourceCode: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mSourceCode = readHTMLFromDefaultFile()
if (mEditorFragment == null) {
mEditorFragment = EditorFragment.newInstance(mSourceCode)
}
if (mPreviewFragment == null) {
mPreviewFragment = PreviewFragment.newInstance(mSourceCode)
}
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
// Set up the ViewPager with the sections adapter.
mViewPager = findViewById<View>(R.id.container) as ViewPager
mViewPager!!.adapter = mSectionsPagerAdapter
mViewPager!!.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
mEditorFragment = mSectionsPagerAdapter!!.getRegisteredFragment(0) as EditorFragment
if (mEditorFragment == null) return
mSourceCode = mEditorFragment!!.getmSourceCode()
mPreviewFragment = mSectionsPagerAdapter!!.getRegisteredFragment(1) as PreviewFragment
if (mPreviewFragment == null) return
mPreviewFragment!!.setmSourceCode(mSourceCode)
}
override fun onPageScrollStateChanged(state: Int) {
}
})
val tabLayout = findViewById<View>(R.id.tabs) as TabLayout
tabLayout.setupWithViewPager(mViewPager)
val fab = findViewById<View>(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
mEditorFragment = mSectionsPagerAdapter!!.getRegisteredFragment(0) as EditorFragment
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND
sendIntent.putExtra(Intent.EXTRA_TEXT, mEditorFragment!!.getmSourceCode())
sendIntent.type = "text/html"
startActivity(Intent.createChooser(sendIntent, resources.getText(R.string.send_to)))
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
mEditorFragment = mSectionsPagerAdapter!!.getRegisteredFragment(0) as EditorFragment
mPreviewFragment = mSectionsPagerAdapter!!.getRegisteredFragment(1) as PreviewFragment
when (id) {
R.id.action_save -> {
mEditorFragment?.let{
mSourceCode = it.getmSourceCode()
this.writeHTMLToDefaultFile(mSourceCode!!)
val duration = Toast.LENGTH_SHORT
val toast = Toast.makeText(this.applicationContext, SAVED, duration)
toast.show()
}
}
R.id.action_restore_default -> {
mSourceCode = DEFAULT_HTML_STRING
mEditorFragment?.let { it.setmSourceCode(mSourceCode)}
mPreviewFragment?.let{ it.setmSourceCode(mSourceCode)}
val duration = Toast.LENGTH_SHORT
val toast = Toast.makeText(this.applicationContext, RESTORED_TO_DEFAULT_TEXT, duration)
toast.show()
}
R.id.action_return_to_saved -> {
mSourceCode = this.readHTMLFromDefaultFile()
mEditorFragment!!.setmSourceCode(mSourceCode)
mPreviewFragment!!.setmSourceCode(mSourceCode)
val duration = Toast.LENGTH_SHORT
val toast = Toast.makeText(this.applicationContext, RESTORED_TO_LAST_SAVED_FILE, duration)
toast.show()
}
R.id.action_insert_tag -> showAddTagDialog()
}
return super.onOptionsItemSelected(item)
}
private fun showAddTagDialog() {
val input = EditText(this)
input.setSingleLine()
val dialog = AlertDialog.Builder(this)
.setTitle(R.string.title_add_tag)
.setMessage(R.string.tag_dialog_text)
.setPositiveButton(R.string.action_insert_Tag){ dialogInterface, i ->
mEditorFragment?.let {
val tag = input.text.toString()
it.insertTextAtCursorPoint(String.format(TAG_PATTERN, tag, tag))
}
}
.setNegativeButton(R.string.action_cancel){ dialogInterface, i ->
dialogInterface.cancel()
}
.create()
dialog.setView(input,20,0,20,0)
dialog.show()
}
private fun writeHTMLToDefaultFile(HTMLString: String): Boolean {
val file = File(getExternalFilesDir(null), DEFAULT_FILE_NAME)
try {
val stream = FileOutputStream(file)
try {
stream.write(HTMLString.toByteArray())
} catch (e: IOException) {
Log.e(TAG, "Error: " + e.localizedMessage)
} finally {
stream.close()
}
} catch (e: IOException) {
Log.e(TAG, "Error: " + e.localizedMessage)
}
return true
}
private fun readHTMLFromDefaultFile(): String {
var fileContents: String
val file = File(getExternalFilesDir(null), DEFAULT_FILE_NAME)
val length = file.length().toInt()
val bytes = ByteArray(length)
try {
val `in` = FileInputStream(file)
try {
`in`.read(bytes)
fileContents = String(bytes)
} catch (e: IOException) {
fileContents = DEFAULT_HTML_STRING
Log.e(TAG, "Error: " + e.localizedMessage)
} finally {
`in`.close()
}
} catch (e: IOException) {
fileContents = DEFAULT_HTML_STRING
Log.e(TAG, "Error: " + e.localizedMessage)
}
Log.d(TAG, fileContents)
if (fileContents.isEmpty()) fileContents = DEFAULT_HTML_STRING
return fileContents
}
/***
* Overriden from AddTagDialogFragment.OnAddTagDialogFragmentInteractionListener
* Receives the input from the AddTagDialogFragment
* @param tag the input tag
*/
override fun onFinishTagEditDialog(tag: String) {
mEditorFragment = mSectionsPagerAdapter!!.getRegisteredFragment(0) as EditorFragment
mEditorFragment!!.insertTextAtCursorPoint(String.format(TAG_PATTERN, tag, tag))
}
/**
* The Editor Fragment which contains the EditText element that we'll use as the source editor
*/
class EditorFragment : Fragment() {
/**
* The EditText element reference
*/
private var mEditor: EditText? = null
/**
* Convenience storage of the html code
*/
private var mSourceCode: String? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_main, container, false)
mEditor = rootView.findViewById<View>(R.id.editText) as EditText
setTextToEditor()
return rootView
}
/**
* Inserts text at the current cursor point of the EditText
* @param textToAdd the text to add
* @return if the operation was successful or not
*/
fun insertTextAtCursorPoint(textToAdd: String): Boolean {
var success = false
if (mEditor != null) {
mEditor!!.text.insert(mEditor!!.selectionStart, textToAdd)
success = true
}
return success
}
fun setTextToEditor() {
if (mEditor != null) {
mEditor!!.setText(mSourceCode)
}
}
//Getters
fun getmSourceCode(): String {
if (mEditor != null) {
return mEditor!!.text.toString()
}
return ""
}
//Setters
fun setmSourceCode(mSourceCode: String?) {
this.mSourceCode = mSourceCode
setTextToEditor()
}
companion object {
/**
* Returns a new instance of this fragment with the initializing the mEditor
* with the initial Code
* @param initialCode The code which will initialize the mEditor
*/
fun newInstance(initialCode: String?): EditorFragment {
val fragment = EditorFragment()
fragment.mSourceCode = initialCode
return fragment
}
}
}
/**
* The Preview Fragment which contains the WebView element used to test the HTML
*/
class PreviewFragment : Fragment() {
/**
* The WebView element reference
*/
private var mWebView: WebView? = null
/**
* Convenience storage of the html code
*/
private var mSourceCode: String? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_html_preview, container, false)
mWebView = rootView.findViewById<View>(R.id.webView) as WebView
return rootView
}
override fun setUserVisibleHint(visible: Boolean) {
super.setUserVisibleHint(visible)
if (visible && isResumed) {
//Manually call onResume so it loads the HTMLStringAgain
onResume()
}
}
override fun onResume() {
super.onResume()
if (!userVisibleHint || mWebView == null) {
return
}
loadHTMLInWebView()
}
private fun loadHTMLInWebView() {
if (mWebView != null) {
val settings = mWebView!!.settings
settings.defaultTextEncodingName = "utf-8"
mSourceCode?.let { mWebView!!.loadData(it, "text/html; charset=utf-8", "UTF-8") }
}
}
//Getters
fun getmSourceCode(): String? {
return mSourceCode
}
//Setters
fun setmSourceCode(mSourceCode: String?) {
this.mSourceCode = mSourceCode
loadHTMLInWebView()
}
companion object {
/**
* Returns a new instance of this fragment with the initializing the mEditor
* with the initial Code
* @param initialCode The code which will initialize the mEditor
*/
fun newInstance(initialCode: String?): PreviewFragment {
val fragment = PreviewFragment()
fragment.mSourceCode = initialCode
return fragment
}
}
}
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
internal var registeredFragments = SparseArray<Fragment>()
override fun getItem(position: Int): Fragment {
// getItem is called to instantiate the fragment for the given page.
// Return a EditorFragment (defined as a static inner class below).
if (mEditorFragment == null) {
mEditorFragment = EditorFragment.newInstance(mSourceCode)
}
if (mPreviewFragment == null) {
mPreviewFragment = PreviewFragment.newInstance(mSourceCode)
}
return if (position == 0) mEditorFragment!! else mPreviewFragment!!
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val fragment = super.instantiateItem(container, position) as Fragment
registeredFragments.put(position, fragment)
return fragment
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
registeredFragments.remove(position)
super.destroyItem(container, position, `object`)
}
fun getRegisteredFragment(position: Int): Fragment {
return registeredFragments.get(position)
}
override fun getCount(): Int {
// Show 2 total pages.
return 2
}
override fun getPageTitle(position: Int): CharSequence? {
when (position) {
0 -> return "EDITOR"
1 -> return "PREVIEW"
}
return null
}
}
companion object {
val TAG = "MainActivity"
val SAVED = "Saved"
val RESTORED_TO_DEFAULT_TEXT = "Restored to default text"
val RESTORED_TO_LAST_SAVED_FILE = "Restored to last saved file"
val TAG_PATTERN = "<%s> </%s>"
private val DEFAULT_HTML_STRING = "<html><body><h1>TODO: Write your own code here!!</h1></body></html>"
private val DEFAULT_FILE_NAME = "test.html"
}
}
| apache-2.0 | cac32e02c624d146ca4debe5f0fb1a98 | 33.781513 | 111 | 0.607393 | 5.125697 | false | false | false | false |
jtransc/jtransc | jtransc-core/src/com/jtransc/plugin/finalizer/FinalizerJTranscPlugin.kt | 1 | 785 | package com.jtransc.plugin.finalizer
import com.jtransc.ast.AstClass
import com.jtransc.ast.AstModifiers
import com.jtransc.ast.AstProgram
import com.jtransc.lang.extraProperty
import com.jtransc.plugin.JTranscPlugin
var AstClass.descendantList by extraProperty { arrayListOf<AstClass>() }
val AstClass.descendantCount get() = descendantList.size
class FinalizerJTranscPlugin : JTranscPlugin() {
override fun processAfterTreeShaking(program: AstProgram) {
for (clazz in program.classes) {
for (related in clazz.getAllRelatedTypes()) {
if (related == clazz) continue
related.descendantList.add(related)
}
}
for (clazz in program.classes) {
if (clazz.descendantCount == 0) {
clazz.modifiers.acc = clazz.modifiers.acc or AstModifiers.ACC_FINAL
}
}
}
} | apache-2.0 | 3bfa78e1a69ecce10f1176dcacdb3708 | 29.230769 | 72 | 0.763057 | 3.617512 | false | false | false | false |
msebire/intellij-community | python/src/com/jetbrains/python/console/PydevConsoleCli.kt | 3 | 4333 | @file:JvmName("PydevConsoleCli")
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.console
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.ParamsGroup
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkAdditionalData
import com.jetbrains.python.PythonHelper
import com.jetbrains.python.run.PythonCommandLineState
import com.jetbrains.python.sdk.PythonEnvUtil
import com.jetbrains.python.sdk.PythonSdkAdditionalData
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import java.io.File
const val MODE_OPTION = "mode"
const val MODE_OPTION_SERVER_VALUE = "server"
const val MODE_OPTION_CLIENT_VALUE = "client"
const val PORT_OPTION = "port"
private fun getOptionString(name: String, value: Any): String = "--$name=$value"
/**
* Adds new or replaces existing [PythonCommandLineState.GROUP_SCRIPT]
* parameters of [this] command line with the path to Python console script
* (*pydevconsole.py*) and parameters required for running it in the *client*
* mode.
*
* @param port the port that Python console script will connect to
*
* @see PythonHelper.CONSOLE
*/
fun GeneralCommandLine.setupPythonConsoleScriptInClientMode(sdk: Sdk, port: Int) {
initializePydevConsoleScriptGroup(PythonSdkFlavor.getFlavor(sdk)).appendClientModeParameters(port)
}
/**
* Adds new or replaces existing [PythonCommandLineState.GROUP_SCRIPT]
* parameters of [this] command line with the path to Python console script
* (*pydevconsole.py*) and parameters required for running it in the *server*
* mode.
*
* Updates Python path according to the flavor defined in [sdkAdditionalData].
*
* @param sdkAdditionalData the additional data where [PythonSdkFlavor] is taken
* from
* @param port the optional port that Python console script will listen at
*
* @see PythonHelper.CONSOLE
*/
@JvmOverloads
fun GeneralCommandLine.setupPythonConsoleScriptInServerMode(sdkAdditionalData: SdkAdditionalData, port: Int? = null) {
initializePydevConsoleScriptGroup((sdkAdditionalData as? PythonSdkAdditionalData)?.flavor).appendServerModeParameters(port)
}
private fun GeneralCommandLine.initializePydevConsoleScriptGroup(pythonSdkFlavor: PythonSdkFlavor?): ParamsGroup {
val group: ParamsGroup = parametersList.getParamsGroup(PythonCommandLineState.GROUP_SCRIPT)?.apply { parametersList.clearAll() }
?: parametersList.addParamsGroup(PythonCommandLineState.GROUP_SCRIPT)
val pythonPathEnv = hashMapOf<String, String>()
PythonHelper.CONSOLE.addToPythonPath(pythonPathEnv)
val consolePythonPath = pythonPathEnv[PythonEnvUtil.PYTHONPATH]
// here we get Python console path for the system interpreter
// let us convert it to the project interpreter path
consolePythonPath?.split(File.pathSeparator)?.let { pythonPathList ->
pythonSdkFlavor?.initPythonPath(pythonPathList, false, environment) ?: PythonEnvUtil.addToPythonPath(environment, pythonPathList)
}
group.addParameter(PythonHelper.CONSOLE.asParamString())
return group
}
private fun ParamsGroup.appendServerModeParameters(port: Int? = null) {
addParameter(getOptionString(MODE_OPTION, MODE_OPTION_SERVER_VALUE))
port?.let { addParameter(getOptionString(PORT_OPTION, it)) }
}
private fun ParamsGroup.appendClientModeParameters(port: Int) {
addParameter(getOptionString(MODE_OPTION, MODE_OPTION_CLIENT_VALUE))
addParameter(getOptionString(PORT_OPTION, port))
}
/**
* Waits for Python console server to be started. The indication for this is
* the server port that Python console script outputs to *stdout* when the
* server socket is bound to the port and it is listening to it.
*
* The connection to Python console script server should be established *after*
* this method finishes.
*
* @throws ExecutionException if timeout occurred or an other error
*
* @see PydevConsoleRunnerImpl.PORTS_WAITING_TIMEOUT
* @see PydevConsoleRunnerImpl.getRemotePortFromProcess
*/
@Throws(ExecutionException::class)
fun waitForPythonConsoleServerToBeStarted(process: Process) {
PydevConsoleRunnerImpl.getRemotePortFromProcess(process)
} | apache-2.0 | d5bea4dd9973f8ce78ed43b5c2b8c3f0 | 41.490196 | 140 | 0.791369 | 4.403455 | false | false | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/ui/detail/dialogs/SelectQualityDialog.kt | 1 | 2418 | package de.christinecoenen.code.zapp.app.mediathek.ui.detail.dialogs
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.setFragmentResult
import de.christinecoenen.code.zapp.R
import de.christinecoenen.code.zapp.models.shows.MediathekShow
import de.christinecoenen.code.zapp.models.shows.Quality
class SelectQualityDialog : AppCompatDialogFragment() {
companion object {
const val REQUEST_KEY_SELECT_QUALITY = "REQUEST_KEY_SELECT_QUALITY"
private const val REQUEST_KEY_SELECT_QUALITY_KEY_QUALITY =
"REQUEST_KEY_SELECT_QUALITY_KEY_QUALITY"
private const val ARGUMENT_MEDIATHEK_SHOW = "ARGUMENT_MEDIATHEK_SHOW"
private const val ARGUMENT_MODE = "ARGUMENT_MODE"
@JvmStatic
fun newInstance(mediathekShow: MediathekShow, mode: Mode): SelectQualityDialog {
return SelectQualityDialog().apply {
arguments = Bundle().apply {
putSerializable(ARGUMENT_MEDIATHEK_SHOW, mediathekShow)
putSerializable(ARGUMENT_MODE, mode)
}
}
}
@JvmStatic
fun getSelectedQuality(bundle: Bundle): Quality {
return bundle.getSerializable(REQUEST_KEY_SELECT_QUALITY_KEY_QUALITY) as Quality
}
}
private lateinit var mode: Mode
private lateinit var qualities: List<Quality>
private lateinit var qualityLabels: List<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mode = requireArguments().getSerializable(ARGUMENT_MODE) as Mode
val show = requireArguments().getSerializable(ARGUMENT_MEDIATHEK_SHOW) as MediathekShow
qualities = when (mode) {
Mode.DOWNLOAD -> show.supportedDownloadQualities
Mode.SHARE -> show.supportedStreamingQualities
}
qualityLabels = qualities.map { getString(it.labelResId) }
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireActivity())
.setTitle(R.string.fragment_mediathek_qualities_title)
.setItems(qualityLabels.toTypedArray()) { _, i ->
onItemSelected(qualities[i])
}
.setNegativeButton(android.R.string.cancel, null)
.create()
}
private fun onItemSelected(quality: Quality) {
val bundle = Bundle().apply {
putSerializable(REQUEST_KEY_SELECT_QUALITY_KEY_QUALITY, quality)
}
setFragmentResult(REQUEST_KEY_SELECT_QUALITY, bundle)
}
enum class Mode {
DOWNLOAD, SHARE
}
}
| mit | 645824946889bc085cfa1a7dca1a19ad | 30 | 89 | 0.770885 | 3.856459 | false | false | false | false |
rock3r/detekt | detekt-sample-extensions/src/main/kotlin/io/gitlab/arturbosch/detekt/sample/extensions/processors/QualifiedNameProcessor.kt | 1 | 1311 | package io.gitlab.arturbosch.detekt.sample.extensions.processors
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.api.Detektion
import io.gitlab.arturbosch.detekt.api.FileProcessListener
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
class QualifiedNameProcessor : FileProcessListener {
override fun onProcess(file: KtFile) {
val packageName = file.packageFqName.asString()
val nameVisitor = ClassNameVisitor()
file.accept(nameVisitor)
val fqNames = nameVisitor.names
.mapTo(HashSet()) { "$packageName.$it" }
file.putUserData(fqNamesKey, fqNames)
}
override fun onFinish(files: List<KtFile>, result: Detektion) {
val fqNames = files
.mapNotNull { it.getUserData(fqNamesKey) }
.flatMapTo(HashSet()) { it }
result.addData(fqNamesKey, fqNames)
}
class ClassNameVisitor : DetektVisitor() {
val names = mutableSetOf<String>()
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
names.add(classOrObject.nameAsSafeName.asString())
}
}
}
val fqNamesKey: Key<Set<String>> = Key.create<Set<String>>("FQNames")
| apache-2.0 | 8429c19a6976ef1195c7492aa315646c | 33.5 | 73 | 0.705568 | 4.414141 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/ui/home/HomeDataHelper.kt | 1 | 3016 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.ui.home
import android.app.Activity
import co.timetableapp.data.handler.AssignmentHandler
import co.timetableapp.data.handler.EventHandler
import co.timetableapp.data.handler.ExamHandler
import co.timetableapp.model.Assignment
import co.timetableapp.model.Event
import co.timetableapp.model.Exam
import org.threeten.bp.LocalDate
/**
* A helper class for formatting and filtering data to show on the home page.
*/
class HomeDataHelper(private val activity: Activity) {
private val application = activity.application
private val today = LocalDate.now()
/**
* @return a list of all [assignments][Assignment] due today
*/
fun getAssignmentsToday() = AssignmentHandler(activity).getItems(application).filter {
it.occursOnDate(today)
}
/**
* @return a list of overdue [assignments][Assignment]
*/
fun getOverdueAssignments() =
AssignmentHandler(activity).getItems(application).filter { it.isOverdue() }
/**
* @return a list of [assignments][Assignment] occurring in the next [numOfDays] days, not
* including today
*/
fun getUpcomingAssignments(numOfDays: Long) =
AssignmentHandler(activity).getItems(application).filter {
it.dueDate.isAfter(today) && it.dueDate.isBefore(today.plusDays(numOfDays))
}
/**
* @return a list of [exams][Exam] occurring today
*/
fun getExamsToday() =
ExamHandler(activity).getItems(application).filter { it.occursOnDate(today) }
/**
* @return a list of [exams][Exam] occurring in the next [numOfDays] days, not including today
*/
fun getUpcomingExams(numOfDays: Long) = ExamHandler(activity).getItems(application).filter {
it.date.isAfter(today) && it.date.isBefore(today.plusDays(numOfDays))
}
/**
* @return a list of [events][Event] occurring today
*/
fun getEventsToday() =
EventHandler(activity).getItems(application).filter { it.occursOnDate(today) }
/**
* @return a list of [events][Event] occurring in the next [numOfDays] days, not including today
*/
fun getUpcomingEvents(numOfDays: Long) = EventHandler(activity).getItems(application).filter {
it.startDateTime.toLocalDate().isAfter(today) &&
it.startDateTime.toLocalDate().isBefore(today.plusDays(numOfDays))
}
}
| apache-2.0 | 29e1e3c530584a613ee067956b0f8592 | 34.482353 | 100 | 0.694629 | 4.247887 | false | false | false | false |
tipsy/javalin | javalin/src/test/java/io/javalin/TestFilters.kt | 1 | 3319 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*
*/
package io.javalin
import io.javalin.testing.TestUtil
import kong.unirest.HttpMethod
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class TestFilters {
@Test
fun `filters run before root handler`() = TestUtil.test { app, http ->
app.before { it.header("X-BEFOREFILTER", "Before-filter ran") }
app.after { it.header("X-AFTERFILTER", "After-filter ran") }
app.get("/", TestUtil.okHandler)
assertThat(http.get("/").headers.getFirst("X-BEFOREFILTER")).isEqualTo("Before-filter ran")
assertThat(http.get("/").headers.getFirst("X-AFTERFILTER")).isEqualTo("After-filter ran")
}
@Test
fun `app returns 404 for GET if only before-handler present`() = TestUtil.test { app, http ->
app.before(TestUtil.okHandler)
val response = http.call(HttpMethod.GET, "/hello")
assertThat(response.status).isEqualTo(404)
assertThat(response.body).isEqualTo("Not found")
}
@Test
fun `app returns 404 for POST if only before-handler present`() = TestUtil.test { app, http ->
app.before(TestUtil.okHandler)
val response = http.call(HttpMethod.POST, "/hello")
assertThat(response.status).isEqualTo(404)
assertThat(response.body).isEqualTo("Not found")
}
@Test
fun `before-handler can set header`() = TestUtil.test { app, http ->
app.before { it.header("X-FILTER", "Before-filter ran") }
app.get("/mapped", TestUtil.okHandler)
assertThat(http.get("/maped").headers.getFirst("X-FILTER")).isEqualTo("Before-filter ran")
}
@Test
fun `before- and after-handlers can set a bunch of headers`() = TestUtil.test { app, http ->
app.before { it.header("X-BEFORE-1", "Before-filter 1 ran") }
app.before { it.header("X-BEFORE-2", "Before-filter 2 ran") }
app.after { it.header("X-AFTER-1", "After-filter 1 ran") }
app.after { it.header("X-AFTER-2", "After-filter 2 ran") }
app.get("/mapped", TestUtil.okHandler)
assertThat(http.get("/maped").headers.getFirst("X-BEFORE-1")).isEqualTo("Before-filter 1 ran")
assertThat(http.get("/maped").headers.getFirst("X-BEFORE-2")).isEqualTo("Before-filter 2 ran")
assertThat(http.get("/maped").headers.getFirst("X-AFTER-1")).isEqualTo("After-filter 1 ran")
assertThat(http.get("/maped").headers.getFirst("X-AFTER-2")).isEqualTo("After-filter 2 ran")
}
@Test
fun `after-handler sets header after endpoint-handler`() = TestUtil.test { app, http ->
app.get("/mapped", TestUtil.okHandler)
app.after { it.header("X-AFTER", "After-filter ran") }
assertThat(http.get("/mapped").headers.getFirst("X-AFTER")).isEqualTo("After-filter ran")
}
@Test
fun `after is after before`() = TestUtil.test { app, http ->
app.before { it.header("X-FILTER", "This header is mine!") }
app.after { it.header("X-FILTER", "After-filter beats before-filter") }
app.get("/mapped", TestUtil.okHandler)
assertThat(http.get("/maped").headers.getFirst("X-FILTER")).isEqualTo("After-filter beats before-filter")
}
}
| apache-2.0 | 728caf488621df787790fd0c9a32b228 | 42.090909 | 113 | 0.647679 | 3.711409 | false | true | false | false |
Heapy/ApiaryApi | apiary-api-cli/src/main/kotlin/by/heap/apiary/api/cli/ApiaryMain.kt | 1 | 1639 | package by.heap.apiary.api.cli
import by.heap.apiary.api.lib.Fetch
import by.heap.apiary.api.lib.Preview
import by.heap.apiary.api.lib.Publish
import com.beust.jcommander.JCommander
import java.io.File
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths
fun main(args: Array<String>) {
val params = CommandLineInterface();
val jcommander = JCommander(params, *args);
if (params.help) {
jcommander.usage()
}
when (params.operation) {
"publish" -> {
println("Publishing project '${params.name}' from file '${params.input}'")
println(Publish.publish(projectName = params.name, userToken = params.token, file = getFile(params.input)))
}
"preview" -> {
println("Generating preview of '${params.input}' to file '${params.output}'")
val out = Preview.preview(name = params.name, file = getFile(params.input))
saveFile(fileName = params.output, fileContent = out)
}
"fetch" -> {
println("Fetching project '${params.name}' to file '${params.input}.fetched'")
val out = Fetch.fetch(params.name, params.token)
out.code?.let {
saveFile(fileName = "${params.input}.fetched", fileContent = it)
}
}
}
}
private fun getFile(name: String) = File(name).readText(Charset.defaultCharset())
private fun saveFile(fileName: String, fileContent: String) {
val path = Paths.get(fileName)
if (Files.exists(path)) Files.delete(path)
Files.createFile(path)
Files.write(path, fileContent.toByteArray());
}
| gpl-3.0 | 08f5e5125670729a90e2b4dde855bcbd | 32.44898 | 119 | 0.640024 | 3.883886 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/entity/vanilla/AbstractZombieEntityProtocol.kt | 1 | 1420 | /*
* 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.vanilla
import org.lanternpowered.api.data.Keys
import org.lanternpowered.server.entity.LanternEntity
import org.lanternpowered.server.network.entity.parameter.ParameterList
abstract class AbstractZombieEntityProtocol<E : LanternEntity>(entity: E) : AgeableEntityProtocol<E>(entity) {
private var lastAreHandsUp = false
private val areHandsUp: Boolean
get() = this.entity.get(Keys.ARE_HANDS_UP).orElse(false)
override fun spawn(parameterList: ParameterList) {
super.spawn(parameterList)
parameterList.add(EntityParameters.AbstractZombie.UNUSED, 0)
parameterList.add(EntityParameters.AbstractZombie.HANDS_UP, this.areHandsUp)
}
override fun update(parameterList: ParameterList) {
super.update(parameterList)
val handsUp = this.areHandsUp
if (handsUp != this.lastAreHandsUp) {
parameterList.add(EntityParameters.AbstractZombie.HANDS_UP, handsUp)
this.lastAreHandsUp = handsUp
}
}
override fun hasEquipment(): Boolean = true
}
| mit | e36c7af2b5635e1ac9e2ce2f89398c7d | 34.5 | 110 | 0.726056 | 4.022663 | false | false | false | false |
raatiniemi/worker | core/src/main/java/me/raatiniemi/worker/domain/model/TimeInterval.kt | 1 | 3341 | /*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.domain.model
import me.raatiniemi.worker.domain.exception.ClockOutBeforeClockInException
import java.util.*
/**
* Represent a time interval registered to a project.
*/
data class TimeInterval(
val id: Long? = null,
val projectId: Long,
val startInMilliseconds: Long,
val stopInMilliseconds: Long = 0,
val isRegistered: Boolean = false
) {
val isActive: Boolean
get() = 0L == stopInMilliseconds
val time: Long
get() = if (isActive) {
0L
} else calculateInterval(stopInMilliseconds)
val interval: Long
get() = if (isActive) {
calculateInterval(Date().time)
} else calculateInterval(stopInMilliseconds)
init {
if (stopInMilliseconds > 0) {
if (stopInMilliseconds < startInMilliseconds) {
throw ClockOutBeforeClockInException()
}
}
}
fun markAsRegistered(): TimeInterval {
return if (isRegistered) {
this
} else copy(isRegistered = true)
}
fun unmarkRegistered(): TimeInterval {
return if (!isRegistered) {
this
} else copy(isRegistered = false)
}
/**
* Set the clock out timestamp at given date.
*
* @param date Date at which to clock out.
* @throws NullPointerException If date argument is null.
*/
fun clockOutAt(date: Date): TimeInterval {
return copy(stopInMilliseconds = date.time)
}
private fun calculateInterval(stopInMilliseconds: Long): Long {
return stopInMilliseconds - startInMilliseconds
}
class Builder(internal val projectId: Long) {
internal var id: Long? = null
internal var startInMilliseconds = 0L
internal var stopInMilliseconds = 0L
internal var registered = false
fun id(id: Long?): Builder {
this.id = id
return this
}
fun startInMilliseconds(startInMilliseconds: Long): Builder {
this.startInMilliseconds = startInMilliseconds
return this
}
fun stopInMilliseconds(stopInMilliseconds: Long): Builder {
this.stopInMilliseconds = stopInMilliseconds
return this
}
fun register(): Builder {
registered = true
return this
}
fun build(): TimeInterval {
return TimeInterval(id, projectId, startInMilliseconds, stopInMilliseconds, registered)
}
}
companion object {
@JvmStatic
fun builder(projectId: Long): Builder {
return Builder(projectId)
}
}
}
| gpl-2.0 | b5f5b92dbd9b5a4fcd034dbb1239febb | 27.801724 | 99 | 0.629153 | 5.077508 | false | false | false | false |
PKRoma/github-android | app/src/main/java/com/github/pockethub/android/ui/item/commit/CommitHeaderItem.kt | 5 | 2585 | package com.github.pockethub.android.ui.item.commit
import android.content.Context
import android.view.View
import androidx.core.text.buildSpannedString
import com.github.pockethub.android.R
import com.github.pockethub.android.util.android.text.append
import com.github.pockethub.android.core.commit.CommitUtils
import com.github.pockethub.android.util.AvatarLoader
import com.meisolsson.githubsdk.model.Commit
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.commit_header.*
class CommitHeaderItem(
private val avatarLoader: AvatarLoader,
private val context: Context,
val commit: Commit
) : Item(commit.sha()!!.hashCode().toLong()) {
override fun getLayout() = R.layout.commit_header
override fun bind(holder: ViewHolder, position: Int) {
holder.tv_commit_message.text = commit.commit()!!.message()
val commitAuthor = CommitUtils.getAuthor(commit)
val commitCommitter = CommitUtils.getCommitter(commit)
if (commitAuthor != null) {
CommitUtils.bindAuthor(commit, avatarLoader, holder.iv_author)
holder.tv_author.text = commitAuthor
holder.tv_author_date.text = buildSpannedString {
append(context.getString(R.string.authored))
val commitAuthorDate = CommitUtils.getAuthorDate(commit)
if (commitAuthorDate != null) {
append(' ')
append(commitAuthorDate)
}
}
holder.ll_author.visibility = View.VISIBLE
} else {
holder.ll_author.visibility = View.GONE
}
if (isDifferentCommitter(commitAuthor, commitCommitter)) {
CommitUtils.bindCommitter(commit, avatarLoader, holder.iv_committer)
holder.tv_committer.text = commitCommitter
holder.tv_commit_date.text = buildSpannedString {
append(context.getString(R.string.committed))
val commitCommitterDate = CommitUtils.getCommitterDate(commit)
if (commitCommitterDate != null) {
append(' ')
append(commitCommitterDate)
}
}
holder.ll_committer.visibility = View.VISIBLE
} else {
holder.ll_committer.visibility = View.GONE
}
}
private fun isDifferentCommitter(author: String?, committer: String?): Boolean {
return committer != null && committer != author
}
}
| apache-2.0 | db43a28fe1af340edce47b20041dc651 | 37.58209 | 84 | 0.654159 | 4.674503 | false | false | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/tracking/internal/views/ResultViewTrack.kt | 1 | 3572 | package com.mercadopago.android.px.tracking.internal.views
import com.mercadopago.android.px.configuration.PaymentResultScreenConfiguration
import com.mercadopago.android.px.internal.features.payment_result.remedies.RemedyType
import com.mercadopago.android.px.internal.repository.PaymentSettingRepository
import com.mercadopago.android.px.internal.viewmodel.BusinessPaymentModel
import com.mercadopago.android.px.internal.viewmodel.PaymentModel
import com.mercadopago.android.px.model.PaymentResult
import com.mercadopago.android.px.model.internal.remedies.RemediesResponse
import com.mercadopago.android.px.tracking.internal.TrackFactory
import com.mercadopago.android.px.tracking.internal.TrackWrapper
import com.mercadopago.android.px.tracking.internal.model.RemedyTrackData
import com.mercadopago.android.px.tracking.internal.model.ResultViewTrackModel
import java.util.*
class ResultViewTrack : TrackWrapper {
private val resultViewTrackModel: ResultViewTrackModel
private val paymentStatus: String
private val remediesResponse: RemediesResponse
constructor(paymentModel: PaymentModel, screenConfiguration: PaymentResultScreenConfiguration,
paymentSetting: PaymentSettingRepository, isMP: Boolean) {
resultViewTrackModel = ResultViewTrackModel(paymentModel, screenConfiguration, paymentSetting.checkoutPreference!!,
paymentSetting.currency.id, isMP)
paymentStatus = getMappedResult(paymentModel.paymentResult)
this.remediesResponse = paymentModel.remedies
}
constructor(paymentModel: BusinessPaymentModel, paymentSetting: PaymentSettingRepository, isMP: Boolean) {
resultViewTrackModel = ResultViewTrackModel(paymentModel, paymentSetting.checkoutPreference!!,
paymentSetting.currency.id, isMP)
paymentStatus = getMappedResult(paymentModel.paymentResult)
this.remediesResponse = paymentModel.remedies
}
override fun getTrack() = TrackFactory.withView(getViewPath()).addData(getData()).build()
private fun getData(): Map<String, Any> {
val map = resultViewTrackModel.toMap()
if (paymentStatus == ERROR) {
map["remedies"] = getRemedies()
}
return map
}
private fun getViewPath() = String.format(Locale.US, PATH, paymentStatus)
private fun getMappedResult(payment: PaymentResult): String {
return when {
payment.isApproved || payment.isInstructions -> SUCCESS
payment.isRejected -> ERROR
payment.isPending -> PENDING
else -> UNKNOWN
}
}
private fun getRemedies(): List<RemedyTrackData>? {
val remedies = mutableListOf<RemedyTrackData>()
when {
remediesResponse.suggestedPaymentMethod != null -> {
remedies.add(getRemedyData(RemedyType.PAYMENT_METHOD_SUGGESTION))
}
remediesResponse.cvv != null -> {
remedies.add(getRemedyData(RemedyType.CVV_REQUEST))
}
remediesResponse.highRisk != null -> {
remedies.add(getRemedyData(RemedyType.KYC_REQUEST))
}
}
return remedies
}
private fun getRemedyData(type: RemedyType) = RemedyTrackData(type.getType(), remediesResponse.trackingData)
companion object {
private const val PATH = "$BASE_PATH/result/%s"
private const val SUCCESS = "success"
private const val PENDING = "further_action_needed"
private const val ERROR = "error"
private const val UNKNOWN = "unknown"
}
} | mit | 2ecaa1754ec1d0656c47259d87977c06 | 42.573171 | 123 | 0.722284 | 4.614987 | false | true | false | false |
jcam3ron/cassandra-migration | src/main/java/com/builtamont/cassandra/migration/internal/command/Validate.kt | 1 | 3184 | /**
* File : Validate.kt
* License :
* Original - Copyright (c) 2015 - 2016 Contrast Security
* Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd
*
* 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.builtamont.cassandra.migration.internal.command
import com.builtamont.cassandra.migration.api.MigrationVersion
import com.builtamont.cassandra.migration.api.resolver.MigrationResolver
import com.builtamont.cassandra.migration.internal.dbsupport.SchemaVersionDAO
import com.builtamont.cassandra.migration.internal.info.MigrationInfoServiceImpl
import com.builtamont.cassandra.migration.internal.util.StopWatch
import com.builtamont.cassandra.migration.internal.util.TimeFormat
import com.builtamont.cassandra.migration.internal.util.logging.LogFactory
/**
* Handles the validate command.
* Validates the applied migrations against the available ones.
*
* @param migrationResolver The Cassandra migration resolver.
* @param migrationTarget The target version of the migration.
* @param schemaVersionDAO The Cassandra migration schema version DAO.
* @param outOfOrder True to allow migration to be run "out of order".
* @param pendingOrFuture True to allow pending or Future<T> migration to be run.
*/
class Validate(
private val migrationResolver: MigrationResolver,
private val migrationTarget: MigrationVersion,
private val schemaVersionDAO: SchemaVersionDAO,
private val outOfOrder: Boolean,
private val pendingOrFuture: Boolean
) {
/**
* Runs the actual migration.
*
* @return The validation error, if any.
*/
fun run(): String? {
val stopWatch = StopWatch()
stopWatch.start()
val infoService = MigrationInfoServiceImpl(migrationResolver, schemaVersionDAO, migrationTarget, outOfOrder, pendingOrFuture)
infoService.refresh()
val count = infoService.all().size
val validationError = infoService.validate()
stopWatch.stop()
logSummary(count, stopWatch.totalTimeMillis)
return validationError
}
/**
* Logs the summary of this migration run.
*
* @param count The number of successfully applied migrations.
* @param executionTime The total time taken to perform this migration run (in ms).
*/
private fun logSummary(count: Int, executionTime: Long) {
val time = TimeFormat.format(executionTime)
LOG.info("Validated $count migrations (execution time $time)")
}
/**
* Validate command companion object.
*/
companion object {
private val LOG = LogFactory.getLog(Validate::class.java)
}
}
| apache-2.0 | 46844a99a714ca12d0a5b64e9e238ec3 | 36.023256 | 133 | 0.726759 | 4.555079 | false | false | false | false |
sabi0/intellij-community | python/src/com/jetbrains/python/testing/pyTestFixtures/PyTestFixtureReferenceContributor.kt | 1 | 2613 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.testing.pyTestFixtures
import com.intellij.openapi.util.Ref
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.*
import com.intellij.util.ProcessingContext
import com.jetbrains.python.BaseReference
import com.jetbrains.python.psi.PyElementGenerator
import com.jetbrains.python.psi.PyNamedParameter
import com.jetbrains.python.psi.PyParameter
import com.jetbrains.python.psi.types.PyType
import com.jetbrains.python.psi.types.PyTypeProviderBase
import com.jetbrains.python.psi.types.TypeEvalContext
class PyTestFixtureReference(namedParameter: PyNamedParameter, fixture: PyTestFixture) : BaseReference(namedParameter) {
private val functionRef = fixture.function?.let { SmartPointerManager.createPointer(it) }
private val resolveRef = fixture.resolveTarget?.let { SmartPointerManager.createPointer(it) }
override fun resolve() = resolveRef?.element
fun getFunction() = functionRef?.element
override fun getVariants() = emptyArray<Any>()
override fun isSoft() = true
override fun handleElementRename(newElementName: String) = myElement.replace(
PyElementGenerator.getInstance(myElement.project).createParameter(newElementName))!!
}
object PyTextFixtureTypeProvider : PyTypeProviderBase() {
override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): Ref<PyType>? {
val param = referenceTarget as? PyNamedParameter ?: return null
val fixtureFunc = param.references.filterIsInstance(PyTestFixtureReference::class.java).firstOrNull()?.getFunction() ?: return null
return context.getReturnType(fixtureFunc)?.let { Ref(it) }
}
}
private object PyTestReferenceProvider : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
val namedParam = element as? PyNamedParameter ?: return emptyArray()
val fixture = getFixture(namedParam, TypeEvalContext.codeAnalysis(element.project, element.containingFile)) ?: return emptyArray()
return arrayOf(PyTestFixtureReference(namedParam, fixture))
}
}
object PyTestFixtureReferenceContributor : PsiReferenceContributor() {
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
registrar.registerReferenceProvider(PlatformPatterns.psiElement(PyParameter::class.java), PyTestReferenceProvider,
PsiReferenceRegistrar.HIGHER_PRIORITY)
}
}
| apache-2.0 | 69f4053b5bd6e5ffd4fa41d27b85ce9d | 44.842105 | 140 | 0.795637 | 4.911654 | false | true | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/SpannerWriter.kt | 1 | 3971 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers
import com.google.cloud.Timestamp
import com.google.cloud.spanner.SpannerException
import com.google.cloud.spanner.TransactionContext
import java.time.Clock
import java.util.concurrent.atomic.AtomicBoolean
import java.util.logging.Logger
import org.wfanet.measurement.common.identity.IdGenerator
import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient
/**
* Abstracts a common pattern:
* - Run a RMW transaction
* - Optionally perform additional reads after the transaction is done
* - Transform all of the outputs into a result
*
* Each SpannerWriter instance will be executed at most once.
*
* This provides some conveniences, like running in the right dispatcher for Spanner.
*/
abstract class SpannerWriter<T, R> {
data class TransactionScope(
val transactionContext: AsyncDatabaseClient.TransactionContext,
val idGenerator: IdGenerator
)
data class ResultScope<T>(val transactionResult: T?, val commitTimestamp: Timestamp)
/**
* Override this to perform the body of the Spanner transaction.
*
* This runs in the scope of a [TransactionScope], so it has convenient access to the
* [TransactionContext], an [IdGenerator], and a [Clock].
*/
protected abstract suspend fun TransactionScope.runTransaction(): T
/**
* Override this to compute the final result from [execute]. This is guaranteed to run after the
* Spanner transaction is complete.
*/
protected abstract fun ResultScope<T>.buildResult(): R
// To ensure the transaction is only executed once:
private val executed = AtomicBoolean(false)
private suspend fun runTransaction(
runner: AsyncDatabaseClient.TransactionRunner,
idGenerator: IdGenerator
): T? {
return try {
runner.execute { transactionContext ->
val scope = TransactionScope(transactionContext, idGenerator)
scope.runTransaction()
}
} catch (e: SpannerException) {
handleSpannerException(e)
}
}
/**
* Executes the SpannerWriter by starting a SpannerWriter, running [runTransaction], then calling
* [buildResult] on the output.
*
* This can only be called once per instance. This will bubble up anything that
* [handleSpannerException] throws.
*
* @return the output of [buildResult]
*/
suspend fun execute(databaseClient: AsyncDatabaseClient, idGenerator: IdGenerator): R {
logger.fine("Running ${this::class.simpleName} transaction")
check(executed.compareAndSet(false, true)) { "Cannot execute SpannerWriter multiple times" }
val runner = databaseClient.readWriteTransaction()
val transactionResult: T? = runTransaction(runner, idGenerator)
val resultScope = ResultScope(transactionResult, runner.getCommitTimestamp())
return resultScope.buildResult()
}
/** Override this to handle Spanner exception thrown from [execute]. */
protected open suspend fun handleSpannerException(e: SpannerException): T? {
throw e
}
companion object {
private val logger: Logger = Logger.getLogger(this::class.java.name)
}
}
/** A [SpannerWriter] whose result is the non-null transaction result. */
abstract class SimpleSpannerWriter<T : Any> : SpannerWriter<T, T>() {
final override fun ResultScope<T>.buildResult(): T {
return checkNotNull(transactionResult)
}
}
| apache-2.0 | 21a36abd46a135609547434a8180d642 | 35.768519 | 99 | 0.744145 | 4.492081 | false | false | false | false |
harningt/atomun-keygen | src/main/java/us/eharning/atomun/keygen/internal/spi/bip0032/BIP0032Node.kt | 1 | 3384 | /*
* Copyright 2015, 2017 Thomas Harning Jr. <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package us.eharning.atomun.keygen.internal.spi.bip0032
import com.google.common.primitives.Ints
import us.eharning.atomun.core.ec.ECKey
import java.util.*
import javax.annotation.concurrent.Immutable
/**
* BIP0032 node data.
*
* TODO: Embed address base so that appropriate serialization is performed.
*/
@Immutable
internal class BIP0032Node
/**
* Construct a BIP0032 node with the given properties.
*
* @param master
* master key for this node.
* @param chainCode
* chain code byte array.
* @param depth
* depth into the BIP0032 hierarchy.
* @param parent
* parent node's fingerprint.
* @param sequence
* sequence into the parent node.
*/
(
val master: ECKey,
chainCode: ByteArray,
val depth: Int,
val parent: Int,
val sequence: Int
) {
private val chainCode: ByteArray = chainCode.copyOf()
/**
* Get the node's chain code.
*
* @return the node's chain code as a byte array copy.
*/
fun getChainCode(): ByteArray {
return Arrays.copyOf(chainCode, chainCode.size)
}
/**
* Get the node's fingerprint based on the first 4 bytes of the address hash of the master key.
*
* @return the node's fingerprint as an integer.
*/
val fingerPrint: Int
get() {
val address = master.addressHash
return Ints.fromByteArray(address)
}
/**
* Obtain whether or not the master key has private bits.
*
* @return true if the master key has private bits.
*/
fun hasPrivate(): Boolean {
return master.hasPrivate()
}
/**
* Return true if this is equivalent to the passed in object (same type and same properties).
*
* @param other
* instance to compare against.
*
* @return true if the values are equivalent, else false.
*/
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (javaClass != other?.javaClass) {
return false
}
other as BIP0032Node
return depth == other.depth
&& sequence == other.sequence
&& master == other.master
&& parent == other.parent
&& Arrays.equals(chainCode, other.chainCode)
}
/**
* Returns a hash code value for the object.
*
* @return a hash code value for this object.
*/
override fun hashCode(): Int {
var result = master.hashCode()
result = 31 * result + depth
result = 31 * result + parent
result = 31 * result + sequence
result = 31 * result + Arrays.hashCode(chainCode)
return result
}
}
| apache-2.0 | 8d398869d2a2de4aa032828c6349a71c | 27.436975 | 99 | 0.617612 | 4.310828 | false | false | false | false |
FHannes/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/autoimplement/AutoImplementTransformationSupport.kt | 14 | 3297 | /*
* 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 org.jetbrains.plugins.groovy.transformations.autoimplement
import com.intellij.psi.HierarchicalMethodSignature
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.infos.CandidateInfo
import com.intellij.psi.util.MethodSignature
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierFlags
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport
import org.jetbrains.plugins.groovy.transformations.TransformationContext
import org.jetbrains.plugins.groovy.transformations.plusAssign
import org.jetbrains.plugins.groovy.util.GroovyOverrideImplementExploreUtil
internal val autoImplementFqn = GroovyCommonClassNames.GROOVY_TRANSFORM_AUTOIMPLEMENT
internal val autoImplementOriginInfo = "by @AutoImplement"
class AutoImplementTransformation : AstTransformationSupport {
override fun applyTransformation(context: TransformationContext) {
val annotation = context.getAnnotation(autoImplementFqn) ?: return
val candidateInfo = getMapToOverrideImplement(context).values
for (info in candidateInfo) {
val toImplementMethod = info.element as? PsiMethod ?: continue
val substitutor = toImplementMethod.containingClass?.let {
TypeConversionUtil.getClassSubstitutor(it, context.codeClass, PsiSubstitutor.EMPTY)
} ?: info.substitutor
val signature = toImplementMethod.getSignature(substitutor)
context += context.memberBuilder.method(toImplementMethod.name) {
setModifiers(GrModifierFlags.PUBLIC_MASK)
returnType = substitutor.substitute(toImplementMethod.returnType)
navigationElement = annotation
originInfo = autoImplementOriginInfo
if (toImplementMethod.hasTypeParameters()) {
toImplementMethod.typeParameters.forEach {
typeParameterList.addParameter(it)
}
}
for ((index, value) in signature.parameterTypes.withIndex()) {
addParameter(toImplementMethod.parameterList.parameters[index].name ?: ("var" + index), value)
}
}
}
}
fun getMapToOverrideImplement(context: TransformationContext): Map<MethodSignature, CandidateInfo> {
val signatures = ContainerUtil.newArrayList<HierarchicalMethodSignature>()
context.superTypes.forEach {
it.resolve()?.visibleSignatures?.let {
signatures.addAll(it)
}
}
return GroovyOverrideImplementExploreUtil.getMapToOverrideImplement(context.codeClass, signatures, true, false)
}
} | apache-2.0 | 9f2eba074f545919f54e8c0b47c31e60 | 38.261905 | 115 | 0.77252 | 4.771346 | false | false | false | false |
xamoom/xamoom-android-sdk | xamoomsdk/src/main/java/com/xamoom/android/xamoomcontentblocks/ViewHolders/ContentEventViewHolder.kt | 1 | 8465 | /*
* Copyright (c) 2017 xamoom GmbH <[email protected]>
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at the root of this project.
*/
package com.xamoom.android.xamoomcontentblocks.ViewHolders
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.net.Uri
import android.preference.PreferenceManager
import android.provider.CalendarContract
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.xamoom.android.xamoomsdk.R
import com.xamoom.android.xamoomsdk.Resource.Content
import com.xamoom.android.xamoomsdk.Resource.ContentBlock
import com.xamoom.android.xamoomsdk.Resource.Spot
import com.xamoom.android.xamoomsdk.Resource.Style
import java.text.SimpleDateFormat
import java.util.*
/**
* Displays the content heading.
*/
class ContentEventViewHolder(itemView: View, val navigationMode: String?, val fragment: Fragment) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
private val mNavigationTitleTextView: TextView = itemView.findViewById<View>(R.id.event_navigation_titleTextView) as TextView
private val mNavigationDescriptionTextView: TextView = itemView.findViewById<View>(R.id.event_navigation_contentTextView) as TextView
private val mCalendarTitleTextView: TextView = itemView.findViewById<View>(R.id.event_calendar_titleTextView) as TextView
private val mCalendarDescriptionTextView: TextView = itemView.findViewById<View>(R.id.event_calendar_contentTextView) as TextView
private val mNavigationLayout: LinearLayout = itemView.findViewById(R.id.event_navigation_layout)
private val mCalendarLayout: LinearLayout = itemView.findViewById(R.id.event_calendar_layout)
private val mCalendarImageView: ImageView = itemView.findViewById(R.id.event_calendar_iconImageView)
private val mNavigationImageView: ImageView = itemView.findViewById(R.id.event_navigation_iconImageView)
private var mContext: Context? = null
private var sharedPreferences: SharedPreferences? = null
init {
mContext = fragment.context
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext)
mNavigationLayout.visibility = View.GONE
mCalendarLayout.visibility = View.GONE
}
@SuppressLint("SetTextI18n")
fun setupContentBlock(contentBlock: ContentBlock, content: Content?, offline: Boolean, style: Style?) {
if (content != null && content.relatedSpot != null) {
val spot = content.relatedSpot
mNavigationTitleTextView.text = mContext!!.resources.getString(R.string.event_navigation_title)
mNavigationDescriptionTextView.text = spot.name
mNavigationLayout.setOnClickListener {
navigateToSpot(spot)
}
mNavigationLayout.visibility = View.VISIBLE
if (content.fromDate != null) {
val langPickerLanguage = sharedPreferences!!.getString("current_language_code", null)
val locale: Locale?
locale = if (langPickerLanguage != null){
Locale(langPickerLanguage)
} else {
Locale("en")
}
val dateFormatter = SimpleDateFormat("E d MMM HH:mm", locale)
val fromDate = dateFormatter.format(content.fromDate)
mCalendarTitleTextView.text = mContext!!.resources.getString(R.string.event_calendar_title)
mCalendarDescriptionTextView.text = "$fromDate"
mCalendarLayout.setOnClickListener {
val intent = Intent(Intent.ACTION_INSERT)
.setData(CalendarContract.Events.CONTENT_URI)
.putExtra(CalendarContract.Events.TITLE, content.title)
.putExtra(CalendarContract.Events.EVENT_LOCATION, spot.name)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, content.fromDate.time)
if (content.toDate != null) {
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, content.toDate.time)
} else {
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, content.fromDate.time)
}
fragment.activity!!.startActivity(Intent.createChooser(intent, ""))
}
mCalendarLayout.visibility = View.VISIBLE
} else {
mCalendarLayout.visibility = View.GONE
}
} else if (content != null && content.fromDate != null) {
val langPickerLanguage = sharedPreferences!!.getString("current_language_code", null)
val locale: Locale?
locale = if (langPickerLanguage != null){
Locale(langPickerLanguage)
} else {
Locale("en")
}
val dateFormatter = SimpleDateFormat("E d MMM HH:mm", locale)
val fromDate = dateFormatter.format(content.fromDate)
mNavigationLayout.visibility = View.GONE
mCalendarTitleTextView.text = mContext!!.resources.getString(R.string.event_calendar_title)
mCalendarDescriptionTextView.text = "$fromDate"
mCalendarLayout.setOnClickListener {
val intent = Intent(Intent.ACTION_INSERT)
.setData(CalendarContract.Events.CONTENT_URI)
.putExtra(CalendarContract.Events.TITLE, content.title)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, content.fromDate.time)
if (content.toDate != null) {
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, content.toDate.time)
} else {
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, content.fromDate.time)
}
fragment.activity!!.startActivity(Intent.createChooser(intent, ""))
}
mCalendarLayout.visibility = View.VISIBLE
} else {
mNavigationLayout.visibility = View.GONE
mCalendarLayout.visibility = View.GONE
}
val ta = mContext!!.obtainStyledAttributes(R.style.ContentBlocksTheme_Event, R.styleable.Event)
val calendarBackgroundColor = ta.getResourceId(R.styleable.Event_event_calendar_background_color, 0)
val calendarTintColor = ta.getColor(R.styleable.Event_event_calendar_tint_color, Color.BLACK)
val navigationBackgroundColor = ta.getResourceId(R.styleable.Event_event_navigation_background_color, 0)
val navigationTintColor = ta.getColor(R.styleable.Event_event_navigation_tint_color, Color.BLACK)
val isBackgroundImage = PreferenceManager.getDefaultSharedPreferences(mContext).getString("is_background_image", null)
if (isBackgroundImage != null && isBackgroundImage == "true") {
mCalendarLayout.setBackgroundResource(R.drawable.background_image)
mNavigationLayout.setBackgroundResource(R.drawable.background_image)
} else {
mCalendarLayout.setBackgroundResource(calendarBackgroundColor)
mNavigationLayout.setBackgroundResource(navigationBackgroundColor)
}
mNavigationTitleTextView.setTextColor(navigationTintColor)
mNavigationDescriptionTextView.setTextColor(navigationTintColor)
mCalendarTitleTextView.setTextColor(calendarTintColor)
mCalendarDescriptionTextView.setTextColor(calendarTintColor)
mCalendarImageView.setColorFilter(calendarTintColor)
mNavigationImageView.setColorFilter(navigationTintColor)
}
private fun navigateToSpot(spot: Spot) {
val urlString = String.format(Locale.US, "google.navigation:q=%f,%f&mode=%s", spot.location.latitude, spot.location.longitude, navigationMode)
val gmmIntentUri = Uri.parse(urlString)
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps")
if (mapIntent.resolveActivity(mContext!!.getPackageManager()) != null) {
mContext!!.startActivity(mapIntent)
}
}
} | mit | c1f94989f5320ee0273a3c7aa3da8db1 | 46.830508 | 164 | 0.684938 | 4.924375 | false | false | false | false |
FHannes/intellij-community | platform/configuration-store-impl/src/StorageVirtualFileTracker.kt | 15 | 4280 | package com.intellij.configurationStore
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.*
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.messages.MessageBus
import java.nio.file.Paths
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicBoolean
class StorageVirtualFileTracker(private val messageBus: MessageBus) {
private val filePathToStorage: ConcurrentMap<String, TrackedStorage> = ContainerUtil.newConcurrentMap()
private @Volatile var hasDirectoryBasedStorages = false
private val vfsListenerAdded = AtomicBoolean()
interface TrackedStorage : StateStorage {
val storageManager: StateStorageManagerImpl
}
fun put(path: String, storage: TrackedStorage) {
filePathToStorage.put(path, storage)
if (storage is DirectoryBasedStorage) {
hasDirectoryBasedStorages = true
}
if (vfsListenerAdded.compareAndSet(false, true)) {
addVfsChangesListener()
}
}
fun remove(path: String) {
filePathToStorage.remove(path)
}
fun remove(processor: (TrackedStorage) -> Boolean) {
val iterator = filePathToStorage.values.iterator()
for (storage in iterator) {
if (processor(storage)) {
iterator.remove()
}
}
}
private fun addVfsChangesListener() {
messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: MutableList<out VFileEvent>) {
eventLoop@ for (event in events) {
var storage: StateStorage?
if (event is VFilePropertyChangeEvent && VirtualFile.PROP_NAME == event.propertyName) {
val oldPath = event.oldPath
storage = filePathToStorage.remove(oldPath)
if (storage != null) {
filePathToStorage.put(event.path, storage)
if (storage is FileBasedStorage) {
storage.setFile(null, Paths.get(event.path))
}
// we don't support DirectoryBasedStorage renaming
// StoragePathMacros.MODULE_FILE -> old path, we must update value
storage.storageManager.pathRenamed(oldPath, event.path, event)
}
}
else {
val path = event.path
storage = filePathToStorage.get(path)
// we don't care about parent directory create (because it doesn't affect anything) and move (because it is not supported case),
// but we should detect deletion - but again, it is not supported case. So, we don't check if some of registered storages located inside changed directory.
// but if we have DirectoryBasedStorage, we check - if file located inside it
if (storage == null && hasDirectoryBasedStorages && path.endsWith(FileStorageCoreUtil.DEFAULT_EXT, ignoreCase = true)) {
storage = filePathToStorage.get(VfsUtil.getParentDir(path))
}
}
if (storage == null) {
continue
}
when (event) {
is VFileMoveEvent -> {
if (storage is FileBasedStorage) {
storage.setFile(null, Paths.get(event.path))
}
}
is VFileCreateEvent -> {
if (storage is FileBasedStorage && event.requestor !is StateStorage.SaveSession) {
storage.setFile(event.file, null)
}
}
is VFileDeleteEvent -> {
if (storage is FileBasedStorage) {
storage.setFile(null, null)
}
else {
(storage as DirectoryBasedStorage).setVirtualDir(null)
}
}
is VFileCopyEvent -> continue@eventLoop
}
val componentManager = storage.storageManager.componentManager!!
componentManager.messageBus.syncPublisher(STORAGE_TOPIC).storageFileChanged(event, storage, componentManager)
}
}
})
}
} | apache-2.0 | 99393227209cd49a0eaec7f2af607226 | 36.884956 | 167 | 0.653505 | 5.238678 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/ValueParameter.kt | 1 | 3046 | /*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.parameters
import javafx.beans.property.StringProperty
import javafx.util.StringConverter
import kotlin.reflect.KProperty
/**
* Parameters, which can hold a value.
*/
interface ValueParameter<T>
: Parameter {
val converter: StringConverter<T>
var value: T
var stringValue: String
get() = converter.toString(value)
set(v) {
value = converter.fromString(v)
}
val expressionProperty: StringProperty
var expression: String?
get() = expressionProperty.get()
set(v) {
expressionProperty.set(v)
}
fun saveValue(): Boolean = true
/**
* Set the value based on an evaluated expression, and therefore the type T isn't known by the
* caller.
*/
fun evaluated(v: Any?) {
val parent = parent
if (v is Iterable<*> && parent is MultipleParameter<*, *>) {
parent.evaluateMultiple(this, v)
} else {
coerce(v)
}
expression = null
}
/**
* Used when evaluating expressions, the value is coerced to fit the required data type. For example,
* DoubleParameter can coerce all numbers types to doubles. However, the default behaviour is to
* convert the value to a string, and set the parameter via stringValue. Therefore DoubleParameter doesn't NEED
* to override this method, but it would be more efficient if it did.
*/
fun coerce(v: Any?) {
stringValue = v.toString()
}
override fun errorMessage(): String? = errorMessage(value)
fun errorMessage(v: T?): String?
/**
* For delegation :
*
* val fooP = IntParameter( "foo" )
*
* val foo by fooP
*/
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value
}
/**
* For delegation :
*
* val fooP = IntParameter( "foo" )
*
* var foo by fooP
*/
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
override fun copy(): ValueParameter<T>
fun copyBounded(): ValueParameter<T> {
val copy = copy()
copy.value = value
copy.listen {
this.value = copy.value
}
this.listen {
copy.value = this.value
}
return copy
}
}
| gpl-3.0 | 093cbd873ec2a6851c642d1c484aea41 | 25.719298 | 115 | 0.632961 | 4.440233 | false | false | false | false |
cwoolner/flex-poker | src/main/kotlin/com/flexpoker/table/query/eventsubscribers/InMemoryAsyncTableEventSubscriber.kt | 1 | 6390 | package com.flexpoker.table.query.eventsubscribers
import com.flexpoker.framework.event.EventHandler
import com.flexpoker.framework.event.subscriber.EventSubscriber
import com.flexpoker.framework.event.subscriber.InMemoryThreadSafeEventSubscriberHelper
import com.flexpoker.table.command.events.ActionOnChangedEvent
import com.flexpoker.table.command.events.AutoMoveHandForwardEvent
import com.flexpoker.table.command.events.CardsShuffledEvent
import com.flexpoker.table.command.events.FlopCardsDealtEvent
import com.flexpoker.table.command.events.HandCompletedEvent
import com.flexpoker.table.command.events.HandDealtEvent
import com.flexpoker.table.command.events.LastToActChangedEvent
import com.flexpoker.table.command.events.PlayerAddedEvent
import com.flexpoker.table.command.events.PlayerBustedTableEvent
import com.flexpoker.table.command.events.PlayerCalledEvent
import com.flexpoker.table.command.events.PlayerCheckedEvent
import com.flexpoker.table.command.events.PlayerFoldedEvent
import com.flexpoker.table.command.events.PlayerForceCheckedEvent
import com.flexpoker.table.command.events.PlayerForceFoldedEvent
import com.flexpoker.table.command.events.PlayerRaisedEvent
import com.flexpoker.table.command.events.PlayerRemovedEvent
import com.flexpoker.table.command.events.PotAmountIncreasedEvent
import com.flexpoker.table.command.events.PotClosedEvent
import com.flexpoker.table.command.events.PotCreatedEvent
import com.flexpoker.table.command.events.RiverCardDealtEvent
import com.flexpoker.table.command.events.RoundCompletedEvent
import com.flexpoker.table.command.events.TableCreatedEvent
import com.flexpoker.table.command.events.TableEvent
import com.flexpoker.table.command.events.TablePausedEvent
import com.flexpoker.table.command.events.TableResumedEvent
import com.flexpoker.table.command.events.TurnCardDealtEvent
import com.flexpoker.table.command.events.WinnersDeterminedEvent
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import java.util.HashMap
import javax.inject.Inject
@Component("tableEventSubscriber")
class InMemoryAsyncTableEventSubscriber @Inject constructor(
private val inMemoryThreadSafeEventSubscriberHelper: InMemoryThreadSafeEventSubscriberHelper<TableEvent>,
private val tableCreatedEventHandler: EventHandler<TableCreatedEvent>,
private val handDealtEventHandler: EventHandler<HandDealtEvent>,
private val playerBustedTableEventHandler: EventHandler<PlayerBustedTableEvent>,
private val playerCalledEventHandler: EventHandler<PlayerCalledEvent>,
private val playerCheckedEventHandler: EventHandler<PlayerCheckedEvent>,
private val playerForceCheckedEventHandler: EventHandler<PlayerForceCheckedEvent>,
private val playerFoldedEventHandler: EventHandler<PlayerFoldedEvent>,
private val playerForceFoldedEventHandler: EventHandler<PlayerForceFoldedEvent>,
private val playerRaisedEventHandler: EventHandler<PlayerRaisedEvent>,
private val flopCardsDealtEventHandler: EventHandler<FlopCardsDealtEvent>,
private val turnCardDealtEventHandler: EventHandler<TurnCardDealtEvent>,
private val riverCardDealtEventHandler: EventHandler<RiverCardDealtEvent>,
private val roundCompletedEventHandler: EventHandler<RoundCompletedEvent>,
private val actionOnChangedEventHandler: EventHandler<ActionOnChangedEvent>,
private val potAmountIncreasedEventHandler: EventHandler<PotAmountIncreasedEvent>,
private val potClosedEventHandler: EventHandler<PotClosedEvent>,
private val potCreatedEventHandler: EventHandler<PotCreatedEvent>,
private val winnersDeterminedEventHandler: EventHandler<WinnersDeterminedEvent>
) : EventSubscriber<TableEvent> {
companion object {
private val NOOP = EventHandler { _: TableEvent -> }
}
init {
inMemoryThreadSafeEventSubscriberHelper.setHandlerMap(createEventHandlerMap()
as MutableMap<Class<TableEvent>, EventHandler<TableEvent>>)
}
@Async
override fun receive(event: TableEvent) {
inMemoryThreadSafeEventSubscriberHelper.receive(event)
}
private fun createEventHandlerMap(): Map<Class<out TableEvent>, EventHandler<out TableEvent>> {
val eventHandlerMap = HashMap<Class<out TableEvent>, EventHandler<out TableEvent>>()
eventHandlerMap[ActionOnChangedEvent::class.java] = actionOnChangedEventHandler
eventHandlerMap[AutoMoveHandForwardEvent::class.java] = NOOP
eventHandlerMap[CardsShuffledEvent::class.java] = NOOP
eventHandlerMap[FlopCardsDealtEvent::class.java] = flopCardsDealtEventHandler
eventHandlerMap[HandCompletedEvent::class.java] = NOOP
eventHandlerMap[HandDealtEvent::class.java] = handDealtEventHandler
eventHandlerMap[LastToActChangedEvent::class.java] = NOOP
eventHandlerMap[PlayerAddedEvent::class.java] = NOOP
eventHandlerMap[PlayerBustedTableEvent::class.java] = playerBustedTableEventHandler
eventHandlerMap[PlayerCalledEvent::class.java] = playerCalledEventHandler
eventHandlerMap[PlayerCheckedEvent::class.java] = playerCheckedEventHandler
eventHandlerMap[PlayerForceCheckedEvent::class.java] = playerForceCheckedEventHandler
eventHandlerMap[PlayerFoldedEvent::class.java] = playerFoldedEventHandler
eventHandlerMap[PlayerForceFoldedEvent::class.java] = playerForceFoldedEventHandler
eventHandlerMap[PlayerRaisedEvent::class.java] = playerRaisedEventHandler
eventHandlerMap[PlayerRemovedEvent::class.java] = NOOP
eventHandlerMap[PotAmountIncreasedEvent::class.java] = potAmountIncreasedEventHandler
eventHandlerMap[PotClosedEvent::class.java] = potClosedEventHandler
eventHandlerMap[PotCreatedEvent::class.java] = potCreatedEventHandler
eventHandlerMap[RiverCardDealtEvent::class.java] = riverCardDealtEventHandler
eventHandlerMap[RoundCompletedEvent::class.java] = roundCompletedEventHandler
eventHandlerMap[TableCreatedEvent::class.java] = tableCreatedEventHandler
eventHandlerMap[TablePausedEvent::class.java] = NOOP
eventHandlerMap[TableResumedEvent::class.java] = NOOP
eventHandlerMap[TurnCardDealtEvent::class.java] = turnCardDealtEventHandler
eventHandlerMap[WinnersDeterminedEvent::class.java] = winnersDeterminedEventHandler
return eventHandlerMap
}
} | gpl-2.0 | ec35f806f92be70d1a11dbab7236750a | 59.292453 | 109 | 0.823787 | 5.007837 | false | false | false | false |
arturbosch/detekt | detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseIsNullOrEmpty.kt | 1 | 7274 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.rules.fqNameOrNull
import io.gitlab.arturbosch.detekt.rules.safeAs
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.types.isNullable
/**
* This rule detects null or empty checks that can be replaced with `isNullOrEmpty()` call.
*
* <noncompliant>
* fun foo(x: List<Int>?) {
* if (x == null || x.isEmpty()) return
* }
* fun bar(x: List<Int>?) {
* if (x == null || x.count() == 0) return
* }
* fun baz(x: List<Int>?) {
* if (x == null || x.size == 0) return
* }
* </noncompliant>
*
* <compliant>
* if (x.isNullOrEmpty()) return
* </compliant>
*
*/
@RequiresTypeResolution
@Suppress("TooManyFunctions")
class UseIsNullOrEmpty(config: Config = Config.empty) : Rule(config) {
override val issue: Issue = Issue(
"UseIsNullOrEmpty",
Severity.Style,
"Use 'isNullOrEmpty()' call instead of 'x == null || x.isEmpty()'",
Debt.FIVE_MINS
)
@Suppress("ReturnCount")
override fun visitBinaryExpression(expression: KtBinaryExpression) {
super.visitBinaryExpression(expression)
if (bindingContext == BindingContext.EMPTY) return
if (expression.operationToken != KtTokens.OROR) return
val left = expression.left as? KtBinaryExpression ?: return
val right = expression.right ?: return
val nullCheckedExpression = left.nullCheckedExpression() ?: return
val sizeCheckedExpression = right.sizeCheckedExpression() ?: return
if (nullCheckedExpression.text != sizeCheckedExpression.text) return
val message = "This '${expression.text}' can be replaced with 'isNullOrEmpty()' call"
report(CodeSmell(issue, Entity.from(expression), message))
}
private fun KtBinaryExpression.nullCheckedExpression(): KtSimpleNameExpression? {
if (operationToken != KtTokens.EQEQ) return null
return when {
right.isNullKeyword() -> left
left.isNullKeyword() -> right
else -> null
}?.safeAs<KtSimpleNameExpression>()?.takeIf { it.getType(bindingContext)?.isNullable() == true }
}
private fun KtExpression.sizeCheckedExpression(): KtSimpleNameExpression? {
return when (this) {
is KtDotQualifiedExpression -> sizeCheckedExpression()
is KtBinaryExpression -> sizeCheckedExpression()
else -> null
}
}
private fun KtDotQualifiedExpression.sizeCheckedExpression(): KtSimpleNameExpression? {
if (!selectorExpression.isCalling(emptyCheckFunctions)) return null
return receiverExpression.safeAs<KtSimpleNameExpression>()?.takeIf { it.isCollectionOrArrayOrString() }
}
private fun KtBinaryExpression.sizeCheckedExpression(): KtSimpleNameExpression? {
if (operationToken != KtTokens.EQEQ) return null
return when {
right.isEmptyString() -> left?.sizeCheckedEmptyString()
left.isEmptyString() -> right?.sizeCheckedEmptyString()
right.isZero() -> left?.sizeCheckedEqualToZero()
left.isZero() -> right?.sizeCheckedEqualToZero()
else -> null
}
}
private fun KtExpression.sizeCheckedEmptyString(): KtSimpleNameExpression? {
return safeAs<KtSimpleNameExpression>()?.takeIf { it.isString() }
}
@Suppress("ReturnCount")
private fun KtExpression.sizeCheckedEqualToZero(): KtSimpleNameExpression? {
if (this !is KtDotQualifiedExpression) return null
val receiver = receiverExpression as? KtSimpleNameExpression ?: return null
val selector = selectorExpression ?: return null
when {
selector is KtCallExpression ->
if (!receiver.isCollectionOrArrayOrString() || !selector.isCalling(countFunctions)) return null
selector.text == "size" ->
if (!receiver.isCollectionOrArray()) return null
selector.text == "length" ->
if (!receiver.isString()) return null
}
return receiver
}
private fun KtExpression?.isNullKeyword() = this?.text == KtTokens.NULL_KEYWORD.value
private fun KtExpression?.isZero() = this?.text == "0"
private fun KtExpression?.isEmptyString() = this?.text == "\"\""
private fun KtExpression?.isCalling(fqNames: List<FqName>): Boolean {
val callExpression = this?.safeAs()
?: safeAs<KtDotQualifiedExpression>()?.selectorExpression?.safeAs<KtCallExpression>()
?: return false
return callExpression.calleeExpression?.text in fqNames.map { it.shortName().asString() } &&
callExpression.getResolvedCall(bindingContext)?.resultingDescriptor?.fqNameOrNull() in fqNames
}
private fun KtSimpleNameExpression.classFqName() = getType(bindingContext)?.fqNameOrNull()
private fun KtSimpleNameExpression.isCollectionOrArrayOrString(): Boolean {
val classFqName = classFqName() ?: return false
return classFqName() in collectionClasses || classFqName == arrayClass || classFqName == stringClass
}
private fun KtSimpleNameExpression.isCollectionOrArray(): Boolean {
val classFqName = classFqName() ?: return false
return classFqName() in collectionClasses || classFqName == arrayClass
}
private fun KtSimpleNameExpression.isString() = classFqName() == stringClass
companion object {
private val collectionClasses = listOf(
StandardNames.FqNames.list,
StandardNames.FqNames.set,
StandardNames.FqNames.collection,
StandardNames.FqNames.map,
StandardNames.FqNames.mutableList,
StandardNames.FqNames.mutableSet,
StandardNames.FqNames.mutableCollection,
StandardNames.FqNames.mutableMap,
)
private val arrayClass = StandardNames.FqNames.array.toSafe()
private val stringClass = StandardNames.FqNames.string.toSafe()
private val emptyCheckFunctions = collectionClasses.map { FqName("$it.isEmpty") } +
listOf("kotlin.collections.isEmpty", "kotlin.text.isEmpty").map(::FqName)
private val countFunctions = listOf("kotlin.collections.count", "kotlin.text.count").map(::FqName)
}
}
| apache-2.0 | 7c8db13cad48f3ae83bba21ddc036bc5 | 40.329545 | 111 | 0.696178 | 5.009642 | false | false | false | false |
wiltonlazary/kotlin-native | tools/benchmarksAnalyzer/src/main/kotlin/org/jetbrains/renders/HTMLRender.kt | 1 | 25853 | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.renders
import org.jetbrains.analyzer.*
import org.jetbrains.report.*
import kotlin.math.sin
import kotlin.math.abs
import kotlin.math.pow
private fun <T : Comparable<T>> clamp(value: T, minValue: T, maxValue: T): T =
minOf(maxOf(value, minValue), maxValue)
// Natural number.
class Natural(initValue: Int) {
val value = if (initValue > 0) initValue else error("Provided value $initValue isn't natural")
override fun toString(): String {
return value.toString()
}
}
interface Element {
fun render(builder: StringBuilder, indent: String)
}
class TextElement(val text: String) : Element {
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent$text\n")
}
}
@DslMarker
annotation class HtmlTagMarker
@HtmlTagMarker
abstract class Tag(val name: String) : Element {
val children = arrayListOf<Element>()
val attributes = hashMapOf<String, String>()
protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T {
tag.init()
children.add(tag)
return tag
}
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent<$name${renderAttributes()}>\n")
for (c in children) {
c.render(builder, indent + " ")
}
builder.append("$indent</$name>\n")
}
private fun renderAttributes(): String =
attributes.map { (attr, value) ->
"$attr=\"$value\""
}.joinToString(separator = " ", prefix = " ")
override fun toString(): String {
val builder = StringBuilder()
render(builder, "")
return builder.toString()
}
}
abstract class TagWithText(name: String) : Tag(name) {
operator fun String.unaryPlus() {
children.add(TextElement(this))
}
}
class HTML : TagWithText("html") {
fun head(init: Head.() -> Unit) = initTag(Head(), init)
fun body(init: Body.() -> Unit) = initTag(Body(), init)
}
class Head : TagWithText("head") {
fun title(init: Title.() -> Unit) = initTag(Title(), init)
fun link(init: Link.() -> Unit) = initTag(Link(), init)
fun script(init: Script.() -> Unit) = initTag(Script(), init)
}
class Title : TagWithText("title")
class Link : TagWithText("link")
class Script : TagWithText("script")
abstract class BodyTag(name: String) : TagWithText(name) {
fun b(init: B.() -> Unit) = initTag(B(), init)
fun p(init: P.() -> Unit) = initTag(P(), init)
fun h1(init: H1.() -> Unit) = initTag(H1(), init)
fun h2(init: H2.() -> Unit) = initTag(H2(), init)
fun h4(init: H4.() -> Unit) = initTag(H4(), init)
fun hr(init: HR.() -> Unit) = initTag(HR(), init)
fun a(href: String, init: A.() -> Unit) {
val a = initTag(A(), init)
a.href = href
}
fun img(src: String, init: Image.() -> Unit) {
val element = initTag(Image(), init)
element.src = src
}
fun table(init: Table.() -> Unit) = initTag(Table(), init)
fun div(classAttr: String, init: Div.() -> Unit) = initTag(Div(classAttr), init)
fun button(classAttr: String, init: Button.() -> Unit) = initTag(Button(classAttr), init)
fun header(classAttr: String, init: Header.() -> Unit) = initTag(Header(classAttr), init)
fun span(classAttr: String, init: Span.() -> Unit) = initTag(Span(classAttr), init)
}
abstract class BodyTagWithClass(name: String, val classAttr: String) : BodyTag(name) {
init {
attributes["class"] = classAttr
}
}
class Body : BodyTag("body")
class B : BodyTag("b")
class P : BodyTag("p")
class H1 : BodyTag("h1")
class H2 : BodyTag("h2")
class H4 : BodyTag("h4")
class HR : BodyTag("hr")
class Div(classAttr: String) : BodyTagWithClass("div", classAttr)
class Header(classAttr: String) : BodyTagWithClass("header", classAttr)
class Button(classAttr: String) : BodyTagWithClass("button", classAttr)
class Span(classAttr: String) : BodyTagWithClass("span", classAttr)
class A : BodyTag("a") {
var href: String by attributes
}
class Image : BodyTag("img") {
var src: String by attributes
}
abstract class TableTag(name: String) : BodyTag(name) {
fun thead(init: THead.() -> Unit) = initTag(THead(), init)
fun tbody(init: TBody.() -> Unit) = initTag(TBody(), init)
fun tfoot(init: TFoot.() -> Unit) = initTag(TFoot(), init)
}
abstract class TableBlock(name: String) : TableTag(name) {
fun tr(init: TableRow.() -> Unit) = initTag(TableRow(), init)
}
class Table : TableTag("table")
class THead : TableBlock("thead")
class TFoot : TableBlock("tfoot")
class TBody : TableBlock("tbody")
abstract class TableRowTag(name: String) : TableBlock(name) {
var colspan = Natural(1)
set(value) {
attributes["colspan"] = value.toString()
}
var rowspan = Natural(1)
set(value) {
attributes["rowspan"] = value.toString()
}
fun th(rowspan: Natural = Natural(1), colspan: Natural = Natural(1), init: TableHeadInfo.() -> Unit) {
val element = initTag(TableHeadInfo(), init)
element.rowspan = rowspan
element.colspan = colspan
}
fun td(rowspan: Natural = Natural(1), colspan: Natural = Natural(1), init: TableDataInfo.() -> Unit) {
val element = initTag(TableDataInfo(), init)
element.rowspan = rowspan
element.colspan = colspan
}
}
class TableRow : TableRowTag("tr")
class TableHeadInfo : TableRowTag("th")
class TableDataInfo : TableRowTag("td")
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
// Report render to html format.
class HTMLRender: Render() {
override val name: String
get() = "html"
override fun render (report: SummaryBenchmarksReport, onlyChanges: Boolean) =
html {
head {
title { +"Benchmarks report" }
// Links to bootstrap files.
link {
attributes["href"] = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
attributes["rel"] = "stylesheet"
}
script {
attributes["src"] = "https://code.jquery.com/jquery-3.3.1.slim.min.js"
}
script {
attributes["src"] = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"
}
script {
attributes["src"] = "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"
}
}
body {
header("navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar") {
attributes["style"] = "background-color:#161616;"
img("https://dashboard.snapcraft.io/site_media/appmedia/2018/04/256px-kotlin-logo-svg.png") {
attributes["style"] = "width:60px;height:60px;"
}
span("navbar-brand mb-0 h1") { +"Benchmarks report" }
}
div("container-fluid") {
p{}
renderEnvironmentTable(report.environments)
renderCompilerTable(report.compilers)
hr {}
renderStatusSummary(report)
hr {}
renderPerformanceSummary(report)
renderPerformanceDetails(report, onlyChanges)
}
}
}.toString()
private fun TableRowTag.formatComparedTableData(data: String, compareToData: String?) {
td {
compareToData?. let {
// Highlight changed data.
if (it != data)
attributes["bgcolor"] = "yellow"
}
if (data.isEmpty()) {
+"-"
} else {
+data
}
}
}
private fun TableTag.renderEnvironment(environment: Environment, name: String, compareTo: Environment? = null) {
tbody {
tr {
th {
attributes["scope"] = "row"
+name
}
formatComparedTableData(environment.machine.os, compareTo?.machine?.os)
formatComparedTableData(environment.machine.cpu, compareTo?.machine?.cpu)
formatComparedTableData(environment.jdk.version, compareTo?.jdk?.version)
formatComparedTableData(environment.jdk.vendor, compareTo?.jdk?.vendor)
}
}
}
private fun BodyTag.renderEnvironmentTable(environments: Pair<Environment, Environment?>) {
h4 { +"Environment" }
table {
attributes["class"] = "table table-sm table-bordered table-hover"
attributes["style"] = "width:initial;"
val firstEnvironment = environments.first
val secondEnvironment = environments.second
// Table header.
thead {
tr {
th(rowspan = Natural(2)) { +"Run" }
th(colspan = Natural(2)) { +"Machine" }
th(colspan = Natural(2)) { +"JDK" }
}
tr {
th { + "OS" }
th { + "CPU" }
th { + "Version"}
th { + "Vendor"}
}
}
renderEnvironment(firstEnvironment, "First")
secondEnvironment?. let { renderEnvironment(it, "Second", firstEnvironment) }
}
}
private fun TableTag.renderCompiler(compiler: Compiler, name: String, compareTo: Compiler? = null) {
tbody {
tr {
th {
attributes["scope"] = "row"
+name
}
formatComparedTableData(compiler.backend.type.type, compareTo?.backend?.type?.type)
formatComparedTableData(compiler.backend.version, compareTo?.backend?.version)
formatComparedTableData(compiler.backend.flags.joinToString(), compareTo?.backend?.flags?.joinToString())
formatComparedTableData(compiler.kotlinVersion, compareTo?.kotlinVersion)
}
}
}
private fun BodyTag.renderCompilerTable(compilers: Pair<Compiler, Compiler?>) {
h4 { +"Compiler" }
table {
attributes["class"] = "table table-sm table-bordered table-hover"
attributes["style"] = "width:initial;"
val firstCompiler = compilers.first
val secondCompiler = compilers.second
// Table header.
thead {
tr {
th(rowspan = Natural(2)) { +"Run" }
th(colspan = Natural(3)) { +"Backend" }
th(rowspan = Natural(2)) { +"Kotlin" }
}
tr {
th { + "Type" }
th { + "Version" }
th { + "Flags"}
}
}
renderCompiler(firstCompiler, "First")
secondCompiler?. let { renderCompiler(it, "Second", firstCompiler) }
}
}
private fun TableBlock.renderBucketInfo(bucket: Collection<Any>, name: String) {
if (!bucket.isEmpty()) {
tr {
th {
attributes["scope"] = "row"
+name
}
td {
+"${bucket.size}"
}
}
}
}
private fun BodyTag.renderCollapsedData(name: String, isCollapsed: Boolean = false, colorStyle: String = "",
init: BodyTag.() -> Unit) {
val show = if (!isCollapsed) "show" else ""
val tagName = name.replace(' ', '_')
div("accordion") {
div("card") {
attributes["style"] = "border-bottom: 1px solid rgba(0,0,0,.125);"
div("card-header") {
attributes["id"] = "heading"
attributes["style"] = "padding: 0;$colorStyle"
button("btn btn-link") {
attributes["data-toggle"] = "collapse"
attributes["data-target"] = "#$tagName"
+name
}
}
div("collapse $show") {
attributes["id"] = tagName
div("accordion-inner") {
init()
}
}
}
}
}
private fun TableTag.renderTableFromList(list: List<String>, name: String) {
if (!list.isEmpty()) {
thead {
tr {
th { +name }
}
}
list.forEach {
tbody {
tr {
td { +it }
}
}
}
}
}
private fun BodyTag.renderStatusSummary(report: SummaryBenchmarksReport) {
h4 { +"Status Summary" }
val failedBenchmarks = report.failedBenchmarks
if (failedBenchmarks.isEmpty()) {
div("alert alert-success") {
attributes["role"] = "alert"
+"All benchmarks passed!"
}
} else {
div("alert alert-danger") {
attributes["role"] = "alert"
+"There are failed benchmarks!"
}
}
val benchmarksWithChangedStatus = report.getBenchmarksWithChangedStatus()
val newFailures = benchmarksWithChangedStatus
.filter { it.current == BenchmarkResult.Status.FAILED }
val newPasses = benchmarksWithChangedStatus
.filter { it.current == BenchmarkResult.Status.PASSED }
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
thead {
tr {
th { +"Status Group" }
th { +"#" }
}
}
tbody {
renderBucketInfo(failedBenchmarks, "Failed (total)")
renderBucketInfo(newFailures, "New Failures")
renderBucketInfo(newPasses, "New Passes")
renderBucketInfo(report.addedBenchmarks, "Added")
renderBucketInfo(report.removedBenchmarks, "Removed")
}
tfoot {
tr {
th { +"Total becnhmarks number" }
th { +"${report.benchmarksNumber}" }
}
}
}
if (!failedBenchmarks.isEmpty()) {
renderCollapsedData("Failures", colorStyle = "background-color: lightpink") {
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
val newFailuresList = newFailures.map { it.field }
renderTableFromList(newFailuresList, "New Failures")
val existingFailures = failedBenchmarks.filter { it !in newFailuresList }
renderTableFromList(existingFailures, "Existing Failures")
}
}
}
if (!newPasses.isEmpty()) {
renderCollapsedData("New Passes", colorStyle = "background-color: lightgreen") {
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
renderTableFromList(newPasses.map { it.field }, "New Passes")
}
}
}
if (!report.addedBenchmarks.isEmpty()) {
renderCollapsedData("Added", true) {
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
renderTableFromList(report.addedBenchmarks, "Added benchmarks")
}
}
}
if (!report.removedBenchmarks.isEmpty()) {
renderCollapsedData("Removed", true) {
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial; font-size: 11pt;"
renderTableFromList(report.removedBenchmarks, "Removed benchmarks")
}
}
}
}
private fun BodyTag.renderPerformanceSummary(report: SummaryBenchmarksReport) {
if (!report.improvements.isEmpty() || !report.regressions.isEmpty()) {
h4 { +"Performance Summary" }
table {
attributes["class"] = "table table-sm table-striped table-hover"
attributes["style"] = "width:initial;"
thead {
tr {
th { +"Change" }
th { +"#" }
th { +"Maximum" }
th { +"Geometric mean" }
}
}
val maximumRegression = report.maximumRegression
val maximumImprovement = report.maximumImprovement
val regressionsGeometricMean = report.regressionsGeometricMean
val improvementsGeometricMean = report.improvementsGeometricMean
tbody {
if (!report.regressions.isEmpty()) {
tr {
th { +"Regressions" }
td { +"${report.regressions.size}" }
td {
attributes["bgcolor"] = ColoredCell(
maximumRegression/maxOf(maximumRegression, abs(maximumImprovement)))
.backgroundStyle
+formatValue(maximumRegression, true)
}
td {
attributes["bgcolor"] = ColoredCell(
regressionsGeometricMean/maxOf(regressionsGeometricMean,
abs(improvementsGeometricMean)))
.backgroundStyle
+formatValue(report.regressionsGeometricMean, true)
}
}
}
if (!report.improvements.isEmpty()) {
tr {
th { +"Improvements" }
td { +"${report.improvements.size}" }
td {
attributes["bgcolor"] = ColoredCell(
maximumImprovement/maxOf(maximumRegression, abs(maximumImprovement)))
.backgroundStyle
+formatValue(report.maximumImprovement, true)
}
td {
attributes["bgcolor"] = ColoredCell(
improvementsGeometricMean/maxOf(regressionsGeometricMean,
abs(improvementsGeometricMean)))
.backgroundStyle
+formatValue(report.improvementsGeometricMean, true)
}
}
}
}
}
}
}
private fun TableBlock.renderBenchmarksDetails(fullSet: Map<String, SummaryBenchmark>,
bucket: Map<String, ScoreChange>? = null, rowStyle: String? = null) {
if (bucket != null && !bucket.isEmpty()) {
// Find max ratio.
val maxRatio = bucket.values.map { it.second.mean }.maxOrNull()!!
// There are changes in performance.
// Output changed benchmarks.
for ((name, change) in bucket) {
tr {
rowStyle?. let {
attributes["style"] = rowStyle
}
th { +name }
td { +"${fullSet.getValue(name).first?.description}" }
td { +"${fullSet.getValue(name).second?.description}" }
td {
attributes["bgcolor"] = ColoredCell(if (bucket.values.first().first.mean == 0.0) null
else change.first.mean / abs(bucket.values.first().first.mean))
.backgroundStyle
+"${change.first.description + " %"}"
}
td {
val scaledRatio = if (maxRatio == 0.0) null else change.second.mean / maxRatio
attributes["bgcolor"] = ColoredCell(scaledRatio,
borderPositive = { cellValue -> cellValue > 1.0 / maxRatio }).backgroundStyle
+"${change.second.description}"
}
}
}
} else if (bucket == null) {
// Output all values without performance changes.
val placeholder = "-"
for ((name, value) in fullSet) {
tr {
th { +name }
td { +"${value.first?.description ?: placeholder}" }
td { +"${value.second?.description ?: placeholder}" }
td { +placeholder }
td { +placeholder }
}
}
}
}
private fun BodyTag.renderPerformanceDetails(report: SummaryBenchmarksReport, onlyChanges: Boolean) {
if (onlyChanges) {
if (report.regressions.isEmpty() && report.improvements.isEmpty()) {
div("alert alert-success") {
attributes["role"] = "alert"
+"All becnhmarks are stable!"
}
}
}
table {
attributes["id"] = "result"
attributes["class"] = "table table-striped table-bordered"
thead {
tr {
th { +"Benchmark" }
th { +"First score" }
th { +"Second score" }
th { +"Percent" }
th { +"Ratio" }
}
}
val geoMeanChangeMap = report.geoMeanScoreChange?.
let { mapOf(report.geoMeanBenchmark.first!!.name to report.geoMeanScoreChange!!) }
tbody {
renderBenchmarksDetails(
mutableMapOf(report.geoMeanBenchmark.first!!.name to report.geoMeanBenchmark),
geoMeanChangeMap, "border-bottom: 2.3pt solid black; border-top: 2.3pt solid black")
renderBenchmarksDetails(report.mergedReport, report.regressions)
renderBenchmarksDetails(report.mergedReport, report.improvements)
if (!onlyChanges) {
// Print all remaining results.
renderBenchmarksDetails(report.mergedReport.filter { it.key !in report.regressions.keys &&
it.key !in report.improvements.keys })
}
}
}
}
data class Color(val red: Double, val green: Double, val blue: Double) {
operator fun times(coefficient: Double) =
Color(red * coefficient, green * coefficient, blue * coefficient)
operator fun plus(other: Color) =
Color(red + other.red, green + other.green, blue + other.blue)
override fun toString() =
"#" + buildString {
listOf(red, green, blue).forEach {
append(clamp((it * 255).toInt(), 0, 255).toString(16).padStart(2, '0'))
}
}
}
class ColoredCell(val scaledValue: Double?, val reverse: Boolean = false,
val borderPositive: (cellValue: Double) -> Boolean = { cellValue -> cellValue > 0 }) {
val value: Double
val neutralColor = Color(1.0,1.0 , 1.0)
val negativeColor = Color(0.0, 1.0, 0.0)
val positiveColor = Color(1.0, 0.0, 0.0)
init {
value = scaledValue?.let { if (abs(scaledValue) <= 1.0) scaledValue else error ("Value should be scaled in range [-1.0; 1.0]") }
?: 0.0
}
val backgroundStyle: String
get() = scaledValue?.let { getColor().toString() } ?: ""
fun getColor(): Color {
val currentValue = clamp(value, -1.0, 1.0)
val cellValue = if (reverse) -currentValue else currentValue
val baseColor = if (borderPositive(cellValue)) positiveColor else negativeColor
// Smooth mapping to put first 20% of change into 50% of range,
// although really we should compensate for luma.
val color = sin((abs(cellValue).pow(.477)) * kotlin.math.PI * .5)
return linearInterpolation(neutralColor, baseColor, color)
}
private fun linearInterpolation(a: Color, b: Color, coefficient: Double): Color {
val reversedCoefficient = 1.0 - coefficient
return a * reversedCoefficient + b * coefficient
}
}
} | apache-2.0 | bfdfe9a163c2797710a37eea77587581 | 37.473214 | 140 | 0.504197 | 4.791142 | false | false | false | false |
bihe/mydms-java | Api/src/main/kotlin/net/binggl/mydms/features/filestore/model/FileItem.kt | 1 | 786 | package net.binggl.mydms.features.filestore.model
data class FileItem(val fileName: String, val mimeType: String,
val payload: Array<Byte>, val folderName: String) {
override fun equals(other: Any?): Boolean {
if (other is FileItem) {
if (other.fileName == this.fileName &&
other.folderName == this.folderName &&
other.mimeType == this.mimeType &&
other.payload.size == this.payload.size) {
return true
}
}
return false
}
override fun hashCode(): Int {
var result = fileName.hashCode()
result = 31 * result + mimeType.hashCode()
result = 31 * result + folderName.hashCode()
return result
}
} | apache-2.0 | 69cdb8ec0010136521c095dc80b5d0c9 | 31.791667 | 71 | 0.553435 | 4.822086 | false | false | false | false |
iovation/launchkey-android-whitelabel-sdk | demo-app/app/src/kotlinApp/java/com/launchkey/android/authenticator/demo/push/PushMessagingService.kt | 2 | 4183 | package com.launchkey.android.authenticator.demo.push
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.launchkey.android.authenticator.demo.R
import com.launchkey.android.authenticator.demo.ui.activity.ListDemoActivity
import com.launchkey.android.authenticator.sdk.core.authentication_management.AuthenticatorManager
class PushMessagingService : FirebaseMessagingService() {
override fun onNewToken(newToken: String) {
super.onNewToken(newToken)
Log.i(PushMessagingService::class.java.simpleName, "newToken=$newToken")
// If this method is called, the push token has changed and the LK API
// has to be notified.
AuthenticatorManager.instance.setPushDeviceToken(newToken)
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
notifyOfRequest(remoteMessage.notification)
AuthenticatorManager.instance.handlePushPayload(remoteMessage.data)
}
private fun notifyOfRequest(optionalPushNotification: RemoteMessage.Notification?) {
val context = applicationContext
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val tapIntent = Intent(context, ListDemoActivity::class.java)
tapIntent.putExtra(ListDemoActivity.EXTRA_SHOW_REQUEST, true)
val tapPendingIntent = PendingIntent.getActivity(context, 1, tapIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val channelId = createAndGetNotificationChannel(context, notificationManager)
// Check if a push notification has defined a notification and use its title and body instead
var title: String? = null
var body: String? = null
if (optionalPushNotification != null) {
title = optionalPushNotification.title
body = optionalPushNotification.body
}
if (title == null) {
title = context.getString(R.string.app_name)
}
if (body == null) {
body = context.getString(R.string.demo_notification_message)
}
val notification = NotificationCompat.Builder(context, channelId)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSmallIcon(R.drawable.ic_stat_logo)
.setColor(ContextCompat.getColor(context, R.color.demo_primary))
.setContentTitle(title)
.setContentText(body)
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
.setContentIntent(tapPendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true)
.build()
notificationManager.notify(NOTIFICATION_ID, notification)
}
private fun createAndGetNotificationChannel(context: Context, notificationManager: NotificationManager): String {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name: CharSequence = context.getString(R.string.demo_notification_channel_authrequests_name)
val desc = context.getString(R.string.demo_notification_channel_authrequests_desc)
val importance = NotificationManager.IMPORTANCE_HIGH
val id = context.getString(R.string.demo_notification_channel_authrequests_id)
val channel = NotificationChannel(id, name, importance)
channel.description = desc
channel.importance = NotificationManager.IMPORTANCE_HIGH
channel.setShowBadge(true)
channel.enableLights(true)
channel.enableVibration(true)
notificationManager.createNotificationChannel(channel)
return id
}
return "none"
}
companion object {
const val NOTIFICATION_ID = 100
}
} | mit | 68175b11f65ba92d1ce907643815e422 | 46.011236 | 117 | 0.710495 | 5.076456 | false | false | false | false |
vindkaldr/libreplicator | libreplicator-core/src/test/kotlin/org/libreplicator/core/wrapper/DefaultPayloadWrapperTest.kt | 2 | 2162 | /*
* Copyright (C) 2016 Mihály Szabó
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplicator.core.wrapper
import org.hamcrest.Matchers.equalTo
import org.junit.Assert.assertThat
import org.junit.Test
import org.libreplicator.core.testdouble.JsonMapperStub
import org.libreplicator.core.wrapper.api.PayloadWrapper
import org.libreplicator.core.wrapper.testdouble.CipherStub
import org.libreplicator.core.model.ReplicatorMessage
import org.libreplicator.core.model.ReplicatorPayload
import org.libreplicator.core.model.TimeTable
private val payload = ReplicatorPayload("", emptyList(), TimeTable())
private const val serializedPayload = "serializedReplicatorPayload"
private const val encryptedSerializedPayload = "encryptedSerializedReplicatorMessage"
private const val groupId = "groupId"
private val message = ReplicatorMessage(groupId, encryptedSerializedPayload)
private val jsonMapperStub = JsonMapperStub(payload to serializedPayload)
private val cipherStub = CipherStub(serializedPayload to encryptedSerializedPayload)
private val payloadWrapper: PayloadWrapper = DefaultPayloadWrapper(groupId, jsonMapperStub, cipherStub)
class DefaultPayloadWrapperTest {
@Test
fun `wrap creates message from serialized and encrypted payload`() {
assertThat(payloadWrapper.wrap(payload), equalTo(message))
}
@Test
fun `unwrap returns decrypted and deserialized payload from message`() {
assertThat(payloadWrapper.unwrap(message), equalTo(payload))
}
}
| gpl-3.0 | c1e225d7616f1711280ae07e4828e48c | 40.538462 | 103 | 0.776389 | 4.481328 | false | true | false | false |
sinnerschrader/account-tool | src/main/kotlin/com/sinnerschrader/s2b/accounttool/config/authentication/LdapAuthenticationDetails.kt | 1 | 971 | package com.sinnerschrader.s2b.accounttool.config.authentication
import org.springframework.security.web.authentication.WebAuthenticationDetails
import java.nio.charset.StandardCharsets
import java.util.*
import javax.servlet.http.HttpServletRequest
class LdapAuthenticationDetails
internal constructor(request: HttpServletRequest,
dn: (uid: String) -> String) : WebAuthenticationDetails(request) {
val username = request.basicAuth()?.first ?: request.getParameter("uid")
val password = request.basicAuth()?.second ?: request.getParameter("password")
val userDN = dn.invoke(username)
private fun HttpServletRequest.basicAuth() = try{
with(getHeader("Authorization").substring("Basic ".length).trim()) {
String(Base64.getDecoder().decode(this), StandardCharsets.UTF_8).split(":", limit=2).let {
it[0] to it[1]
}
}
} catch (e: java.lang.Exception) {
null
}
}
| mit | f00fcc89acb4c94b12edd8a60299241e | 36.346154 | 102 | 0.6931 | 4.474654 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/map/render/mapbox/grid/loader/GridsLoader.kt | 1 | 7545 | package com.telenav.osv.map.render.mapbox.grid.loader
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.geometry.LatLngBounds
import com.telenav.osv.network.GenericJarvisApiErrorHandler
import com.telenav.osv.network.GenericJarvisApiErrorHandlerListener
import com.telenav.osv.tasks.model.Task
import com.telenav.osv.tasks.usecases.FetchAssignedTasksUseCase
import com.telenav.osv.utils.Log
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.lang.Exception
/**
* Handles the load logic for the grids. This will apply a 3 bounding box system where the current bounding box (visible screen size) is checked against a minimum threshold bounding box and a maximum threshold bounding box.
* If any of the corners intersect the maximum threshold bbox the grids load trigger will be performed.
*
* The MTB (Maximum Threshold Bbox) will contain the bbox used for grid load, always, the current and minimal bboxes are only used for triggering load logic.
*/
class GridsLoader(private val fetchAssignedTasksUseCase: FetchAssignedTasksUseCase, private val genericJarvisApiErrorHandler: GenericJarvisApiErrorHandler) {
init {
TAG = GridsLoader::class.java.simpleName
clear()
}
private lateinit var disposables: CompositeDisposable
private var minimumThresholdBBox: LatLngBounds? = null
private var maximumThresholdBBox: LatLngBounds? = null
private var coefficientX = 0.0
private var coefficientY = 0.0
/**
* Loads the grids if the bellow logic is passed. This will either trigger the [successCallback] or the [errorCallback] based on the api response.
*
* The [visibleRegion] will be checked against the calculated [minimumThresholdBBox] and [maximumThresholdBBox], based on this the trigger for load will be when:
* * [maximumThresholdBBox] is empty
* * [visibleRegion] is outside [minimumThresholdBBox] meaning is entirely in the [maximumThresholdBBox]
* * [visibleRegion] points intersect any [maximumThresholdBBox] points
* @param visibleRegion the visible region representing the bounding box of the screen
* @param currentUserLocation the current user location which will be used to calculate [minimumThresholdBBox] and [maximumThresholdBBox]
* @param successCallback the callback used for a success grid load request
* @param errorCallback the callback used for error grid load request
* @param forceLoad the status which if set it will trigger a load without any checks
*/
fun loadIfNecessary(visibleRegion: LatLngBounds, currentUserLocation: LatLng, successCallback: (List<Task>) -> Unit, errorCallback: (Throwable) -> Unit, forceLoad: Boolean = false) {
if (maximumThresholdBBox == null || forceLoad) {
Log.d(TAG, "loadIfNecessary. Status: Load data. Force load: $forceLoad. Maximum threshold: $maximumThresholdBBox.")
reloadBoundingBox(visibleRegion, currentUserLocation)
loadGrids(successCallback, errorCallback)
return
}
if (minimumThresholdBBox != null) {
val minIntersection = visibleRegion.intersect(minimumThresholdBBox!!)
if (minIntersection == null || minIntersection != visibleRegion) {
Log.d(TAG, "loadIfNecessary. Status: Loading grids. Message: Visible region intersect max region.")
reloadBoundingBox(visibleRegion, currentUserLocation)
loadGrids(successCallback, errorCallback)
return
}
}
Log.d(TAG, "loadIfNecessary. Status: Ignoring grids request. Message: Visible region does not intersect with max region.")
}
/**
* Clears the resources from the grids setting them at the initial state.
*/
fun clear() {
disposables = CompositeDisposable()
minimumThresholdBBox = null
maximumThresholdBBox = null
coefficientX = 0.0
coefficientY = 0.0
}
private fun calculateCoefficient(bboxCoordinate: Double, currentUserCoordinate: Double): Double {
var coefficient = bboxCoordinate - currentUserCoordinate
if (coefficient < 0.0) {
coefficient *= SIGN_CHANGE_VALUE
}
return coefficient
}
private fun loadGrids(successCallback: (List<Task>) -> Unit, errorCallback: (Throwable) -> Unit) {
maximumThresholdBBox?.let { bounds ->
disposables.add(fetchAssignedTasksUseCase
.fetchTasks(bounds.northEast.latitude, bounds.northEast.longitude, bounds.southWest.latitude, bounds.southWest.longitude)
.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(
{
successCallback(it)
},
{
onGridsLoadHandleError(it, successCallback, errorCallback)
}))
}
}
private fun onGridsLoadHandleError(it: Throwable, successCallback: (List<Task>) -> Unit, errorCallback: (Throwable) -> Unit) {
genericJarvisApiErrorHandler.onError(
it,
object : GenericJarvisApiErrorHandlerListener {
override fun onRefreshTokenSuccess() {
loadGrids(successCallback, errorCallback)
}
override fun onError() {
successCallback(listOf())
}
override fun reLogin() {
Log.d(TAG, "onGridsLoadHandleError. Status: error. Message: ${it.message}.")
errorCallback(it)
}
},
disposables)
}
private fun reloadBoundingBox(visibleRegion: LatLngBounds, currentUserLocation: LatLng) {
coefficientX = calculateCoefficient(visibleRegion.lonEast, currentUserLocation.longitude)
coefficientY = calculateCoefficient(visibleRegion.latNorth, currentUserLocation.latitude)
minimumThresholdBBox = loadThreshold(THRESHOLD_MULTIPLIER_MIN, currentUserLocation)
maximumThresholdBBox = loadThreshold(THRESHOLD_MULTIPLIER_MAX, currentUserLocation)
Log.d(TAG, "reloadBoundingBox. Status: reload data. CoefficientX: $coefficientX. CoefficientY: $coefficientY. Minimum Bbox: $minimumThresholdBBox. Maximum BBOX: $maximumThresholdBBox")
}
private fun loadThreshold(thresholdMultiplier: Int, currentUserLocation: LatLng): LatLngBounds? {
val newLatitudeValue = coefficientY * thresholdMultiplier
val newLongitudeValue = coefficientX * thresholdMultiplier
var newLatLngBounds: LatLngBounds? = null
try {
newLatLngBounds = LatLngBounds.from(currentUserLocation.latitude + newLatitudeValue, currentUserLocation.longitude + newLongitudeValue, currentUserLocation.latitude - newLatitudeValue, currentUserLocation.longitude - newLongitudeValue)
} catch (e: Exception) {
Log.d(TAG, "loadThreshold. Status: error. Message: ${e.message}")
}
return newLatLngBounds
}
private companion object {
private const val THRESHOLD_MULTIPLIER_MIN = 3
private const val THRESHOLD_MULTIPLIER_MAX = 5
private const val SIGN_CHANGE_VALUE = -1
private lateinit var TAG: String
}
} | lgpl-3.0 | 1a3dead597fa6f0228fb2f9912d75130 | 48.320261 | 247 | 0.682174 | 5.199862 | false | false | false | false |
BitPrepared/login-app | app/src/main/java/it/bitprepared/loginapp/StartActivity.kt | 1 | 3179 | package it.bitprepared.loginapp
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_start.*
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.IOException
class StartActivity : AppCompatActivity() {
private val scoutList: MutableList<Scout> = mutableListOf()
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.start_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == R.id.menu_reset) {
resetInputForm()
}
return super.onOptionsItemSelected(item)
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_start)
scoutList.addAll(loadJsonFile())
button_login.setOnClickListener { _ ->
// Check if name/surname are inside the JSON File
val result = scoutList.firstOrNull {
it.isTheSamePerson(edit_name.text.toString(), edit_surname.text.toString())
}
if (result == null) {
showErrorMessage()
} else {
openResultActivity(result.sq)
}
}
}
private fun showErrorMessage() {
error_message.visibility = View.VISIBLE
}
private fun openResultActivity(value: String) {
val intent = Intent(this@StartActivity, ResultActivity::class.java)
intent.putExtra(KEY_RESULT_SQ, value)
startActivity(intent)
}
private fun resetInputForm() {
edit_name.setText("")
edit_surname.setText("")
error_message.visibility = View.GONE
}
private fun loadJsonFile(): List<Scout> {
val scout = mutableListOf<Scout>()
val inputStream = resources.openRawResource(R.raw.ragazzi)
val byteArrayOutputStream = ByteArrayOutputStream()
var ctr: Int
try {
ctr = inputStream.read()
while (ctr != -1) {
byteArrayOutputStream.write(ctr)
ctr = inputStream.read()
}
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
try {
// Parse the data into JSONObject to get original data in form of json.
val jObject = JSONObject(byteArrayOutputStream.toString())
val jObjectResult = jObject.getJSONArray("ragazzi")
for (i in 0 until jObjectResult.length()) {
scout.add(Scout(
jObjectResult.getJSONObject(i).getString("nome"),
jObjectResult.getJSONObject(i).getString("cognome"),
jObjectResult.getJSONObject(i).getString("squadriglia")))
}
} catch (e: Exception) {
throw RuntimeException("Failure during JSON Parsing!", e)
}
return scout
}
}
| gpl-2.0 | ed205a4c75b71720a813641969188bb8 | 31.438776 | 91 | 0.616232 | 4.846037 | false | false | false | false |
ejeinc/VR-MultiView-UDP | common-messaging/src/main/java/com/eje_c/multilink/udp/UdpSocketService.kt | 1 | 1174 | package com.eje_c.multilink.udp
import android.app.Service
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Binder
import android.os.IBinder
import android.util.Log
class UdpSocketService : Service() {
private val tag = "UdpSocketService"
private lateinit var lock: WifiManager.MulticastLock
lateinit var udpSocket: UdpSocket
inner class LocalBinder : Binder() {
val service: UdpSocketService
get() = this@UdpSocketService
}
override fun onCreate() {
super.onCreate()
Log.d(tag, "onCreate")
// Enable multicast/broadcast
val wifi = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
lock = wifi.createMulticastLock("lock")
lock.acquire()
udpSocket = UdpSocket(port = MultiLinkUdpMessenger.broadcastPort)
}
override fun onDestroy() {
Log.d(tag, "onDestroy")
udpSocket.release()
lock.release()
super.onDestroy()
}
override fun onBind(intent: Intent): IBinder {
Log.d(tag, "onBind")
return LocalBinder()
}
} | apache-2.0 | 217add67a411eb6e9bbea4b3bf1764a0 | 22.5 | 91 | 0.67121 | 4.269091 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/timeTracker/actions/PauseTrackerAction.kt | 1 | 1442 | package com.github.jk1.ytplugin.timeTracker.actions
import com.github.jk1.ytplugin.ComponentAware
import com.github.jk1.ytplugin.ui.YouTrackPluginIcons
import com.github.jk1.ytplugin.whenActive
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
class PauseTrackerAction : AnAction(
"Pause Work Timer",
"Pause work timer for ongoing task tracking",
YouTrackPluginIcons.YOUTRACK_PAUSE_TIME_TRACKER) {
override fun actionPerformed(event: AnActionEvent) {
event.whenActive {project ->
val timer = ComponentAware.of(project).timeTrackerComponent
if (timer.isAutoTrackingEnabled) {
timer.isAutoTrackingTemporaryDisabled = true
}
timer.pause("Work timer paused")
val store: PropertiesComponent = PropertiesComponent.getInstance(project)
store.saveFields(timer)
}
}
override fun update(event: AnActionEvent) {
val project = event.project
if (project != null) {
val timer = ComponentAware.of(event.project!!).timeTrackerComponent
event.presentation.isVisible = (!timer.isPaused && timer.isRunning
&& (timer.isManualTrackingEnabled || timer.isAutoTrackingEnabled)) &&
!timer.isAutoTrackingTemporaryDisabled
}
}
} | apache-2.0 | 4f2064a5d7b9d60b7cec92290f1ad782 | 38 | 89 | 0.68724 | 4.855219 | false | false | false | false |
McGars/basekitk | app/src/main/java/com/mcgars/basekitkotlin/tabs/TabsViewController.kt | 1 | 2012 | package com.mcgars.basekitkotlin.tabs
import android.view.View
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.support.RouterPagerAdapter
import com.mcgars.basekitk.features.base.BaseViewController
import com.mcgars.basekitk.tools.pagecontroller.ExTabs
import com.mcgars.basekitkotlin.R
import com.mcgars.basekitkotlin.sample.EmptyViewController
import kotlinx.android.synthetic.main.view_pager.view.*
import com.mcgars.basekitk.animatorHandlers.CircularRevealChangeHandler
import com.mcgars.basekitk.animatorHandlers.CircularRevealChangeHandlerCompat
/**
* Created by Владимир on 12.01.2017.
*/
@ExTabs
class TabsViewController : BaseViewController() {
override fun getLayoutId() = R.layout.view_pager
override fun getTitleInt() = R.string.feature_toolbar_tabs
init {
// animation
overridePushHandler(CircularRevealChangeHandlerCompat().apply {
halfPosition = CircularRevealChangeHandler.RIGHT_CENTER
})
overridePopHandler(CircularRevealChangeHandlerCompat().apply {
halfPosition = CircularRevealChangeHandler.RIGHT_CENTER
})
}
val pagerAdapter: RouterPagerAdapter by lazy {
object : RouterPagerAdapter(this) {
override fun configureRouter(router: Router, position: Int) {
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(
EmptyViewController("page: $position", true)
))
}
}
override fun getCount() = 3
override fun getPageTitle(position: Int) = "Page " + position
}
}
override fun onReady(view: View) {
view.viewPager.adapter = pagerAdapter
tabs?.setupWithViewPager(view.viewPager)
}
override fun onDestroyView(view: View) {
super.onDestroyView(view)
view.viewPager.adapter = null
}
} | apache-2.0 | b3d168614120dfc62ed0ac5897671dfd | 30.825397 | 77 | 0.694112 | 4.8523 | false | false | false | false |
applivery/applivery-android-sdk | applvsdklib/src/main/java/com/applivery/applvsdklib/domain/login/UnBindUserInteractor.kt | 1 | 2159 | /*
* Copyright (c) 2019 Applivery
*
* 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.applivery.applvsdklib.domain.login
import android.util.Log
import com.applivery.applvsdklib.domain.model.ErrorObject
import com.applivery.applvsdklib.tools.executor.InteractorExecutor
import com.applivery.applvsdklib.tools.executor.MainThread
import com.applivery.base.domain.PreferencesManager
import com.applivery.base.domain.SessionManager
import java.io.IOException
class UnBindUserInteractor(
private val interactorExecutor: InteractorExecutor,
private val mainThread: MainThread,
private val sessionManager: SessionManager,
private val preferencesManager: PreferencesManager
) : Runnable {
lateinit var onSuccess: () -> Unit
lateinit var onError: (error: ErrorObject) -> Unit
fun unBindUser(
onSuccess: () -> Unit = {},
onError: (error: ErrorObject) -> Unit = {}
) {
this.onSuccess = onSuccess
this.onError = onError
interactorExecutor.run(this)
}
override fun run() {
try {
sessionManager.clearSession()
preferencesManager.anonymousEmail = null
notifySuccess()
} catch (exception: IOException) {
Log.e(TAG, "unBindUser() -> ${exception.message}")
notifyError(ErrorObject())
}
}
private fun notifySuccess() {
mainThread.execute(Runnable { onSuccess() })
}
private fun notifyError(error: ErrorObject) {
mainThread.execute(Runnable { onError(error) })
}
companion object {
private const val TAG = "UnBindUserInteractor"
}
}
| apache-2.0 | 54dc694411cd6bc5be0affb78e1757e5 | 30.289855 | 75 | 0.696156 | 4.583864 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/FadingViewPager.kt | 2 | 1425 | package com.habitrpg.android.habitica.ui.views
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.viewpager.widget.ViewPager
import kotlin.math.abs
class FadingViewPager : ViewPager {
var disableFading: Boolean = false
constructor(context: Context) : super(context) {
setTransformer()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
setTransformer()
}
private fun setTransformer() {
this.setPageTransformer(true) { page, position ->
page.translationX = page.width * -position
if (position <= -1.0f || position >= 1.0f) {
page.alpha = 0.0f
page.visibility = View.INVISIBLE
} else if (position == 0.0f) {
page.visibility = View.VISIBLE
page.alpha = 1.0f
} else {
if (disableFading) {
return@setPageTransformer
}
page.visibility = View.VISIBLE
// position is between -1.0F & 0.0F OR 0.0F & 1.0F
page.alpha = 1.0f - abs(position)
}
}
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
return false
}
override fun onInterceptHoverEvent(event: MotionEvent): Boolean {
return false
}
}
| gpl-3.0 | fe4d6334d1f63136640ee8851a21b572 | 28.081633 | 80 | 0.587368 | 4.384615 | false | false | false | false |
google/dokka | core/src/main/kotlin/Model/Content.kt | 1 | 9050 | package org.jetbrains.dokka
interface ContentNode {
val textLength: Int
}
object ContentEmpty : ContentNode {
override val textLength: Int get() = 0
}
open class ContentBlock() : ContentNode {
open val children = arrayListOf<ContentNode>()
fun append(node: ContentNode) {
children.add(node)
}
fun isEmpty() = children.isEmpty()
override fun equals(other: Any?): Boolean =
other is ContentBlock && javaClass == other.javaClass && children == other.children
override fun hashCode(): Int =
children.hashCode()
override val textLength: Int
get() = children.sumBy { it.textLength }
}
class NodeRenderContent(
val node: DocumentationNode,
val mode: LanguageService.RenderMode
): ContentNode {
override val textLength: Int
get() = 0 //TODO: Clarify?
}
class LazyContentBlock(private val fillChildren: (ContentBlock) -> Unit) : ContentBlock() {
private var computed = false
override val children: ArrayList<ContentNode>
get() {
if (!computed) {
computed = true
fillChildren(this)
}
return super.children
}
override fun equals(other: Any?): Boolean {
return other is LazyContentBlock && other.fillChildren == fillChildren && super.equals(other)
}
override fun hashCode(): Int {
return super.hashCode() + 31 * fillChildren.hashCode()
}
}
enum class IdentifierKind {
TypeName,
ParameterName,
AnnotationName,
SummarizedTypeName,
Other
}
data class ContentText(val text: String) : ContentNode {
override val textLength: Int
get() = text.length
}
data class ContentKeyword(val text: String) : ContentNode {
override val textLength: Int
get() = text.length
}
data class ContentIdentifier(val text: String,
val kind: IdentifierKind = IdentifierKind.Other,
val signature: String? = null) : ContentNode {
override val textLength: Int
get() = text.length
}
data class ContentSymbol(val text: String) : ContentNode {
override val textLength: Int
get() = text.length
}
data class ContentEntity(val text: String) : ContentNode {
override val textLength: Int
get() = text.length
}
object ContentNonBreakingSpace: ContentNode {
override val textLength: Int
get() = 1
}
object ContentSoftLineBreak: ContentNode {
override val textLength: Int
get() = 0
}
object ContentIndentedSoftLineBreak: ContentNode {
override val textLength: Int
get() = 0
}
class ContentParagraph() : ContentBlock()
class ContentEmphasis() : ContentBlock()
class ContentStrong() : ContentBlock()
class ContentStrikethrough() : ContentBlock()
class ContentCode() : ContentBlock()
class ContentDescriptionList() : ContentBlock()
class ContentDescriptionTerm() : ContentBlock()
class ContentDescriptionDefinition() : ContentBlock()
class ContentTable() : ContentBlock()
class ContentTableBody() : ContentBlock()
class ContentTableRow() : ContentBlock()
class ContentTableHeader(val colspan: String? = null, val rowspan: String? = null) : ContentBlock()
class ContentTableCell(val colspan: String? = null, val rowspan: String? = null) : ContentBlock()
class ContentSpecialReference() : ContentBlock()
open class ContentBlockCode(val language: String = "") : ContentBlock()
class ContentBlockSampleCode(language: String = "kotlin", val importsBlock: ContentBlockCode = ContentBlockCode(language)) : ContentBlockCode(language)
abstract class ContentNodeLink() : ContentBlock() {
abstract val node: DocumentationNode?
}
object ContentHardLineBreak : ContentNode {
override val textLength: Int
get() = 0
}
class ContentNodeDirectLink(override val node: DocumentationNode): ContentNodeLink() {
override fun equals(other: Any?): Boolean =
super.equals(other) && other is ContentNodeDirectLink && node.name == other.node.name
override fun hashCode(): Int =
children.hashCode() * 31 + node.name.hashCode()
}
class ContentNodeLazyLink(val linkText: String, val lazyNode: () -> DocumentationNode?): ContentNodeLink() {
override val node: DocumentationNode? get() = lazyNode()
override fun equals(other: Any?): Boolean =
super.equals(other) && other is ContentNodeLazyLink && linkText == other.linkText
override fun hashCode(): Int =
children.hashCode() * 31 + linkText.hashCode()
}
class ContentExternalLink(val href : String) : ContentBlock() {
override fun equals(other: Any?): Boolean =
super.equals(other) && other is ContentExternalLink && href == other.href
override fun hashCode(): Int =
children.hashCode() * 31 + href.hashCode()
}
data class ContentBookmark(val name: String): ContentBlock()
data class ContentLocalLink(val href: String) : ContentBlock()
class ContentUnorderedList() : ContentBlock()
class ContentOrderedList() : ContentBlock()
class ContentListItem() : ContentBlock()
class ContentHeading(val level: Int) : ContentBlock()
class ContentSection(val tag: String, val subjectName: String?) : ContentBlock() {
override fun equals(other: Any?): Boolean =
super.equals(other) && other is ContentSection && tag == other.tag && subjectName == other.subjectName
override fun hashCode(): Int =
children.hashCode() * 31 * 31 + tag.hashCode() * 31 + (subjectName?.hashCode() ?: 0)
}
object ContentTags {
val Description = "Description"
val SeeAlso = "See Also"
val Return = "Return"
val Exceptions = "Exceptions"
val Parameters = "Parameters"
}
fun content(body: ContentBlock.() -> Unit): ContentBlock {
val block = ContentBlock()
block.body()
return block
}
fun ContentBlock.text(value: String) = append(ContentText(value))
fun ContentBlock.keyword(value: String) = append(ContentKeyword(value))
fun ContentBlock.symbol(value: String) = append(ContentSymbol(value))
fun ContentBlock.identifier(value: String, kind: IdentifierKind = IdentifierKind.Other, signature: String? = null) {
append(ContentIdentifier(value, kind, signature))
}
fun ContentBlock.nbsp() = append(ContentNonBreakingSpace)
fun ContentBlock.softLineBreak() = append(ContentSoftLineBreak)
fun ContentBlock.indentedSoftLineBreak() = append(ContentIndentedSoftLineBreak)
fun ContentBlock.hardLineBreak() = append(ContentHardLineBreak)
fun ContentBlock.strong(body: ContentBlock.() -> Unit) {
val strong = ContentStrong()
strong.body()
append(strong)
}
fun ContentBlock.code(body: ContentBlock.() -> Unit) {
val code = ContentCode()
code.body()
append(code)
}
fun ContentBlock.link(to: DocumentationNode, body: ContentBlock.() -> Unit) {
val block = if (to.kind == NodeKind.ExternalLink)
ContentExternalLink(to.name)
else
ContentNodeDirectLink(to)
block.body()
append(block)
}
open class Content(): ContentBlock() {
open val sections: List<ContentSection> get() = emptyList()
open val summary: ContentNode get() = ContentEmpty
open val description: ContentNode get() = ContentEmpty
fun findSectionByTag(tag: String): ContentSection? =
sections.firstOrNull { tag.equals(it.tag, ignoreCase = true) }
companion object {
val Empty = Content()
fun of(vararg child: ContentNode): Content {
val result = MutableContent()
child.forEach { result.append(it) }
return result
}
}
}
open class MutableContent() : Content() {
private val sectionList = arrayListOf<ContentSection>()
override val sections: List<ContentSection>
get() = sectionList
fun addSection(tag: String?, subjectName: String?): ContentSection {
val section = ContentSection(tag ?: "", subjectName)
sectionList.add(section)
return section
}
override val summary: ContentNode get() = children.firstOrNull() ?: ContentEmpty
override val description: ContentNode by lazy {
val descriptionNodes = children.drop(1)
if (descriptionNodes.isEmpty()) {
ContentEmpty
} else {
val result = ContentSection(ContentTags.Description, null)
result.children.addAll(descriptionNodes)
result
}
}
override fun equals(other: Any?): Boolean {
if (other !is Content)
return false
return sections == other.sections && children == other.children
}
override fun hashCode(): Int {
return sections.map { it.hashCode() }.sum()
}
override fun toString(): String {
if (sections.isEmpty())
return "<empty>"
return (listOf(summary, description) + sections).joinToString()
}
}
fun javadocSectionDisplayName(sectionName: String?): String? =
when(sectionName) {
"param" -> "Parameters"
"throws", "exception" -> ContentTags.Exceptions
else -> sectionName?.capitalize()
}
| apache-2.0 | 6c44f4d4e10cf47ddc78f373617fdef5 | 29.677966 | 151 | 0.674254 | 4.410331 | false | false | false | false |
androidx/androidx | room/room-compiler-processing/src/test/java/androidx/room/compiler/processing/javac/kotlin/JvmDescriptorUtilsTest.kt | 3 | 13581 | /*
* Copyright 2020 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.javac.kotlin
import com.google.auto.common.MoreElements
import com.google.common.truth.Truth
import com.google.common.truth.Truth.assertThat
import com.google.testing.compile.JavaFileObjects
import com.google.testing.compile.JavaSourcesSubjectFactory
import com.squareup.javapoet.ArrayTypeName
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.TypeName
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.ElementKind.CONSTRUCTOR
import javax.lang.model.element.ElementKind.FIELD
import javax.lang.model.element.ElementKind.METHOD
import javax.lang.model.element.TypeElement
import javax.tools.JavaFileObject
@RunWith(JUnit4::class)
class JvmDescriptorUtilsTest {
private val describeAnnotation =
"""
package androidx.room.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface Describe { }
""".toJFO("androidx.room.test.Describe")
@Test
fun descriptor_method_simple() {
singleRun(
"""
package androidx.room.test;
public class DummyClass {
@Describe
public void emptyMethod() {
}
}
""".toJFO("androidx.room.test.DummyClass")
) { descriptors ->
assertThat(descriptors.first())
.isEqualTo("emptyMethod()V")
}
}
@Test
fun descriptor_field() {
singleRun(
"""
package androidx.room.test;
import java.util.List;
class DummyClass<T> {
@Describe
int field1;
@Describe
String field2;
@Describe
T field3;
@Describe
List<String> field4;
}
""".toJFO("androidx.room.test.DummyClass")
) { descriptors ->
assertThat(descriptors).isEqualTo(
setOf(
"field1:I",
"field2:Ljava/lang/String;",
"field3:Ljava/lang/Object;",
"field4:Ljava/util/List;"
)
)
}
}
@Test
fun descriptor_method_erasured() {
singleRun(
"""
package androidx.room.test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
class DummyClass<T> {
@Describe
void method1(T something) { }
@Describe
T method2() { return null; }
@Describe
List<? extends String> method3() { return null; }
@Describe
Map<T, String> method4() { return null; }
@Describe
ArrayList<Map<T, String>> method5() { return null; }
@Describe
static <I, O extends I> O method6(I input) { return null; }
@Describe
static <I, O extends String> O method7(I input) { return null; }
@Describe
static <P extends Collection & Comparable> P method8() { return null; }
@Describe
static <P extends String & List<Character>> P method9() { return null; }
}
""".toJFO("androidx.room.test.DummyClass")
) { descriptors ->
assertThat(descriptors).isEqualTo(
setOf(
"method1(Ljava/lang/Object;)V",
"method2()Ljava/lang/Object;",
"method3()Ljava/util/List;",
"method4()Ljava/util/Map;",
"method5()Ljava/util/ArrayList;",
"method6(Ljava/lang/Object;)Ljava/lang/Object;",
"method7(Ljava/lang/Object;)Ljava/lang/String;",
"method8()Ljava/util/Collection;",
"method9()Ljava/lang/String;"
)
)
}
}
@Test
fun descriptor_method_primitiveParams() {
singleRun(
"""
package androidx.room.test;
class DummyClass {
@Describe
void method1(boolean yesOrNo, int number) { }
@Describe
byte method2(char letter) { return 0; }
@Describe
void method3(double realNumber1, float realNummber2) { }
@Describe
void method4(long bigNumber, short littlerNumber) { }
}
""".toJFO("androidx.room.test.DummyClass")
) { descriptors ->
assertThat(descriptors)
.isEqualTo(setOf("method1(ZI)V", "method2(C)B", "method3(DF)V", "method4(JS)V"))
}
}
@Test
fun descriptor_method_classParam_javaTypes() {
singleRun(
"""
package androidx.room.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
class DummyClass {
@Describe
void method1(Object something) { }
@Describe
Object method2() { return null; }
@Describe
List<String> method3(ArrayList<Integer> list) { return null; }
@Describe
Map<String, Object> method4() { return null; }
}
""".toJFO("androidx.room.test.DummyClass")
) { descriptors ->
assertThat(descriptors).isEqualTo(
setOf(
"method1(Ljava/lang/Object;)V",
"method2()Ljava/lang/Object;",
"method3(Ljava/util/ArrayList;)Ljava/util/List;",
"method4()Ljava/util/Map;"
)
)
}
}
@Test
fun descriptor_method_classParam_testClass() {
val extraJfo =
"""
package androidx.room.test;
class DataClass { }
""".toJFO("androidx.room.test.DataClass")
singleRun(
"""
package androidx.room.test;
class DummyClass {
@Describe
void method1(DataClass data) { }
@Describe
DataClass method2() { return null; }
}
""".toJFO("androidx.room.test.DummyClass"),
extraJfo
) { descriptors ->
assertThat(descriptors).isEqualTo(
setOf(
"method1(Landroidx/room/test/DataClass;)V",
"method2()Landroidx/room/test/DataClass;"
)
)
}
}
@Test
fun descriptor_method_classParam_innerTestClass() {
val extraJfo =
"""
package androidx.room.test;
class DataClass {
class MemberInnerData { }
static class StaticInnerData { }
enum EnumData {
VALUE1, VALUE2
}
}
""".toJFO("androidx.room.test.DataClass")
singleRun(
"""
package androidx.room.test;
class DummyClass {
@Describe
void method1(DataClass.MemberInnerData data) { }
@Describe
void method2(DataClass.StaticInnerData data) { }
@Describe
void method3(DataClass.EnumData enumData) { }
@Describe
DataClass.StaticInnerData method4() { return null; }
}
""".toJFO("androidx.room.test.DummyClass"),
extraJfo
) { descriptors ->
assertThat(descriptors).isEqualTo(
setOf(
"method1(Landroidx/room/test/DataClass\$MemberInnerData;)V",
"method2(Landroidx/room/test/DataClass\$StaticInnerData;)V",
"method3(Landroidx/room/test/DataClass\$EnumData;)V",
"method4()Landroidx/room/test/DataClass\$StaticInnerData;"
)
)
}
}
@Test
fun descriptor_method_arrayParams() {
val extraJfo =
"""
package androidx.room.test;
class DataClass { }
""".toJFO("androidx.room.test.DataClass")
singleRun(
"""
package androidx.room.test;
class DummyClass {
@Describe
void method1(DataClass[] data) { }
@Describe
DataClass[] method2() { return null; }
@Describe
void method3(int[] array) { }
@Describe
void method4(int... array) { }
}
""".toJFO("androidx.room.test.DummyClass"),
extraJfo
) { descriptors ->
assertThat(descriptors).isEqualTo(
setOf(
"method1([Landroidx/room/test/DataClass;)V",
"method2()[Landroidx/room/test/DataClass;",
"method3([I)V",
"method4([I)V"
)
)
}
}
@Test
fun typeNameFromDescriptor() {
val extraJfo =
"""
import androidx.room.test.Describe;
class Custom {
static class Nested1 {
static class Nested2 {
@Describe
Custom c;
@Describe
Custom.Nested1 n1;
@Describe
Custom.Nested1.Nested2 n2;
}
}
}
""".toJFO("Custom")
singleRun(
"""
package androidx.room.test;
class Foo {
@Describe
int x;
@Describe
java.util.Map map;
@Describe
java.util.Map.Entry entry;
@Describe
int[] intArray;
@Describe
int[][] intArrayOfArray;
}
""".toJFO("androidx.room.test.Foo"),
extraJfo
) {
assertThat(
it.map {
// the format is name:type so we strip everything before `:`
it.split(':')[1].typeNameFromJvmSignature()
}
).containsExactly(
TypeName.INT,
ClassName.get(Map::class.java),
ClassName.get(Map.Entry::class.java),
ArrayTypeName.of(
TypeName.INT
),
ArrayTypeName.of(
ArrayTypeName.of(
TypeName.INT
)
),
ClassName.get("", "Custom"),
ClassName.get("", "Custom", "Nested1"),
ClassName.get("", "Custom", "Nested1", "Nested2"),
)
}
}
private fun String.toJFO(qName: String): JavaFileObject =
JavaFileObjects.forSourceLines(qName, this)
@Suppress("UnstableApiUsage")
private fun singleRun(
vararg jfo: JavaFileObject,
handler: (Set<String>) -> Unit
) {
Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
.that(listOf(describeAnnotation) + jfo)
.processedWith(object : AbstractProcessor() {
override fun process(
annotations: Set<TypeElement>,
roundEnv: RoundEnvironment
): Boolean {
if (annotations.isNotEmpty()) {
roundEnv.getElementsAnnotatedWith(annotations.first()).map { element ->
when (element.kind) {
FIELD ->
MoreElements.asVariable(element).descriptor()
METHOD, CONSTRUCTOR ->
MoreElements.asExecutable(element).descriptor()
else -> error("Unsupported element to describe.")
}
}.toSet().let(handler)
}
return true
}
override fun getSupportedAnnotationTypes(): Set<String> {
return setOf("androidx.room.test.Describe")
}
}).compilesWithoutError()
}
} | apache-2.0 | 1155812e3cfff3193368e30191cf1ab5 | 29.659142 | 96 | 0.489802 | 5.14237 | false | true | false | false |
androidx/androidx | tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/ItemIndex.kt | 3 | 1843 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.tv.foundation.lazy.grid
/**
* Represents a line index in the lazy grid.
*/
@Suppress("NOTHING_TO_INLINE")
@kotlin.jvm.JvmInline
internal value class LineIndex(val value: Int) {
inline operator fun inc(): LineIndex = LineIndex(value + 1)
inline operator fun dec(): LineIndex = LineIndex(value - 1)
inline operator fun plus(i: Int): LineIndex = LineIndex(value + i)
inline operator fun minus(i: Int): LineIndex = LineIndex(value - i)
inline operator fun minus(i: LineIndex): LineIndex = LineIndex(value - i.value)
inline operator fun compareTo(other: LineIndex): Int = value - other.value
}
/**
* Represents an item index in the lazy grid.
*/
@Suppress("NOTHING_TO_INLINE")
@kotlin.jvm.JvmInline
internal value class ItemIndex(val value: Int) {
inline operator fun inc(): ItemIndex = ItemIndex(value + 1)
inline operator fun dec(): ItemIndex = ItemIndex(value - 1)
inline operator fun plus(i: Int): ItemIndex = ItemIndex(value + i)
inline operator fun minus(i: Int): ItemIndex = ItemIndex(value - i)
inline operator fun minus(i: ItemIndex): ItemIndex = ItemIndex(value - i.value)
inline operator fun compareTo(other: ItemIndex): Int = value - other.value
}
| apache-2.0 | dea6aef7d007b0d0834cb6061661387c | 39.955556 | 83 | 0.720564 | 3.855649 | false | false | false | false |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/core-kotlin-2/src/test/kotlin/stringcomparison/StringComparisonTest.kt | 1 | 1385 | package stringcomparison
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class StringComparisonUnitTest {
@Test
fun `compare using equals operator`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first == second }
assertFalse { first == firstCapitalized }
}
@Test
fun `compare using referential equals operator`() {
val first = "kotlin"
val second = "kotlin"
val copyOfFirst = buildString { "kotlin" }
assertTrue { first === second }
assertFalse { first === copyOfFirst }
}
@Test
fun `compare using equals method`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first.equals(second) }
assertFalse { first.equals(firstCapitalized) }
assertTrue { first.equals(firstCapitalized, true) }
}
@Test
fun `compare using compare method`() {
val first = "kotlin"
val second = "kotlin"
val firstCapitalized = "KOTLIN"
assertTrue { first.compareTo(second) == 0 }
assertTrue { first.compareTo(firstCapitalized) == 32 }
assertTrue { firstCapitalized.compareTo(first) == -32 }
assertTrue { first.compareTo(firstCapitalized, true) == 0 }
}
} | gpl-3.0 | 30cbe2de068008a8512af7daeb146d07 | 28.489362 | 67 | 0.615162 | 4.616667 | false | true | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/handlers/InvokerHandler.kt | 1 | 3877 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.handlers
import com.demonwav.mcdev.platform.mixin.util.MethodTargetMember
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.INVOKER
import com.demonwav.mcdev.platform.mixin.util.MixinTargetMember
import com.demonwav.mcdev.platform.mixin.util.findMethod
import com.demonwav.mcdev.platform.mixin.util.findOrConstructSourceMethod
import com.demonwav.mcdev.util.MemberReference
import com.demonwav.mcdev.util.constantStringValue
import com.demonwav.mcdev.util.decapitalize
import com.demonwav.mcdev.util.descriptor
import com.demonwav.mcdev.util.findAnnotation
import com.demonwav.mcdev.util.fullQualifiedName
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.util.createSmartPointer
import com.intellij.psi.util.parentOfType
import java.util.Locale
import org.objectweb.asm.tree.ClassNode
class InvokerHandler : MixinMemberAnnotationHandler {
companion object {
private val PATTERN = Regex("(call|invoke|new|create)([A-Z].*?)(_\\\$md.*)?")
fun getInstance(): InvokerHandler? {
return MixinAnnotationHandler.forMixinAnnotation(INVOKER) as? InvokerHandler
}
}
override fun resolveTarget(annotation: PsiAnnotation, targetClass: ClassNode): List<MixinTargetMember> {
val member = annotation.parentOfType<PsiMethod>() ?: return emptyList()
val name = getInvokerTargetName(annotation, member) ?: return emptyList()
val constructor = name == "<init>"
if (constructor &&
(member.returnType as? PsiClassType)?.resolve()?.fullQualifiedName?.replace('.', '/') != targetClass.name
) {
return emptyList()
}
var wantedDesc = member.descriptor ?: return emptyList()
if (constructor) {
wantedDesc = wantedDesc.replaceAfterLast(')', "V")
}
val method = targetClass.findMethod(MemberReference(name, wantedDesc)) ?: return emptyList()
return listOf(MethodTargetMember(targetClass, method))
}
override fun createUnresolvedMessage(annotation: PsiAnnotation): String? {
val method = annotation.parentOfType<PsiMethod>() ?: return null
val targetName = getInvokerTargetName(annotation, method) ?: return "Invalid invoker name ${method.name}"
return "Cannot find method $targetName in target class"
}
private fun getInvokerTargetName(invoker: PsiAnnotation, member: PsiMember): String? {
val value = invoker.findDeclaredAttributeValue("value")?.constantStringValue
if (value != null) {
return value
}
val memberName = member.name ?: return null
val result = PATTERN.matchEntire(memberName) ?: return null
val prefix = result.groupValues[1]
if (prefix == "new" || prefix == "create") {
return "<init>"
}
val name = result.groupValues[2]
if (name.uppercase(Locale.ENGLISH) != name) {
return name.decapitalize()
}
return name
}
fun findInvokerTargetForReference(member: PsiMember): SmartPsiElementPointer<PsiMethod>? {
val accessor = member.findAnnotation(INVOKER) ?: return null
val invokerTarget = resolveTarget(accessor).firstOrNull() as? MethodTargetMember ?: return null
return invokerTarget.classAndMethod.method.findOrConstructSourceMethod(
invokerTarget.classAndMethod.clazz,
member.project,
member.resolveScope,
canDecompile = false
).createSmartPointer()
}
override val isEntryPoint = false
}
| mit | 22e21d377bc0910c6439f3cfb880f131 | 38.969072 | 117 | 0.704669 | 4.728049 | false | false | false | false |
danwallach/CalWatch | app/src/main/kotlin/org/dwallach/calwatch2/VersionWrapper.kt | 1 | 1198 | /*
* CalWatch / CalWatch2
* Copyright © 2014-2022 by Dan S. Wallach
* Home page: http://www.cs.rice.edu/~dwallach/calwatch/
* Licensing: http://www.cs.rice.edu/~dwallach/calwatch/licensing.html
*/
package org.dwallach.calwatch2
import android.content.Context
import android.util.Log
import androidx.core.content.pm.PackageInfoCompat
private val TAG = "VersionWrapper"
/**
* Deals with reading our version name and number from the APK.
*/
object VersionWrapper {
fun logVersion(activity: Context) {
try {
val pinfo = activity.packageManager.getPackageInfo(activity.packageName, 0)
if (pinfo == null) {
Log.e(TAG, "package info was null, can't figure out version information")
} else {
val versionInfo = PackageInfoCompat.getLongVersionCode(pinfo)
val hiBits = (versionInfo shr 32) and 0xffffffff
val loBits = versionInfo and 0xffffff
Log.i(TAG, "Version: ${pinfo.versionName} (versionCodeMajor: $hiBits, versionCode: $loBits)")
}
} catch (e: Throwable) {
Log.e(TAG, "failed to get version information!", e)
}
}
}
| gpl-3.0 | ccfcafb9a9c87ea321c921e886684d2b | 31.351351 | 109 | 0.639098 | 4.003344 | false | false | false | false |
EddieVanHalen98/vision-kt | main/out/production/core/com/evh98/vision/util/Icons.kt | 2 | 2911 | package com.evh98.vision.util
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.Sprite
object Icons {
var ACCOUNT: Sprite? = null
var APPS: Sprite? = null
var BACK: Sprite? = null
var BULB: Sprite? = null
var COLLECTIONS: Sprite? = null
var CONFIRM: Sprite? = null
var FACEBOOK: Sprite? = null
var FEEDBACK: Sprite? = null
var FOLDER: Sprite? = null
var GAMES: Sprite? = null
var INFO: Sprite? = null
var MEDIA: Sprite? = null
var MOVIES: Sprite? = null
var MUSIC: Sprite? = null
var NETFLIX: Sprite? = null
var PHONE: Sprite? = null
var PLEX: Sprite? = null
var SEARCH: Sprite? = null
var SETTINGS: Sprite? = null
var SPOTIFY: Sprite? = null
var TV_GUIDE: Sprite? = null
var TWITTER: Sprite? = null
var WHATSAPP: Sprite? = null
var WWE: Sprite? = null
var YOUTUBE: Sprite? = null
fun loadAll() {
ACCOUNT = Graphics.createSprite(Gdx.files.internal("icons/account.png"))
APPS = Graphics.createSprite(Gdx.files.internal("icons/apps.png"))
BACK = Graphics.createSprite(Gdx.files.internal("icons/back.png"))
BULB = Graphics.createSprite(Gdx.files.internal("icons/bulb.png"))
COLLECTIONS = Graphics.createSprite(Gdx.files.internal("icons/collections.png"))
CONFIRM = Graphics.createSprite(Gdx.files.internal("icons/confirm.png"))
FACEBOOK = Graphics.createSprite(Gdx.files.internal("icons/facebook.png"))
FEEDBACK = Graphics.createSprite(Gdx.files.internal("icons/feedback.png"))
FOLDER = Graphics.createSprite(Gdx.files.internal("icons/folder.png"))
GAMES = Graphics.createSprite(Gdx.files.internal("icons/games.png"))
INFO = Graphics.createSprite(Gdx.files.internal("icons/info.png"))
MEDIA = Graphics.createSprite(Gdx.files.internal("icons/media.png"))
MOVIES = Graphics.createSprite(Gdx.files.internal("icons/movies.png"))
MUSIC = Graphics.createSprite(Gdx.files.internal("icons/music.png"))
NETFLIX = Graphics.createSprite(Gdx.files.internal("icons/netflix.png"))
PHONE = Graphics.createSprite(Gdx.files.internal("icons/phone.png"))
PLEX = Graphics.createSprite(Gdx.files.internal("icons/plex.png"))
SEARCH = Graphics.createSprite(Gdx.files.internal("icons/search.png"))
SETTINGS = Graphics.createSprite(Gdx.files.internal("icons/settings.png"))
SPOTIFY = Graphics.createSprite(Gdx.files.internal("icons/spotify.png"))
TV_GUIDE = Graphics.createSprite(Gdx.files.internal("icons/tv_guide.png"))
TWITTER = Graphics.createSprite(Gdx.files.internal("icons/twitter.png"))
WHATSAPP = Graphics.createSprite(Gdx.files.internal("icons/whatsapp.png"))
WWE = Graphics.createSprite(Gdx.files.internal("icons/wwe.png"))
YOUTUBE = Graphics.createSprite(Gdx.files.internal("icons/youtube.png"))
}
} | mit | ddefa96ce6b25edbbe9c144597712d3f | 45.967742 | 88 | 0.683614 | 3.68948 | false | false | false | false |
handstandsam/ShoppingApp | app/src/main/java/com/handstandsam/shoppingapp/compose/HomeScreen.kt | 1 | 2166 | package com.handstandsam.shoppingapp.compose
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.handstandsam.shoppingapp.features.home.HomeViewModel
import com.handstandsam.shoppingapp.models.ItemWithQuantity
import kotlinx.coroutines.flow.Flow
@Composable
fun HomeScreen(
itemsInCart: Flow<List<ItemWithQuantity>>,
showCartClicked: () -> Unit,
logoutClicked: () -> Unit,
homeViewModel: HomeViewModel
) {
AppScaffold(
itemsInCart = itemsInCart,
showCartClicked = showCartClicked,
logoutClicked = logoutClicked
) {
val state by homeViewModel.states.collectAsState(initial = HomeViewModel.State())
Column(
modifier = Modifier
.fillMaxSize()
) {
Text(
text = state.welcomeMessage,
modifier = Modifier
.wrapContentHeight()
.fillMaxWidth()
.padding(16.dp),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.body1
)
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
state.categories.forEach { category ->
item {
CategoryRow(category) {
homeViewModel.send(HomeViewModel.Intention.CategoryClicked(category))
}
}
}
}
}
}
} | apache-2.0 | 8240a40f8df649f27ccaed6e72c853ab | 33.396825 | 97 | 0.635734 | 5.401496 | false | false | false | false |
bazelbuild/rules_kotlin | src/main/kotlin/io/bazel/worker/CpuTimeBasedGcScheduler.kt | 1 | 1792 | package io.bazel.worker
import com.sun.management.OperatingSystemMXBean
import src.main.kotlin.io.bazel.worker.GcScheduler
import java.lang.management.ManagementFactory
import java.time.Duration
import java.util.concurrent.atomic.AtomicReference
// This class is intended to mirror https://github.com/Bencodes/bazel/blob/3835d9b21ad524d06873dfbf465ffd2dfb635ba8/src/main/java/com/google/devtools/build/lib/worker/WorkRequestHandler.java#L431-L474
class CpuTimeBasedGcScheduler(
/**
* After this much CPU time has elapsed, we may force a GC run. Set to [Duration.ZERO] to
* disable.
*/
private val cpuUsageBeforeGc: Duration,
) : GcScheduler {
/** The total process CPU time at the last GC run (or from the start of the worker). */
private val cpuTime: Duration
get() = if (cpuUsageBeforeGc.isZero) Duration.ZERO else Duration.ofNanos(bean.processCpuTime)
private val cpuTimeAtLastGc: AtomicReference<Duration> = AtomicReference(cpuTime)
/** Call occasionally to perform a GC if enough CPU time has been used. */
override fun maybePerformGc() {
if (!cpuUsageBeforeGc.isZero) {
val currentCpuTime = cpuTime
val lastCpuTime = cpuTimeAtLastGc.get()
// Do GC when enough CPU time has been used, but only if nobody else beat us to it.
if (currentCpuTime.minus(lastCpuTime).compareTo(cpuUsageBeforeGc) > 0 &&
cpuTimeAtLastGc.compareAndSet(lastCpuTime, currentCpuTime)
) {
System.gc()
// Avoid counting GC CPU time against CPU time before next GC.
cpuTimeAtLastGc.compareAndSet(currentCpuTime, cpuTime)
}
}
}
companion object {
/** Used to get the CPU time used by this process. */
private val bean = ManagementFactory.getOperatingSystemMXBean() as OperatingSystemMXBean
}
}
| apache-2.0 | 804a30bf778b85c3868868192c50d6f5 | 40.674419 | 200 | 0.739955 | 3.845494 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/market/dto/MarketMarketItem.kt | 1 | 3265 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.market.dto
import com.google.gson.annotations.SerializedName
import com.vk.dto.common.id.UserId
import kotlin.Boolean
import kotlin.Int
import kotlin.String
/**
* @param availability
* @param category
* @param description - Item description
* @param id - Item ID
* @param ownerId - Item owner's ID
* @param price
* @param title - Item title
* @param accessKey - Access key for the market item
* @param buttonTitle - Title for button for url
* @param date - Date when the item has been created in Unixtime
* @param externalId
* @param isFavorite
* @param thumbPhoto - URL of the preview image
* @param url - URL to item
* @param variantsGroupingId
* @param isMainVariant
* @param sku
*/
data class MarketMarketItem(
@SerializedName("availability")
val availability: MarketMarketItemAvailability,
@SerializedName("category")
val category: MarketMarketCategory,
@SerializedName("description")
val description: String,
@SerializedName("id")
val id: Int,
@SerializedName("owner_id")
val ownerId: UserId,
@SerializedName("price")
val price: MarketPrice,
@SerializedName("title")
val title: String,
@SerializedName("access_key")
val accessKey: String? = null,
@SerializedName("button_title")
val buttonTitle: String? = null,
@SerializedName("date")
val date: Int? = null,
@SerializedName("external_id")
val externalId: String? = null,
@SerializedName("is_favorite")
val isFavorite: Boolean? = null,
@SerializedName("thumb_photo")
val thumbPhoto: String? = null,
@SerializedName("url")
val url: String? = null,
@SerializedName("variants_grouping_id")
val variantsGroupingId: Int? = null,
@SerializedName("is_main_variant")
val isMainVariant: Boolean? = null,
@SerializedName("sku")
val sku: String? = null
)
| mit | a00000945de22f9dcbc371bb0485c074 | 35.277778 | 81 | 0.685758 | 4.341755 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/other/generic/adapter/GridEqualSpacingDecoration.kt | 1 | 757 | package de.tum.`in`.tumcampusapp.component.other.generic.adapter
import android.graphics.Rect
import androidx.recyclerview.widget.RecyclerView
import android.view.View
class GridEqualSpacingDecoration(
private val spacing: Int,
private val spanCount: Int
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
val column = position % spanCount
outRect.left = spacing - column * spacing / spanCount
outRect.right = (column + 1) * spacing / spanCount
if (position < spanCount) {
outRect.top = spacing
}
outRect.bottom = spacing
}
} | gpl-3.0 | aa3d50309d131273953545157f3b0017 | 30.583333 | 109 | 0.69749 | 4.67284 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/ClassSelectionActivity.kt | 1 | 13109 | package com.habitrpg.android.habitica.ui.activities
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.navigation.navArgs
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.ActivityClassSelectionBinding
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.user.Gear
import com.habitrpg.android.habitica.models.user.Items
import com.habitrpg.android.habitica.models.user.Outfit
import com.habitrpg.android.habitica.models.user.Preferences
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaProgressDialog
import kotlinx.coroutines.launch
import javax.inject.Inject
class ClassSelectionActivity : BaseActivity() {
@Inject
lateinit var userViewModel: MainUserViewModel
private lateinit var binding: ActivityClassSelectionBinding
private var currentClass: String? = null
private var newClass: String = "healer"
set(value) {
field = value
when (value) {
"healer" -> healerSelected()
"wizard" -> mageSelected()
"mage" -> mageSelected()
"rogue" -> rogueSelected()
"warrior" -> warriorSelected()
}
}
private var className: String? = null
set(value) {
field = value
binding.selectedTitleTextView.text = getString(R.string.x_class, className)
binding.selectedButton.text = getString(R.string.become_x, className)
}
private var isInitialSelection: Boolean = false
private var classWasUnset: Boolean? = false
private var shouldFinish: Boolean? = false
private var progressDialog: HabiticaProgressDialog? = null
override fun getLayoutResId(): Int {
return R.layout.activity_class_selection
}
override fun getContentView(): View {
binding = ActivityClassSelectionBinding.inflate(layoutInflater)
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
val args = navArgs<ClassSelectionActivityArgs>().value
isInitialSelection = args.isInitialSelection
currentClass = args.className
newClass = currentClass ?: "healer"
userViewModel.user.observe(this) {
it?.preferences?.let { preferences ->
val unmanagedPrefs = userRepository.getUnmanagedCopy(preferences)
unmanagedPrefs.costume = false
setAvatarViews(unmanagedPrefs)
}
}
if (!isInitialSelection) {
lifecycleScope.launch(ExceptionHandler.coroutine()) {
userRepository.changeClass()
classWasUnset
}
}
binding.healerWrapper.setOnClickListener { newClass = "healer" }
binding.mageWrapper.setOnClickListener { newClass = "wizard" }
binding.rogueWrapper.setOnClickListener { newClass = "rogue" }
binding.warriorWrapper.setOnClickListener { newClass = "warrior" }
binding.selectedButton.setOnClickListener { displayConfirmationDialogForClass() }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.class_selection, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.opt_out -> optOutSelected()
}
return super.onOptionsItemSelected(item)
}
private fun setAvatarViews(preferences: Preferences) {
val healerOutfit = Outfit()
healerOutfit.armor = "armor_healer_5"
healerOutfit.head = "head_healer_5"
healerOutfit.shield = "shield_healer_5"
healerOutfit.weapon = "weapon_healer_6"
val healer = this.makeUser(preferences, healerOutfit)
binding.healerAvatarView.setAvatar(healer)
val healerIcon = BitmapDrawable(resources, HabiticaIconsHelper.imageOfHealerLightBg())
binding.healerButton.setCompoundDrawablesWithIntrinsicBounds(healerIcon, null, null, null)
val mageOutfit = Outfit()
mageOutfit.armor = "armor_wizard_5"
mageOutfit.head = "head_wizard_5"
mageOutfit.weapon = "weapon_wizard_6"
val mage = this.makeUser(preferences, mageOutfit)
binding.mageAvatarView.setAvatar(mage)
val mageIcon = BitmapDrawable(resources, HabiticaIconsHelper.imageOfMageLightBg())
binding.mageButton.setCompoundDrawablesWithIntrinsicBounds(mageIcon, null, null, null)
val rogueOutfit = Outfit()
rogueOutfit.armor = "armor_rogue_5"
rogueOutfit.head = "head_rogue_5"
rogueOutfit.shield = "shield_rogue_6"
rogueOutfit.weapon = "weapon_rogue_6"
val rogue = this.makeUser(preferences, rogueOutfit)
binding.rogueAvatarView.setAvatar(rogue)
val rogueIcon = BitmapDrawable(resources, HabiticaIconsHelper.imageOfRogueLightBg())
binding.rogueButton.setCompoundDrawablesWithIntrinsicBounds(rogueIcon, null, null, null)
val warriorOutfit = Outfit()
warriorOutfit.armor = "armor_warrior_5"
warriorOutfit.head = "head_warrior_5"
warriorOutfit.shield = "shield_warrior_5"
warriorOutfit.weapon = "weapon_warrior_6"
val warrior = this.makeUser(preferences, warriorOutfit)
binding.warriorAvatarView.setAvatar(warrior)
val warriorIcon = BitmapDrawable(resources, HabiticaIconsHelper.imageOfWarriorLightBg())
binding.warriorButton.setCompoundDrawablesWithIntrinsicBounds(warriorIcon, null, null, null)
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
private fun makeUser(preferences: Preferences, outfit: Outfit): User {
val user = User()
user.preferences = preferences
user.items = Items()
user.items?.gear = Gear()
user.items?.gear?.equipped = outfit
return user
}
private fun healerSelected() {
className = getString(R.string.healer)
binding.selectedDescriptionTextView.text = getString(R.string.healer_description)
binding.selectedWrapperView.setBackgroundColor(ContextCompat.getColor(this, R.color.yellow_100))
binding.selectedTitleTextView.setTextColor(ContextCompat.getColor(this, R.color.dark_brown))
binding.selectedDescriptionTextView.setTextColor(ContextCompat.getColor(this, R.color.dark_brown))
binding.selectedButton.setBackgroundResource(R.drawable.layout_rounded_bg_yellow_10)
updateButtonBackgrounds(binding.healerButton, ContextCompat.getDrawable(this, R.drawable.layout_rounded_bg_window_yellow_border))
}
private fun mageSelected() {
className = getString(R.string.mage)
binding.selectedDescriptionTextView.text = getString(R.string.mage_description)
binding.selectedWrapperView.setBackgroundColor(ContextCompat.getColor(this, R.color.blue_10))
binding.selectedTitleTextView.setTextColor(ContextCompat.getColor(this, R.color.white))
binding.selectedDescriptionTextView.setTextColor(ContextCompat.getColor(this, R.color.white))
binding.selectedButton.setBackgroundResource(R.drawable.layout_rounded_bg_gray_alpha)
updateButtonBackgrounds(binding.mageButton, ContextCompat.getDrawable(this, R.drawable.layout_rounded_bg_window_blue_border))
}
private fun rogueSelected() {
className = getString(R.string.rogue)
binding.selectedDescriptionTextView.text = getString(R.string.rogue_description)
binding.selectedWrapperView.setBackgroundColor(ContextCompat.getColor(this, R.color.brand_200))
binding.selectedTitleTextView.setTextColor(ContextCompat.getColor(this, R.color.white))
binding.selectedDescriptionTextView.setTextColor(ContextCompat.getColor(this, R.color.white))
binding.selectedButton.setBackgroundResource(R.drawable.layout_rounded_bg_gray_alpha)
updateButtonBackgrounds(binding.rogueButton, ContextCompat.getDrawable(this, R.drawable.layout_rounded_bg_window_brand_border))
}
private fun warriorSelected() {
className = getString(R.string.warrior)
binding.selectedDescriptionTextView.text = getString(R.string.warrior_description)
binding.selectedWrapperView.setBackgroundColor(ContextCompat.getColor(this, R.color.maroon_50))
binding.selectedTitleTextView.setTextColor(ContextCompat.getColor(this, R.color.white))
binding.selectedDescriptionTextView.setTextColor(ContextCompat.getColor(this, R.color.white))
binding.selectedButton.setBackgroundResource(R.drawable.layout_rounded_bg_gray_alpha)
updateButtonBackgrounds(binding.warriorButton, ContextCompat.getDrawable(this, R.drawable.layout_rounded_bg_window_red_border))
}
private fun updateButtonBackgrounds(selectedButton: TextView, background: Drawable?) {
val deselectedBackground = ContextCompat.getDrawable(this, R.drawable.layout_rounded_bg_window)
binding.healerButton.background = if (binding.healerButton == selectedButton) background else deselectedBackground
binding.mageButton.background = if (binding.mageButton == selectedButton) background else deselectedBackground
binding.rogueButton.background = if (binding.rogueButton == selectedButton) background else deselectedBackground
binding.warriorButton.background = if (binding.warriorButton == selectedButton) background else deselectedBackground
}
private fun optOutSelected() {
if (!this.isInitialSelection && this.classWasUnset == false) {
return
}
val alert = HabiticaAlertDialog(this)
alert.setTitle(getString(R.string.opt_out_confirmation))
alert.addButton(R.string.opt_out_class, true) { _, _ -> optOutOfClasses() }
alert.addButton(R.string.dialog_go_back, false)
alert.show()
}
private fun displayConfirmationDialogForClass() {
if (!this.isInitialSelection && this.classWasUnset == false) {
val alert = HabiticaAlertDialog(this)
alert.setTitle(getString(R.string.change_class_confirmation))
alert.setMessage(getString(R.string.change_class_equipment_warning, currentClass))
alert.addButton(R.string.choose_class, true) { _, _ ->
selectClass(newClass)
displayClassChanged()
}
alert.addButton(R.string.dialog_go_back, false)
alert.show()
} else {
val alert = HabiticaAlertDialog(this)
alert.setTitle(getString(R.string.class_confirmation, className))
alert.addButton(R.string.choose_class, true) { _, _ -> selectClass(newClass) }
alert.addButton(R.string.dialog_go_back, false)
alert.show()
}
}
private fun displayClassChanged() {
val alert = HabiticaAlertDialog(this)
alert.setTitle(getString(R.string.class_changed, className))
alert.setMessage(getString(R.string.class_changed_description))
alert.addButton(getString(R.string.complete_tutorial), true)
alert.enqueue()
}
private fun optOutOfClasses() {
shouldFinish = true
this.displayProgressDialog(getString(R.string.opting_out_progress))
lifecycleScope.launch(ExceptionHandler.coroutine()) {
userRepository.disableClasses()
dismiss()
}
}
private fun selectClass(selectedClass: String) {
shouldFinish = true
this.displayProgressDialog(getString(R.string.changing_class_progress))
lifecycleScope.launch(ExceptionHandler.coroutine()) {
userRepository.changeClass(selectedClass)
dismiss()
}
}
private fun displayProgressDialog(progressText: String) {
HabiticaProgressDialog.show(this, progressText)
}
private fun dismiss() {
if (shouldFinish == true) {
progressDialog?.dismiss()
finish()
}
}
}
| gpl-3.0 | c343ad1dcdfd39b4d28eda7c0df9136d | 44.321555 | 137 | 0.691662 | 4.695201 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/MainActivity.kt | 1 | 22543 | package com.habitrpg.android.habitica.ui.activities
import android.app.NotificationChannel
import android.app.NotificationManager
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.view.children
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavDestination
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import com.google.android.gms.wearable.Wearable
import com.google.android.material.composethemeadapter.MdcTheme
import com.google.firebase.perf.FirebasePerformance
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.databinding.ActivityMainBinding
import com.habitrpg.android.habitica.extensions.hideKeyboard
import com.habitrpg.android.habitica.extensions.observeOnce
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.extensions.updateStatusBarColor
import com.habitrpg.android.habitica.helpers.AmplitudeManager
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.NotificationOpenHandler
import com.habitrpg.android.habitica.helpers.SoundManager
import com.habitrpg.android.habitica.interactors.CheckClassSelectionUseCase
import com.habitrpg.android.habitica.interactors.DisplayItemDropUseCase
import com.habitrpg.android.habitica.interactors.NotifyUserUseCase
import com.habitrpg.android.habitica.models.TutorialStep
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.models.user.UserQuestStatus
import com.habitrpg.android.habitica.ui.TutorialView
import com.habitrpg.android.habitica.ui.fragments.NavigationDrawerFragment
import com.habitrpg.android.habitica.ui.viewmodels.MainActivityViewModel
import com.habitrpg.android.habitica.ui.viewmodels.NotificationsViewModel
import com.habitrpg.android.habitica.ui.views.AppHeaderView
import com.habitrpg.android.habitica.ui.views.SnackbarActivity
import com.habitrpg.android.habitica.ui.views.dialogs.QuestCompletedDialog
import com.habitrpg.android.habitica.ui.views.yesterdailies.YesterdailyDialog
import com.habitrpg.android.habitica.widget.AvatarStatsWidgetProvider
import com.habitrpg.android.habitica.widget.DailiesWidgetProvider
import com.habitrpg.android.habitica.widget.HabitButtonWidgetProvider
import com.habitrpg.android.habitica.widget.TodoListWidgetProvider
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.getThemeColor
import com.habitrpg.common.habitica.extensions.isUsingNightModeResources
import com.habitrpg.common.habitica.views.AvatarView
import com.habitrpg.shared.habitica.models.responses.MaintenanceResponse
import com.habitrpg.shared.habitica.models.responses.TaskScoringResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.util.Date
import javax.inject.Inject
import kotlin.time.DurationUnit
import kotlin.time.toDuration
var mainActivityCreatedAt: Date? = null
open class MainActivity : BaseActivity(), SnackbarActivity {
private var launchScreen: String? = null
@Inject
internal lateinit var apiClient: ApiClient
@Inject
internal lateinit var soundManager: SoundManager
@Inject
internal lateinit var checkClassSelectionUseCase: CheckClassSelectionUseCase
@Inject
internal lateinit var displayItemDropUseCase: DisplayItemDropUseCase
@Inject
internal lateinit var notifyUserUseCase: NotifyUserUseCase
@Inject
internal lateinit var taskRepository: TaskRepository
@Inject
internal lateinit var inventoryRepository: InventoryRepository
@Inject
internal lateinit var appConfigManager: AppConfigManager
lateinit var binding: ActivityMainBinding
val snackbarContainer: ViewGroup
get() = binding.content.snackbarContainer
val notificationsViewModel: NotificationsViewModel by viewModels()
val viewModel: MainActivityViewModel by viewModels()
private var sideAvatarView: AvatarView? = null
private var drawerFragment: NavigationDrawerFragment? = null
var drawerToggle: ActionBarDrawerToggle? = null
private var resumeFromActivity = false
private var userQuestStatus = UserQuestStatus.NO_QUEST
private var lastNotificationOpen: Long? = null
val isAppBarExpanded: Boolean
get() = binding.content.appbar.height - binding.content.appbar.bottom == 0
override fun getLayoutResId(): Int {
return R.layout.activity_main
}
override fun getContentView(): View {
binding = ActivityMainBinding.inflate(layoutInflater)
return binding.root
}
private var launchTrace: com.google.firebase.perf.metrics.Trace? = null
public override fun onCreate(savedInstanceState: Bundle?) {
if (BuildConfig.DEBUG) {
mainActivityCreatedAt = Date()
}
try {
launchTrace = FirebasePerformance.getInstance().newTrace("MainActivityLaunch")
} catch (e: IllegalStateException) {
ExceptionHandler.reportError(e)
}
launchTrace?.start()
super.onCreate(savedInstanceState)
if (!viewModel.isAuthenticated) {
val intent = Intent(this, IntroActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
return
} else {
Wearable.getCapabilityClient(this).addLocalCapability("provide_auth")
}
setupToolbar(binding.content.toolbar)
sideAvatarView = AvatarView(this, showBackground = true, showMount = false, showPet = false)
viewModel.user.observe(this) {
setUserData(it)
}
compositeSubscription.add(
userRepository.getUserQuestStatus().subscribeWithErrorHandler {
userQuestStatus = it
}
)
val drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout)
drawerFragment = supportFragmentManager.findFragmentById(R.id.navigation_drawer) as? NavigationDrawerFragment
drawerFragment?.setUp(R.id.navigation_drawer, drawerLayout, notificationsViewModel)
drawerToggle = object : ActionBarDrawerToggle(
this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {}
// Set the drawer toggle as the DrawerListener
drawerToggle?.let { drawerLayout.addDrawerListener(it) }
drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
private var isOpeningDrawer: Boolean? = null
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
if (!isUsingNightModeResources()) {
if (slideOffset < 0.5f && isOpeningDrawer == null) {
window.updateStatusBarColor(getThemeColor(R.attr.colorPrimaryDark), false)
isOpeningDrawer = true
} else if (slideOffset > 0.5f && isOpeningDrawer == null) {
window.updateStatusBarColor(getThemeColor(R.attr.headerBackgroundColor), true)
isOpeningDrawer = false
}
}
}
override fun onDrawerOpened(drawerView: View) {
hideKeyboard()
if (!isUsingNightModeResources()) {
window.updateStatusBarColor(getThemeColor(R.attr.colorPrimaryDark), false)
}
isOpeningDrawer = null
drawerFragment?.updatePromo()
}
override fun onDrawerClosed(drawerView: View) {
if (!isUsingNightModeResources()) {
window.updateStatusBarColor(getThemeColor(R.attr.headerBackgroundColor), true)
}
isOpeningDrawer = null
}
override fun onDrawerStateChanged(newState: Int) {
}
})
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
setupNotifications()
setupBottomnavigationLayoutListener()
binding.content.headerView.setContent {
MdcTheme(setTextColors = true) {
AppHeaderView(viewModel.userViewModel)
}
}
viewModel.onCreate()
}
override fun setTitle(title: CharSequence?) {
binding.content.toolbarTitle.text = title
}
override fun setTitle(titleId: Int) {
binding.content.toolbarTitle.text = getString(titleId)
}
private fun updateToolbarTitle(destination: NavDestination, arguments: Bundle?) {
viewModel.getToolbarTitle(destination.id, destination.label, arguments?.getString("type")) {
title = it
}
drawerFragment?.setSelection(destination.id, null, false)
}
override fun onSupportNavigateUp(): Boolean {
hideKeyboard()
onBackPressed()
return true
}
private fun setupNotifications() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "default"
val channel = NotificationChannel(
channelId,
"Habitica Notifications",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(channel)
}
}
private fun setupBottomnavigationLayoutListener() {
binding.content.bottomNavigation.viewTreeObserver.addOnGlobalLayoutListener {
if (binding.content.bottomNavigation.visibility == View.VISIBLE) {
snackbarContainer.setPadding(0, 0, 0, binding.content.bottomNavigation.barHeight + 12.dpToPx(this))
} else {
snackbarContainer.setPadding(0, 0, 0, 0)
}
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle?.syncState()
launchScreen = viewModel.launchScreen
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
drawerToggle?.onConfigurationChanged(newConfig)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (binding.root.parent is DrawerLayout && drawerToggle?.onOptionsItemSelected(item) == true) {
true
} else if (item.itemId == android.R.id.home) {
if (drawerToggle?.isDrawerIndicatorEnabled == true) {
drawerFragment?.toggleDrawer()
} else {
MainNavigationController.navigateBack()
}
true
} else super.onOptionsItemSelected(item)
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onResume() {
super.onResume()
viewModel.onResume()
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navigationController = navHostFragment.navController
MainNavigationController.setup(navigationController)
navigationController.addOnDestinationChangedListener { _, destination, arguments -> updateToolbarTitle(destination, arguments) }
if (launchScreen == "/party") {
viewModel.user.observeOnce(this) {
if (viewModel.userViewModel.isUserInParty) {
MainNavigationController.navigate(R.id.partyFragment)
}
}
}
launchScreen = null
if (!resumeFromActivity) {
retrieveUser()
this.checkMaintenance()
}
resumeFromActivity = false
if ((intent.hasExtra("notificationIdentifier") || intent.hasExtra("openURL")) && lastNotificationOpen != intent.getLongExtra("notificationTimeStamp", 0)) {
lastNotificationOpen = intent.getLongExtra("notificationTimeStamp", 0)
val identifier = intent.getStringExtra("notificationIdentifier") ?: ""
if (intent.hasExtra("sendAnalytics")) {
val additionalData = HashMap<String, Any>()
additionalData["identifier"] = identifier
AmplitudeManager.sendEvent(
"open notification",
AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR,
AmplitudeManager.EVENT_HITTYPE_EVENT,
additionalData
)
}
retrieveUser(true)
NotificationOpenHandler.handleOpenedByNotification(identifier, intent)
}
launchTrace?.stop()
launchTrace = null
if (binding.content.toolbarTitle.text?.isNotBlank() != true) {
navigationController.currentDestination?.let { updateToolbarTitle(it, null) }
}
}
override fun onPause() {
updateWidgets()
super.onPause()
}
override fun startActivity(intent: Intent?) {
resumeFromActivity = true
super.startActivity(intent)
}
override fun startActivity(intent: Intent?, options: Bundle?) {
resumeFromActivity = true
super.startActivity(intent, options)
}
private fun updateWidgets() {
updateWidget(AvatarStatsWidgetProvider::class.java)
updateWidget(TodoListWidgetProvider::class.java)
updateWidget(DailiesWidgetProvider::class.java)
updateWidget(HabitButtonWidgetProvider::class.java)
}
private fun updateWidget(widgetClass: Class<*>) {
val intent = Intent(this, widgetClass)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids = AppWidgetManager.getInstance(application).getAppWidgetIds(ComponentName(application, widgetClass))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
sendBroadcast(intent)
}
fun navigate(transitionId: Int) {
findNavController(R.id.nav_host_fragment).navigate(transitionId)
}
private fun setUserData(user: User?) {
if (user != null) {
val preferences = user.preferences
preferences?.language?.let { apiClient.setLanguageCode(it) }
if (preferences?.language != viewModel.preferenceLanguage) {
viewModel.preferenceLanguage = preferences?.language
}
preferences?.sound?.let { soundManager.soundTheme = it }
displayDeathDialogIfNeeded()
YesterdailyDialog.showDialogIfNeeded(this, user.id, userRepository, taskRepository)
if (user.flags?.verifiedUsername == false && isActivityVisible) {
val intent = Intent(this, VerifyUsernameActivity::class.java)
startActivity(intent)
}
val quest = user.party?.quest
if (quest?.completed?.isNotBlank() == true) {
lifecycleScope.launch(ExceptionHandler.coroutine()) {
val questContent = inventoryRepository.getQuestContent(user.party?.quest?.completed ?: "").firstOrNull()
if (questContent != null) {
QuestCompletedDialog.showWithQuest(this@MainActivity, questContent)
}
viewModel.updateUser("party.quest.completed", "")
}
}
if (user.flags?.welcomed == false) {
viewModel.updateUser("flags.welcomed", true)
}
val title = binding.content.toolbarTitle.text
if (title.isBlank()) {
viewModel.getToolbarTitle(0, null, null) { newTitle ->
this.title = newTitle
}
}
}
}
override fun onBackPressed() {
if (drawerFragment?.isDrawerOpen == true) {
drawerFragment?.closeDrawer()
} else {
try {
super.onBackPressed()
} catch (ignored: Exception) {
}
}
}
// region Events
public override fun onDestroy() {
userRepository.close()
inventoryRepository.close()
super.onDestroy()
}
// endregion
internal fun displayTaskScoringResponse(data: TaskScoringResult?) {
if (viewModel.user.value != null && data != null) {
val damageValue = when (userQuestStatus) {
UserQuestStatus.QUEST_BOSS -> data.questDamage
else -> 0.0
}
compositeSubscription.add(
notifyUserUseCase.observable(
NotifyUserUseCase.RequestValues(
this, snackbarContainer,
viewModel.user.value, data.experienceDelta, data.healthDelta, data.goldDelta, data.manaDelta, damageValue, data.hasLeveledUp, data.level
)
)
.subscribe({ }, ExceptionHandler.rx())
)
}
val showItemsFound = userQuestStatus == UserQuestStatus.QUEST_COLLECT
compositeSubscription.add(
displayItemDropUseCase.observable(DisplayItemDropUseCase.RequestValues(data, this, snackbarContainer, showItemsFound))
.subscribe({ }, ExceptionHandler.rx())
)
}
private var lastDeathDialogDisplay = 0L
private fun displayDeathDialogIfNeeded() {
if (!viewModel.userViewModel.isUserFainted) {
return
}
val now = Date().time
if (!this.isFinishing && MainNavigationController.isReady && now - lastDeathDialogDisplay > 60000) {
lastDeathDialogDisplay = now
MainNavigationController.navigate(R.id.deathActivity)
}
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_MENU) {
drawerFragment?.openDrawer()
return true
}
return super.onKeyUp(keyCode, event)
}
protected fun retrieveUser(forced: Boolean = false) {
viewModel.retrieveUser(forced)
}
fun displayTutorialStep(step: TutorialStep, texts: List<String>, canBeDeferred: Boolean) {
val view = TutorialView(this, step, viewModel)
view.setTutorialTexts(texts)
view.setCanBeDeferred(canBeDeferred)
binding.content.overlayFrameLayout.children.forEach {
if (it is TutorialView) {
binding.content.overlayFrameLayout.removeView(it)
}
}
binding.content.overlayFrameLayout.addView(view)
viewModel.logTutorialStatus(step, false)
}
private fun checkMaintenance() {
viewModel.ifNeedsMaintenance { maintenanceResponse ->
if (maintenanceResponse.activeMaintenance == true) {
val intent = createMaintenanceIntent(maintenanceResponse, false)
startActivity(intent)
} else {
if (maintenanceResponse.minBuild != null) {
try {
val packageInfo = packageManager.getPackageInfo(packageName, 0)
@Suppress("DEPRECATION")
if (packageInfo.versionCode < (maintenanceResponse.minBuild ?: 0)) {
val intent = createMaintenanceIntent(maintenanceResponse, true)
startActivity(intent)
}
} catch (e: PackageManager.NameNotFoundException) {
ExceptionHandler.reportError(e)
}
}
}
}
}
private fun createMaintenanceIntent(
maintenanceResponse: MaintenanceResponse,
isDeprecationNotice: Boolean
): Intent {
val intent = Intent(this, MaintenanceActivity::class.java)
val data = Bundle()
data.putString("title", maintenanceResponse.title)
data.putString("imageUrl", maintenanceResponse.imageUrl)
data.putString("description", maintenanceResponse.description)
data.putBoolean("deprecationNotice", isDeprecationNotice)
intent.putExtras(data)
return intent
}
override fun snackbarContainer(): ViewGroup {
return snackbarContainer
}
private var errorJob: Job? = null
override fun showConnectionProblem(title: String?, message: String) {
if (title != null) {
super.showConnectionProblem(title, message)
} else {
if (errorJob?.isCancelled == false) {
// a new error resets the timer to hide the error message
errorJob?.cancel()
}
binding.content.connectionIssueView.visibility = View.VISIBLE
binding.content.connectionIssueTextview.text = message
errorJob = lifecycleScope.launch(Dispatchers.Main) {
delay(1.toDuration(DurationUnit.MINUTES))
binding.content.connectionIssueView.visibility = View.GONE
}
}
}
override fun hideConnectionProblem() {
if (errorJob?.isCancelled == false) {
errorJob?.cancel()
}
lifecycleScope.launch(Dispatchers.Main) {
if (binding.content.connectionIssueView.visibility == View.VISIBLE) {
binding.content.connectionIssueView.visibility = View.GONE
}
}
}
}
| gpl-3.0 | 27b015df53d593ed3ab86071e43497fe | 38.137153 | 163 | 0.664508 | 5.325537 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/building_levels/AddBuildingLevels.kt | 1 | 1793 | package de.westnordost.streetcomplete.quests.building_levels
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
class AddBuildingLevels : OsmFilterQuestType<BuildingLevelsAnswer>() {
// building:height is undocumented, but used the same way as height and currently over 50k times
override val elementFilter = """
ways, relations with building ~ ${BUILDINGS_WITH_LEVELS.joinToString("|")}
and !building:levels and !height and !building:height
and !man_made and location != underground and ruins != yes
"""
override val commitMessage = "Add building and roof levels"
override val wikiLink = "Key:building:levels"
override val icon = R.drawable.ic_quest_building_levels
override fun getTitle(tags: Map<String, String>) =
if (tags.containsKey("building:part"))
R.string.quest_buildingLevels_title_buildingPart
else
R.string.quest_buildingLevels_title
override fun createForm() = AddBuildingLevelsForm()
override fun applyAnswerTo(answer: BuildingLevelsAnswer, changes: StringMapChangesBuilder) {
changes.add("building:levels", answer.levels.toString())
answer.roofLevels?.let { changes.addOrModify("roof:levels", it.toString()) }
}
}
private val BUILDINGS_WITH_LEVELS = arrayOf(
"house","residential","apartments","detached","terrace","dormitory","semi",
"semidetached_house","bungalow","school","civic","college","university","public",
"hospital","kindergarten","transportation","train_station", "hotel","retail",
"commercial","office","industrial","manufacture","parking","farm","farm_auxiliary",
"cabin")
| gpl-3.0 | 197c61b1435bd2d628a45425fa27af0b | 46.184211 | 100 | 0.722811 | 4.330918 | false | false | false | false |
slak44/gitforandroid | app/src/main/java/slak/gitforandroid/RepoListItemView.kt | 1 | 2621 | package slak.gitforandroid
import android.content.Context
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import org.eclipse.jgit.diff.DiffEntry
import slak.fslistview.FSAbstractListItem
import slak.fslistview.FSItemType
enum class GitStatus {
ADDED, MODIFIED, RENAMED, COPIED, NONE;
companion object {
fun from(t: DiffEntry.ChangeType): GitStatus = when (t) {
DiffEntry.ChangeType.ADD -> ADDED
DiffEntry.ChangeType.MODIFY -> MODIFIED
DiffEntry.ChangeType.RENAME -> RENAMED
DiffEntry.ChangeType.COPY -> COPIED
DiffEntry.ChangeType.DELETE -> NONE
}
}
}
class RepoListItemView : FSAbstractListItem {
constructor(context: Context) : super(context)
constructor(context: Context, set: AttributeSet) : super(context, set)
constructor(context: Context, set: AttributeSet, defStyle: Int) : super(context, set, defStyle)
private fun getTypeDrawable(): Drawable {
val drawable = when (type) {
FSItemType.FILE -> context.getDrawable(R.drawable.ic_file_black_24dp)
FSItemType.FOLDER -> context.getDrawable(R.drawable.ic_folder_black_24dp)
FSItemType.NONE -> ColorDrawable(Color.TRANSPARENT)
}
drawable.mutate()
drawable.setColorFilter(resources.getColor(R.color.white, null), PorterDuff.Mode.SRC_ATOP)
return drawable
}
private fun getStatusDrawable(): Drawable {
val drawableId = when (gitStatus) {
GitStatus.ADDED -> R.drawable.ic_add_black_24dp
GitStatus.MODIFIED -> R.drawable.ic_create_black_24dp
GitStatus.RENAMED, GitStatus.COPIED -> R.drawable.ic_content_copy_black_24dp
GitStatus.NONE -> 0
}
val drawable =
if (drawableId == 0) ColorDrawable(Color.TRANSPARENT)
else context.getDrawable(drawableId)
drawable.mutate()
val color = when (gitStatus) {
GitStatus.ADDED -> R.color.gitAdded
GitStatus.MODIFIED -> R.color.gitModified
GitStatus.RENAMED, GitStatus.COPIED -> R.color.gitMoved
GitStatus.NONE -> R.color.transparent
}
drawable.setColorFilter(resources.getColor(color, null), PorterDuff.Mode.SRC_ATOP)
return drawable
}
private fun redrawDrawables() {
setCompoundDrawablesWithIntrinsicBounds(getTypeDrawable(), null, getStatusDrawable(), null)
}
var gitStatus: GitStatus = GitStatus.NONE
set(value) {
field = value
redrawDrawables()
}
override var type: FSItemType = FSItemType.NONE
set(type) {
field = type
redrawDrawables()
}
}
| mit | 6ee549ac125fa4e2a0bc6b57f9a44f17 | 32.177215 | 97 | 0.720336 | 3.989346 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_NEEDLE_SUCCESS.kt | 1 | 1730 | package info.nightscout.androidaps.diaconn.pumplog
import java.nio.ByteBuffer
import java.nio.ByteOrder
/*
* 바늘 공기빼기 성공
*/
class LOG_CHANGE_NEEDLE_SUCCESS private constructor(
val data: String,
val dttm: String,
typeAndKind: Byte, // 47.5=4750
val primeAmount: Short, // 47.5=4750
val remainAmount: Short,
val batteryRemain: Byte
) {
val type: Byte = PumplogUtil.getType(typeAndKind)
val kind: Byte = PumplogUtil.getKind(typeAndKind)
override fun toString(): String {
val sb = StringBuilder("LOG_CHANGE_NEEDLE_SUCCESS{")
sb.append("LOG_KIND=").append(LOG_KIND.toInt())
sb.append(", data='").append(data).append('\'')
sb.append(", dttm='").append(dttm).append('\'')
sb.append(", type=").append(type.toInt())
sb.append(", kind=").append(kind.toInt())
sb.append(", primeAmount=").append(primeAmount.toInt())
sb.append(", remainAmount=").append(remainAmount.toInt())
sb.append(", batteryRemain=").append(batteryRemain.toInt())
sb.append('}')
return sb.toString()
}
companion object {
const val LOG_KIND: Byte = 0x1C
fun parse(data: String): LOG_CHANGE_NEEDLE_SUCCESS {
val bytes = PumplogUtil.hexStringToByteArray(data)
val buffer = ByteBuffer.wrap(bytes)
buffer.order(ByteOrder.LITTLE_ENDIAN)
return LOG_CHANGE_NEEDLE_SUCCESS(
data,
PumplogUtil.getDttm(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getShort(buffer),
PumplogUtil.getShort(buffer),
PumplogUtil.getByte(buffer)
)
}
}
} | agpl-3.0 | 1cac0c0525402692ee7967ed0d299ba8 | 31.358491 | 67 | 0.602684 | 4.004673 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/adapter/CategoryAdapter.kt | 1 | 6043 | package com.rolandvitezhu.todocloud.ui.activity.main.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import com.rolandvitezhu.todocloud.R
import com.rolandvitezhu.todocloud.data.Category
import com.rolandvitezhu.todocloud.databinding.ItemCategoryBinding
import com.rolandvitezhu.todocloud.databinding.ItemListincategoryBinding
import com.rolandvitezhu.todocloud.di.FragmentScope
import kotlinx.android.synthetic.main.item_category.view.*
import java.util.*
import javax.inject.Inject
@FragmentScope
class CategoryAdapter @Inject constructor() : BaseExpandableListAdapter() {
private val categories: MutableList<Category>
private val lhmCategories: LinkedHashMap<Category, List<com.rolandvitezhu.todocloud.data.List>>
override fun getGroupCount(): Int {
return categories.size
}
override fun getChildrenCount(groupPosition: Int): Int {
val category = categories[groupPosition]
val lists = lhmCategories[category]
return lists?.size ?: 0
}
override fun getGroup(groupPosition: Int): Any {
return categories[groupPosition]
}
override fun getChild(groupPosition: Int, childPosition: Int): Any {
val category = categories[groupPosition]
val lists = lhmCategories[category]
return lists?.get(childPosition)!!
}
override fun getGroupId(groupPosition: Int): Long {
val (_id) = categories[groupPosition]
return _id!!
}
override fun getChildId(groupPosition: Int, childPosition: Int): Long {
val category = categories[groupPosition]
val lists = lhmCategories[category]
val list = lists?.get(childPosition)
return (if (list != null) list._id else -1)!!
}
override fun hasStableIds(): Boolean {
return false
}
override fun getGroupView(
groupPosition: Int,
isExpanded: Boolean,
convertView: View?,
parent: ViewGroup
): View {
var convertView = convertView
val layoutInflater = parent.context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
val itemCategoryBinding: ItemCategoryBinding
if (convertView == null) {
itemCategoryBinding = ItemCategoryBinding.inflate(
layoutInflater,
parent,
false
)
convertView = itemCategoryBinding.root
} else {
itemCategoryBinding = convertView.tag as ItemCategoryBinding
}
val category = getGroup(groupPosition) as Category
itemCategoryBinding.category = category
itemCategoryBinding.categoryAdapter = this
itemCategoryBinding.groupPosition = groupPosition
itemCategoryBinding.isExpanded = isExpanded
itemCategoryBinding.convertView = convertView
itemCategoryBinding.executePendingBindings()
convertView.tag = itemCategoryBinding
return convertView
}
fun handleCategoryIndicator(groupPosition: Int, isExpanded: Boolean, convertView: View) {
if (shouldNotShowGroupIndicator(groupPosition)) {
hideExpandedGroupIndicator(convertView)
} else if (isExpanded) {
showExpandedGroupIndicator(convertView)
} else {
showCollapsedGroupIndicator(convertView)
}
}
private fun hideExpandedGroupIndicator(convertView: View) {
convertView.imageview_itemcategory_groupindicator.visibility = View.INVISIBLE
}
private fun showCollapsedGroupIndicator(convertView: View) {
convertView.imageview_itemcategory_groupindicator.visibility = View.VISIBLE
convertView.imageview_itemcategory_groupindicator.setImageResource(R.drawable.baseline_expand_less_24)
}
private fun showExpandedGroupIndicator(convertView: View) {
convertView.imageview_itemcategory_groupindicator.visibility = View.VISIBLE
convertView.imageview_itemcategory_groupindicator.setImageResource(R.drawable.baseline_expand_more_24)
}
private fun shouldNotShowGroupIndicator(groupPosition: Int): Boolean {
return getChildrenCount(groupPosition) == 0
}
override fun getChildView(
groupPosition: Int,
childPosition: Int,
isLastChild: Boolean,
convertView: View?,
parent: ViewGroup
): View {
var convertView = convertView
val itemListincategoryBinding: ItemListincategoryBinding
val layoutInflater = parent.context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE
) as LayoutInflater
if (convertView == null) {
itemListincategoryBinding = ItemListincategoryBinding.inflate(
layoutInflater,
parent,
false
)
convertView = itemListincategoryBinding.root
} else {
itemListincategoryBinding = convertView.tag as ItemListincategoryBinding
}
val list = getChild(groupPosition, childPosition) as com.rolandvitezhu.todocloud.data.List
itemListincategoryBinding.list = list
itemListincategoryBinding.executePendingBindings()
convertView.tag = itemListincategoryBinding
return convertView
}
override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
return true
}
fun update(lhmCategories: LinkedHashMap<Category, List<com.rolandvitezhu.todocloud.data.List>>) {
categories.clear()
this.lhmCategories.clear()
categories.addAll(lhmCategories.keys)
this.lhmCategories.putAll(lhmCategories)
}
fun clear() {
categories.clear()
lhmCategories.clear()
notifyDataSetChanged()
}
init {
categories = ArrayList()
lhmCategories = LinkedHashMap()
}
} | mit | a269e04b897a095ffa70b2788f5ca244 | 32.765363 | 110 | 0.681119 | 5.286964 | false | false | false | false |
CherryPerry/Amiami-kotlin-backend | src/main/kotlin/com/cherryperry/amiami/model/update/UpdateComponent.kt | 1 | 3927 | package com.cherryperry.amiami.model.update
import com.cherryperry.amiami.model.mongodb.Item
import com.cherryperry.amiami.model.mongodb.ItemRepository
import com.cherryperry.amiami.model.push.PushService
import org.apache.logging.log4j.LogManager
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
@Component
class UpdateComponent @Autowired constructor(
private val itemRepository: ItemRepository,
private val pushService: PushService,
private val restClient: AmiamiRestClient,
private val timeout: Pair<Long, TimeUnit> = DEFAULT_TIMEOUT_MINUTES to TimeUnit.MINUTES,
) {
companion object {
const val PER_PAGE = 20
const val CATEGORY_FIGURE_BISHOUJO = 14
const val CATEGORY_FIGURE_CHARACTER = 15
const val CATEGORY_FIGURE_DOLL = 2
const val DEFAULT_TIMEOUT_MINUTES = 5L
}
private val log = LogManager.getLogger(UpdateComponent::class.java)
private var threadCounter = 0
private var syncInProgress = false
fun sync() {
log.trace("sync")
synchronized(this) {
if (syncInProgress) {
log.warn("Sync already in progress!")
return
}
syncInProgress = true
}
val countDownLatch = CountDownLatch(1)
val thread = thread(name = "SyncThread#${threadCounter++}") {
try {
doSync()
} catch (expected: Exception) {
log.error(expected)
} finally {
countDownLatch.countDown()
}
}
// if sync is stuck – interrupt it
val success = countDownLatch.await(timeout.first, timeout.second)
if (!success) thread.interrupt()
synchronized(this) { syncInProgress = false }
}
private fun doSync() {
log.trace("doSync")
val startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
log.info("Sync started at $startTime")
// Загружаем а парсим информацию об элементах
val allItems = arrayListOf<AmiamiListItem>()
arrayOf(CATEGORY_FIGURE_BISHOUJO, CATEGORY_FIGURE_CHARACTER).forEach {
var page: AmiamiApiListResponse
var pageNumber = 1
do {
page = restClient.items(it, PER_PAGE, pageNumber++)
val items = page.items
items?.let { allItems += it.filter { it.hasPrice } }
} while (page.success && items != null && items.isNotEmpty())
}
// Сохраняем элементы в бд, попутно запоманая те, которые участвовали в транзакции
val ids = ArrayList<String>()
var updatedItemsCount = 0
allItems.forEach { item ->
try {
val dbItem = Item(
"https://www.amiami.com/eng/detail/?gcode=${item.url}", item.name ?: "",
"https://img.amiami.com${item.image}", "${item.price} JPY", "", startTime
)
ids.add(dbItem.url)
if (itemRepository.compareAndSave(dbItem)) {
updatedItemsCount++
}
} catch (expected: Exception) {
log.error("Failed to download and parse detail page", expected)
}
if (Thread.interrupted()) {
return
}
}
// Удалим ненайденные элементы
itemRepository.deleteOther(ids)
// Отправим оповещение об обновлении
if (updatedItemsCount > 0) {
pushService.sendPushWithUpdatedCount(updatedItemsCount)
}
}
}
| apache-2.0 | 5705fd7a5fa90ed3e1653e0cf5a94502 | 33.236364 | 93 | 0.60462 | 4.384168 | false | false | false | false |
square/wire | wire-library/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt | 1 | 13392 | /*
* Copyright 2015 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import com.squareup.wire.internal.createRuntimeMessageAdapter
import okio.BufferedSink
import okio.BufferedSource
import okio.ByteString
import okio.buffer
import okio.sink
import okio.source
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import kotlin.reflect.KClass
actual abstract class ProtoAdapter<E> actual constructor(
internal actual val fieldEncoding: FieldEncoding,
actual val type: KClass<*>?,
actual val typeUrl: String?,
actual val syntax: Syntax,
actual val identity: E?,
actual val sourceFile: String?,
) {
internal actual val packedAdapter: ProtoAdapter<List<E>>? = when {
this is PackedProtoAdapter<*> || this is RepeatedProtoAdapter<*> -> null
fieldEncoding == FieldEncoding.LENGTH_DELIMITED -> null
else -> commonCreatePacked()
}
internal actual val repeatedAdapter: ProtoAdapter<List<E>>? = when {
this is RepeatedProtoAdapter<*> || this is PackedProtoAdapter<*> -> null
else -> commonCreateRepeated()
}
// Obsolete; for Java classes generated before typeUrl was added.
constructor(fieldEncoding: FieldEncoding, type: Class<*>) : this(fieldEncoding, type.kotlin)
// Obsolete; for Java classes generated before syntax was added.
constructor(fieldEncoding: FieldEncoding, type: Class<*>, typeUrl: String?) :
this(fieldEncoding, type.kotlin, typeUrl, Syntax.PROTO_2)
// Obsolete; for Java classes generated before identity was added.
constructor(fieldEncoding: FieldEncoding, type: Class<*>, typeUrl: String?, syntax: Syntax) :
this(fieldEncoding, type.kotlin, typeUrl, syntax)
// Obsolete; for Java classes generated before sourceFile was added.
constructor(fieldEncoding: FieldEncoding, type: Class<*>, typeUrl: String?, syntax: Syntax, identity: E?) :
this(fieldEncoding, type.kotlin, typeUrl, syntax, identity, null)
// Obsolete; for Kotlin classes generated before typeUrl was added.
constructor(fieldEncoding: FieldEncoding, type: KClass<*>?) :
this(fieldEncoding, type, null, Syntax.PROTO_2)
// Obsolete; for Kotlin classes generated before syntax was added.
constructor(fieldEncoding: FieldEncoding, type: KClass<*>?, typeUrl: String?) :
this(fieldEncoding, type, typeUrl, Syntax.PROTO_2)
// Obsolete; for Kotlin classes generated before identity was added.
constructor(fieldEncoding: FieldEncoding, type: KClass<*>?, typeUrl: String?, syntax: Syntax) :
this(fieldEncoding, type, typeUrl, syntax, null)
// Obsolete; for Kotlin classes generated before sourceFile was added.
constructor(
fieldEncoding: FieldEncoding,
type: KClass<*>?,
typeUrl: String?,
syntax: Syntax,
identity: E?
) :
this(fieldEncoding, type, typeUrl, syntax, identity, null)
constructor(
fieldEncoding: FieldEncoding,
type: Class<*>,
typeUrl: String?,
syntax: Syntax,
identity: E?,
sourceFile: String?,
) : this(fieldEncoding, type.kotlin, typeUrl, syntax, identity, sourceFile)
actual abstract fun redact(value: E): E
actual abstract fun encodedSize(value: E): Int
actual open fun encodedSizeWithTag(tag: Int, value: E?): Int {
return commonEncodedSizeWithTag(tag, value)
}
@Throws(IOException::class)
actual abstract fun encode(writer: ProtoWriter, value: E)
@Throws(IOException::class)
actual open fun encode(writer: ReverseProtoWriter, value: E) {
delegateEncode(writer, value)
}
@Throws(IOException::class)
actual open fun encodeWithTag(writer: ProtoWriter, tag: Int, value: E?) {
commonEncodeWithTag(writer, tag, value)
}
@Throws(IOException::class)
actual open fun encodeWithTag(writer: ReverseProtoWriter, tag: Int, value: E?) {
commonEncodeWithTag(writer, tag, value)
}
@Throws(IOException::class)
actual fun encode(sink: BufferedSink, value: E) {
commonEncode(sink, value)
}
actual fun encode(value: E): ByteArray {
return commonEncode(value)
}
actual fun encodeByteString(value: E): ByteString {
return commonEncodeByteString(value)
}
@Throws(IOException::class)
fun encode(stream: OutputStream, value: E) {
val buffer = stream.sink().buffer()
encode(buffer, value)
buffer.emit()
}
@Throws(IOException::class)
actual abstract fun decode(reader: ProtoReader): E
@Throws(IOException::class)
actual fun decode(bytes: ByteArray): E {
return commonDecode(bytes)
}
@Throws(IOException::class)
actual fun decode(bytes: ByteString): E {
return commonDecode(bytes)
}
@Throws(IOException::class)
actual fun decode(source: BufferedSource): E {
return commonDecode(source)
}
@Throws(IOException::class)
fun decode(stream: InputStream): E = decode(stream.source().buffer())
actual open fun toString(value: E): String {
return commonToString(value)
}
internal actual fun withLabel(label: WireField.Label): ProtoAdapter<*> {
return commonWithLabel(label)
}
actual fun asPacked(): ProtoAdapter<List<E>> {
require(fieldEncoding != FieldEncoding.LENGTH_DELIMITED) {
"Unable to pack a length-delimited type."
}
return packedAdapter ?: throw UnsupportedOperationException(
"Can't create a packed adapter from a packed or repeated adapter."
)
}
actual fun asRepeated(): ProtoAdapter<List<E>> {
return repeatedAdapter ?: throw UnsupportedOperationException(
"Can't create a repeated adapter from a repeated or packed adapter."
)
}
internal val isStruct: Boolean
get() = this == STRUCT_MAP || this == STRUCT_LIST || this == STRUCT_VALUE || this == STRUCT_NULL
actual class EnumConstantNotFoundException actual constructor(
@JvmField actual val value: Int,
type: KClass<*>?
) : IllegalArgumentException("Unknown enum tag $value for ${type?.java?.name}") {
constructor(value: Int, type: Class<*>) : this(value, type.kotlin)
}
actual companion object {
@JvmStatic actual fun <K, V> newMapAdapter(
keyAdapter: ProtoAdapter<K>,
valueAdapter: ProtoAdapter<V>
): ProtoAdapter<Map<K, V>> {
return commonNewMapAdapter(keyAdapter, valueAdapter)
}
// Obsolete; for Java classes generated before typeUrl and syntax were added.
@JvmStatic fun <M : Message<M, B>, B : Message.Builder<M, B>> newMessageAdapter(
type: Class<M>
): ProtoAdapter<M> {
return createRuntimeMessageAdapter(type, null, Syntax.PROTO_2)
}
// Obsolete; for Java classes generated before typeUrl and syntax were added.
@JvmStatic fun <M : Message<M, B>, B : Message.Builder<M, B>> newMessageAdapter(
type: Class<M>,
typeUrl: String
): ProtoAdapter<M> {
return createRuntimeMessageAdapter(type, typeUrl, Syntax.PROTO_2)
}
/** Creates a new proto adapter for `type`. */
@JvmStatic fun <M : Message<M, B>, B : Message.Builder<M, B>> newMessageAdapter(
type: Class<M>,
typeUrl: String,
syntax: Syntax
): ProtoAdapter<M> {
return createRuntimeMessageAdapter(type, typeUrl, syntax)
}
/** Creates a new proto adapter for `type`. */
@JvmStatic fun <E : WireEnum> newEnumAdapter(type: Class<E>): EnumAdapter<E> {
return RuntimeEnumAdapter(type)
}
/** Returns the adapter for the type of `Message`. */
@JvmStatic fun <M : Message<*, *>> get(message: M): ProtoAdapter<M> {
return get(message.javaClass)
}
/** Returns the adapter for `type`. */
@JvmStatic fun <M> get(type: Class<M>): ProtoAdapter<M> {
try {
return type.getField("ADAPTER").get(null) as ProtoAdapter<M>
} catch (e: IllegalAccessException) {
throw IllegalArgumentException("failed to access ${type.name}#ADAPTER", e)
} catch (e: NoSuchFieldException) {
throw IllegalArgumentException("failed to access ${type.name}#ADAPTER", e)
}
}
/**
* Returns the adapter for a given `adapterString`. `adapterString` is specified on a proto
* message field's [WireField] annotation in the form
* `com.squareup.wire.protos.person.Person#ADAPTER`.
*/
@JvmStatic fun get(adapterString: String): ProtoAdapter<*> {
try {
val hash = adapterString.indexOf('#')
val className = adapterString.substring(0, hash)
val fieldName = adapterString.substring(hash + 1)
return Class.forName(className).getField(fieldName).get(null) as ProtoAdapter<Any>
} catch (e: IllegalAccessException) {
throw IllegalArgumentException("failed to access $adapterString", e)
} catch (e: NoSuchFieldException) {
throw IllegalArgumentException("failed to access $adapterString", e)
} catch (e: ClassNotFoundException) {
throw IllegalArgumentException("failed to access $adapterString", e)
}
}
@JvmField actual val BOOL: ProtoAdapter<Boolean> = commonBool()
@JvmField actual val INT32: ProtoAdapter<Int> = commonInt32()
@JvmField actual val UINT32: ProtoAdapter<Int> = commonUint32()
@JvmField actual val SINT32: ProtoAdapter<Int> = commonSint32()
@JvmField actual val FIXED32: ProtoAdapter<Int> = commonFixed32()
@JvmField actual val SFIXED32: ProtoAdapter<Int> = commonSfixed32()
@JvmField actual val INT64: ProtoAdapter<Long> = commonInt64()
@JvmField actual val UINT64: ProtoAdapter<Long> = commonUint64()
@JvmField actual val SINT64: ProtoAdapter<Long> = commonSint64()
@JvmField actual val FIXED64: ProtoAdapter<Long> = commonFixed64()
@JvmField actual val SFIXED64: ProtoAdapter<Long> = commonSfixed64()
@JvmField actual val FLOAT: ProtoAdapter<Float> = commonFloat()
@JvmField actual val DOUBLE: ProtoAdapter<Double> = commonDouble()
@JvmField actual val BYTES: ProtoAdapter<ByteString> = commonBytes()
@JvmField actual val STRING: ProtoAdapter<String> = commonString()
@JvmField actual val EMPTY: ProtoAdapter<Unit> = commonEmpty()
@JvmField actual val STRUCT_MAP: ProtoAdapter<Map<String, *>?> = commonStructMap()
@JvmField actual val STRUCT_LIST: ProtoAdapter<List<*>?> = commonStructList()
@JvmField actual val STRUCT_NULL: ProtoAdapter<Nothing?> = commonStructNull()
@JvmField actual val STRUCT_VALUE: ProtoAdapter<Any?> = commonStructValue()
@JvmField actual val DOUBLE_VALUE: ProtoAdapter<Double?> = commonWrapper(DOUBLE, "type.googleapis.com/google.protobuf.DoubleValue")
@JvmField actual val FLOAT_VALUE: ProtoAdapter<Float?> = commonWrapper(FLOAT, "type.googleapis.com/google.protobuf.FloatValue")
@JvmField actual val INT64_VALUE: ProtoAdapter<Long?> = commonWrapper(INT64, "type.googleapis.com/google.protobuf.Int64Value")
@JvmField actual val UINT64_VALUE: ProtoAdapter<Long?> = commonWrapper(UINT64, "type.googleapis.com/google.protobuf.UInt64Value")
@JvmField actual val INT32_VALUE: ProtoAdapter<Int?> = commonWrapper(INT32, "type.googleapis.com/google.protobuf.Int32Value")
@JvmField actual val UINT32_VALUE: ProtoAdapter<Int?> = commonWrapper(UINT32, "type.googleapis.com/google.protobuf.UInt32Value")
@JvmField actual val BOOL_VALUE: ProtoAdapter<Boolean?> = commonWrapper(BOOL, "type.googleapis.com/google.protobuf.BoolValue")
@JvmField actual val STRING_VALUE: ProtoAdapter<String?> = commonWrapper(STRING, "type.googleapis.com/google.protobuf.StringValue")
@JvmField actual val BYTES_VALUE: ProtoAdapter<ByteString?> = commonWrapper(BYTES, "type.googleapis.com/google.protobuf.BytesValue")
@JvmField actual val DURATION: ProtoAdapter<Duration> = try {
commonDuration()
} catch (_: NoClassDefFoundError) {
UnsupportedTypeProtoAdapter() as ProtoAdapter<Duration>
}
@JvmField actual val INSTANT: ProtoAdapter<Instant> = try {
commonInstant()
} catch (_: NoClassDefFoundError) {
UnsupportedTypeProtoAdapter() as ProtoAdapter<Instant>
}
/**
* Stub [ProtoAdapter] for Wire types which are typeliased to `java.time` types on the JVM
* such as [Duration] and [Instant]. This proto adapter is used when the corresponding
* `java.time` type is missing from the JVM classpath.
*/
class UnsupportedTypeProtoAdapter : ProtoAdapter<Nothing>(
FieldEncoding.LENGTH_DELIMITED,
Nothing::class
) {
override fun redact(value: Nothing) =
throw IllegalStateException("Operation not supported.")
override fun encodedSize(value: Nothing) =
throw IllegalStateException("Operation not supported.")
override fun encode(writer: ProtoWriter, value: Nothing) =
throw IllegalStateException("Operation not supported.")
override fun encode(writer: ReverseProtoWriter, value: Nothing) =
throw IllegalStateException("Operation not supported.")
override fun decode(reader: ProtoReader): Nothing =
throw IllegalStateException("Operation not supported.")
}
}
}
| apache-2.0 | ee844f142dbb57ce5a54f31accbffe15 | 39.829268 | 136 | 0.711171 | 4.300578 | false | false | false | false |
Tandrial/Advent_of_Code | src/aoc2017/kot/Day09.kt | 1 | 953 | package aoc2017.kot
import java.io.File
object Day09 {
private enum class State { DEFAULT, GARBAGE, IGNORE }
fun solve(input: String): Pair<Int, Int> {
var state = State.DEFAULT
var sum = 0
var groupCount = 0
var garbageCount = 0
input.forEach {
// Ignore can only be in Garbage
when (state) {
State.DEFAULT -> when (it) {
'<' -> state = State.GARBAGE
'{' -> groupCount++
'}' -> sum += groupCount--
}
State.GARBAGE -> when (it) {
'!' -> state = State.IGNORE
'>' -> state = State.DEFAULT
else -> garbageCount++
}
State.IGNORE -> state = State.GARBAGE
}
}
return Pair(sum, garbageCount)
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day09_input.txt").readText()
val (partOne, partTwo) = Day09.solve(input)
println("Part One = $partOne")
println("Part Two = $partTwo")
}
| mit | fc443e103a3b6345bf185e675412614d | 24.078947 | 61 | 0.558237 | 3.679537 | false | false | false | false |
mutcianm/android-dsl | src/kotlinlib/stringJoin.kt | 2 | 1003 | package kotlinlib
public fun buildString(body: (sb: StringBuilder) -> Unit): String {
val sb = StringBuilder()
body(sb)
return sb.toString()
}
public fun Iterator<Any?>.join(separator: String = "", before: String = "", after: String = ""): String {
return buildString {
it.append(before)
while (hasNext()) {
it.append(next())
if (hasNext()) {
it.append(separator)
}
}
it.append(after)
}
}
public fun Iterable<Any?>.join(separator: String = "", before: String = "", after: String = ""): String
= iterator().join(separator, before, after)
public fun Array<out Any?>.join(separator: String = "", before: String = "", after: String = ""): String {
return buildString {
it.append(before)
for (i in this.indices) {
it.append(this[i])
if (i < size - 1) {
it.append(separator)
}
}
it.append(after)
}
}
| apache-2.0 | 2e5399fe98123838a9685eb171674819 | 26.108108 | 106 | 0.532403 | 4.044355 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/restore/RestoreFragment.kt | 1 | 7250 | package org.wordpress.android.ui.jetpack.restore
import android.app.Activity.RESULT_CANCELED
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.snackbar.Snackbar
import org.wordpress.android.R
import org.wordpress.android.R.dimen
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.JetpackBackupRestoreFragmentBinding
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.jetpack.common.adapters.JetpackBackupRestoreAdapter
import org.wordpress.android.ui.jetpack.restore.RestoreNavigationEvents.ShowJetpackSettings
import org.wordpress.android.ui.jetpack.restore.RestoreNavigationEvents.VisitSite
import org.wordpress.android.ui.jetpack.restore.RestoreViewModel.RestoreWizardState.RestoreCanceled
import org.wordpress.android.ui.jetpack.restore.RestoreViewModel.RestoreWizardState.RestoreCompleted
import org.wordpress.android.ui.jetpack.restore.RestoreViewModel.RestoreWizardState.RestoreInProgress
import org.wordpress.android.ui.jetpack.scan.adapters.HorizontalMarginItemDecoration
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.viewmodel.observeEvent
import org.wordpress.android.widgets.WPSnackbar
import javax.inject.Inject
const val KEY_RESTORE_REWIND_ID = "key_restore_rewind_id"
const val KEY_RESTORE_RESTORE_ID = "key_restore_restore_id"
class RestoreFragment : Fragment(R.layout.jetpack_backup_restore_fragment) {
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject lateinit var uiHelpers: UiHelpers
@Inject lateinit var imageManager: ImageManager
private lateinit var viewModel: RestoreViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(JetpackBackupRestoreFragmentBinding.bind(view)) {
initDagger()
initBackPressHandler()
initAdapter()
initViewModel(savedInstanceState)
}
}
private fun initDagger() {
(requireActivity().application as WordPress).component().inject(this)
}
private fun initBackPressHandler() {
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(
true
) {
override fun handleOnBackPressed() {
onBackPressed()
}
})
}
private fun onBackPressed() {
viewModel.onBackPressed()
}
private fun JetpackBackupRestoreFragmentBinding.initAdapter() {
recyclerView.adapter = JetpackBackupRestoreAdapter(imageManager, uiHelpers)
recyclerView.itemAnimator = null
recyclerView.addItemDecoration(
HorizontalMarginItemDecoration(resources.getDimensionPixelSize(dimen.margin_extra_large))
)
}
private fun JetpackBackupRestoreFragmentBinding.initViewModel(savedInstanceState: Bundle?) {
viewModel = ViewModelProvider(this@RestoreFragment, viewModelFactory).get(RestoreViewModel::class.java)
val (site, activityId) = when {
requireActivity().intent?.extras != null -> {
val site = requireNotNull(requireActivity().intent.extras).getSerializable(WordPress.SITE) as SiteModel
val activityId = requireNotNull(requireActivity().intent.extras).getString(
KEY_RESTORE_ACTIVITY_ID_KEY
) as String
site to activityId
}
else -> {
AppLog.e(T.JETPACK_REWIND, "Error initializing ${this.javaClass.simpleName}")
throw Throwable("Couldn't initialize ${this.javaClass.simpleName} view model")
}
}
initObservers()
viewModel.start(site, activityId, savedInstanceState)
}
private fun JetpackBackupRestoreFragmentBinding.initObservers() {
viewModel.uiState.observe(viewLifecycleOwner, {
updateToolbar(it.toolbarState)
showView(it)
})
viewModel.snackbarEvents.observeEvent(viewLifecycleOwner, {
it.showSnackbar()
})
viewModel.navigationEvents.observeEvent(viewLifecycleOwner, { events ->
when (events) {
is VisitSite -> ActivityLauncher.openUrlExternal(requireContext(), events.url)
is ShowJetpackSettings -> ActivityLauncher.openUrlExternal(requireContext(), events.url)
}
})
viewModel.wizardFinishedObservable.observeEvent(viewLifecycleOwner, { state ->
val intent = Intent()
val (restoreCreated, ids) = when (state) {
is RestoreCanceled -> Pair(false, null)
is RestoreInProgress -> Pair(true, Pair(state.rewindId, state.restoreId))
is RestoreCompleted -> Pair(true, null)
}
intent.putExtra(KEY_RESTORE_REWIND_ID, ids?.first)
intent.putExtra(KEY_RESTORE_RESTORE_ID, ids?.second)
requireActivity().let { activity ->
activity.setResult(if (restoreCreated) RESULT_OK else RESULT_CANCELED, intent)
activity.finish()
}
})
}
private fun JetpackBackupRestoreFragmentBinding.showView(state: RestoreUiState) {
((recyclerView.adapter) as JetpackBackupRestoreAdapter).update(state.items)
}
private fun updateToolbar(toolbarState: ToolbarState) {
val activity = requireActivity() as? AppCompatActivity
activity?.supportActionBar?.let {
it.setHomeButtonEnabled(true)
it.setDisplayHomeAsUpEnabled(true)
it.title = getString(toolbarState.title)
it.setHomeAsUpIndicator(toolbarState.icon)
}
}
private fun SnackbarMessageHolder.showSnackbar() {
activity?.findViewById<View>(R.id.coordinator_layout)?.let { coordinator ->
val snackbar = WPSnackbar.make(
coordinator,
uiHelpers.getTextOfUiString(requireContext(), this.message),
Snackbar.LENGTH_LONG
)
if (this.buttonTitle != null) {
snackbar.setAction(
uiHelpers.getTextOfUiString(
requireContext(),
this.buttonTitle
)
) {
this.buttonAction.invoke()
}
}
snackbar.show()
}
}
override fun onSaveInstanceState(outState: Bundle) {
viewModel.writeToBundle(outState)
super.onSaveInstanceState(outState)
}
}
| gpl-2.0 | fa8b3fd12de2c2555eeb7267aaab2264 | 40.193182 | 119 | 0.674897 | 5.378338 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/reactnative/ReactNativeRequestHandler.kt | 1 | 3221 | package org.wordpress.android.ui.posts.reactnative
import android.os.Bundle
import androidx.core.util.Consumer
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.BaseRequest
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest
import org.wordpress.android.fluxc.store.ReactNativeFetchResponse
import org.wordpress.android.fluxc.store.ReactNativeFetchResponse.Error
import org.wordpress.android.fluxc.store.ReactNativeFetchResponse.Success
import org.wordpress.android.fluxc.store.ReactNativeStore
import org.wordpress.android.modules.BG_THREAD
import javax.inject.Inject
import javax.inject.Named
class ReactNativeRequestHandler @Inject constructor(
private val reactNativeStore: ReactNativeStore,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher
) : CoroutineScope {
override val coroutineContext = bgDispatcher + Job()
fun performGetRequest(
pathWithParams: String,
mSite: SiteModel,
enableCaching: Boolean,
onSuccess: Consumer<String>,
onError: Consumer<Bundle>
) {
launch {
val response = reactNativeStore.executeRequest(mSite, pathWithParams, enableCaching)
handleResponse(response, onSuccess::accept, onError::accept)
}
}
/**
* A given instance of this class may not be used after [destroy] is called because:
* (1) this class's coroutineContext has a single job instance that is created on initialization;
* (2) calling `destroy()` cancels that job; and
* (3) jobs cannot be reused once cancelled.
*/
fun destroy() {
coroutineContext[Job]!!.cancel()
}
private fun handleResponse(
response: ReactNativeFetchResponse,
onSuccess: (String) -> Unit,
onError: (Bundle) -> Unit
) {
when (response) {
is Success -> onSuccess(response.result.toString())
is Error -> {
val bundle = Bundle().apply {
response.error.volleyError?.networkResponse?.statusCode?.let {
putInt("code", it)
}
extractErrorMessage(response.error)?.let {
putString("message", it)
}
}
onError(bundle)
}
}
}
private fun extractErrorMessage(networkError: BaseRequest.BaseNetworkError): String? {
val volleyError = networkError.volleyError?.message
val wpComError = (networkError as? WPComGsonRequest.WPComGsonNetworkError)?.apiError
val baseError = networkError.message
val errorType = networkError.type?.toString()
return when {
volleyError?.isNotBlank() == true -> volleyError
wpComError?.isNotBlank() == true -> wpComError
baseError?.isNotBlank() == true -> baseError
errorType?.isNotBlank() == true -> errorType
else -> "Unknown ${networkError.javaClass.simpleName} Error"
}
}
}
| gpl-2.0 | 1dad03ea3ddb571e5ba0eea831b73ce9 | 37.807229 | 105 | 0.665321 | 4.993798 | false | false | false | false |
ingokegel/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/refsFromAnotherModule/after/gen/ReferredEntityImpl.kt | 1 | 8657 | package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ReferredEntityImpl : ReferredEntity, WorkspaceEntityBase() {
companion object {
internal val CONTENTROOT_CONNECTION_ID: ConnectionId = ConnectionId.create(ReferredEntity::class.java, ContentRootEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
CONTENTROOT_CONNECTION_ID,
)
}
override var version: Int = 0
@JvmField
var _name: String? = null
override val name: String
get() = _name!!
override val contentRoot: ContentRootEntity?
get() = snapshot.extractOneToOneChild(CONTENTROOT_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ReferredEntityData?) : ModifiableWorkspaceEntityBase<ReferredEntity>(), ReferredEntity.Builder {
constructor() : this(ReferredEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ReferredEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field ReferredEntity#name should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ReferredEntity
this.entitySource = dataSource.entitySource
this.version = dataSource.version
this.name = dataSource.name
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var version: Int
get() = getEntityData().version
set(value) {
checkModificationAllowed()
getEntityData().version = value
changedProperty.add("version")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var contentRoot: ContentRootEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CONTENTROOT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
CONTENTROOT_CONNECTION_ID)] as? ContentRootEntity
}
else {
this.entityLinks[EntityLink(true, CONTENTROOT_CONNECTION_ID)] as? ContentRootEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CONTENTROOT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CONTENTROOT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CONTENTROOT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CONTENTROOT_CONNECTION_ID)] = value
}
changedProperty.add("contentRoot")
}
override fun getEntityData(): ReferredEntityData = result ?: super.getEntityData() as ReferredEntityData
override fun getEntityClass(): Class<ReferredEntity> = ReferredEntity::class.java
}
}
class ReferredEntityData : WorkspaceEntityData<ReferredEntity>() {
var version: Int = 0
lateinit var name: String
fun isNameInitialized(): Boolean = ::name.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ReferredEntity> {
val modifiable = ReferredEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ReferredEntity {
val entity = ReferredEntityImpl()
entity.version = version
entity._name = name
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ReferredEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ReferredEntity(version, name, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ReferredEntityData
if (this.entitySource != other.entitySource) return false
if (this.version != other.version) return false
if (this.name != other.name) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ReferredEntityData
if (this.version != other.version) return false
if (this.name != other.name) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 1166cc2988476a676468f7deb31c56b1 | 33.353175 | 150 | 0.694236 | 5.190048 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/migLayout/componentConstraints.kt | 9 | 3803 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout.migLayout
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.layout.*
import com.intellij.util.ui.JBUI
import net.miginfocom.layout.BoundSize
import net.miginfocom.layout.CC
import net.miginfocom.layout.ConstraintParser
import java.awt.Component
import javax.swing.*
import javax.swing.text.JTextComponent
internal fun overrideFlags(cc: CC, flags: Array<out CCFlags>) {
for (flag in flags) {
when (flag) {
CCFlags.grow -> cc.grow()
CCFlags.growX -> {
cc.growX(1000f)
}
CCFlags.growY -> cc.growY(1000f)
// If you have more than one component in a cell the alignment keywords will not work since the behavior would be indeterministic.
// You can however accomplish the same thing by setting a gap before and/or after the components.
// That gap may have a minimum size of 0 and a preferred size of a really large value to create a "pushing" gap.
// There is even a keyword for this: "push". So "gapleft push" will be the same as "align right" and work for multi-component cells as well.
//CCFlags.right -> horizontal.gapBefore = BoundSize(null, null, null, true, null)
CCFlags.push -> cc.push()
CCFlags.pushX -> cc.pushX()
CCFlags.pushY -> cc.pushY()
}
}
}
internal class DefaultComponentConstraintCreator(private val spacing: SpacingConfiguration) {
private val shortTextSizeSpec = ConstraintParser.parseBoundSize("${spacing.shortTextWidth}px!", false, true)
private val mediumTextSizeSpec = ConstraintParser.parseBoundSize("${spacing.shortTextWidth}px::${spacing.maxShortTextWidth}px", false, true)
val vertical1pxGap: BoundSize = ConstraintParser.parseBoundSize("${JBUI.scale(1)}px!", true, false)
val horizontalUnitSizeGap = gapToBoundSize(spacing.unitSize, true)
fun addGrowIfNeeded(cc: CC, component: Component, spacing: SpacingConfiguration) {
when {
component is ComponentWithBrowseButton<*> -> {
// yes, no max width. approved by UI team (all path fields stretched to the width of the window)
cc.minWidth("${spacing.maxShortTextWidth}px")
cc.growX()
}
component is JTextField && component.columns != 0 ->
return
component is JTextComponent || component is SeparatorComponent || component is ComponentWithBrowseButton<*> -> {
cc.growX()
//.pushX()
}
component is JScrollPane || component.isPanelWithToolbar() || component.isToolbarDecoratorPanel() -> {
// no need to use pushX - default pushX for cell is 100. avoid to configure more than need
cc.grow()
.pushY()
}
component is JScrollPane -> {
val view = component.viewport.view
if (view is JTextArea && view.rows == 0) {
// set min size to 2 lines (yes, for some reasons it means that rows should be set to 3)
view.rows = 3
}
}
}
}
fun applyGrowPolicy(cc: CC, growPolicy: GrowPolicy) {
cc.horizontal.size = when (growPolicy) {
GrowPolicy.SHORT_TEXT -> shortTextSizeSpec
GrowPolicy.MEDIUM_TEXT -> mediumTextSizeSpec
}
}
}
private fun Component.isPanelWithToolbar(): Boolean {
return this is JPanel && componentCount == 1 &&
(getComponent(0) as? JComponent)?.getClientProperty(ActionToolbar.ACTION_TOOLBAR_PROPERTY_KEY) != null
}
private fun Component.isToolbarDecoratorPanel(): Boolean {
return this is JPanel && getClientProperty(ToolbarDecorator.DECORATOR_KEY) != null
} | apache-2.0 | c78c789df4779a43be4b4c7617523030 | 39.468085 | 146 | 0.70497 | 4.341324 | false | false | false | false |
datarank/tempest | src/main/java/com/simplymeasured/elasticsearch/plugins/tempest/balancer/MoveDescription.kt | 1 | 2202 | /*
* The MIT License (MIT)
* Copyright (c) 2018 DataRank, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.simplymeasured.elasticsearch.plugins.tempest.balancer
import com.simplymeasured.elasticsearch.plugins.tempest.balancer.model.ModelCluster
import org.elasticsearch.index.shard.ShardId
data class MoveDescription(val sourceNodeId: String, val shardId: ShardId, val destNodeId: String) {
fun buildMoveAction(hypotheticalCluster: ModelCluster): MoveAction? {
val localSourceNode = hypotheticalCluster.modelNodes.find { it.nodeId == sourceNodeId } ?: return null
val localDestNode = hypotheticalCluster.modelNodes.find { it.nodeId == destNodeId } ?: return null
val localShard = localSourceNode.shards.find { it.backingShard.shardId() == shardId } ?: return null
return MoveAction(
sourceNode = localSourceNode.backingNode,
shard = localShard.backingShard,
destNode = localDestNode.backingNode,
overhead = localShard.shardSizeInfo.actualSize,
shardScoreGroupDescriptions = localShard.scoreGroupDescriptions)
}
} | mit | 540aee69ee0a35edb1d84906237e422d | 50.232558 | 110 | 0.737965 | 4.39521 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.