repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
NilsRenaud/kotlin-presentation | examples/src/org/nilsr/kotlin/examples/6OperatorOverloading.kt | 1 | 1593 | package org.nilsr.kotlin.examples
/**
* Shows :
* - Operator Overloading
*/
fun main(args : Array<String>) {
val one = MyInt(1)
val two = MyInt(2)
println(one + two)
one()
two()
}
class MyInt(private val value : Int = 0){
operator fun plus(b : MyInt) = this.value + b.value
operator fun invoke() = println("What am I supposed to do ??")
// +a a.unaryPlus()
// -a a.unaryMinus()
// !a a.not()
// a++ a.inc()
// a-- a.dec()
// a + b a.plus(b)
// a - b a.minus(b)
// a * b a.times(b)
// a / b a.div(b)
// a % b a.rem(b), a.mod(b) (deprecated)
// a..b a.rangeTo(b)
// a in b b.contains(a)
// a !in b !b.contains(a)
// a[i] a.get(i)
// a[i, j] a.get(i, j)
// a[i_1, ..., i_n] a.get(i_1, ..., i_n)
// a[i] = b a.set(i, b)
// a[i, j] = b a.set(i, j, b)
// a[i_1, ..., i_n] = b a.set(i_1, ..., i_n, b)
// a() a.invoke()
// a(i) a.invoke(i)
// a(i, j) a.invoke(i, j)
// a(i_1, ..., i_n) a.invoke(i_1, ..., i_n)
// a += b a.plusAssign(b)
// a -= b a.minusAssign(b)
// a *= b a.timesAssign(b)
// a /= b a.divAssign(b)
// a %= b a.remAssign(b), a.modAssign(b) (deprecated)
// a == b a?.equals(b) ?: (b === null)
// a != b !(a?.equals(b) ?: (b === null))
// a > b a.compareTo(b) > 0
// a < b a.compareTo(b) < 0
// a >= b a.compareTo(b) >= 0
// a <= b a.compareTo(b) <= 0
} | mit | 5184d8e19a0afe5ae00d7e3f8f7d4477 | 25.566667 | 66 | 0.404896 | 2.43578 | false | false | false | false |
ZoranPandovski/al-go-rithms | sort/insertion_sort/kotlin/insertionSort.kt | 2 | 501 | import java.util.Arrays
fun insertionSort(arr: Array<Long>) {
for (j in 1..arr.size - 1){
var i = j - 1;
val processedValue = arr[j];
while ( (i >= 0) && (arr[i] > processedValue) ){
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = processedValue;
}
}
fun main(args: Array<String>) {
val arr = arrayOf(1, 3, 5, 4, 2, 6, 8, 9, 7, 10, 13, 15, 17, 16, 14, 12, 19, 18, 11)
insertionSort(arr)
println(Arrays.toString(arr))
}
| cc0-1.0 | 5b402f709a332ba078f1b431ddb22fc4 | 21.772727 | 88 | 0.49501 | 2.912791 | false | false | false | false |
softappeal/yass | kotlin/yass/main/ch/softappeal/yass/transport/MessageSerializer.kt | 1 | 1474 | package ch.softappeal.yass.transport
import ch.softappeal.yass.remote.*
import ch.softappeal.yass.serialize.*
internal const val Request = 0.toByte()
internal const val ValueReply = 1.toByte()
internal const val ExceptionReply = 2.toByte()
fun messageSerializer(contractSerializer: Serializer) = object : Serializer {
override fun read(reader: Reader): Message = when (val type = reader.readByte()) {
Request -> Request(
reader.readZigZagInt(),
reader.readZigZagInt(),
contractSerializer.read(reader) as List<Any?>
)
ValueReply -> ValueReply(
contractSerializer.read(reader)
)
ExceptionReply -> ExceptionReply(
contractSerializer.read(reader) as Exception
)
else -> error("unexpected type $type")
}
override fun write(writer: Writer, value: Any?) = when (value) {
is Request -> {
writer.writeByte(Request)
writer.writeZigZagInt(value.serviceId)
writer.writeZigZagInt(value.methodId)
contractSerializer.write(writer, value.arguments)
}
is ValueReply -> {
writer.writeByte(ValueReply)
contractSerializer.write(writer, value.value)
}
is ExceptionReply -> {
writer.writeByte(ExceptionReply)
contractSerializer.write(writer, value.exception)
}
else -> error("unexpected value '$value'")
}
}
| bsd-3-clause | fa6e7e61ff5e328ae8ef2013889eca49 | 33.27907 | 86 | 0.626866 | 4.453172 | false | false | false | false |
batagliao/onebible.android | app/src/main/java/com/claraboia/bibleandroid/activities/DispatchActivity.kt | 1 | 4423 | package com.claraboia.bibleandroid.activities
import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.util.Log
import android.widget.Toast
import com.claraboia.bibleandroid.R
import com.claraboia.bibleandroid.bibleApplication
import com.claraboia.bibleandroid.helpers.*
import com.claraboia.bibleandroid.models.Bible
import com.claraboia.bibleandroid.viewmodels.BookForSort
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.firebase.auth.FirebaseAuth
import kotlin.concurrent.thread
class DispatchActivity : AppCompatActivity() {
private lateinit var firebaseauth: FirebaseAuth
private val REQUEST_GOOGLE_PLAY_SERVICES = 90909
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//TODO: get this code back
//verifyGooglePlay()
firebaseauth = FirebaseAuth.getInstance()
if (firebaseauth.currentUser == null) {
firebaseauth.signInAnonymously().addOnCompleteListener {
Log.d("DispatchActivity", "signInAnonymously:onComplete:" + it.isSuccessful)
bibleApplication.currentUser = firebaseauth.currentUser
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!it.isSuccessful) {
Log.w("DispatchActivity", "signInAnonymously", it.exception)
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show()
}
performStartupPath()
}
}else{
bibleApplication.currentUser = firebaseauth.currentUser
performStartupPath()
}
}
// private fun verifyGooglePlay(){
// val playServicesStatus = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)
// if(playServicesStatus != ConnectionResult.SUCCESS){
// //If google play services in not available show an error dialog and return
// GoogleApiAvailability.getInstance().showErrorDialogFragment(this, playServicesStatus, 0)
// //val errorDialog = GoogleApiAvailability.getInstance().getErrorDialog(this, playServicesStatus, 0, null)
// //errorDialog.show()
// return
// }
// }
private fun performStartupPath(){
bibleApplication.localBibles.addAll(getAvailableBiblesLocal())
if(bibleApplication.localBibles.size == 0 || bibleApplication.preferences.selectedTranslation.isEmpty()) {
val builder = AlertDialog.Builder(this)
builder.setMessage(R.string.translationNeededToStart)
builder.setPositiveButton(R.string.ok) { dialog, button ->
val intent = Intent(this, SelectTranslationActivity::class.java)
intent.putExtra(SHOULD_OPEN_CLOUD_TAB_KEY, true)
startActivity(intent)
finish()
}
val dialog = builder.create()
dialog.show()
}else{
loadCurrentBible()
val intent = Intent(this, ReadActivity::class.java)
startActivity(intent)
finish()
}
}
private fun loadCurrentBible() {
bibleApplication.currentBible = loadBible(bibleApplication.preferences.selectedTranslation)
//load last accessed address as current position
val lastAddress = bibleApplication.preferences.lastAccessedAddress
bibleApplication.currentBook = lastAddress.bookOrder
bibleApplication.currentChapter = lastAddress.chapterOrder
//create a bookCollection to be able to sort, change without affect orignal list
bibleApplication.currentBible.books.forEach { b ->
val newbook = BookForSort(
b.bookOrder,
b.chapters.size,
b.getBookName(),
b.getBookAbbrev(),
b.getBookType()
)
bibleApplication.booksForSelection.add(newbook)
}
}
}
| apache-2.0 | fdf8a4a2b45c79db194ca576c8b6ecbc | 37.12931 | 119 | 0.665159 | 5.04333 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/external/service/httpws/param/HttpWsResponseParam.kt | 1 | 2216 | package org.evomaster.core.problem.external.service.httpws.param
import org.evomaster.core.problem.api.service.param.Param
import org.evomaster.core.problem.external.service.param.ResponseParam
import org.evomaster.core.search.gene.collection.EnumGene
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.gene.string.StringGene
class HttpWsResponseParam (
/**
* Contains the values for HTTP status codes.
* Avoid having 404 as status, since WireMock will return 404 if there is
* no stub for the specific request.
*/
val status: EnumGene<Int> = getDefaultStatusEnumGene(),
/**
* Response content type, for now supports only JSON
*
* TODO might want to support XML and other formats here in the future
*/
responseType: EnumGene<String> = EnumGene("responseType", listOf("JSON")),
/**
* The body payload of the response, if any.
* Notice that the gene is a String, although the body might NOT be a string, but rather an Object or Array.
* This still works because we handle it in the phenotype representation, ie using raw values of specializations,
* which will not be quoted ""
*
* TODO: might want to extend StringGene to avoid cases in which taint is lost due to mutation
*/
responseBody: OptionalGene = OptionalGene(RESPONSE_GENE_NAME, StringGene(RESPONSE_GENE_NAME)),
val connectionHeader : String? = DEFAULT_HEADER_CONNECTION
): ResponseParam("response", responseType, responseBody, listOf(status)) {
companion object{
const val RESPONSE_GENE_NAME = "WireMockResponseGene"
const val DEFAULT_HEADER_CONNECTION : String = "close"
fun getDefaultStatusEnumGene() = EnumGene("status", listOf(200, 201, 204, 400, 401, 403, 500))
}
override fun copyContent(): Param {
return HttpWsResponseParam(status.copy() as EnumGene<Int>, responseType.copy() as EnumGene<String>, responseBody.copy() as OptionalGene, connectionHeader)
}
fun setStatus(statusCode : Int) : Boolean{
val index = status.values.indexOf(statusCode)
if (index == -1) return false
status.index = index
return true
}
} | lgpl-3.0 | db64175e06a8599a78deb22b900ed12e | 41.634615 | 162 | 0.71074 | 4.379447 | false | false | false | false |
badoualy/kotlogram | mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTRpcError.kt | 1 | 1381 | package com.github.badoualy.telegram.mtproto.tl
import com.github.badoualy.telegram.tl.StreamUtils.*
import com.github.badoualy.telegram.tl.TLContext
import com.github.badoualy.telegram.tl.core.TLObject
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.regex.Pattern
class MTRpcError @JvmOverloads constructor(var errorCode: Int = 0, var message: String = "") : TLObject() {
val errorTag: String
get() {
if (message.isEmpty())
return "DEFAULT"
val matcher = REGEXP_PATTERN.matcher(message)
if (matcher.find())
return matcher.group()
return "DEFAULT"
}
override fun getConstructorId(): Int {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeInt(errorCode, stream)
writeString(message, stream)
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
errorCode = readInt(stream)
message = readTLString(stream)
}
override fun toString(): String {
return "rpc_error#2144ca19"
}
companion object {
private val REGEXP_PATTERN = Pattern.compile("[A-Z_0-9]+")
@JvmField
val CONSTRUCTOR_ID = 558156313
}
}
| mit | da42fa5acc837938227c81bb4d84f939 | 26.078431 | 107 | 0.651702 | 4.236196 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/client/LogsActivity.kt | 1 | 7280 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Adrien Beraud <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cx.ring.client
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.material.snackbar.Snackbar
import cx.ring.R
import cx.ring.application.JamiApplication
import cx.ring.databinding.ActivityLogsBinding
import cx.ring.utils.AndroidFileUtils
import cx.ring.utils.ContentUriHandler
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import net.jami.services.HardwareService
import net.jami.utils.StringUtils
import java.io.File
import java.io.FileOutputStream
import javax.inject.Inject
import javax.inject.Singleton
@AndroidEntryPoint
class LogsActivity : AppCompatActivity() {
private lateinit var binding: ActivityLogsBinding
private val compositeDisposable = CompositeDisposable()
private var disposable: Disposable? = null
private lateinit var fileSaver: ActivityResultLauncher<String>
private var mCurrentFile: File? = null
@Inject
@Singleton
lateinit var mHardwareService: HardwareService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
JamiApplication.instance?.startDaemon()
binding = ActivityLogsBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
fileSaver = registerForActivityResult(ActivityResultContracts.CreateDocument()) { result: Uri? ->
if (result != null)
compositeDisposable.add(AndroidFileUtils.copyFileToUri(contentResolver, mCurrentFile, result)
.observeOn(AndroidSchedulers.mainThread()).subscribe({
if (!mCurrentFile!!.delete())
Log.w(TAG, "Can't delete temp file")
mCurrentFile = null
Snackbar.make(binding.root, R.string.file_saved_successfully, Snackbar.LENGTH_SHORT).show()
}) { Snackbar.make(binding.root, R.string.generic_error, Snackbar.LENGTH_SHORT).show()
})
}
binding.fab.setOnClickListener { if (disposable == null) startLogging() else stopLogging() }
if (mHardwareService.isLogging) startLogging()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.logs_menu, menu)
return super.onCreateOptionsMenu(menu)
}
private val log: Maybe<String>
get() {
if (mHardwareService.isLogging)
return mHardwareService.startLogs().firstElement()
val log = binding.logView.text
return if (StringUtils.isEmpty(log)) Maybe.empty()
else Maybe.just(log.toString())
}
private val logFile: Maybe<File>
get() = log
.observeOn(Schedulers.io())
.map { log: String ->
val file = AndroidFileUtils.createLogFile(this)
FileOutputStream(file).use { os -> os.write(log.toByteArray()) }
file
}
private val logUri: Maybe<Uri>
get() = logFile.map { file: File ->
ContentUriHandler.getUriForFile(this, ContentUriHandler.AUTHORITY_FILES, file)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.menu_log_share -> {
compositeDisposable.add(logUri.observeOn(AndroidSchedulers.mainThread())
.subscribe({ uri: Uri ->
Log.w(TAG, "saved logs to $uri")
val sendIntent = Intent(Intent.ACTION_SEND).apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
setDataAndType(uri, contentResolver.getType(uri))
putExtra(Intent.EXTRA_STREAM, uri)
}
startActivity(Intent.createChooser(sendIntent, null))
}) { e: Throwable ->
Snackbar.make(binding.root, "Error sharing logs: " + e.localizedMessage, Snackbar.LENGTH_SHORT).show()
})
return true
}
R.id.menu_log_save -> {
compositeDisposable.add(logFile.subscribe { file: File ->
mCurrentFile = file
fileSaver.launch(file.name)
})
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun startLogging() {
binding.logView.text = ""
disposable = mHardwareService.startLogs()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ message: String ->
binding.logView.text = message
binding.scroll.post { binding.scroll.fullScroll(View.FOCUS_DOWN) }
}) { e -> Log.w(TAG, "Error in logger", e) }
compositeDisposable.add(disposable)
setButtonState(true)
}
private fun stopLogging() {
disposable?.let {
it.dispose()
disposable = null
}
mHardwareService.stopLogs()
setButtonState(false)
}
private fun setButtonState(logging: Boolean) {
binding.fab.setText(if (logging) R.string.pref_logs_stop else R.string.pref_logs_start)
binding.fab.setBackgroundColor(ContextCompat.getColor(this, if (logging) R.color.red_400 else R.color.colorSecondary))
}
override fun onDestroy() {
disposable?.let {
it.dispose()
disposable = null
}
compositeDisposable.clear()
super.onDestroy()
}
companion object {
private val TAG = LogsActivity::class.simpleName!!
}
} | gpl-3.0 | 996f14d251ca7d4874e9c9f421bbc81b | 39.226519 | 130 | 0.637225 | 4.802111 | false | false | false | false |
VoIPGRID/vialer-android | app/src/main/java/com/voipgrid/vialer/notifications/EncryptionDisabledNotification.kt | 1 | 2034 | package com.voipgrid.vialer.notifications
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 androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder
import com.voipgrid.vialer.MainActivity
import com.voipgrid.vialer.R
import com.voipgrid.vialer.SettingsActivity
class EncryptionDisabledNotification : AbstractNotification() {
override val notificationId: Int = 3
@RequiresApi(Build.VERSION_CODES.O)
override fun buildChannel(context : Context): NotificationChannel {
return NotificationChannel(
CHANNEL_ID,
context.getString(R.string.notification_channel_encryption_disabled),
NotificationManager.IMPORTANCE_LOW
)
}
override fun buildNotification(context: Context): android.app.Notification {
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_lock_open)
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setContentTitle(context.getString(R.string.encrypted_calling_notification_title))
.setContentText(context.getString(R.string.encrypted_calling_notification_description))
.setOngoing(true)
.setVibrate(null)
val stackBuilder = TaskStackBuilder.create(context)
stackBuilder.addParentStack(MainActivity::class.java)
stackBuilder.addNextIntent(Intent(context, SettingsActivity::class.java))
builder.setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
return builder.build()
}
override fun provideChannelsToDelete() = listOf("vialer_encryption_disabled")
companion object {
const val CHANNEL_ID: String = "vialer_encryption_disabled_notifications"
}
} | gpl-3.0 | 780b875566d9d16ff061626d82d2dab0 | 37.396226 | 103 | 0.730088 | 5.097744 | false | false | false | false |
Jire/Acelta | src/main/kotlin/com/acelta/world/mob/Direction.kt | 1 | 1001 | package com.acelta.world.mob
import com.acelta.world.Position
enum class Direction(val value: Int) {
NONE(-1), NORTH_WEST(0), NORTH(1), NORTH_EAST(2), WEST(3), EAST(4), SOUTH_WEST(5), SOUTH(6), SOUTH_EAST(7);
companion object {
fun between(currentX: Int, currentY: Int, nextX: Int, nextY: Int): Direction {
val deltaX = nextX - currentX
val deltaY = nextY - currentY
if (deltaY == 1) {
if (deltaX == 1) return NORTH_EAST
else if (deltaX == 0) return NORTH
else if (deltaX == -1) return NORTH_WEST
} else if (deltaY == -1) {
if (deltaX == 1) return SOUTH_EAST
else if (deltaX == 0) return SOUTH
else if (deltaX == -1) return SOUTH_WEST
} else if (deltaY == 0) {
if (deltaX == 1) return EAST
else if (deltaX == 0) return NONE
else if (deltaX == -1) return WEST
}
return NONE
}
fun between(currentPosition: Position, nextPosition: Position)
= between(currentPosition.x, currentPosition.y, nextPosition.x, nextPosition.y)
}
} | gpl-3.0 | 7a4bf74f16a594cdb5b26f61b9d74a47 | 26.081081 | 108 | 0.643357 | 3.21865 | false | false | false | false |
google/private-compute-libraries | javatests/com/google/android/libraries/pcc/chronicle/analysis/DefaultChronicleContextTest.kt | 1 | 9281 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.analysis
import com.google.android.libraries.pcc.chronicle.api.Connection
import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider
import com.google.android.libraries.pcc.chronicle.api.ConnectionRequest
import com.google.android.libraries.pcc.chronicle.api.DataType
import com.google.android.libraries.pcc.chronicle.api.ManagedDataType
import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy
import com.google.android.libraries.pcc.chronicle.api.ProcessorNode
import com.google.android.libraries.pcc.chronicle.api.ReadConnection
import com.google.android.libraries.pcc.chronicle.api.WriteConnection
import com.google.android.libraries.pcc.chronicle.api.dataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.api.error.ConnectionTypeAmbiguity
import com.google.android.libraries.pcc.chronicle.util.Key
import com.google.android.libraries.pcc.chronicle.util.MutableTypedMap
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.mock
import kotlin.test.assertFailsWith
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class DefaultChronicleContextTest {
@Test
fun moreThanOneConnectibleByConnectionType_throws() {
val node1 =
object : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Foo", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(FooReader::class.java)
)
override fun getConnection(
connectionRequest: ConnectionRequest<out Connection>
): Connection = FooReader()
}
// Same connection type should cause the error to be thrown. The dataType being different is
// not relevant to the check.
val node2 =
object : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Bar", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(FooReader::class.java)
)
override fun getConnection(
connectionRequest: ConnectionRequest<out Connection>
): Connection = FooReader()
}
assertFailsWith<ConnectionTypeAmbiguity> {
DefaultChronicleContext(setOf(node1, node2), emptySet(), DefaultPolicySet(emptySet()), mock())
}
}
@Test
fun findConnectionProvider() {
val readerConnectionProvider = FooReaderConnectionProvider()
val writerConnectionProvider = FooWriterConnectionProvider()
val context =
DefaultChronicleContext(
setOf(readerConnectionProvider, writerConnectionProvider),
emptySet(),
DefaultPolicySet(emptySet()),
mock()
)
assertThat(context.findConnectionProvider(FooReader::class.java))
.isSameInstanceAs(readerConnectionProvider)
assertThat(context.findConnectionProvider(FooWriter::class.java))
.isSameInstanceAs(writerConnectionProvider)
}
@Test
fun findDataType() {
val fooReaderConnectionProvider = FooReaderConnectionProvider()
val fooWriterConnectionProvider = FooWriterConnectionProvider()
val barReaderWriterConnectionProvider = BarReaderWriterConnectionProvider()
val context =
DefaultChronicleContext(
setOf(
fooReaderConnectionProvider,
fooWriterConnectionProvider,
barReaderWriterConnectionProvider
),
emptySet(),
DefaultPolicySet(emptySet()),
mock()
)
assertThat(context.findDataType(FooReader::class.java))
.isEqualTo(dataTypeDescriptor("Foo", Unit::class))
assertThat(context.findDataType(FooWriter::class.java))
.isEqualTo(dataTypeDescriptor("Foo", Unit::class))
assertThat(context.findDataType(BarReader::class.java))
.isEqualTo(dataTypeDescriptor("Bar", Unit::class))
assertThat(context.findDataType(BarWriter::class.java))
.isEqualTo(dataTypeDescriptor("Bar", Unit::class))
}
@Test
fun withNode_processor_leavesExistingUnchanged() {
val context =
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock()
)
val updated = context.withNode(FooBarProcessor())
assertThat(context)
.isEqualTo(
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock()
)
)
assertThat(updated).isNotEqualTo(context)
assertThat(updated)
.isEqualTo(
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
setOf(FooBarProcessor()),
DefaultPolicySet(emptySet()),
mock()
)
)
}
@Test
fun withConnectionContext_processor_leavesExistingUnchanged() {
val mutableTypedMap = MutableTypedMap()
val connectionContext = mutableTypedMap.toTypedMap()
val context =
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock(),
connectionContext
)
// Update the `connectionContext`
mutableTypedMap[Name] = "test"
val otherConnectionContext = mutableTypedMap.toTypedMap()
val updated = context.withConnectionContext(otherConnectionContext)
// Initial context should not have the Name key
assertThat(context.connectionContext[Name]).isNull()
assertThat(context)
.isEqualTo(
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock(),
connectionContext
)
)
// Updated context has the Name key
assertThat(updated.connectionContext[Name]).isEqualTo("test")
assertThat(updated).isNotEqualTo(context)
assertThat(updated)
.isEqualTo(
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock(),
otherConnectionContext
)
)
}
// Test key for `connectionContext`
private object Name : Key<String>
class FooReader : ReadConnection
class FooWriter : WriteConnection
class BarReader : ReadConnection
class BarWriter : WriteConnection
class FooReaderConnectionProvider : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Foo", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(FooReader::class.java)
)
override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection =
FooReader()
override fun equals(other: Any?): Boolean = other is FooReaderConnectionProvider
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
class FooWriterConnectionProvider : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Foo", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(FooWriter::class.java)
)
override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection =
FooWriter()
override fun equals(other: Any?): Boolean = other is FooWriterConnectionProvider
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
class BarReaderWriterConnectionProvider : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Bar", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(BarReader::class.java, BarWriter::class.java)
)
override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection =
BarWriter()
override fun equals(other: Any?): Boolean = other is BarReaderWriterConnectionProvider
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
class FooBarProcessor : ProcessorNode {
override val requiredConnectionTypes =
setOf(
FooReader::class.java,
FooWriter::class.java,
BarReader::class.java,
BarWriter::class.java
)
override fun equals(other: Any?): Boolean = other is FooBarProcessor
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
}
| apache-2.0 | d55bf2c81d3c7903cf9c1b280d391bb4 | 32.872263 | 100 | 0.704558 | 5.055011 | false | false | false | false |
tonyofrancis/Fetch | fetch2/src/main/java/com/tonyodev/fetch2/helper/PriorityListProcessorImpl.kt | 1 | 8867 | package com.tonyodev.fetch2.helper
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.tonyodev.fetch2.*
import com.tonyodev.fetch2.downloader.DownloadManager
import com.tonyodev.fetch2core.HandlerWrapper
import com.tonyodev.fetch2.provider.DownloadProvider
import com.tonyodev.fetch2.provider.NetworkInfoProvider
import com.tonyodev.fetch2.util.DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS
import com.tonyodev.fetch2.NetworkType
import com.tonyodev.fetch2.fetch.ListenerCoordinator
import com.tonyodev.fetch2core.Logger
import com.tonyodev.fetch2core.isFetchFileServerUrl
import java.util.concurrent.TimeUnit
class PriorityListProcessorImpl constructor(private val handlerWrapper: HandlerWrapper,
private val downloadProvider: DownloadProvider,
private val downloadManager: DownloadManager,
private val networkInfoProvider: NetworkInfoProvider,
private val logger: Logger,
private val listenerCoordinator: ListenerCoordinator,
@Volatile
override var downloadConcurrentLimit: Int,
private val context: Context,
private val namespace: String,
private val prioritySort: PrioritySort)
: PriorityListProcessor<Download> {
private val lock = Any()
@Volatile
override var globalNetworkType = NetworkType.GLOBAL_OFF
@Volatile
private var paused = false
override val isPaused: Boolean
get() = paused
@Volatile
private var stopped = true
override val isStopped: Boolean
get() = stopped
@Volatile
private var backOffTime = DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS
private val networkChangeListener: NetworkInfoProvider.NetworkChangeListener = object : NetworkInfoProvider.NetworkChangeListener {
override fun onNetworkChanged() {
handlerWrapper.post {
if (!stopped && !paused && networkInfoProvider.isNetworkAvailable
&& backOffTime > DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS) {
resetBackOffTime()
}
}
}
}
private val priorityBackoffResetReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null && intent != null) {
when (intent.action) {
ACTION_QUEUE_BACKOFF_RESET -> {
if (!stopped && !paused && namespace == intent.getStringExtra(EXTRA_NAMESPACE)) {
resetBackOffTime()
}
}
}
}
}
}
init {
networkInfoProvider.registerNetworkChangeListener(networkChangeListener)
context.registerReceiver(priorityBackoffResetReceiver, IntentFilter(ACTION_QUEUE_BACKOFF_RESET))
}
private val priorityIteratorRunnable = Runnable {
if (canContinueToProcess()) {
if (downloadManager.canAccommodateNewDownload() && canContinueToProcess()) {
val priorityList = getPriorityList()
var shouldBackOff = false
if (priorityList.isEmpty() || !networkInfoProvider.isNetworkAvailable) {
shouldBackOff = true
}
if (!shouldBackOff) {
shouldBackOff = true
for (index in 0..priorityList.lastIndex) {
if (downloadManager.canAccommodateNewDownload() && canContinueToProcess()) {
val download = priorityList[index]
val isFetchServerRequest = isFetchFileServerUrl(download.url)
if ((isFetchServerRequest || networkInfoProvider.isNetworkAvailable) && canContinueToProcess()) {
val networkType = when {
globalNetworkType != NetworkType.GLOBAL_OFF -> globalNetworkType
download.networkType == NetworkType.GLOBAL_OFF -> NetworkType.ALL
else -> download.networkType
}
val properNetworkConditions = networkInfoProvider.isOnAllowedNetwork(networkType)
if (!properNetworkConditions) {
listenerCoordinator.mainListener.onWaitingNetwork(download)
}
if ((isFetchServerRequest || properNetworkConditions)) {
shouldBackOff = false
if (!downloadManager.contains(download.id) && canContinueToProcess()) {
downloadManager.start(download)
}
}
} else {
break
}
} else {
break
}
}
}
if (shouldBackOff) {
increaseBackOffTime()
}
}
if (canContinueToProcess()) {
registerPriorityIterator()
}
}
}
override fun start() {
synchronized(lock) {
resetBackOffTime()
stopped = false
paused = false
registerPriorityIterator()
logger.d("PriorityIterator started")
}
}
override fun stop() {
synchronized(lock) {
unregisterPriorityIterator()
paused = false
stopped = true
downloadManager.cancelAll()
logger.d("PriorityIterator stop")
}
}
override fun pause() {
synchronized(lock) {
unregisterPriorityIterator()
paused = true
stopped = false
downloadManager.cancelAll()
logger.d("PriorityIterator paused")
}
}
override fun resume() {
synchronized(lock) {
resetBackOffTime()
paused = false
stopped = false
registerPriorityIterator()
logger.d("PriorityIterator resumed")
}
}
override fun getPriorityList(): List<Download> {
synchronized(lock) {
return try {
downloadProvider.getPendingDownloadsSorted(prioritySort)
} catch (e: Exception) {
logger.d("PriorityIterator failed access database", e)
listOf()
}
}
}
private fun registerPriorityIterator() {
if (downloadConcurrentLimit > 0) {
handlerWrapper.postDelayed(priorityIteratorRunnable, backOffTime)
}
}
private fun unregisterPriorityIterator() {
if (downloadConcurrentLimit > 0) {
handlerWrapper.removeCallbacks(priorityIteratorRunnable)
}
}
private fun canContinueToProcess(): Boolean {
return !stopped && !paused
}
override fun resetBackOffTime() {
synchronized(lock) {
backOffTime = DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS
unregisterPriorityIterator()
registerPriorityIterator()
logger.d("PriorityIterator backoffTime reset to $backOffTime milliseconds")
}
}
override fun sendBackOffResetSignal() {
synchronized(lock) {
val intent = Intent(ACTION_QUEUE_BACKOFF_RESET)
intent.putExtra(EXTRA_NAMESPACE, namespace)
context.sendBroadcast(intent)
}
}
override fun close() {
synchronized(lock) {
networkInfoProvider.unregisterNetworkChangeListener(networkChangeListener)
context.unregisterReceiver(priorityBackoffResetReceiver)
}
}
private fun increaseBackOffTime() {
backOffTime = if (backOffTime == DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS) {
ONE_MINUTE_IN_MILLISECONDS
} else {
backOffTime * 2L
}
val minutes = TimeUnit.MILLISECONDS.toMinutes(backOffTime)
logger.d("PriorityIterator backoffTime increased to $minutes minute(s)")
}
private companion object {
private const val ONE_MINUTE_IN_MILLISECONDS = 60000L
}
} | apache-2.0 | 994abc87b378436719f324c7c9642f7c | 38.066079 | 135 | 0.55622 | 5.991216 | false | false | false | false |
AlmasB/FXGL | fxgl-core/src/main/kotlin/com/almasb/fxgl/input/view/MouseButtonView.kt | 1 | 4673 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.input.view
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.scene.input.MouseButton
import javafx.scene.layout.Pane
import javafx.scene.paint.*
import javafx.scene.shape.Line
import javafx.scene.shape.Rectangle
/**
* View for a mouse button.
*
* @author Almas Baimagambetov ([email protected])
*/
class MouseButtonView
@JvmOverloads constructor(button: MouseButton,
color: Color = Color.ORANGE,
size: Double = 24.0) : Pane() {
private val border = Rectangle(size, size * 1.5)
fun colorProperty(): ObjectProperty<Paint> = border.strokeProperty()
var color: Paint
get() = border.stroke
set(value) { border.stroke = value }
private val bgColorProp = SimpleObjectProperty(Color.BLACK)
//fun backgroundColorProperty(): ObjectProperty<Color> = bgColorProp
var backgroundColor: Color
get() = bgColorProp.value
set(value) { bgColorProp.value = value }
init {
border.fillProperty().bind(bgColorProp)
border.stroke = color
border.strokeWidth = size / 7
border.arcWidth = size / 1.5
border.arcHeight = size / 1.5
val borderTop = Rectangle(size, size * 1.5)
borderTop.fill = null
borderTop.strokeProperty().bind(border.strokeProperty())
borderTop.strokeWidth = size / 7
borderTop.arcWidth = size / 1.5
borderTop.arcHeight = size / 1.5
val line1 = Line(size / 2, 0.0, size / 2, size / 5)
line1.strokeProperty().bind(border.strokeProperty())
line1.strokeWidth = size / 7
val ellipse = Rectangle(size / 6, size / 6 * 1.5)
ellipse.fill = null
ellipse.strokeProperty().bind(border.strokeProperty())
ellipse.strokeWidth = size / 10
ellipse.arcWidth = size / 1.5
ellipse.arcHeight = size / 1.5
ellipse.translateX = size / 2 - size / 6 / 2
ellipse.translateY = size / 5
val line2 = Line(size / 2, size / 5 * 2.75, size / 2, size / 5 * 5)
line2.stroke = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, color), Stop(0.75, backgroundColor))
line2.strokeWidth = size / 7
border.strokeProperty().addListener { _, _, paint ->
if (paint is Color)
line2.stroke = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, paint), Stop(0.75, backgroundColor))
}
children.addAll(border, line1, line2, ellipse, borderTop)
when(button) {
MouseButton.PRIMARY -> {
val highlight = Rectangle(size / 2.5, size / 6 * 3.5)
highlight.fill = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, backgroundColor), Stop(0.25, color), Stop(0.8, color), Stop(0.9, backgroundColor))
highlight.arcWidth = size / 4
highlight.arcHeight = size / 4
highlight.translateX = size / 20
highlight.translateY = size / 8
border.strokeProperty().addListener { _, _, paint ->
if (paint is Color)
highlight.fill = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, backgroundColor), Stop(0.25, paint), Stop(0.8, paint), Stop(0.9, backgroundColor))
}
children.add(1, highlight)
}
MouseButton.SECONDARY -> {
val highlight = Rectangle(size / 2.5, size / 6 * 3.5)
highlight.fill = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, backgroundColor), Stop(0.25, color), Stop(0.8, color), Stop(0.9, backgroundColor))
highlight.arcWidth = size / 4
highlight.arcHeight = size / 4
highlight.translateX = size - size / 20 - highlight.width
highlight.translateY = size / 8
border.strokeProperty().addListener { _, _, paint ->
if (paint is Color)
highlight.fill = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, backgroundColor), Stop(0.25, paint), Stop(0.8, paint), Stop(0.9, backgroundColor))
}
children.add(1, highlight)
}
else -> {
throw IllegalArgumentException("View for $button type is not (yet?) supported")
}
}
}
} | mit | 07fe0b6171c271d4ed86e57ef3643d9a | 38.277311 | 196 | 0.588915 | 3.897415 | false | false | false | false |
AlmasB/FXGL | fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/DataComponents.kt | 1 | 3473 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.entity.components
import com.almasb.fxgl.core.serialization.Bundle
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.entity.component.SerializableComponent
import javafx.beans.property.*
/**
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
/**
* Represents a boolean value based component.
*/
abstract class BooleanComponent
@JvmOverloads constructor(initialValue: Boolean = false) : Component(), SerializableComponent {
private val property: BooleanProperty = SimpleBooleanProperty(initialValue)
var value: Boolean
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun write(bundle: Bundle) {
bundle.put("value", value)
}
override fun read(bundle: Bundle) {
value = bundle.get("value")
}
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
/**
* Represents an int value based component.
*/
abstract class IntegerComponent
@JvmOverloads constructor(initialValue: Int = 0) : Component(), SerializableComponent {
private val property: IntegerProperty = SimpleIntegerProperty(initialValue)
var value: Int
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun write(bundle: Bundle) {
bundle.put("value", value)
}
override fun read(bundle: Bundle) {
value = bundle.get("value")
}
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
/**
* Represents a double value based component.
*/
abstract class DoubleComponent
@JvmOverloads constructor(initialValue: Double = 0.0) : Component(), SerializableComponent {
private val property: DoubleProperty = SimpleDoubleProperty(initialValue)
var value: Double
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun write(bundle: Bundle) {
bundle.put("value", value)
}
override fun read(bundle: Bundle) {
value = bundle.get("value")
}
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
/**
* Represents a String value based component.
*/
abstract class StringComponent
@JvmOverloads constructor(initialValue: String = "") : Component(), SerializableComponent {
private val property: StringProperty = SimpleStringProperty(initialValue)
var value: String
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun write(bundle: Bundle) {
bundle.put("value", value)
}
override fun read(bundle: Bundle) {
value = bundle.get("value")
}
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
/**
* Represents an Object value based component.
*/
abstract class ObjectComponent<T>(initialValue: T) : Component() {
private val property: ObjectProperty<T> = SimpleObjectProperty(initialValue)
var value: T
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
| mit | 4868b642a8a44406a51984910bb60ea5 | 25.112782 | 95 | 0.684135 | 4.469755 | false | false | false | false |
AsynkronIT/protoactor-kotlin | examples/src/main/kotlin/actor/proto/examples/spawnbenchmark/SpawnBenchmark.kt | 1 | 2654 | package actor.proto.examples.spawnbenchmark
import actor.proto.Actor
import actor.proto.Context
import actor.proto.PID
import actor.proto.Props
import actor.proto.fromFunc
import actor.proto.fromProducer
import actor.proto.send
import actor.proto.spawn
import actor.proto.stop
import java.util.concurrent.CountDownLatch
fun main(args: Array<String>) {
repeat(10) {
runOnce()
}
readLine()
}
private fun runOnce() {
val (cd, managerPid: PID) = spawnManager()
send(managerPid, Begin)
cd.await()
System.gc()
System.runFinalization()
}
private fun spawnManager(): Pair<CountDownLatch, PID> {
var start: Long = 0
val cd = CountDownLatch(1)
val managerProps = fromFunc { msg ->
when (msg) {
is Begin -> {
val root = spawn(SpawnActor.props)
start = System.currentTimeMillis()
send(root, Request(10, 0, 1_000_000, self))
}
is Long -> {
val millis = System.currentTimeMillis() - start
println("Elapsed $millis")
println("Result $msg")
cd.countDown()
}
}
}
val managerPid: PID = spawn(managerProps)
return Pair(cd, managerPid)
}
object Begin
data class Request(val div: Long, val num: Long, val size: Long, val respondTo: PID)
class SpawnActor : Actor {
companion object Foo {
private fun produce() = SpawnActor()
val props: Props = fromProducer(SpawnActor.Foo::produce)
}
private var replies: Long = 0
private lateinit var replyTo: PID
private var sum: Long = 0
override suspend fun Context.receive(msg: Any) {
when (msg) {
is Request -> when {
msg.size == 1L -> {
send(msg.respondTo, msg.num)
stop(self)
}
else -> {
replies = msg.div
replyTo = msg.respondTo
for (i in 0 until msg.div) {
val child: PID = spawn(props)
val s = msg.size / msg.div
send(
child, Request(
msg.div,
msg.num + i * s,
s,
self
)
)
}
}
}
is Long -> {
sum += msg
replies--
if (replies == 0L) send(replyTo, sum)
}
}
}
}
| apache-2.0 | 6e5bb89be444d903e594054c2e92e617 | 25.54 | 84 | 0.484175 | 4.575862 | false | false | false | false |
industrial-data-space/trusted-connector | ids-connector/src/main/kotlin/de/fhg/aisec/ids/ServerConfiguration.kt | 1 | 2144 | /*-
* ========================LICENSE_START=================================
* ids-connector
* %%
* Copyright (C) 2021 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids
// import de.fhg.aisec.ids.dynamictls.AcmeSslContextFactory
// import org.eclipse.jetty.server.Connector
// import org.eclipse.jetty.server.Server
// import org.eclipse.jetty.server.ServerConnector
// import org.eclipse.jetty.util.ssl.SslContextFactory
// import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer
// import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory
// import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory
// import org.springframework.context.annotation.Bean
// import org.springframework.context.annotation.Configuration
//
// @Configuration
// class ServerConfiguration {
//
// @Bean
// fun sslContextFactory(): SslContextFactory.Server {
// return AcmeSslContextFactory()
// }
//
// @Bean
// fun webServerFactory(sslContextFactory: SslContextFactory.Server): ConfigurableServletWebServerFactory {
// return JettyServletWebServerFactory().apply {
// port = 8443
// serverCustomizers = listOf(
// JettyServerCustomizer { server: Server ->
// server.connectors = arrayOf<Connector>(
// ServerConnector(server, sslContextFactory)
// )
// }
// )
// }
// }
// }
| apache-2.0 | c33528eb00bd83dc65df5f1757ce824a | 38.703704 | 111 | 0.653918 | 4.466667 | false | true | false | false |
androidx/constraintlayout | constraintlayout/compose/src/main/java/androidx/constraintlayout/compose/ConstraintScopeCommon.kt | 2 | 6832 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.constraintlayout.compose
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.AnchorFunctions.verticalAnchorFunctions
import androidx.constraintlayout.core.state.ConstraintReference
/**
* Represents a vertical side of a layout (i.e start and end) that can be anchored using
* [linkTo] in their `Modifier.constrainAs` blocks.
*/
interface VerticalAnchorable {
/**
* Adds a link towards a [ConstraintLayoutBaseScope.VerticalAnchor].
*/
fun linkTo(
anchor: ConstraintLayoutBaseScope.VerticalAnchor,
margin: Dp = 0.dp,
goneMargin: Dp = 0.dp
)
}
/**
* Represents a horizontal side of a layout (i.e top and bottom) that can be anchored using
* [linkTo] in their `Modifier.constrainAs` blocks.
*/
interface HorizontalAnchorable {
/**
* Adds a link towards a [ConstraintLayoutBaseScope.HorizontalAnchor].
*/
fun linkTo(
anchor: ConstraintLayoutBaseScope.HorizontalAnchor,
margin: Dp = 0.dp,
goneMargin: Dp = 0.dp
)
}
/**
* Represents the [FirstBaseline] of a layout that can be anchored
* using [linkTo] in their `Modifier.constrainAs` blocks.
*/
interface BaselineAnchorable {
/**
* Adds a link towards a [ConstraintLayoutBaseScope.BaselineAnchor].
*/
fun linkTo(
anchor: ConstraintLayoutBaseScope.BaselineAnchor,
margin: Dp = 0.dp,
goneMargin: Dp = 0.dp
)
}
internal abstract class BaseVerticalAnchorable(
private val tasks: MutableList<(State) -> Unit>,
private val index: Int
) : VerticalAnchorable {
abstract fun getConstraintReference(state: State): ConstraintReference
final override fun linkTo(
anchor: ConstraintLayoutBaseScope.VerticalAnchor,
margin: Dp,
goneMargin: Dp
) {
tasks.add { state ->
val layoutDirection = state.layoutDirection
val index1 =
AnchorFunctions.verticalAnchorIndexToFunctionIndex(index, layoutDirection)
val index2 = AnchorFunctions.verticalAnchorIndexToFunctionIndex(
anchor.index,
layoutDirection
)
with(getConstraintReference(state)) {
verticalAnchorFunctions[index1][index2]
.invoke(this, anchor.id, state.layoutDirection)
.margin(margin)
.marginGone(goneMargin)
}
}
}
}
internal abstract class BaseHorizontalAnchorable(
private val tasks: MutableList<(State) -> Unit>,
private val index: Int
) : HorizontalAnchorable {
abstract fun getConstraintReference(state: State): ConstraintReference
final override fun linkTo(
anchor: ConstraintLayoutBaseScope.HorizontalAnchor,
margin: Dp,
goneMargin: Dp
) {
tasks.add { state ->
with(getConstraintReference(state)) {
AnchorFunctions.horizontalAnchorFunctions[index][anchor.index]
.invoke(this, anchor.id)
.margin(margin)
.marginGone(goneMargin)
}
}
}
}
internal object AnchorFunctions {
val verticalAnchorFunctions:
Array<Array<ConstraintReference.(Any, LayoutDirection) -> ConstraintReference>> =
arrayOf(
arrayOf(
{ other, layoutDirection ->
clearLeft(layoutDirection); leftToLeft(other)
},
{ other, layoutDirection ->
clearLeft(layoutDirection); leftToRight(other)
}
),
arrayOf(
{ other, layoutDirection ->
clearRight(layoutDirection); rightToLeft(other)
},
{ other, layoutDirection ->
clearRight(layoutDirection); rightToRight(other)
}
)
)
private fun ConstraintReference.clearLeft(layoutDirection: LayoutDirection) {
leftToLeft(null)
leftToRight(null)
when (layoutDirection) {
LayoutDirection.Ltr -> {
startToStart(null); startToEnd(null)
}
LayoutDirection.Rtl -> {
endToStart(null); endToEnd(null)
}
}
}
private fun ConstraintReference.clearRight(layoutDirection: LayoutDirection) {
rightToLeft(null)
rightToRight(null)
when (layoutDirection) {
LayoutDirection.Ltr -> {
endToStart(null); endToEnd(null)
}
LayoutDirection.Rtl -> {
startToStart(null); startToEnd(null)
}
}
}
/**
* Converts the index (-2 -> start, -1 -> end, 0 -> left, 1 -> right) to an index in
* the arrays above (0 -> left, 1 -> right).
*/
// TODO(popam, b/157886946): this is temporary until we can use CL's own RTL handling
fun verticalAnchorIndexToFunctionIndex(index: Int, layoutDirection: LayoutDirection) =
when {
index >= 0 -> index // already left or right
layoutDirection == LayoutDirection.Ltr -> 2 + index // start -> left, end -> right
else -> -index - 1 // start -> right, end -> left
}
val horizontalAnchorFunctions:
Array<Array<ConstraintReference.(Any) -> ConstraintReference>> = arrayOf(
arrayOf(
{ other -> topToBottom(null); baselineToBaseline(null); topToTop(other) },
{ other -> topToTop(null); baselineToBaseline(null); topToBottom(other) }
),
arrayOf(
{ other -> bottomToBottom(null); baselineToBaseline(null); bottomToTop(other) },
{ other -> bottomToTop(null); baselineToBaseline(null); bottomToBottom(other) }
)
)
val baselineAnchorFunction: ConstraintReference.(Any) -> ConstraintReference =
{ other ->
topToTop(null)
topToBottom(null)
bottomToTop(null)
bottomToBottom(null)
baselineToBaseline(other)
}
} | apache-2.0 | 5f4dbbebf220471019421d6c59c44845 | 32.995025 | 94 | 0.617828 | 4.859175 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/social/EditarXPCommand.kt | 1 | 2458 | package net.perfectdreams.loritta.morenitta.commands.vanilla.social
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.extensions.retrieveMemberOrNull
import net.dv8tion.jda.api.Permission
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.LorittaBot
class EditarXPCommand(loritta: LorittaBot) : AbstractCommand(loritta, "editxp", listOf("editarxp", "setxp"), category = net.perfectdreams.loritta.common.commands.CommandCategory.SOCIAL) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.editxp.description")
override fun getExamplesKey() = LocaleKeyData("commands.command.editxp.examples")
override fun canUseInPrivateChannel(): Boolean {
return false
}
override fun getDiscordPermissions(): List<Permission> {
return listOf(Permission.MANAGE_SERVER)
}
override fun getUsage() = arguments {
argument(ArgumentType.USER) {}
argument(ArgumentType.NUMBER) {}
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
val user = context.getUserAt(0)
if (user != null && context.rawArgs.size == 2) {
val newXp = context.rawArgs[1].toLongOrNull()
if (newXp == null) {
context.sendMessage("${Constants.ERROR} **|** ${context.getAsMention(true)}${context.locale["commands.invalidNumber", context.rawArgs[1]]}")
return
}
if (0 > newXp) {
context.sendMessage(Constants.ERROR + " **|** " + context.getAsMention(true) + context.locale["commands.command.editxp.moreThanZero"])
return
}
// We will only set that the guild is in the guild if the member is *actually* in the guild
// This fixes a bug that a user could edit XP of users that weren't in the server just to put a dumb badge on their profile
val userData = context.config.getUserData(loritta, user.idLong, context.guild.retrieveMemberOrNull(user) != null)
loritta.newSuspendedTransaction {
userData.xp = newXp
}
context.sendMessage(context.getAsMention(true) + context.locale["commands.command.editxp.success", user.asMention])
} else {
context.explain()
}
}
}
| agpl-3.0 | 07c193d7b84df4b233e8d85940db9bf5 | 40.661017 | 187 | 0.769325 | 3.958132 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/ui/main/tune/TaskerPluginActivity.kt | 1 | 9013 | package com.androidvip.hebf.ui.main.tune
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.widget.CompoundButton
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.androidvip.hebf.R
import com.androidvip.hebf.adapters.ForceStopAppsAdapter
import com.androidvip.hebf.hide
import com.androidvip.hebf.models.App
import com.androidvip.hebf.receivers.TaskerReceiver
import com.androidvip.hebf.show
import com.androidvip.hebf.ui.base.BaseActivity
import com.androidvip.hebf.utils.*
import com.androidvip.hebf.utils.vip.VipServices
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_tasker_plugin.*
import kotlinx.coroutines.launch
import java.util.ArrayList
import java.util.HashSet
import kotlin.Comparator
class TaskerPluginActivity : BaseActivity() {
private var selectedFeature: Int = TaskerReceiver.HEBF_FEATURE_INVALID
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tasker_plugin)
setUpToolbar(toolbar)
val vipPrefs = VipPrefs(applicationContext)
val gbPrefs = GbPrefs(applicationContext)
vipTaskerDefaultSaver.setUpOnCheckedChange(vipPrefs, K.PREF.VIP_DEFAULT_SAVER)
vipTaskerDisableData.setUpOnCheckedChange(vipPrefs, K.PREF.VIP_DISABLE_DATA)
vipTaskerDisableSync.setUpOnCheckedChange(vipPrefs, K.PREF.VIP_DISABLE_SYNC)
vipTaskerDisableBluetooth.setUpOnCheckedChange(vipPrefs, K.PREF.VIP_DISABLE_BLUETOOTH)
vipTaskerGrayScale.setUpOnCheckedChange(vipPrefs, K.PREF.VIP_GRAYSCALE)
vipTaskerForceDoze.setUpOnCheckedChange(vipPrefs, K.PREF.VIP_DEVICE_IDLE)
vipTaskerForceStop.setUpOnCheckedChange(vipPrefs, K.PREF.VIP_FORCE_STOP)
vipTaskerSelectAppsButton.setOnClickListener { showPickAppsDialog() }
taskerSelectFeatureVip.setOnClickListener {
taskerSelectFeatureLayout.hide()
vipTaskerScroll.show()
taskerDoneButton.show()
supportActionBar?.subtitle = getString(R.string.vip_battery_saver)
selectedFeature = TaskerReceiver.HEBF_FEATURE_VIP
}
gameBoosterTaskerCaches.setUpOnCheckedChange(gbPrefs, K.PREF.GB_CLEAR_CACHES)
gameBoosterTaskerDnd.setUpOnCheckedChange(gbPrefs, K.PREF.GB_DND)
gameBoosterTaskerForceStop.setUpOnCheckedChange(gbPrefs, K.PREF.GB_FORCE_STOP)
gameBoosterTaskerLmk.setUpOnCheckedChange(gbPrefs, K.PREF.GB_CHANGE_LMK)
gameBoosterTaskerSelectAppsButton.setOnClickListener { showPickAppsDialog() }
taskerSelectFeatureGameBooster.setOnClickListener {
taskerSelectFeatureLayout.hide()
gameBoosterTaskerScroll.show()
taskerDoneButton.show()
supportActionBar?.subtitle = getString(R.string.game_booster)
selectedFeature = TaskerReceiver.HEBF_FEATURE_GB
}
taskerDoneButton.setOnClickListener {
val name = when (selectedFeature) {
TaskerReceiver.HEBF_FEATURE_GB -> {
if (gameBoosterTaskerActionSwitch.isChecked)
"${getString(R.string.game_booster)} (${getString(R.string.enable)})"
else
"${getString(R.string.game_booster)} (${getString(R.string.disable)})"
}
TaskerReceiver.HEBF_FEATURE_VIP -> {
if (vipTaskerActionSwitch.isChecked)
"${getString(R.string.vip_battery_saver)} (${getString(R.string.enable)})"
else
"${getString(R.string.vip_battery_saver)} (${getString(R.string.disable)})"
}
else -> getString(android.R.string.unknownName)
}
val actionType: Int = when (selectedFeature) {
TaskerReceiver.HEBF_FEATURE_GB -> {
if (gameBoosterTaskerActionSwitch.isChecked)
TaskerReceiver.ACTION_TYPE_ENABLE
else
TaskerReceiver.ACTION_TYPE_DISABLE
}
TaskerReceiver.HEBF_FEATURE_VIP -> {
if (vipTaskerActionSwitch.isChecked)
TaskerReceiver.ACTION_TYPE_ENABLE
else
TaskerReceiver.ACTION_TYPE_DISABLE
}
else -> TaskerReceiver.ACTION_TYPE_INVALID
}
val resultBundle = Bundle().apply {
putInt(TaskerReceiver.BUNDLE_EXTRA_HEBF_FEATURE, selectedFeature)
putInt(TaskerReceiver.BUNDLE_EXTRA_ACTION_TYPE, actionType)
putString(TaskerReceiver.EXTRA_STRING_BLURB, name)
}
val resultIntent = Intent().apply {
putExtra(TaskerReceiver.EXTRA_BUNDLE, resultBundle)
}
VipServices.toggleVipService(false, this)
VipServices.toggleChargerService(false, this)
vipPrefs.edit {
putBoolean(K.PREF.VIP_AUTO_TURN_ON, false)
putBoolean(K.PREF.VIP_DISABLE_WHEN_CHARGING, false)
}
Logger.logInfo("Set tasker profile to $name", this)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.fragment_close_enter, R.anim.fragment_close_exit)
}
private fun showPickAppsDialog() {
val loadingSnackBar = Snackbar.make(taskerDoneButton, R.string.loading, Snackbar.LENGTH_INDEFINITE)
loadingSnackBar.show()
val activity = this
val builder = AlertDialog.Builder(activity)
val dialogView = layoutInflater.inflate(R.layout.dialog_list_force_stop_apps, null)
builder.setTitle(R.string.hibernate_apps)
builder.setView(dialogView)
lifecycleScope.launch(workerContext) {
val packagesManager = PackagesManager(activity)
val savedAppSet = userPrefs.getStringSet(K.PREF.FORCE_STOP_APPS_SET, HashSet())
val packages = if (userPrefs.getInt(K.PREF.USER_TYPE, K.USER_TYPE_NORMAL) == K.USER_TYPE_NORMAL) {
packagesManager.installedPackages
} else {
(packagesManager.getSystemApps() + packagesManager.getThirdPartyApps()).map {
it.packageName
}
}
val allApps = ArrayList<App>()
for (packageName in packages) {
// Remove HEBF from the list
if (packageName.contains("com.androidvip")) continue
App().apply {
this.packageName = packageName
label = packagesManager.getAppLabel(packageName)
icon = packagesManager.getAppIcon(packageName)
isChecked = savedAppSet.contains(packageName)
allApps.add(this)
}
}
allApps.sortWith(Comparator { one: App, other: App -> one.label.compareTo(other.label) })
runSafeOnUiThread {
loadingSnackBar.dismiss()
val rv = dialogView.findViewById<RecyclerView>(R.id.force_stop_apps_rv)
val layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
rv.layoutManager = layoutManager
val fullAdapter = ForceStopAppsAdapter(activity, allApps)
rv.adapter = fullAdapter
builder.setPositiveButton(android.R.string.ok) { _, _ ->
val appSet = fullAdapter.selectedApps
val packageNamesSet = HashSet<String>()
appSet.forEach {
if (it.packageName.isNotEmpty()) {
packageNamesSet.add(it.packageName)
}
}
userPrefs.putStringSet(K.PREF.FORCE_STOP_APPS_SET, packageNamesSet)
}
builder.setNegativeButton(android.R.string.cancel) { _, _ -> }
builder.show()
}
}
}
private fun CompoundButton.setUpOnCheckedChange(prefs: BasePrefs, prefName: String) {
setOnCheckedChangeListener(null)
isChecked = prefs.getBoolean(prefName, false)
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(prefName, isChecked)
}
}
}
| apache-2.0 | fa65c4cfacd740d647a74e94ebaaea9c | 41.314554 | 110 | 0.632309 | 4.786511 | false | false | false | false |
madtcsa/AppManager | app/src/main/java/com/md/appmanager/listeners/HidingScrollListener.kt | 1 | 941 | package com.md.appmanager.listeners
import android.support.v7.widget.RecyclerView
abstract class HidingScrollListener : RecyclerView.OnScrollListener() {
private var scrolledDistance = 0
private var controlsVisible = true
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
onHide()
controlsVisible = false
scrolledDistance = 0
} else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
onShow()
controlsVisible = true
scrolledDistance = 0
}
if (controlsVisible && dy > 0 || !controlsVisible && dy < 0) {
scrolledDistance += dy
}
}
abstract fun onHide()
abstract fun onShow()
companion object {
private val HIDE_THRESHOLD = 20
}
}
| gpl-3.0 | 559452dc9624a6e3e25e3412067eecc2 | 26.676471 | 76 | 0.621679 | 4.901042 | false | false | false | false |
alxnns1/MobHunter | src/main/kotlin/com/alxnns1/mobhunter/item/MHSpawnEggItem.kt | 1 | 2383 | package com.alxnns1.mobhunter.item
import com.alxnns1.mobhunter.withPrivateValue
import net.minecraft.block.DispenserBlock
import net.minecraft.dispenser.DefaultDispenseItemBehavior
import net.minecraft.dispenser.IBlockSource
import net.minecraft.entity.EntityType
import net.minecraft.entity.SpawnReason
import net.minecraft.item.ItemStack
import net.minecraft.item.SpawnEggItem
import net.minecraft.nbt.CompoundNBT
import net.minecraft.util.Direction
/*
This class exists due to limitations with SpawnEggItem where its constructor requires an EntityType instance.
Unfortunately, items are registered before entity types, so we need to use a supplier instead.
We also need to inject our eggs into SpawnEggItem.EGGS, however by the time we do, the list has already been used to
register dispenser behaviours and egg colours, so we need to do those manually. Inserting into the list therefore is
just in-case other mods use the list.
Some of this logic was influenced by Cadiboo's example here:
https://github.com/Cadiboo/Example-Mod/blob/1.15.2/src/main/java/io/github/cadiboo/examplemod/item/ModdedSpawnEggItem.java
*/
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class MHSpawnEggItem(
private val entityTypeSupplier: () -> EntityType<*>,
primaryColour: Int,
secondaryColour: Int,
props: Properties
) : SpawnEggItem(null, primaryColour, secondaryColour, props) {
companion object {
private val DISPENSE_BEHAVIOUR = object : DefaultDispenseItemBehavior() {
override fun dispenseStack(source: IBlockSource, stack: ItemStack): ItemStack {
val dir = source.blockState[DispenserBlock.FACING]
val type = (stack.item as SpawnEggItem).getType(stack.tag)
type.spawn(source.world, stack, null, source.blockPos.offset(dir), SpawnReason.DISPENSER, dir != Direction.UP, false)
stack.shrink(1)
return stack
}
}
private val NEW_EGGS = mutableSetOf<MHSpawnEggItem>()
fun getNewEggsArray(): Array<MHSpawnEggItem> = NEW_EGGS.toTypedArray()
fun initEggs() =
withPrivateValue<MutableMap<EntityType<*>, SpawnEggItem>, SpawnEggItem>(null, "field_195987_b") { eggs ->
NEW_EGGS.forEach { eggs[it.getType(null)] = it }
NEW_EGGS.clear()
}
}
init {
NEW_EGGS += this
DispenserBlock.registerDispenseBehavior(this, DISPENSE_BEHAVIOUR)
}
override fun getType(nbt: CompoundNBT?): EntityType<*> = entityTypeSupplier()
}
| gpl-2.0 | a92dc727b6e051a1c6e24bd626a1f87f | 38.716667 | 123 | 0.776332 | 3.489019 | false | false | false | false |
Shynixn/PetBlocks | petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/business/extension/ExtensionMethod.kt | 1 | 5342 | @file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.petblocks.core.logic.business.extension
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.enumeration.ChatColor
import com.github.shynixn.petblocks.api.business.service.ConcurrencyService
import com.github.shynixn.petblocks.api.business.service.LoggingService
import com.github.shynixn.petblocks.api.persistence.entity.ChatMessage
import com.github.shynixn.petblocks.api.persistence.entity.Position
import com.github.shynixn.petblocks.api.persistence.entity.PropertyTrackable
import com.github.shynixn.petblocks.core.logic.persistence.entity.ChatMessageEntity
import java.lang.reflect.Field
import java.util.concurrent.CompletableFuture
import kotlin.reflect.KProperty
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
/**
* Creates a new chat message.
*/
fun chatMessage(f: ChatMessage.() -> Unit): ChatMessage {
val chatMessage = ChatMessageEntity()
f.invoke(chatMessage)
return chatMessage
}
/**
* Casts any instance to any type.
*/
fun <T> Any?.cast(): T {
return this as T
}
/**
* Gets if the given server is a bukkit server.
*/
val isBukkitServer: Boolean
get() {
return try {
Class.forName("com.github.shynixn.petblocks.bukkit.PetBlocksPlugin")
true
} catch (e: Exception) {
false
}
}
/**
* Changes the position to it's yaw front by the given amount.
*/
fun Position.relativeFront(amount: Double): Position {
this.x = x + amount * Math.cos(Math.toRadians(yaw + 90))
this.z = z + amount * Math.sin(Math.toRadians(yaw + 90))
return this
}
/**
* Changes the position to it's yaw back by the given amount.
*/
fun Position.relativeBack(amount: Double): Position {
this.x = x + amount * Math.cos(Math.toRadians(yaw + 90))
this.z = z + amount * Math.sin(Math.toRadians(yaw + 90))
return this
}
/**
* Gets the column value.
*/
inline fun <reified V> Map<String, Any?>.getItem(key: String): V {
val data = this[key]
if (data is Int && V::class == Boolean::class) {
return (this[key] == 1) as V
}
return this[key] as V
}
/**
* Merges the args after the first parameter.
*
* @param args args
* @return merged.
*/
fun mergeArgs(args: Array<out String>): String {
val builder = StringBuilder()
for (i in 1 until args.size) {
if (builder.isNotEmpty()) {
builder.append(' ')
}
builder.append(args[i])
}
return builder.toString()
}
/**
* Executes the given [f] via the [concurrencyService] synchronized with the server tick.
*/
inline fun sync(
concurrencyService: ConcurrencyService,
delayTicks: Long = 0L,
repeatingTicks: Long = 0L,
crossinline f: () -> Unit
) {
concurrencyService.runTaskSync(delayTicks, repeatingTicks) {
f.invoke()
}
}
/**
* Gets if the given property has changed.
*/
fun <R> KProperty<R>.hasChanged(instance: PropertyTrackable): Boolean {
val hasChanged = instance.propertyTracker.hasChanged(this)
instance.propertyTracker.onPropertyChanged(this, false)
return hasChanged
}
/**
* Executes the given [f] via the [concurrencyService] asynchronous.
*/
inline fun async(
concurrencyService: ConcurrencyService,
delayTicks: Long = 0L,
repeatingTicks: Long = 0L,
crossinline f: () -> Unit
) {
concurrencyService.runTaskAsync(delayTicks, repeatingTicks) {
f.invoke()
}
}
/**
* Change the accessible field.
*/
fun Field.accessible(flag: Boolean) : Field {
this.isAccessible = flag
return this
}
/**
* Accepts the action safely.
*/
fun <T> CompletableFuture<T>.thenAcceptSafely(f: (T) -> Unit) {
this.thenAccept(f).exceptionally { e ->
PetBlocksApi.resolve<LoggingService>(LoggingService::class.java).error("Failed to execute Task.", e)
throw RuntimeException(e)
}
}
/**
* Translates the given chatColor.
*/
fun String.translateChatColors(): String {
return ChatColor.translateChatColorCodes('&', this)
}
/**
* Strips the chatcolors.
*/
fun String.stripChatColors(): String {
return ChatColor.stripChatColors(this)
}
| apache-2.0 | 6655f184ac3fb04ebda825a034428e11 | 27.115789 | 108 | 0.697304 | 3.896426 | false | false | false | false |
Shynixn/PetBlocks | petblocks-sponge-plugin/src/main/java/com/github/shynixn/petblocks/sponge/logic/business/service/ItemTypeServiceImpl.kt | 1 | 9485 | @file:Suppress("UNCHECKED_CAST")
package com.github.shynixn.petblocks.sponge.logic.business.service
import com.github.shynixn.petblocks.api.business.enumeration.MaterialType
import com.github.shynixn.petblocks.api.business.service.ItemTypeService
import com.github.shynixn.petblocks.api.persistence.entity.Item
import com.github.shynixn.petblocks.core.logic.business.extension.cast
import com.github.shynixn.petblocks.core.logic.persistence.entity.ItemEntity
import com.github.shynixn.petblocks.sponge.logic.business.extension.toText
import com.github.shynixn.petblocks.sponge.logic.business.extension.toTextString
import net.minecraft.nbt.JsonToNBT
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.nbt.NBTTagList
import org.spongepowered.api.Sponge
import org.spongepowered.api.block.BlockType
import org.spongepowered.api.data.key.Keys
import org.spongepowered.api.item.ItemType
import org.spongepowered.api.item.inventory.ItemStack
import org.spongepowered.api.text.Text
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder
import java.util.*
import kotlin.collections.HashMap
/**
* Created by Shynixn 2019.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2019 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class ItemTypeServiceImpl : ItemTypeService {
private val cache = HashMap<Any, Any>()
/**
* Tries to find a matching itemType matching the given hint.
*/
override fun <I> findItemType(sourceHint: Any): I {
if (cache.containsKey(sourceHint)) {
return cache[sourceHint]!! as I
}
var descHint = sourceHint
if (descHint is ItemStack) {
return descHint.type as I
}
if (sourceHint is MaterialType) {
descHint = sourceHint.name
}
val intHint: Int? = if (descHint is Int) {
descHint
} else if (descHint is String && descHint.toIntOrNull() != null) {
descHint.toInt()
} else {
null
}
if (intHint != null) {
// It is a number.
for (material in MaterialType.values()) {
if (material.numericId == intHint) {
cache[sourceHint] = Sponge.getGame().registry.getType(ItemType::class.java, material.minecraftName).get()
return cache[sourceHint]!! as I
}
}
}
if (descHint is BlockType) {
descHint = descHint.name
}
if (descHint is ItemType) {
cache[sourceHint] = descHint
return cache[sourceHint]!! as I
}
if (descHint is String) {
cache[sourceHint] = try {
Sponge.getGame().registry.getType(ItemType::class.java, MaterialType.valueOf(descHint).minecraftName).get()
} catch (e: Exception) {
try {
Sponge.getGame().registry.getType(ItemType::class.java, descHint).get()
} catch (e: Exception) {
Sponge.getGame().registry.getType(BlockType::class.java, descHint).get()
}
}
return cache[sourceHint]!! as I
}
throw IllegalArgumentException("Hint $sourceHint does not exist!")
}
/**
* Tries to find the data value of the given hint.
*/
override fun findItemDataValue(sourceHint: Any): Int {
if (sourceHint is ItemStack) {
return sourceHint.cast<net.minecraft.item.ItemStack>().itemDamage
}
if (sourceHint is Int) {
return sourceHint
}
throw IllegalArgumentException("Hint $sourceHint does not exist!")
}
/**
* Converts the given itemStack ot an item.
*/
override fun <I> toItem(itemStack: I): Item {
require(itemStack is ItemStack)
val optDisplay = itemStack.get(Keys.DISPLAY_NAME)
val displayName = if (optDisplay.isPresent) {
optDisplay.get().toTextString()
} else {
null
}
val optLore = itemStack.get(Keys.ITEM_LORE)
val lore = if (optLore.isPresent) {
val items = ArrayList<String>()
for (line in optLore.get()) {
items.add(line.toTextString())
}
items
} else {
null
}
return ItemEntity(
findItemType<ItemType>(itemStack).name,
findItemDataValue(itemStack),
"",
displayName,
lore,
null
)
}
/**
* Converts the given item to an ItemStack.
*/
override fun <I> toItemStack(item: Item): I {
val itemstack = ItemStack.builder()
.itemType(findItemType(item.type)).build()
itemstack.cast<net.minecraft.item.ItemStack>().itemDamage = item.dataValue
if (item.displayName != null) {
itemstack.offer(Keys.DISPLAY_NAME, item.displayName!!.toText())
}
if (item.lore != null) {
val items = ArrayList<Text>()
for (line in item.lore!!) {
items.add(line.toText())
}
itemstack.offer(Keys.ITEM_LORE, items)
}
if (item.skin != null) {
val nmsItemStack = itemstack.cast<net.minecraft.item.ItemStack>()
var newSkin = item.skin!!
val nbtTagCompound = if (nmsItemStack.tagCompound != null) {
nmsItemStack.tagCompound!!
} else {
NBTTagCompound()
}
if (newSkin.length > 32) {
if (newSkin.contains("textures.minecraft.net")) {
if (!newSkin.startsWith("http://")) {
newSkin = "http://$newSkin"
}
newSkin = Base64Coder.encodeString("{textures:{SKIN:{url:\"$newSkin\"}}}")
}
val skinProfile = Sponge.getServer().gameProfileManager.createProfile(UUID.randomUUID(), null)
val profileProperty =
Sponge.getServer().gameProfileManager.createProfileProperty("textures", newSkin, null)
skinProfile.propertyMap.put("textures", profileProperty)
val internalTag = NBTTagCompound()
internalTag.setString("Id", skinProfile.uniqueId.toString())
val propertiesTag = NBTTagCompound()
for (content in skinProfile.propertyMap.keySet()) {
val nbtTagList = NBTTagList()
for (itemSkin in skinProfile.propertyMap.get(content)) {
val nbtItem = NBTTagCompound()
nbtItem.setString("Value", itemSkin.value)
if (itemSkin.hasSignature()) {
nbtItem.setString("Signature", itemSkin.signature.get())
}
nbtTagList.appendTag(nbtItem)
}
propertiesTag.setTag(content, nbtTagList)
}
internalTag.setTag("Properties", propertiesTag)
nbtTagCompound.setTag("SkullOwner", internalTag)
} else if (newSkin.isNotEmpty()) {
nbtTagCompound.setString("SkullOwner", newSkin)
}
nmsItemStack.tagCompound = nbtTagCompound
}
if (item.nbtTag != "") {
val nmsItemStack = itemstack.cast<net.minecraft.item.ItemStack>()
val targetNbtTag = if (nmsItemStack.tagCompound != null) {
nmsItemStack.tagCompound!!
} else {
NBTTagCompound()
}
val compoundMapField = NBTTagCompound::class.java.getDeclaredField("field_74784_a")
compoundMapField.isAccessible = true
val targetNbtMap = compoundMapField.get(targetNbtTag) as MutableMap<Any?, Any?>
try {
val sourceNbtTag = JsonToNBT.getTagFromJson(item.nbtTag)
val sourceNbtMap = compoundMapField.get(sourceNbtTag) as MutableMap<Any?, Any?>
for (key in sourceNbtMap.keys) {
targetNbtMap[key] = sourceNbtMap[key]
}
nmsItemStack.tagCompound = targetNbtTag
} catch (e: Exception) {
e.printStackTrace()
}
}
return itemstack as I
}
} | apache-2.0 | 90de9c68127a7b1889750923227ef61c | 33.620438 | 125 | 0.59378 | 4.647232 | false | false | false | false |
siempredelao/Distance-From-Me-Android | app/src/main/java/gc/david/dfm/showinfo/presentation/ShowInfoPresenter.kt | 1 | 3767 | /*
* Copyright (c) 2019 David Aguiar Gonzalez
*
* 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 gc.david.dfm.showinfo.presentation
import android.text.TextUtils
import com.google.android.gms.maps.model.LatLng
import gc.david.dfm.ConnectionManager
import gc.david.dfm.address.domain.GetAddressNameByCoordinatesUseCase
import gc.david.dfm.address.domain.model.AddressCollection
import gc.david.dfm.database.Distance
import gc.david.dfm.database.Position
import gc.david.dfm.distance.domain.InsertDistanceUseCase
import java.util.*
/**
* Created by david on 15.01.17.
*/
class ShowInfoPresenter(
private val showInfoView: ShowInfo.View,
private val getOriginAddressNameByCoordinatesUseCase: GetAddressNameByCoordinatesUseCase,
private val getDestinationAddressNameByCoordinatesUseCase: GetAddressNameByCoordinatesUseCase,
private val insertDistanceUseCase: InsertDistanceUseCase,
private val connectionManager: ConnectionManager
) : ShowInfo.Presenter {
override fun searchPositionByCoordinates(originLatLng: LatLng, destinationLatLng: LatLng) {
if (!connectionManager.isOnline()) {
showInfoView.showNoInternetError()
} else {
showInfoView.showProgress()
getOriginAddress(getOriginAddressNameByCoordinatesUseCase, originLatLng, true)
getOriginAddress(getDestinationAddressNameByCoordinatesUseCase, destinationLatLng, false)
}
}
private fun getOriginAddress(getAddressUseCase: GetAddressNameByCoordinatesUseCase,
latLng: LatLng,
isOrigin: Boolean) {
getAddressUseCase.execute(latLng, 1, object : GetAddressNameByCoordinatesUseCase.Callback {
override fun onAddressLoaded(addressCollection: AddressCollection) {
showInfoView.hideProgress()
val addressList = addressCollection.addressList
if (addressList.isEmpty()) {
showInfoView.showNoMatchesMessage(isOrigin)
} else {
showInfoView.setAddress(addressList.first().formattedAddress, isOrigin)
}
}
override fun onError(errorMessage: String) {
showInfoView.hideProgress()
showInfoView.showError(errorMessage, isOrigin)
}
})
}
override fun saveDistance(name: String, distance: String, latLngPositionList: List<LatLng>) {
val distanceAsDistance = Distance(id = null, name = name, distance = distance, date = Date())
val positionList = latLngPositionList.map {
Position(id = null, latitude = it.latitude, longitude = it.longitude, distanceId = -1L) // FIXME
}
insertDistanceUseCase.execute(distanceAsDistance, positionList, object : InsertDistanceUseCase.Callback {
override fun onInsert() {
if (name.isNotEmpty()) {
showInfoView.showSuccessfulSaveWithName(name)
} else {
showInfoView.showSuccessfulSave()
}
}
override fun onError() {
showInfoView.showFailedSave()
}
})
}
}
| apache-2.0 | 1b591bf653c49bd38c2d7893edec9b06 | 38.652632 | 113 | 0.675073 | 4.924183 | false | false | false | false |
siempredelao/Distance-From-Me-Android | app/src/main/java/gc/david/dfm/database/Distance.kt | 1 | 1185 | /*
* Copyright (c) 2019 David Aguiar Gonzalez
*
* 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 gc.david.dfm.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import gc.david.dfm.database.Distance.Companion.TABLE_NAME
import java.util.*
@Entity(tableName = TABLE_NAME)
data class Distance(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") val id: Long?,
@ColumnInfo(name = "NAME") val name: String,
@ColumnInfo(name = "DISTANCE") val distance: String,
@ColumnInfo(name = "DATE") val date: Date
) {
companion object {
const val TABLE_NAME = "DISTANCE"
}
} | apache-2.0 | 4c4b9da3da263e3309ab582380b1aa4b | 31.054054 | 81 | 0.716456 | 3.989899 | false | false | false | false |
anthologist/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/models/Medium.kt | 1 | 2840 | package com.simplemobiletools.gallery.models
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Index
import android.arch.persistence.room.PrimaryKey
import com.simplemobiletools.commons.extensions.formatDate
import com.simplemobiletools.commons.extensions.formatSize
import com.simplemobiletools.commons.extensions.isDng
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.gallery.helpers.TYPE_GIF
import com.simplemobiletools.gallery.helpers.TYPE_IMAGE
import com.simplemobiletools.gallery.helpers.TYPE_VIDEO
import java.io.Serializable
@Entity(tableName = "media", indices = [(Index(value = "full_path", unique = true))])
data class Medium(
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "filename") var name: String,
@ColumnInfo(name = "full_path") var path: String,
@ColumnInfo(name = "parent_path") var parentPath: String,
@ColumnInfo(name = "last_modified") val modified: Long,
@ColumnInfo(name = "date_taken") val taken: Long,
@ColumnInfo(name = "size") val size: Long,
@ColumnInfo(name = "type") val type: Int) : Serializable, Comparable<Medium> {
companion object {
private const val serialVersionUID = -6553149366975455L
var sorting: Int = 0
}
fun isGif() = type == TYPE_GIF
fun isImage() = type == TYPE_IMAGE
fun isVideo() = type == TYPE_VIDEO
fun isDng() = path.isDng()
override fun compareTo(other: Medium): Int {
var result: Int
when {
sorting and SORT_BY_NAME != 0 -> result = AlphanumericComparator().compare(name.toLowerCase(), other.name.toLowerCase())
sorting and SORT_BY_PATH != 0 -> result = AlphanumericComparator().compare(path.toLowerCase(), other.path.toLowerCase())
sorting and SORT_BY_SIZE != 0 -> result = when {
size == other.size -> 0
size > other.size -> 1
else -> -1
}
sorting and SORT_BY_DATE_MODIFIED != 0 -> result = when {
modified == other.modified -> 0
modified > other.modified -> 1
else -> -1
}
else -> result = when {
taken == other.taken -> 0
taken > other.taken -> 1
else -> -1
}
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
return result
}
fun getBubbleText() = when {
sorting and SORT_BY_NAME != 0 -> name
sorting and SORT_BY_PATH != 0 -> path
sorting and SORT_BY_SIZE != 0 -> size.formatSize()
sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate()
else -> taken.formatDate()
}
}
| apache-2.0 | eb81af0c4988e341a207cd78ce72e9e1 | 36.866667 | 132 | 0.616901 | 4.322679 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/utilities/GridUtilities.kt | 1 | 9668 | package net.dinkla.raytracer.objects.utilities
import net.dinkla.raytracer.math.Normal
import net.dinkla.raytracer.math.Point3D
import net.dinkla.raytracer.math.Vector3D
import net.dinkla.raytracer.objects.SmoothTriangle
import net.dinkla.raytracer.objects.Triangle
import java.lang.Math.sin
import java.lang.Math.cos
import java.lang.Math.PI
object GridUtilities {
fun tessellateFlatSphere(list: MutableList<Triangle>, horizontalSteps: Int, verticalSteps: Int) {
// define the top triangles which all touch the north pole
var k = 1
for (j in 0..horizontalSteps - 1) {
// define vertices
val v0 = Point3D(0.0, 1.0, 0.0) // top (north pole)
val v1 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // bottom left
cos(PI * k / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val v2 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // bottom right
cos(PI * k / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val triangle_ptr = Triangle(v0, v1, v2)
list.add(triangle_ptr)
}
// define the bottom triangles which all touch the south pole
k = verticalSteps - 1
for (j in 0..horizontalSteps - 1) {
// define vertices
val v0 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top left
cos(PI * k / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val v1 = Point3D(0.0, -1.0, 0.0) // bottom (south pole)
val v2 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top right
cos(PI * k / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val triangle_ptr = Triangle(v0, v1, v2)
list.add(triangle_ptr)
}
// define the other triangles
k = 1
while (k <= verticalSteps - 2) {
for (j in 0..horizontalSteps - 1) {
// define the first triangle
// vertices
var v0 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps), // bottom left, use k + 1, j
cos(PI * (k + 1) / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps))
var v1 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps), // bottom right, use k + 1, j + 1
cos(PI * (k + 1) / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps))
var v2 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top left, use k, j
cos(PI * k / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val triangle_ptr1 = Triangle(v0, v1, v2)
list.add(triangle_ptr1)
// define the second triangle
// vertices
v0 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top right, use k, j + 1
cos(PI * k / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
v1 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top left, use k, j
cos(PI * k / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
v2 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps), // bottom right, use k + 1, j + 1
cos(PI * (k + 1) / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps))
val triangle_ptr2 = Triangle(v0, v1, v2)
list.add(triangle_ptr2)
}
k++
}
}
fun tessellateSmoothSphere(list: MutableList<SmoothTriangle>, horizontalSteps: Int, verticalSteps: Int) {
// define the top triangles which all touch the north pole
var k = 1
for (j in 0..horizontalSteps - 1) {
// define vertices
val v0 = Point3D(0.0, 1.0, 0.0) // top (north pole)
val v1 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // bottom left
cos(PI * k / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val v2 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // bottom right
cos(PI * k / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val triangle = SmoothTriangle(v0, v1, v2)
triangle.n0 = Normal(Vector3D(v0))
triangle.n1 = Normal(Vector3D(v1))
triangle.n2 = Normal(Vector3D(v2))
list.add(triangle)
}
// define the bottom triangles which all touch the south pole
k = verticalSteps - 1
for (j in 0..horizontalSteps - 1) {
// define vertices
val v0 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top left
cos(PI * k / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val v1 = Point3D(0.0, -1.0, 0.0) // bottom (south pole)
val v2 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top right
cos(PI * k / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val triangle = SmoothTriangle(v0, v1, v2)
triangle.n0 = Normal(Vector3D(v0))
triangle.n1 = Normal(Vector3D(v1))
triangle.n2 = Normal(Vector3D(v2))
list.add(triangle)
}
// define the other triangles
k = 1
while (k <= verticalSteps - 2) {
for (j in 0..horizontalSteps - 1) {
// define the first triangle
// vertices
var v0 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps), // bottom left, use k + 1, j
cos(PI * (k + 1) / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps))
var v1 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps), // bottom right, use k + 1, j + 1
cos(PI * (k + 1) / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps))
var v2 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top left, use k, j
cos(PI * k / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
val triangle = SmoothTriangle(v0, v1, v2)
triangle.n0 = Normal(Vector3D(v0))
triangle.n1 = Normal(Vector3D(v1))
triangle.n2 = Normal(Vector3D(v2))
list.add(triangle)
// define the second triangle
// vertices
v0 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top right, use k, j + 1
cos(PI * k / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
v1 = Point3D(sin(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps), // top left, use k, j
cos(PI * k / verticalSteps),
cos(2.0 * PI * j.toDouble() / horizontalSteps) * sin(PI * k / verticalSteps))
v2 = Point3D(sin(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps), // bottom right, use k + 1, j + 1
cos(PI * (k + 1) / verticalSteps),
cos(2.0 * PI * (j + 1).toDouble() / horizontalSteps) * sin(PI * (k + 1) / verticalSteps))
val triangle2 = SmoothTriangle(v0, v1, v2)
triangle2.n0 = Normal(Vector3D(v0))
triangle2.n1 = Normal(Vector3D(v1))
triangle2.n2 = Normal(Vector3D(v2))
list.add(triangle2)
}
k++
}
}
}
| apache-2.0 | 7289560bd9db6dc1688b6e60e9fe9589 | 46.861386 | 157 | 0.498966 | 3.630492 | false | false | false | false |
xfournet/intellij-community | java/java-impl/src/com/intellij/codeInsight/intention/impl/JavaElementActionsFactory.kt | 1 | 5599 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.intention.impl
import com.intellij.codeInsight.daemon.impl.quickfix.ModifierFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.java.actions.*
import com.intellij.lang.jvm.JvmAnnotation
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.JvmModifiersOwner
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmType
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.impl.beanProperties.CreateJavaBeanPropertyFix
import com.intellij.psi.util.PsiUtil
class JavaElementActionsFactory(private val renderer: JavaElementRenderer) : JvmElementActionsFactory() {
override fun createChangeModifierActions(target: JvmModifiersOwner, request: MemberRequest.Modifier): List<IntentionAction> = with(
request) {
val declaration = target as PsiModifierListOwner
if (declaration.language != JavaLanguage.INSTANCE) return@with emptyList()
listOf(ModifierFix(declaration.modifierList, renderer.render(modifier), shouldPresent, false))
}
override fun createAddPropertyActions(targetClass: JvmClass, request: MemberRequest.Property): List<IntentionAction> {
with(request) {
val psiClass = targetClass.toJavaClassOrNull() ?: return emptyList()
val helper = JvmPsiConversionHelper.getInstance(psiClass.project)
val propertyType = helper.convertType(propertyType)
if (getterRequired && setterRequired)
return listOf<IntentionAction>(
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired,
true),
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired,
false))
if (getterRequired || setterRequired)
return listOf<IntentionAction>(
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired,
true),
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired,
false),
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, true, true, true))
return listOf<IntentionAction>(
CreateJavaBeanPropertyFix(psiClass, propertyName, propertyType, getterRequired, setterRequired, true))
}
}
override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> {
val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList()
val constantRequested = request.constant || javaClass.isInterface || request.modifiers.containsAll(constantModifiers)
val result = ArrayList<IntentionAction>()
if (constantRequested || StringUtil.isCapitalized(request.fieldName)) {
result += CreateConstantAction(javaClass, request)
}
if (!constantRequested) {
result += CreateFieldAction(javaClass, request)
}
if (canCreateEnumConstant(javaClass, request)) {
result += CreateEnumConstantAction(javaClass, request)
}
return result
}
override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> {
val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList()
val requestedModifiers = request.modifiers
val staticMethodRequested = JvmModifier.STATIC in requestedModifiers
if (staticMethodRequested) {
// static method in interfaces are allowed starting with Java 8
if (javaClass.isInterface && !PsiUtil.isLanguageLevel8OrHigher(javaClass)) return emptyList()
// static methods in inner classes are disallowed JLS §8.1.3
if (javaClass.containingClass != null && !javaClass.hasModifierProperty(PsiModifier.STATIC)) return emptyList()
}
val result = ArrayList<IntentionAction>()
result += CreateMethodAction(javaClass, request, false)
if (!staticMethodRequested && javaClass.hasModifierProperty(PsiModifier.ABSTRACT) && !javaClass.isInterface) {
result += CreateMethodAction(javaClass, request, true)
}
if (!javaClass.isInterface) {
result += CreatePropertyAction(javaClass, request)
result += CreateGetterWithFieldAction(javaClass, request)
result += CreateSetterWithFieldAction(javaClass, request)
}
return result
}
override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> {
val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList()
return listOf(CreateConstructorAction(javaClass, request))
}
}
class JavaElementRenderer {
companion object {
@JvmStatic
fun getInstance(): JavaElementRenderer {
return ServiceManager.getService(JavaElementRenderer::class.java)
}
}
fun render(visibilityModifiers: List<JvmModifier>): String =
visibilityModifiers.joinToString(" ") { render(it) }
fun render(jvmType: JvmType): String =
(jvmType as PsiType).canonicalText
fun render(jvmAnnotation: JvmAnnotation): String =
"@" + (jvmAnnotation as PsiAnnotation).qualifiedName!!
@PsiModifier.ModifierConstant
fun render(modifier: JvmModifier): String = modifier.toPsiModifier()
}
| apache-2.0 | 8f67f59c6a758960ab0dc1acaebb803e | 44.512195 | 140 | 0.747053 | 5.173752 | false | false | false | false |
googlemaps/android-samples | snippets/app/src/gms/java/com/google/maps/example/kotlin/CameraAndView.kt | 1 | 3941 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.maps.example.kotlin
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
internal class CameraAndView {
// [START maps_android_camera_and_view_zoom_level]
private lateinit var map: GoogleMap
// [START_EXCLUDE silent]
private fun zoomLevel() {
// [END_EXCLUDE]
map.setMinZoomPreference(6.0f)
map.setMaxZoomPreference(14.0f)
// [START_EXCLUDE silent]
}
// [END_EXCLUDE]
// [END maps_android_camera_and_view_zoom_level]
private fun settingBoundaries() {
// [START maps_android_camera_and_view_setting_boundaries]
val australiaBounds = LatLngBounds(
LatLng((-44.0), 113.0), // SW bounds
LatLng((-10.0), 154.0) // NE bounds
)
map.moveCamera(CameraUpdateFactory.newLatLngBounds(australiaBounds, 0))
// [END maps_android_camera_and_view_setting_boundaries]
}
private fun centeringMapWithinAnArea() {
// [START maps_android_camera_and_view_centering_within_area]
val australiaBounds = LatLngBounds(
LatLng((-44.0), 113.0), // SW bounds
LatLng((-10.0), 154.0) // NE bounds
)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(australiaBounds.center, 10f))
// [END maps_android_camera_and_view_centering_within_area]
}
private fun panningRestrictions() {
// [START maps_android_camera_and_view_panning_restrictions]
// Create a LatLngBounds that includes the city of Adelaide in Australia.
val adelaideBounds = LatLngBounds(
LatLng(-35.0, 138.58), // SW bounds
LatLng(-34.9, 138.61) // NE bounds
)
// Constrain the camera target to the Adelaide bounds.
map.setLatLngBoundsForCameraTarget(adelaideBounds)
// [END maps_android_camera_and_view_panning_restrictions]
}
private fun commonMapMovements() {
// [START maps_android_camera_and_view_common_map_movements]
val sydney = LatLng(-33.88, 151.21)
val mountainView = LatLng(37.4, -122.1)
// Move the camera instantly to Sydney with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 15f))
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomIn())
// Zoom out to zoom level 10, animating with a duration of 2 seconds.
map.animateCamera(CameraUpdateFactory.zoomTo(10f), 2000, null)
// Construct a CameraPosition focusing on Mountain View and animate the camera to that position.
val cameraPosition = CameraPosition.Builder()
.target(mountainView) // Sets the center of the map to Mountain View
.zoom(17f) // Sets the zoom
.bearing(90f) // Sets the orientation of the camera to east
.tilt(30f) // Sets the tilt of the camera to 30 degrees
.build() // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
// [END maps_android_camera_and_view_common_map_movements]
}
} | apache-2.0 | a8ebaf8980dd4c5ec3e3c0e608be2afa | 40.93617 | 104 | 0.668105 | 4.139706 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/java/KSValueParameterJavaImpl.kt | 1 | 2852 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.symbol.impl.java
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.impl.kotlin.KSNameImpl
import com.google.devtools.ksp.symbol.impl.toLocation
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiParameter
class KSValueParameterJavaImpl private constructor(val psi: PsiParameter) : KSValueParameter {
companion object : KSObjectCache<PsiParameter, KSValueParameterJavaImpl>() {
fun getCached(psi: PsiParameter) = cache.getOrPut(psi) { KSValueParameterJavaImpl(psi) }
}
override val origin = Origin.JAVA
override val location: Location by lazy {
psi.toLocation()
}
override val parent: KSNode? by lazy {
var parentPsi = psi.parent
while (true) {
when (parentPsi) {
null, is PsiMethod, is PsiAnnotation -> break
else -> parentPsi = parentPsi.parent
}
}
when (parentPsi) {
is PsiMethod -> KSFunctionDeclarationJavaImpl.getCached(parentPsi)
is PsiAnnotation -> KSAnnotationJavaImpl.getCached(parentPsi)
else -> null
}
}
override val annotations: Sequence<KSAnnotation> by lazy {
psi.annotations.asSequence().map { KSAnnotationJavaImpl.getCached(it) }
}
override val isCrossInline: Boolean = false
override val isNoInline: Boolean = false
override val isVararg: Boolean = psi.isVarArgs
override val isVal: Boolean = false
override val isVar: Boolean = false
override val name: KSName? by lazy {
if (psi.name != null) {
KSNameImpl.getCached(psi.name!!)
} else {
null
}
}
override val type: KSTypeReference by lazy {
KSTypeReferenceJavaImpl.getCached(psi.type, this)
}
override val hasDefault: Boolean = false
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitValueParameter(this, data)
}
override fun toString(): String {
return name?.asString() ?: "_"
}
}
| apache-2.0 | f69fcc48b1f8715997c4ab515e705525 | 31.409091 | 96 | 0.682679 | 4.484277 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/test/java/jp/toastkid/yobidashi/main/initial/FirstLaunchInitializerTest.kt | 1 | 4405 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.main.initial
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.net.Uri
import androidx.core.content.ContextCompat
import io.mockk.MockKAnnotations
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.just
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.spyk
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.search.SearchCategory
import jp.toastkid.yobidashi.browser.FaviconFolderProviderService
import jp.toastkid.yobidashi.browser.bookmark.BookmarkInitializer
import jp.toastkid.yobidashi.settings.background.DefaultBackgroundImagePreparation
import jp.toastkid.yobidashi.settings.color.DefaultColorInsertion
import org.junit.After
import org.junit.Before
import org.junit.Test
class FirstLaunchInitializerTest {
private lateinit var firstLaunchInitializer: FirstLaunchInitializer
@MockK
private lateinit var context: Context
private lateinit var preferenceApplier: PreferenceApplier
@MockK
private lateinit var defaultColorInsertion: DefaultColorInsertion
@MockK
private lateinit var faviconFolderProviderService: FaviconFolderProviderService
@MockK
private lateinit var defaultBackgroundImagePreparation: DefaultBackgroundImagePreparation
@MockK
private lateinit var sharedPreferences: SharedPreferences
@MockK
private lateinit var editor: SharedPreferences.Editor
@Before
fun setUp() {
MockKAnnotations.init(this)
every { context.getSharedPreferences(any(), any()) }.returns(sharedPreferences)
every { sharedPreferences.edit() }.returns(editor)
every { editor.putInt(any(), any()) }.returns(editor)
every { editor.apply() }.just(Runs)
preferenceApplier = spyk(PreferenceApplier(context))
every { preferenceApplier.isFirstLaunch() }.returns(true)
every { defaultColorInsertion.insert(any()) }.returns(mockk())
every { faviconFolderProviderService.invoke(any()) }.returns(mockk())
every { defaultBackgroundImagePreparation.invoke(any(), any()) }.returns(mockk())
every { preferenceApplier.setDefaultSearchEngine(any()) }.just(Runs)
mockkStatic(ContextCompat::class)
every { ContextCompat.getColor(any(), any()) }.returns(Color.CYAN)
mockkStatic(Uri::class)
val returnValue = mockk<Uri>()
every { returnValue.host }.returns("yahoo.co.jp")
every { Uri.parse(any()) }.returns(returnValue)
mockkObject(SearchCategory)
every { SearchCategory.getDefaultCategoryName() }.returns("yahoo")
mockkConstructor(BookmarkInitializer::class)
every { anyConstructed<BookmarkInitializer>().invoke() }.returns(mockk())
firstLaunchInitializer = FirstLaunchInitializer(
context,
preferenceApplier,
defaultColorInsertion,
faviconFolderProviderService,
defaultBackgroundImagePreparation
)
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testInvoke() {
firstLaunchInitializer.invoke()
verify(exactly = 1) { preferenceApplier.isFirstLaunch() }
verify(exactly = 1) { defaultColorInsertion.insert(any()) }
verify(exactly = 1) { defaultBackgroundImagePreparation.invoke(any(), any()) }
verify(exactly = 1) { preferenceApplier.setDefaultSearchEngine(any()) }
}
@Test
fun testIsNotFirstLaunch() {
every { preferenceApplier.isFirstLaunch() }.returns(false)
firstLaunchInitializer.invoke()
verify(exactly = 1) { preferenceApplier.isFirstLaunch() }
verify(exactly = 0) { defaultColorInsertion.insert(any()) }
verify(exactly = 0) { defaultBackgroundImagePreparation.invoke(any(), any()) }
verify(exactly = 0) { preferenceApplier.setDefaultSearchEngine(any()) }
}
} | epl-1.0 | 4113a4b7791cfb34f02ff8e76c059535 | 33.968254 | 93 | 0.726901 | 5.034286 | false | false | false | false |
lasp91/DigitsRecognizer_using_Kotlin | src/DigitsRecognizer.kt | 1 | 3579 | import java.io.File
import java.util.stream.IntStream
import java.util.concurrent.atomic.AtomicInteger
data class Observation (val label: String , val Pixels: IntArray)
typealias Distance = (IntArray, IntArray) -> Int
typealias Classifier = (IntArray) -> String
typealias Observations = Array<Observation>
fun observationData(csvData: String) : Observation
{
val columns = csvData.split(',')
val label = columns[0]
val pixels = columns.subList(1, columns.lastIndex).map(String::toInt)
return Observation(label, pixels.toIntArray())
}
fun reader(path: String) : Array<Observation>
{
val observations = File(path).useLines { lines ->
lines.drop(1).map(::observationData).toList().toTypedArray() }
return observations
}
val manhattanDistance = { pixels1: IntArray, pixels2: IntArray -> // Using zip and map
val dist = pixels1.zip(pixels2)
.map { p -> Math.abs(p.first - p.second) }
.sum()
dist
}
val manhattanDistanceImperative = fun(pixels1: IntArray, pixels2: IntArray) : Int
{
var dist = 0
for (i in 0 until pixels1.size)
dist += Math.abs(pixels1[i] - pixels2[i])
return dist
}
val euclideanDistance = { pixels1: IntArray, pixels2: IntArray ->
val dist = pixels1.zip(pixels2)
// .map { p -> Math.pow((p.first - p.second).toDouble(), 2.0) }
.map({ p -> val dist = (p.first - p.second); dist * dist })
.sum()
dist
}
val euclideanDistanceImperative = fun(pixels1: IntArray, pixels2: IntArray) : Int
{
var dist = 0
for (i in 0 until pixels1.size)
{
val dif = Math.abs(pixels1[i] - pixels2[i])
dist += dif * dif
}
return dist
}
fun classify(trainingSet: Array<Observation>, dist: Distance, pixels: IntArray) : String
{
val observation = trainingSet.minBy { (_, Pixels) -> dist(Pixels, pixels) }
return observation!!.label
}
fun evaluate(validationSet: Array<Observation>, classifier: (IntArray) -> String) : Unit
{
// val average = validationSet
// .map({ (label, Pixels) -> if (classifier(Pixels) == label) 1.0 else 0.0 })
// .average()
// println("Correct: $average")
//}
val count = validationSet.size
val sum = AtomicInteger(0)
IntStream.range(0, validationSet.size).parallel().forEach { i ->
if (classifier(validationSet[i].Pixels) == validationSet[i].label)
sum.addAndGet(1)
}
println("Correct: ${sum.toDouble() / count}")
}
//-----------------------------------------------------------------------------------------
fun main(args: Array<String>)
{
val trainingPath = "./Data/trainingsample.csv"
val trainingData = reader(trainingPath)
val validationPath = "./Data/validationsample.csv"
val validationData = reader(validationPath)
val manhattanClassifier = fun(pixels: IntArray) : String
{
return classify(trainingData, manhattanDistanceImperative, pixels)
}
val euclideanClassifier = fun(pixels: IntArray) : String
{
return classify(trainingData, euclideanDistanceImperative, pixels)
}
run {
val startTime = System.currentTimeMillis()
println(" Manhattan Kotlin")
evaluate(validationData, manhattanClassifier)
val endTime = System.currentTimeMillis()
val elapsedTime = (endTime - startTime) / 1000.0
println(">>> Elapsed time is: $elapsedTime sec")
}
run {
val startTime = System.currentTimeMillis()
println(" Euclidean Kotlin")
evaluate(validationData, euclideanClassifier)
val endTime = System.currentTimeMillis()
val elapsedTime = (endTime - startTime) / 1000.0
println(">>> Elapsed time is: $elapsedTime sec")
}
}
| apache-2.0 | d63d22f3f9873d2f54f4bf6c75c33837 | 25.708955 | 91 | 0.663593 | 3.724246 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadHolder.kt | 2 | 2284 | package eu.kanade.tachiyomi.ui.recently_read
import android.view.View
import com.bumptech.glide.load.engine.DiskCacheStrategy
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.MangaChapterHistory
import eu.kanade.tachiyomi.data.glide.GlideApp
import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder
import kotlinx.android.synthetic.main.recently_read_item.*
import java.util.*
/**
* Holder that contains recent manga item
* Uses R.layout.item_recently_read.
* UI related actions should be called from here.
*
* @param view the inflated view for this holder.
* @param adapter the adapter handling this holder.
* @constructor creates a new recent chapter holder.
*/
class RecentlyReadHolder(
view: View,
val adapter: RecentlyReadAdapter
) : BaseFlexibleViewHolder(view, adapter) {
init {
remove.setOnClickListener {
adapter.removeClickListener.onRemoveClick(adapterPosition)
}
resume.setOnClickListener {
adapter.resumeClickListener.onResumeClick(adapterPosition)
}
cover.setOnClickListener {
adapter.coverClickListener.onCoverClick(adapterPosition)
}
}
/**
* Set values of view
*
* @param item item containing history information
*/
fun bind(item: MangaChapterHistory) {
// Retrieve objects
val (manga, chapter, history) = item
// Set manga title
manga_title.text = manga.title
// Set source + chapter title
val formattedNumber = adapter.decimalFormat.format(chapter.chapter_number.toDouble())
manga_source.text = itemView.context.getString(R.string.recent_manga_source)
.format(adapter.sourceManager.get(manga.source)?.toString(), formattedNumber)
// Set last read timestamp title
last_read.text = adapter.dateFormat.format(Date(history.last_read))
// Set cover
GlideApp.with(itemView.context).clear(cover)
if (!manga.thumbnail_url.isNullOrEmpty()) {
GlideApp.with(itemView.context)
.load(manga)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
.centerCrop()
.into(cover)
}
}
}
| apache-2.0 | 97ddc4bb7fe5165f702a38fbe3d87ea7 | 30.722222 | 93 | 0.670753 | 4.568 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/viewModel/EditGroupViewModel.kt | 1 | 3594 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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 com.toshi.viewModel
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.graphics.Bitmap
import android.net.Uri
import com.toshi.R
import com.toshi.model.local.Group
import com.toshi.util.ImageUtil
import com.toshi.util.SingleLiveEvent
import com.toshi.view.BaseApplication
import rx.Single
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
class EditGroupViewModel(val groupId: String) : ViewModel() {
private val subscriptions by lazy { CompositeSubscription() }
private val recipientManager by lazy { BaseApplication.get().recipientManager }
private val chatManager by lazy { BaseApplication.get().chatManager }
val group by lazy { MutableLiveData<Group>() }
val isUpdatingGroup by lazy { MutableLiveData<Boolean>() }
val updatedGroup by lazy { SingleLiveEvent<Boolean>() }
val error by lazy { SingleLiveEvent<Int>() }
var capturedImagePath: String? = null
var avatarUri: Uri? = null
fun fetchGroup() {
val sub = recipientManager
.getGroupFromId(groupId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ group.value = it },
{ error.value = R.string.unable_to_fetch_group }
)
this.subscriptions.add(sub)
}
fun updateGroup(avatarUri: Uri?, groupName: String) {
if (isUpdatingGroup.value == true) return
val sub = Single.zip(
recipientManager.getGroupFromId(groupId),
generateAvatarFromUri(avatarUri),
{ group, avatar -> Pair(group, avatar) }
)
.map { updateGroupObject(it.first, it.second, groupName) }
.flatMapCompletable { saveUpdatedGroup(it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { isUpdatingGroup.value = true }
.doAfterTerminate { isUpdatingGroup.value = false }
.subscribe(
{ updatedGroup.value = true },
{ error.value = R.string.unable_to_update_group }
)
this.subscriptions.add(sub)
}
private fun updateGroupObject(group: Group, newAvatar: Bitmap?, groupName: String): Group {
newAvatar?.let { group.setAvatar(newAvatar) }
group.title = groupName
return group
}
private fun saveUpdatedGroup(group: Group) = chatManager.updateConversationFromGroup(group)
private fun generateAvatarFromUri(avatarUri: Uri?) = ImageUtil.loadAsBitmap(avatarUri, BaseApplication.get())
override fun onCleared() {
super.onCleared()
subscriptions.clear()
}
} | gpl-3.0 | 1a3963e72fa76b37f66ba7fa709bb1e8 | 37.655914 | 113 | 0.656093 | 4.673602 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/NewPlayPlayerSortFragment.kt | 1 | 10098 | package com.boardgamegeek.ui
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentNewPlayPlayerSortBinding
import com.boardgamegeek.databinding.RowNewPlayPlayerSortBinding
import com.boardgamegeek.entities.NewPlayPlayerEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.ui.viewmodel.NewPlayViewModel
import kotlin.properties.Delegates
class NewPlayPlayerSortFragment : Fragment() {
private var _binding: FragmentNewPlayPlayerSortBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<NewPlayViewModel>()
private val adapter: PlayersAdapter by lazy { PlayersAdapter(viewModel, itemTouchHelper) }
private val itemTouchHelper by lazy {
ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// swiping not supported
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return viewModel.movePlayer(viewHolder.bindingAdapterPosition, target.bindingAdapterPosition)
}
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
(viewHolder as? PlayersAdapter.PlayersViewHolder)?.onItemDragging()
}
super.onSelectedChanged(viewHolder, actionState)
}
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
(viewHolder as? PlayersAdapter.PlayersViewHolder)?.onItemClear()
super.clearView(recyclerView, viewHolder)
}
})
}
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentNewPlayPlayerSortBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.adapter = adapter
viewModel.addedPlayers.observe(viewLifecycleOwner) { entity ->
if (entity.all { it.seat != null }) {
adapter.players = entity.sortedBy { it.seat }
} else {
adapter.players = entity
}
}
binding.randomizeAllButton.setOnClickListener {
viewModel.randomizePlayers()
}
binding.randomizeStartButton.setOnClickListener {
viewModel.randomizeStartPlayer()
}
binding.clearButton.setOnClickListener {
viewModel.clearSortOrder()
}
binding.nextButton.setOnClickListener {
viewModel.finishPlayerSort()
}
itemTouchHelper.attachToRecyclerView(binding.recyclerView)
}
override fun onResume() {
super.onResume()
(activity as? AppCompatActivity)?.supportActionBar?.setSubtitle(R.string.title_sort)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private class Diff(private val oldList: List<NewPlayPlayerEntity>, private val newList: List<NewPlayPlayerEntity>) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val o = oldList[oldItemPosition]
val n = newList[newItemPosition]
return o.id == n.id && o.sortOrder == n.sortOrder
}
}
private class DraggingDiff(private val oldList: List<NewPlayPlayerEntity>, private val newList: List<NewPlayPlayerEntity>) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val o = oldList[oldItemPosition]
val n = newList[newItemPosition]
return o.id == n.id
}
}
private class PlayersAdapter(private val viewModel: NewPlayViewModel, private val itemTouchHelper: ItemTouchHelper) :
RecyclerView.Adapter<PlayersAdapter.PlayersViewHolder>() {
var isDraggable = false
var isDragging = false
var players: List<NewPlayPlayerEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
determineDraggability(newValue)
val diffCallback = if (isDragging) DraggingDiff(oldValue, newValue) else Diff(oldValue, newValue)
val diffResult = DiffUtil.calculateDiff(diffCallback)
diffResult.dispatchUpdatesTo(this)
}
private fun determineDraggability(newValue: List<NewPlayPlayerEntity>) {
if (newValue.all { it.seat != null }) {
for (seat in 1..newValue.size + 1) {
if (newValue.find { it.seat == seat } == null) {
isDraggable = false
break
}
}
isDraggable = true
} else isDraggable = false
}
init {
setHasStableIds(true)
}
override fun getItemCount() = players.size
override fun getItemId(position: Int): Long {
return players.getOrNull(position)?.id?.hashCode()?.toLong() ?: RecyclerView.NO_ID
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlayersViewHolder {
return PlayersViewHolder(parent.inflate(R.layout.row_new_play_player_sort), itemTouchHelper)
}
override fun onBindViewHolder(holder: PlayersViewHolder, position: Int) {
holder.bind(position)
}
inner class PlayersViewHolder(itemView: View, private val itemTouchHelper: ItemTouchHelper) : RecyclerView.ViewHolder(itemView) {
val binding = RowNewPlayPlayerSortBinding.bind(itemView)
@SuppressLint("ClickableViewAccessibility")
fun bind(position: Int) {
val entity = players.getOrNull(position)
entity?.let { player ->
binding.nameView.text = player.name
binding.usernameView.setTextOrHide(player.username)
if (player.color.isBlank()) {
binding.colorView.isInvisible = true
binding.teamView.isVisible = false
binding.seatView.setTextColor(Color.TRANSPARENT.getTextColor())
} else {
val color = player.color.asColorRgb()
if (color == Color.TRANSPARENT) {
binding.colorView.isInvisible = true
binding.teamView.setTextOrHide(player.color)
} else {
binding.colorView.setColorViewValue(color)
binding.colorView.isVisible = true
binding.teamView.isVisible = false
}
binding.seatView.setTextColor(color.getTextColor())
}
if (player.seat == null) {
binding.sortView.setTextOrHide(player.sortOrder)
binding.seatView.isInvisible = true
} else {
binding.sortView.isVisible = false
binding.seatView.text = player.seat.toString()
binding.seatView.isVisible = true
}
binding.dragHandle.isVisible = isDraggable
if (isDraggable) {
binding.dragHandle.setOnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
itemTouchHelper.startDrag(this@PlayersViewHolder)
} else if (event.action == MotionEvent.ACTION_UP) {
v.performClick()
}
false
}
}
itemView.setOnClickListener { viewModel.selectStartPlayer(position) }
}
}
fun onItemDragging() {
isDragging = true
itemView.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.light_blue_transparent))
}
@SuppressLint("NotifyDataSetChanged")
fun onItemClear() {
isDragging = false
itemView.setBackgroundColor(Color.TRANSPARENT)
notifyDataSetChanged() // force UI to update the seat numbers
}
}
}
}
| gpl-3.0 | 21216b4e13c785e9e9c662b286302566 | 40.900415 | 150 | 0.620519 | 5.638191 | false | false | false | false |
youkai-app/Youkai | app/src/main/kotlin/app/youkai/ui/feature/media/characters/CharactersFragment.kt | 1 | 3924 | package app.youkai.ui.feature.media.characters
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ViewFlipper
import app.youkai.R
import app.youkai.data.models.Casting
import app.youkai.data.models.ext.MediaType
import app.youkai.ui.common.mvp.MvpLceFragment
import app.youkai.ui.common.view.GridSpacingItemDecoration
import app.youkai.ui.common.view.RecyclerViewEndlessScrollListener
import app.youkai.util.ext.toPx
import app.youkai.util.ext.toVisibility
import app.youkai.util.ext.whenNotNull
import kotlinx.android.synthetic.main.fragment_characters.*
import kotlinx.android.synthetic.main.fragment_characters.view.*
import tr.xip.errorview.ErrorView
class CharactersFragment : MvpLceFragment<CharactersView, CharactersPresenter>(), CharactersView {
val languageChangedListener: (language: String) -> Unit = {
recycler.smoothScrollToPosition(0)
presenter.load(language = it)
}
val errorListener: (e: Throwable) -> Unit = {
presenter.onError(it)
}
override fun createPresenter() = CharactersPresenter()
override fun getViewFlipper(): ViewFlipper = view!!.flipper
override fun getErrorView(): ErrorView = view!!.errorView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_characters, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val args = arguments ?: throw IllegalStateException("arguments are null!")
val mediaId = args.getString(ARG_MEDIA_ID)
val mediaType = MediaType.fromString(args.getString(ARG_MEDIA_TYPE))
val mediaTitle = args.getString(ARG_MEDIA_TITLE)
setUpRecyclerView()
presenter.set(mediaId, mediaType, mediaTitle)
}
override fun setMediaTitle(title: String) {
(activity as AppCompatActivity?)?.supportActionBar?.subtitle = title
}
override fun setCharacters(characters: List<Casting>, add: Boolean) {
if (!add) {
val adapter = CharactersAdapter()
adapter.dataset.addAll(characters)
adapter.notifyDataSetChanged()
recycler.adapter = adapter
} else {
whenNotNull(recycler.adapter as CharactersAdapter?) {
it.dataset.addAll(characters)
it.notifyDataSetChanged()
}
}
bottomProgressBar.visibility = View.GONE
}
private fun setUpRecyclerView() {
val columnsCount = maximumTilesCount()
recycler.layoutManager = GridLayoutManager(context, columnsCount)
recycler.addItemDecoration(GridSpacingItemDecoration(columnsCount, 4.toPx(context!!), true))
recycler.addOnScrollListener(RecyclerViewEndlessScrollListener(recycler.layoutManager) {
presenter.onScrollEndReached()
})
}
private fun maximumTilesCount(): Int {
return 2 // TODO: Calc
}
override fun showBottomProgressBar(show: Boolean) {
bottomProgressBar.visibility = show.toVisibility()
}
companion object {
const val ARG_MEDIA_ID = "media_id"
const val ARG_MEDIA_TYPE = "media_type"
const val ARG_MEDIA_TITLE = "media_title"
fun new(mediaId: String, mediaType: MediaType, mediaTitle: String): CharactersFragment {
val fragment = CharactersFragment()
val ars = Bundle()
ars.putString(ARG_MEDIA_ID, mediaId)
ars.putString(ARG_MEDIA_TYPE, mediaType.value)
ars.putString(ARG_MEDIA_TITLE, mediaTitle)
fragment.arguments = ars
return fragment
}
}
}
| gpl-3.0 | 8c0695ee00422db9b210939863df8d42 | 34.672727 | 116 | 0.699541 | 4.69378 | false | false | false | false |
devulex/eventorage | frontend/src/com/devulex/eventorage/rpc/SettingsService.kt | 1 | 1108 | package com.devulex.eventorage.rpc
import com.devulex.eventorage.model.SettingsGetResponse
import org.w3c.dom.url.URLSearchParams
suspend fun getSettings(): SettingsGetResponse =
getAndParseResult("/settings.get", null, ::parseGetSettings)
private fun parseGetSettings(json: dynamic): SettingsGetResponse {
if (json.error != null) {
throw GetSettingsException(json.error.toString())
}
return SettingsGetResponse(clusterName = json.clusterName, clusterNodes = json.clusterNodes,
language = json.language, dateFormat = json.dateFormat)
}
class GetSettingsException(message: String) : Throwable(message)
suspend fun updateSetting(name: String, value: String) =
postAndParseResult("/settings.update", URLSearchParams().apply {
append("name", name)
append("value", value)
}, ::parseUpdateSettingsResponse)
class SettingUpdateException(message: String) : Throwable(message)
private fun parseUpdateSettingsResponse(json: dynamic) {
if (json.ok == false) {
throw SettingUpdateException(json.error.toString())
}
}
| mit | d79c457c1bd91ba8d255323c8919a6e7 | 34.741935 | 96 | 0.726534 | 4.328125 | false | false | false | false |
googlecodelabs/play-billing-scalable-kotlin | codelab-03/app/src/main/java/com/example/playbilling/trivialdrive/kotlin/viewmodels/BillingViewModel.kt | 1 | 3573 | /**
* Copyright (C) 2019 Google Inc. All Rights Reserved.
*
* 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.playbilling.trivialdrive.kotlin.viewmodels
import android.app.Activity
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import com.example.playbilling.trivialdrive.kotlin.billingrepo.BillingRepository
import com.example.playbilling.trivialdrive.kotlin.billingrepo.localdb.*
import kotlinx.coroutines.*
/**
* Notice just how small and simple this BillingViewModel is!!
*
* This beautiful simplicity is the result of keeping all the hard work buried inside the
* [BillingRepository] and only inside the [BillingRepository]. The rest of your app
* is now free from [BillingClient] tentacles!! And this [BillingViewModel] is the one and only
* object the rest of your Android team need to know about billing.
*
*/
class BillingViewModel(application: Application) : AndroidViewModel(application) {
val gasTankLiveData: LiveData<GasTank>
val premiumCarLiveData: LiveData<PremiumCar>
val goldStatusLiveData: LiveData<GoldStatus>
val subsSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>>
val inappSkuDetailsListLiveData: LiveData<List<AugmentedSkuDetails>>
private val LOG_TAG = "BillingViewModel"
private val viewModelScope = CoroutineScope(Job() + Dispatchers.Main)
private val repository: BillingRepository
init {
repository = BillingRepository.getInstance(application)
repository.startDataSourceConnections()
gasTankLiveData = repository.gasTankLiveData
premiumCarLiveData = repository.premiumCarLiveData
goldStatusLiveData = repository.goldStatusLiveData
subsSkuDetailsListLiveData = repository.subsSkuDetailsListLiveData
inappSkuDetailsListLiveData = repository.inappSkuDetailsListLiveData
}
/**
* Not used in this sample app. But you may want to force refresh in your own app (e.g.
* pull-to-refresh)
*/
fun queryPurchases() = repository.queryPurchasesAsync()
override fun onCleared() {
super.onCleared()
Log.d(LOG_TAG, "onCleared")
repository.endDataSourceConnections()
viewModelScope.coroutineContext.cancel()
}
fun makePurchase(activity: Activity, augmentedSkuDetails: AugmentedSkuDetails) {
repository.launchBillingFlow(activity, augmentedSkuDetails)
}
/**
* It's important to save after decrementing since gas can be updated by both clients and
* the data sources.
*
* Note that even the ViewModel does not need to worry about thread safety because the
* repo has already taken care it. So definitely the clients also don't need to worry about
* thread safety.
*/
fun decrementAndSaveGas() {
val gas = gasTankLiveData.value
gas?.apply {
decrement()
viewModelScope.launch {
repository.updateGasTank(this@apply)
}
}
}
} | apache-2.0 | 3fa353f0a00515e65c4d058795e50ba9 | 37.430108 | 95 | 0.733277 | 4.658409 | false | false | false | false |
shadowfox-ninja/ShadowUtils | shadow-android/src/main/java/tech/shadowfox/shadow/android/view/widgets/WrappedNestedScrollView.kt | 1 | 2449 | package tech.shadowfox.shadow.android.view.widgets
import android.content.Context
import android.content.res.TypedArray
import android.support.v4.widget.NestedScrollView
import android.util.AttributeSet
import android.view.View
import tech.shadowfox.shadow.R
import tech.shadowfox.shadow.android.utils.use
/**
* Copyright 2017 Camaron Crowe
*
* 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.
**/
class WrappedNestedScrollView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : NestedScrollView(context, attrs, defStyleAttr) {
var maxWrapHeight = 0
set(value) {
if (value != field) {
field = value
requestLayout()
}
}
init {
context.theme.obtainStyledAttributes(attrs, R.styleable.WrapNestedScrollView, defStyleAttr, 0).use {
readAttributes(it)
}
}
private fun readAttributes(typedArray: TypedArray) {
maxWrapHeight = typedArray.getDimensionPixelSize(R.styleable.WrapNestedScrollView_maxWrapHeight, 0)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var heightSpec = heightMeasureSpec
if (maxWrapHeight > 0) {
val hSize = View.MeasureSpec.getSize(heightMeasureSpec)
val hMode = View.MeasureSpec.getMode(heightMeasureSpec)
heightSpec = when (hMode) {
View.MeasureSpec.AT_MOST -> View.MeasureSpec.makeMeasureSpec(Math.min(hSize, maxWrapHeight), View.MeasureSpec.AT_MOST)
View.MeasureSpec.UNSPECIFIED -> View.MeasureSpec.makeMeasureSpec(maxWrapHeight, View.MeasureSpec.AT_MOST)
View.MeasureSpec.EXACTLY -> View.MeasureSpec.makeMeasureSpec(Math.min(hSize, maxWrapHeight), View.MeasureSpec.EXACTLY)
else -> error("Invalid MeasureSpec")
}
}
super.onMeasure(widthMeasureSpec, heightSpec)
}
} | apache-2.0 | de7dc308f99dbd96ab2792136715283e | 38.516129 | 176 | 0.700286 | 4.586142 | false | false | false | false |
ziggy42/Blum | app/src/main/java/com/andreapivetta/blu/ui/profile/viewholders/ProfileViewHolder.kt | 1 | 3454 | package com.andreapivetta.blu.ui.profile.viewholders
import android.app.Activity
import android.content.Context
import android.graphics.Typeface
import android.support.v7.widget.RecyclerView
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.view.View
import com.andreapivetta.blu.R
import com.andreapivetta.blu.common.utils.loadAvatar
import com.andreapivetta.blu.common.utils.loadUrl
import com.andreapivetta.blu.common.utils.openUrl
import com.andreapivetta.blu.common.utils.setupText
import com.andreapivetta.blu.ui.custom.Theme
import com.luseen.autolinklibrary.AutoLinkMode
import kotlinx.android.synthetic.main.profile.view.*
import twitter4j.User
/**
* Created by andrea on 14/11/16.
*/
class ProfileViewHolder(container: View) : RecyclerView.ViewHolder(container) {
private val bannerImageView = container.bannerImageView
private val picImageView = container.picImageView
private val nameTextView = container.nameTextView
private val screenNameTextView = container.screenNameTextView
private val descriptionTextView = container.descriptionTextView
private val extraTextView = container.extraTextView
private val statsTextView = container.statsTextView
private val context: Context = container.context
fun setup(user: User) {
bannerImageView.loadUrl(user.profileBannerRetinaURL)
picImageView.loadAvatar(user.biggerProfileImageURLHttps)
nameTextView.text = user.name
screenNameTextView.text = "@${user.screenName}"
statsTextView.text = getStats(user)
descriptionTextView.setupText(user.description)
extraTextView.addAutoLinkMode(AutoLinkMode.MODE_URL)
extraTextView.setUrlModeColor(Theme.getColorPrimary(context))
extraTextView.setAutoLinkText(getExtra(user))
extraTextView.setAutoLinkOnClickListener { mode, text ->
when (mode) {
AutoLinkMode.MODE_URL -> openUrl(context as Activity, text)
else -> throw UnsupportedOperationException("No handlers for mode $mode")
}
}
if (user.isVerified)
nameTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_verified_user, 0)
}
private fun getExtra(user: User): String = if (user.url.isNullOrEmpty()) user.location else {
if (user.location.isNullOrEmpty()) user.url else
"${user.location} • ${user.url}"
}
private fun getStats(user: User): SpannableStringBuilder {
val builder = SpannableStringBuilder()
val followersString = getCount(user.followersCount)
val followersSpan = SpannableString(followersString)
followersSpan.setSpan(StyleSpan(Typeface.BOLD), 0, followersString.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
val followingString = getCount(user.friendsCount)
val followingSpan = SpannableString(followingString)
followingSpan.setSpan(StyleSpan(Typeface.BOLD), 0, followingString.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
builder.append(followersSpan)
.append(" followers ")
.append(followingSpan)
.append(" following")
return builder
}
private fun getCount(amount: Int) = if (amount < 10000) amount.toString() else
(amount / 1000).toString() + "k"
} | apache-2.0 | 2c048d6833e9021c2903e1bde4c8e9cb | 39.151163 | 102 | 0.726825 | 4.639785 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/psi/BibtexIdUtil.kt | 1 | 1347 | package nl.hannahsten.texifyidea.psi
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.search.GlobalSearchScope
import nl.hannahsten.texifyidea.BibtexLanguage
import nl.hannahsten.texifyidea.index.BibtexEntryIndex
import nl.hannahsten.texifyidea.util.firstParentOfType
import nl.hannahsten.texifyidea.util.remove
fun getNameIdentifier(element: BibtexId): PsiElement {
return element
}
fun setName(element: BibtexId, name: String): PsiElement {
// Replace the complete bibtex entry to automatically update the index (which is on entries, not ids)
val entry = element.firstParentOfType(BibtexEntry::class)
val oldName = element.name ?: return element
val newText = entry?.text?.replaceFirst(oldName, name) ?: return element
val newElement = PsiFileFactory.getInstance(element.project).createFileFromText("DUMMY.tex", BibtexLanguage, newText, false, true).firstChild
entry.parent.node.replaceChild(entry.node, newElement.node)
return element
}
fun getName(element: BibtexId): String {
return element.text
}
fun delete(element: BibtexId) {
val text = element.text ?: return
val searchScope = GlobalSearchScope.fileScope(element.containingFile)
BibtexEntryIndex.getEntryByName(text, element.project, searchScope).forEach {
it.remove()
}
} | mit | 73fe6d661fa12ae193f1fbd57444590c | 36.444444 | 145 | 0.778768 | 4.416393 | false | false | false | false |
ihmc/dspcap | src/main/kotlin/us/ihmc/aci/dspro/pcap/Protocol.kt | 1 | 712 | package us.ihmc.aci.dspro.pcap
import io.pkts.buffer.Buffer
import us.ihmc.aci.dspro.pcap.disservice.Data
import java.nio.charset.Charset
/**
* Created by gbenincasa on 11/1/17.
*/
enum class Protocol {
DisService,
DSPro,
NMS
}
fun isDisServicePacket(pkt: NMSMessage): Boolean = pkt.chunkType == NMSMessage.Type.DataMsgComplete
fun isDSProMessage(pkt: DisServiceMessage): Boolean = pkt.body is Data
&& pkt.body.msgInfo.group.startsWith("DSPro")
&& pkt.body.msgInfo.isComplete()
fun <T> readString(buf: Buffer, len: T): String
where T : Comparable<T>, T : Number
= if (len.toInt() > 0) buf.readBytes(len.toInt()).array.toString(Charset.defaultCharset()) else ""
| mit | 937e68de453f5e8ec0ec48857e874ef4 | 28.666667 | 106 | 0.699438 | 3.281106 | false | false | false | false |
GeoffreyMetais/vlc-android | application/tools/src/main/java/videolan/org/commontools/TvChannelUtils.kt | 1 | 8399 | /*****************************************************************************
* TvChannelUtils.kt
*****************************************************************************
* Copyright © 2018 VLC authors, VideoLAN and VideoLabs
* Author: Geoffrey Métais
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package videolan.org.commontools
import android.content.ComponentName
import android.content.ContentUris
import android.content.Context
import android.content.SharedPreferences
import android.database.Cursor
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.WorkerThread
import androidx.tvprovider.media.tv.*
import android.util.Log
import org.videolan.tools.putSingle
typealias ProgramsList = MutableList<TvPreviewProgram>
private const val TAG = "VLC/TvChannelUtils"
const val TV_CHANNEL_SCHEME = "vlclauncher"
const val TV_CHANNEL_PATH_APP = "startapp"
const val TV_CHANNEL_PATH_VIDEO = "video"
const val TV_CHANNEL_QUERY_VIDEO_ID = "contentId"
const val KEY_TV_CHANNEL_ID = "tv_channel_id"
val TV_PROGRAMS_MAP_PROJECTION = arrayOf(
TvContractCompat.PreviewPrograms._ID,
TvContractCompat.PreviewPrograms.COLUMN_INTERNAL_PROVIDER_ID,
TvContractCompat.PreviewPrograms.COLUMN_TITLE)
val WATCH_NEXT_MAP_PROJECTION = arrayOf(
TvContractCompat.PreviewPrograms._ID,
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID,
TvContractCompat.WatchNextPrograms.COLUMN_BROWSABLE)
@RequiresApi(Build.VERSION_CODES.O)
fun createOrUpdateChannel(prefs: SharedPreferences, context: Context, name: String, icon: Int, appId: String): Long {
var channelId = prefs.getLong(KEY_TV_CHANNEL_ID, -1L)
val builder = Channel.Builder()
.setType(TvContractCompat.Channels.TYPE_PREVIEW)
.setDisplayName(name)
.setAppLinkIntentUri(createUri(appId))
if (channelId == -1L) {
val channelUri = context.contentResolver.insert(TvContractCompat.Channels.CONTENT_URI, builder.build().toContentValues()) ?: return -1L
channelId = ContentUris.parseId(channelUri)
prefs.putSingle(KEY_TV_CHANNEL_ID, channelId)
TvContractCompat.requestChannelBrowsable(context, channelId)
val uri = Uri.parse("android.resource://$appId/$icon")
ChannelLogoUtils.storeChannelLogo(context, channelId, uri)
} else {
context.contentResolver.update(TvContractCompat.buildChannelUri(channelId),
builder.build().toContentValues(), null, null)
}
return channelId
}
@WorkerThread
fun deleteChannel(context: Context, id: Long) = try {
context.contentResolver.delete(TvContractCompat.buildChannelUri(id), null, null)
} catch (exception: Exception) {Log.e(TAG, "faild to delete channel $id", exception)}
@WorkerThread
fun existingPrograms(context: Context, channelId: Long) : ProgramsList {
var cursor: Cursor? = null
val list = mutableListOf<TvPreviewProgram>()
try {
val programUri = TvContractCompat.buildPreviewProgramsUriForChannel(channelId)
cursor = context.contentResolver.query(
programUri, TV_PROGRAMS_MAP_PROJECTION, null,
null, null)
while (cursor?.moveToNext() == true) {
val id = cursor.getLong(0)
val internalId = cursor.getLong(1)
val title = cursor.getString(2)
list.add(TvPreviewProgram(internalId, id, title))
}
return list
} catch (e: Exception) {
Log.e(TAG, "fail", e)
return list
} finally {
cursor?.close()
}
}
fun createUri(appId: String, id: String? = null) : Uri {
val builder = Uri.Builder()
.scheme(TV_CHANNEL_SCHEME)
.authority(appId)
if (id != null) builder.appendPath(TV_CHANNEL_PATH_VIDEO)
.appendQueryParameter(TV_CHANNEL_QUERY_VIDEO_ID, id)
else builder.appendPath(TV_CHANNEL_PATH_APP)
return builder.build()
}
fun buildProgram(cn: ComponentName, program: ProgramDesc) : PreviewProgram {
val previewProgramVideoUri = TvContractCompat.buildPreviewProgramUri(program.id)
.buildUpon()
.appendQueryParameter("input", TvContractCompat.buildInputId(cn))
.build()
val stringId = program.id.toString()
return PreviewProgram.Builder()
.setChannelId(program.channelId)
.setType(TvContractCompat.PreviewPrograms.TYPE_CLIP)
.setTitle(program.title)
.setDurationMillis(program.duration)
.setLastPlaybackPositionMillis(program.time)
.setVideoHeight(program.height)
.setVideoWidth(program.width)
.setDescription(program.description)
.setPosterArtUri(program.artUri)
.setPosterArtAspectRatio(TvContractCompat.PreviewProgramColumns.ASPECT_RATIO_16_9)
.setIntentUri(createUri(program.appId, stringId))
.setInternalProviderId(stringId)
.setPreviewVideoUri(previewProgramVideoUri)
.build()
}
fun buildWatchNextProgram(cn: ComponentName, program: ProgramDesc) : WatchNextProgram {
val previewProgramVideoUri = TvContractCompat.buildPreviewProgramUri(program.id)
.buildUpon()
.appendQueryParameter("input", TvContractCompat.buildInputId(cn))
.build()
val stringId = program.id.toString()
return WatchNextProgram.Builder()
.setWatchNextType(TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE)
.setLastEngagementTimeUtcMillis(System.currentTimeMillis())
.setType(TvContractCompat.PreviewPrograms.TYPE_CLIP)
.setTitle(program.title)
.setDurationMillis(program.duration)
.setLastPlaybackPositionMillis(program.time)
.setVideoHeight(program.height)
.setVideoWidth(program.width)
.setDescription(program.description)
.setPosterArtUri(program.artUri)
.setPosterArtAspectRatio(TvContractCompat.PreviewProgramColumns.ASPECT_RATIO_16_9)
.setIntentUri(createUri(program.appId, stringId))
.setInternalProviderId(stringId)
.setPreviewVideoUri(previewProgramVideoUri)
.build()
}
fun updateWatchNext(context: Context, program: WatchNextProgram, time: Long, watchNextProgramId: Long) {
val values = WatchNextProgram.Builder(program)
.setLastEngagementTimeUtcMillis(System.currentTimeMillis())
.setLastPlaybackPositionMillis(time.toInt())
.build().toContentValues()
val watchNextProgramUri = TvContractCompat.buildWatchNextProgramUri(watchNextProgramId)
val rowsUpdated = context.contentResolver.update(watchNextProgramUri,values, null, null)
if (rowsUpdated < 1) Log.e(TAG, "Update program failed")
}
fun deleteWatchNext(context: Context, id: Long) = try {
context.contentResolver.delete(TvContractCompat.buildWatchNextProgramUri(id), null, null)
} catch (exception: Exception) {
Log.e(TAG, "faild to delete program $id", exception)
-42
}
class TvPreviewProgram(val internalId: Long, val programId: Long, val title: String)
fun ProgramsList.indexOfId(id: Long) : Int {
for ((index, program) in this.withIndex()) if (program.internalId == id) return index
return -1
}
data class ProgramDesc(
val channelId: Long,
val id: Long,
val title: String,
val description: String?,
val artUri: Uri,
val duration: Int,
val time: Int,
val width: Int,
val height: Int,
val appId: String,
val previewVideoUri: Uri? = null) | gpl-2.0 | 247ca35903c6a0dd2d9df955929fcf78 | 42.066667 | 143 | 0.682625 | 4.485577 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/viewmodels/HistoryModel.kt | 1 | 2105 | /*****************************************************************************
* HistoryModel.kt
*****************************************************************************
* Copyright © 2018-2019 VLC authors and VideoLAN
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.viewmodels
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import kotlinx.coroutines.withContext
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.tools.CoroutineContextProvider
class HistoryModel(context: Context, coroutineContextProvider: CoroutineContextProvider = CoroutineContextProvider()) : MedialibraryModel<MediaWrapper>(context, coroutineContextProvider) {
override fun canSortByName() = false
override suspend fun updateList() {
dataset.value = withContext(coroutineContextProvider.Default) { medialibrary.lastMediaPlayed().toMutableList() }
}
fun moveUp(media: MediaWrapper) = dataset.move(media, 0)
fun clearHistory() = dataset.clear()
class Factory(private val context: Context) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return HistoryModel(context.applicationContext) as T
}
}
} | gpl-2.0 | 25600a89cb21f595328a916fe2c151cf | 42.854167 | 188 | 0.673004 | 5.313131 | false | false | false | false |
Microsoft/vso-intellij | client/backend/src/test/kotlin/com/microsoft/tfs/tests/ClassicClientUtils.kt | 1 | 2720 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
package com.microsoft.tfs.tests
import com.jetbrains.rd.util.info
import com.microsoft.tfs.Logging
import org.junit.Assert
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
private val logger = Logging.getLogger("ClassicClientUtilsKt")
private fun executeClient(directory: Path, vararg arguments: String) {
logger.info { "Running tf with arguments: [${arguments.joinToString(",")}]" }
val loginArgument = "-login:${IntegrationTestUtils.user},${IntegrationTestUtils.pass}"
val process = ProcessBuilder(IntegrationTestUtils.tfExe, loginArgument, *arguments)
.directory(directory.toFile())
.apply {
environment().also {
it["TF_NOTELEMETRY"] = "TRUE"
it["TF_ADDITIONAL_JAVA_ARGS"] = "-Duser.country=US -Duser.language=en"
it["TF_USE_KEYCHAIN"] = "FALSE" // will be stuck on com.microsoft.tfs.jni.internal.keychain.NativeKeychain.nativeFindInternetPassword on macOS otherwise
}
}
.inheritIO()
.start()
val exitCode = process.waitFor()
Assert.assertEquals(0, exitCode)
}
private fun tfCreateWorkspace(workspacePath: Path, name: String, isServer: Boolean) {
val collectionUrl = IntegrationTestUtils.serverUrl
val location = if (isServer) "server" else "local"
executeClient(workspacePath, "workspace", "-new", "-collection:$collectionUrl", "-location:$location", name)
}
private fun tfDeleteWorkspace(workspacePath: Path, workspaceName: String) {
executeClient(workspacePath, "workspace", "-delete", workspaceName)
}
private fun tfCreateMapping(workspacePath: Path, workspaceName: String, serverPath: String, localPath: Path) {
executeClient(workspacePath, "workfold", "-map", "-workspace:$workspaceName", serverPath, localPath.toString())
}
private fun tfGet(workspacePath: Path) {
executeClient(workspacePath, "get")
}
fun cloneTestRepository(isServer: Boolean = false): Path {
val workspacePath = Files.createTempDirectory("adi.b.test.").toFile().canonicalFile.toPath()
val workspaceName = "${workspacePath.fileName}.${IntegrationTestUtils.workspaceNameSuffix}"
Assert.assertTrue(workspaceName.length <= 64)
tfCreateWorkspace(workspacePath, workspaceName, isServer)
tfCreateMapping(workspacePath, workspaceName, "$/${IntegrationTestUtils.teamProject}", Paths.get("."))
tfGet(workspacePath)
return workspacePath
}
fun deleteWorkspace(path: Path) {
val workspaceName = "${path.fileName}.${IntegrationTestUtils.workspaceNameSuffix}"
tfDeleteWorkspace(path, workspaceName)
}
| mit | 57e2dc0fea1de0c345fe4be5a27b5c66 | 41.5 | 168 | 0.726471 | 4.310618 | false | true | false | false |
cout970/ComputerMod | src/main/kotlin/com/cout970/computer/gui/GuiBase.kt | 1 | 5477 | package com.cout970.computer.gui
import com.cout970.computer.util.vector.Vec2d
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.inventory.GuiContainer
import net.minecraft.client.renderer.texture.TextureAtlasSprite
import net.minecraft.inventory.Container
import net.minecraft.util.ResourceLocation
import java.io.IOException
/**
* Created by cout970 on 20/05/2016.
*/
abstract class GuiBase(cont: Container) : GuiContainer(cont), IGui {
val components = mutableListOf<IComponent>()
override fun initGui() {
super.initGui()
components.clear()
initComponents()
}
abstract fun initComponents()
abstract fun getBackground() : ResourceLocation?
open fun getBackTexSize() = Vec2d(256, 256)
open fun getBackgroundEnd() = Vec2d(176, 166)
override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) {
val background = getBackground()
if(background != null) {
bindTexture(background)
drawScaledCustomSizeModalRect(getStart(), getSize(), Vec2d(), getBackgroundEnd(), getBackTexSize())
}
components.forEach { it.drawFirstLayer(this, Vec2d(mouseX, mouseY), partialTicks) }
}
override fun drawGuiContainerForegroundLayer(mouseX: Int, mouseY: Int) {
components.forEach { it.drawSecondLayer(this, Vec2d(mouseX, mouseY)) }
}
@Throws(IOException::class)
override fun mouseClicked(mouseX: Int, mouseY: Int, mouseButton: Int) {
var block = false;
for (it in components) {
if (it.onMouseClick(this, Vec2d(mouseX, mouseY), mouseButton)) {
block = true
break;
}
}
if (!block) {
super.mouseClicked(mouseX, mouseY, mouseButton)
}
}
override fun mouseClickMove(mouseX: Int, mouseY: Int, clickedMouseButton: Int, timeSinceLastClick: Long) {
var block = false;
for (it in components) {
if (it.onMouseClickMove(this, Vec2d(mouseX, mouseY), clickedMouseButton, timeSinceLastClick)) {
block = true
break;
}
}
if (!block) {
super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick)
}
}
override fun mouseReleased(mouseX: Int, mouseY: Int, state: Int){
components.forEach { it.onMouseReleased(this, Vec2d(mouseX, mouseY), state) }
super.mouseReleased(mouseX, mouseY, state)
}
@Throws(IOException::class)
override fun keyTyped(typedChar: Char, keyCode: Int){
var block = false;
for (it in components) {
if (it.onKeyTyped(this, typedChar, keyCode)) {
block = true
break;
}
}
if (!block) {
super.keyTyped(typedChar, keyCode)
}
}
override fun onGuiClosed(){
components.forEach { it.onGuiClosed(this) }
super.onGuiClosed()
}
override fun bindTexture(res: ResourceLocation) {
Minecraft.getMinecraft().renderEngine.bindTexture(res)
}
override fun drawHoveringText(textLines: List<String>, pos: Vec2d){
super.drawHoveringText(textLines, pos.getXi(), pos.getYi())
}
override fun getSize(): Vec2d = Vec2d(xSize, ySize)
override fun getStart(): Vec2d = Vec2d(guiLeft, guiTop)
override fun getWindowSize(): Vec2d = Vec2d(width, height)
override fun drawCenteredString(text: String, pos: Vec2d, color: Int) {
drawCenteredString(fontRendererObj, text, pos.getXi(), pos.getYi(), color)
}
override fun drawString(text: String, pos: Vec2d, color: Int) {
drawString(fontRendererObj, text, pos.getXi(), pos.getYi(), color)
}
override fun drawHorizontalLine(startX: Int, endX: Int, y: Int, color: Int){
super.drawHorizontalLine(startX, endX, y, color)
}
override fun drawVerticalLine(x: Int, startY: Int, endY: Int, color: Int){
super.drawVerticalLine(x, startY, endY, color)
}
override fun drawRect(start: Vec2d, end: Vec2d, color: Int) {
drawRect(start.getXi(), start.getYi(), end.getXi(), end.getYi(), color)
}
override fun drawGradientRect(start: Vec2d, end: Vec2d, startColor: Int, endColor: Int) {
drawGradientRect(start.getXi(), start.getYi(), end.getXi(), end.getYi(), startColor, endColor)
}
override fun drawTexturedModalRect(pos: Vec2d, size: Vec2d, texture: Vec2d) {
drawTexturedModalRect(pos.getXi(), pos.getYi(), texture.getXi(), texture.getYi(), size.getXi(), size.getYi())
}
override fun drawTexturedModalRect(pos: Vec2d, size: Vec2d, textureSprite: TextureAtlasSprite) {
drawTexturedModalRect(pos.getXi(), pos.getYi(), textureSprite, size.getXi(), size.getYi())
}
override fun drawModalRectWithCustomSizedTexture(pos: Vec2d, size: Vec2d, uv: Vec2d, textureSize: Vec2d) {
drawModalRectWithCustomSizedTexture(pos.getXi(), pos.getYi(), uv.getXf(), uv.getYf(), size.getXi(),
size.getYi(), textureSize.getXf(), textureSize.getYf())
}
override fun drawScaledCustomSizeModalRect(pos: Vec2d, size: Vec2d, uvMin: Vec2d, uvMax: Vec2d, textureSize: Vec2d) {
drawScaledCustomSizeModalRect(pos.getXi(), pos.getYi(), uvMin.getXf(), uvMin.getYf(), uvMax.getXi(),
uvMax.getYi(), size.getXi(), size.getYi(), textureSize.getXf(), textureSize.getYf())
}
} | gpl-3.0 | c0d36fc9408fe512a4833ccb8984afc2 | 35.278146 | 121 | 0.649991 | 3.895448 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/terminal/AbstractTerminalTool.kt | 1 | 4472 | /*
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.tools.terminal
import javafx.application.Platform
import javafx.scene.Node
import javafx.scene.input.DragEvent
import javafx.scene.input.TransferMode
import uk.co.nickthecoder.paratask.AbstractTool
import uk.co.nickthecoder.paratask.Tool
import uk.co.nickthecoder.paratask.gui.DropFiles
import uk.co.nickthecoder.paratask.misc.FileOperations
import uk.co.nickthecoder.paratask.project.Results
import uk.co.nickthecoder.paratask.project.ToolPane
import uk.co.nickthecoder.paratask.util.HasDirectory
import uk.co.nickthecoder.paratask.util.Stoppable
import uk.co.nickthecoder.paratask.util.process.OSCommand
import uk.co.nickthecoder.paratask.util.process.linuxCurrentDirectory
import uk.co.nickthecoder.paratask.util.runAndWait
import java.io.File
abstract class AbstractTerminalTool(
var showCommand: Boolean = true,
var allowInput: Boolean = true)
: AbstractTool(), Stoppable, HasDirectory {
protected var terminalResults: TerminalResults? = null
override fun iconName() = if (taskD.name == "") "terminal" else taskD.name
abstract fun createCommand(): OSCommand
/**
* Returns the current working directory of the running process ON LINUX ONLY.
* Returns null on other platforms. Also returns null if the process has finished.
*/
override val directory
get() = terminalResults?.process?.linuxCurrentDirectory()
override fun run() {
stop()
terminalResults = createTerminalResults()
runAndWait {
updateResults()
//toolPane?.replaceResults(createResults(), resultsList)
}
val command = createCommand()
terminalResults?.start(command)
terminalResults?.waitFor()
Platform.runLater {
finished()
}
}
open fun finished() {
// Default behaviour is to do nothing.
}
open protected fun createTerminalResults(): TerminalResults {
// Let's try to create a RealTerminalResults, but do it using reflection so that this code can be compiled
// without all of the bloat required by JediTerm. Therefore, we have a choice of lots of bloat, but an
// excellent terminal, or no bloat, and a naff terminal.
try {
// The following is a reflection version of : return RealTerminalResults(this)
val realResultsClass = Class.forName("uk.co.nickthecoder.paratask.tools.terminal.RealTerminalResults")
val constructor = realResultsClass.getConstructor(Tool::class.java)
return constructor.newInstance(this) as TerminalResults
} catch (e: Exception) {
// println(e)
// Fall back to using the naff, SimpleTerminalResults
return SimpleTerminalResults(this, showCommand = showCommand, allowInput = allowInput)
}
}
override fun createResults(): List<Results> {
return singleResults(terminalResults)
}
override fun stop() {
terminalResults?.stop()
}
override fun attached(toolPane: ToolPane) {
super.attached(toolPane)
tabDropHelper = object : DropFiles(dropped = { event, files -> droppedFiles(event, files) }) {
override fun acceptTarget(event: DragEvent): Pair<Node?, Array<TransferMode>>? {
// Can't drop files if the process isn't running, or we aren't running on linux!
if (directory == null) {
return null
}
return super.acceptTarget(event)
}
}
}
private fun droppedFiles(event: DragEvent, files: List<File>?): Boolean {
directory?.let {
FileOperations.instance.fileOperation(files!!, it, event.transferMode)
}
return true
}
}
| gpl-3.0 | 43b007e74913d9ceee38f8e818605bbe | 34.212598 | 114 | 0.690966 | 4.591376 | false | false | false | false |
Karumi/Shot | shot-android/src/main/java/com/karumi/shot/compose/ScreenshotTestSession.kt | 1 | 815 | package com.karumi.shot.compose
import com.google.gson.annotations.SerializedName
class ScreenshotTestSession {
companion object {
@Deprecated("ScreenshotTestSession is mutable and thus this instance cannot be guaranteed to be empty.")
val empty: ScreenshotTestSession = ScreenshotTestSession()
}
private var session = ScreenshotSessionMetadata()
fun add(data: ScreenshotMetadata): ScreenshotTestSession {
session = session.save(data)
return this
}
fun getScreenshotSessionMetadata() = session.copy()
}
data class ScreenshotSessionMetadata(@SerializedName("screenshots") val screenshotsData: List<ScreenshotMetadata> = emptyList()) {
fun save(data: ScreenshotMetadata): ScreenshotSessionMetadata = copy(screenshotsData = screenshotsData + data)
}
| apache-2.0 | 46803799aa3baa71e135ce0356d505bb | 31.6 | 130 | 0.752147 | 5.062112 | false | true | false | false |
jitsi/jicofo | jicofo-common/src/main/kotlin/org/jitsi/jicofo/xmpp/jingle/JingleRequestHandler.kt | 1 | 3348 | /*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2015-Present 8x8, 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 org.jitsi.jicofo.xmpp.jingle
import org.jitsi.xmpp.extensions.jingle.ContentPacketExtension
import org.jitsi.xmpp.extensions.jingle.JingleIQ
import org.jivesoftware.smack.packet.StanzaError
/**
* Listener class notified about Jingle requests received during a session.
*
* @author Pawel Domas
*/
interface JingleRequestHandler {
/**
* A 'source-add' IQ was received.
*
* @return a [StanzaError] if an error should be returned as response to the original request or null if
* processing was successful.
*/
fun onAddSource(jingleSession: JingleSession, contents: List<ContentPacketExtension>): StanzaError? = null
/**
* A 'source-remove' IQ was received.
*
* @return a [StanzaError] if an error should be returned as response to the original request or null if
* processing was successful.
*/
fun onRemoveSource(jingleSession: JingleSession, contents: List<ContentPacketExtension>): StanzaError? = null
/**
* A 'session-accept' IQ was received.
*
* @return a [StanzaError] if an error should be returned as response to the original request or null if
* processing was successful.
*/
fun onSessionAccept(jingleSession: JingleSession, contents: List<ContentPacketExtension>): StanzaError? = null
/**
* A 'session-info' IQ was received.
*
* @return a [StanzaError] if an error should be returned as response to the original request or null if
* processing was successful.
*/
fun onSessionInfo(jingleSession: JingleSession, iq: JingleIQ): StanzaError? = null
/**
* A 'session-terminate' IQ was received.
*
* @return a [StanzaError] if an error should be returned as response to the original request or null if
* processing was successful.
*/
fun onSessionTerminate(jingleSession: JingleSession, iq: JingleIQ): StanzaError? = null
/**
* A 'transport-info' IQ was received.
*/
fun onTransportInfo(jingleSession: JingleSession, contents: List<ContentPacketExtension>): StanzaError? = null
/**
* A 'transport-accept' IQ was received.
*
* @return a [StanzaError] if an error should be returned as response to the original request or null if
* processing was successful.
*/
fun onTransportAccept(
jingleSession: JingleSession,
contents: List<ContentPacketExtension>
): StanzaError? = null
/**
* A 'transport-reject' IQ was received.
*/
fun onTransportReject(jingleSession: JingleSession, iq: JingleIQ) { }
}
/** Export a default impl so it can be used in java without -Xjvm-default */
class NoOpJingleRequestHandler : JingleRequestHandler
| apache-2.0 | 01b8838a17f19b775118d33309cca2a7 | 35 | 114 | 0.70221 | 4.336788 | false | false | false | false |
GoogleChromeLabs/android-web-payment | SamplePay/app/src/main/java/com/example/android/samplepay/ViewBindingDelegates.kt | 1 | 1514 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.samplepay
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.viewbinding.ViewBinding
/**
* Retrieves a view binding handle in an Activity.
*
* ```
* private val binding by viewBindings(MainActivityBinding::bind)
*
* override fun onCreate(savedInstanceState: Bundle?) {
* super.onCreate(savedInstanceState)
* binding.someView.someField = ...
* }
* ```
*/
inline fun <reified BindingT : ViewBinding> FragmentActivity.viewBindings(
crossinline bind: (View) -> BindingT
) = object : Lazy<BindingT> {
private var cached: BindingT? = null
override val value: BindingT
get() = cached ?: bind(
findViewById<ViewGroup>(android.R.id.content).getChildAt(0)
).also {
cached = it
}
override fun isInitialized() = cached != null
}
| apache-2.0 | 72698928c14ec7522ae41bb900543f39 | 29.28 | 75 | 0.696169 | 4.22905 | false | false | false | false |
android/databinding-samples | TwoWaySample/app/src/main/java/com/example/android/databinding/twowaysample/ui/NumberOfSetsBindingAdapters.kt | 1 | 5138 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.databinding.twowaysample.ui
import android.content.Context
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
import androidx.databinding.InverseMethod
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.example.android.databinding.twowaysample.R
/**
* The [EditText] that controls the number of sets is using two-way Data Binding. Applying a
* 2-way expression to the `android:text` attribute of the EditText triggers an update on every
* keystroke. This is an alternative implementation that uses a [View.OnFocusChangeListener]
* instead.
*
* `numberOfSetsAttrChanged` creates a listener that triggers when the focus is lost
*
* `hideKeyboardOnInputDone` (in a different file) will clear focus when the `Done` action on
* the keyboard is dispatched, triggering `numberOfSetsAttrChanged`.
*/
object NumberOfSetsBindingAdapters {
/**
* Needs to be used with [NumberOfSetsConverters.setArrayToString].
*/
@BindingAdapter("numberOfSets")
@JvmStatic fun setNumberOfSets(view: EditText, value: String) {
view.setText(value)
}
/**
* Called when the [InverseBindingListener] of the `numberOfSetsAttrChanged` binding adapter
* is notified of a change.
*
* Used with the inverse method of [NumberOfSetsConverters.setArrayToString], which is
* [NumberOfSetsConverters.stringToSetArray].
*/
@InverseBindingAdapter(attribute = "numberOfSets")
@JvmStatic fun getNumberOfSets(editText: EditText): String {
return editText.text.toString()
}
/**
* That this Binding Adapter is not defined in the XML. "AttrChanged" is a special
* suffix that lets you manage changes in the value, using two-way Data Binding.
*
* Note that setting a [View.OnFocusChangeListener] overrides other listeners that might be set
* with `android:onFocusChangeListener`. Consider supporting both in the same binding adapter
* with `requireAll = false`. See [android.databinding.adapters.CompoundButtonBindingAdapter]
* for an example.
*/
@BindingAdapter("numberOfSetsAttrChanged")
@JvmStatic fun setListener(view: EditText, listener: InverseBindingListener?) {
view.onFocusChangeListener = View.OnFocusChangeListener { focusedView, hasFocus ->
val textView = focusedView as TextView
if (hasFocus) {
// Delete contents of the EditText if the focus entered.
textView.text = ""
} else {
// If the focus left, update the listener
listener?.onChange()
}
}
}
/* This sample showcases the NumberOfSetsConverters below, but note that they could be used
also like: */
@BindingAdapter("numberOfSets_alternative")
@JvmStatic fun setNumberOfSets_alternative(view: EditText, value: Array<Int>) {
view.setText(String.format(
view.resources.getString(R.string.sets_format,
value[0] + 1,
value[1])))
}
@InverseBindingAdapter(attribute = "numberOfSets_alternative")
@JvmStatic fun getNumberOfSets_alternative(editText: EditText): Array<Int> {
if (editText.text.isEmpty()) {
return arrayOf(0, 0)
}
return try {
arrayOf(0, editText.text.toString().toInt()) // First item is not passed
} catch (e: NumberFormatException) {
arrayOf(0, 0)
}
}
}
/**
* Converters for the number of sets attribute.
*/
object NumberOfSetsConverters {
/**
* Used with `numberOfSets` to convert from array to String.
*/
@InverseMethod("stringToSetArray")
@JvmStatic fun setArrayToString(context: Context, value: Array<Int>): String {
return context.getString(R.string.sets_format, value[0] + 1, value[1])
}
/**
* This is the Inverse Method used in `numberOfSets`, to convert from String to array.
*
* Note that Context is passed
*/
@JvmStatic fun stringToSetArray(unused: Context, value: String): Array<Int> {
// Converts String to long
if (value.isEmpty()) {
return arrayOf(0, 0)
}
return try {
arrayOf(0, value.toInt()) // First item is not passed
} catch (e: NumberFormatException) {
arrayOf(0, 0)
}
}
}
| apache-2.0 | 13befe1af478b1e5ff30646ad1afe084 | 35.439716 | 99 | 0.677696 | 4.599821 | false | false | false | false |
afollestad/photo-affix | engine/src/test/java/com/afollestad/photoaffix/engine/BitmapIteratorTest.kt | 1 | 4001 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.photoaffix.engine
import android.graphics.BitmapFactory.Options
import com.afollestad.photoaffix.engine.bitmaps.BitmapIterator
import com.afollestad.photoaffix.engine.bitmaps.BitmapManipulator
import com.afollestad.photoaffix.engine.photos.Photo
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import junit.framework.TestCase.fail
import org.junit.Test
class BitmapIteratorTest {
private val photos = listOf(
Photo(0, "file://idk/1", 0, testUriParser),
Photo(0, "file://idk/2", 0, testUriParser),
Photo(0, "file://idk/3", 0, testUriParser)
)
private val bitmapDecoder = mock<BitmapManipulator> {
on { createOptions(any()) } doAnswer { inv ->
Options().apply { inJustDecodeBounds = inv.getArgument(0) }
}
on { decodePhoto(any(), any()) } doAnswer { inv ->
val photo = inv.getArgument<Photo>(0)
val options = inv.getArgument<Options>(1)
when (photo) {
photos[0] -> {
options.outWidth = 2
options.outHeight = 4
}
photos[1] -> {
options.outWidth = 3
options.outHeight = 6
}
photos[2] -> {
options.outWidth = 4
options.outHeight = 8
}
else -> fail("Unknown photo: $photo")
}
if (options.inJustDecodeBounds) {
null
} else {
fakeBitmap(options.outWidth, options.outHeight)
}
}
}
private val bitmapIterator = BitmapIterator(
photos = photos,
bitmapManipulator = bitmapDecoder
)
@Test fun traversal() {
// Test next()
assertThat(bitmapIterator.currentOptions()).isNull()
bitmapIterator.next()
assertThat(bitmapIterator.traverseIndex()).isEqualTo(0)
val optionsCaptor = argumentCaptor<Options>()
verify(bitmapDecoder).decodePhoto(
eq(photos[0]),
optionsCaptor.capture()
)
assertThat(bitmapIterator.currentOptions())
.isEqualTo(optionsCaptor.firstValue)
// Test currentBitmap()
val currentBitmap = bitmapIterator.currentBitmap()
verify(bitmapDecoder, times(2)).decodePhoto(
photos[0],
optionsCaptor.firstValue
)
assertThat(currentBitmap.width).isEqualTo(2)
assertThat(currentBitmap.height).isEqualTo(4)
}
@Test(expected = IllegalArgumentException::class)
fun currentBitmapWithoutNext() {
bitmapIterator.currentBitmap()
}
@Test(expected = IllegalStateException::class)
fun traversalTooFar() {
assertThat(bitmapIterator.hasNext()).isTrue()
bitmapIterator.next()
assertThat(bitmapIterator.hasNext()).isTrue()
bitmapIterator.next()
assertThat(bitmapIterator.hasNext()).isTrue()
bitmapIterator.next()
assertThat(bitmapIterator.hasNext()).isFalse()
bitmapIterator.next()
}
@Test fun size() {
assertThat(bitmapIterator.size()).isEqualTo(3)
}
@Test fun reset() {
bitmapIterator.next()
bitmapIterator.next()
assertThat(bitmapIterator.traverseIndex()).isEqualTo(1)
bitmapIterator.reset()
assertThat(bitmapIterator.traverseIndex()).isEqualTo(-1)
}
}
| apache-2.0 | 9e576166fbbb97df61770d65252cd961 | 30.015504 | 75 | 0.695076 | 4.334778 | false | true | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/refactoring/RsInlineTypeAliasTest.kt | 2 | 6918 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring
import junit.framework.ComparisonFailure
class RsInlineTypeAliasTest : RsInlineTestBase() {
fun `test simple alias, base type as base type`() = doTest("""
type Foo/*caret*/ = i32;
fn func() {
let _: Foo;
}
""", """
fn func() {
let _: i32;
}
""")
fun `test simple alias, base type as path`() = doTest("""
type Foo/*caret*/ = i32;
fn func() {
Foo::new();
}
""", """
fn func() {
i32::new();
}
""")
fun `test simple alias, base type as path (struct literal)`() = doTest("""
struct Struct {}
type Foo/*caret*/ = Struct;
fn func() {
let _ = Foo {};
}
""", """
struct Struct {}
fn func() {
let _ = Struct {};
}
""")
fun `test simple alias, base type with generics as base type`() = doTest("""
type Foo/*caret*/ = HashSet<i32>;
fn func() {
let _: Foo;
}
struct HashSet<T> {}
""", """
fn func() {
let _: HashSet<i32>;
}
struct HashSet<T> {}
""")
fun `test simple alias, base type with generics as path`() = doTest("""
type Foo/*caret*/ = HashSet<i32>;
fn func() {
Foo::new();
}
struct HashSet<T> {}
""", """
fn func() {
HashSet::<i32>::new();
}
struct HashSet<T> {}
""")
fun `test simple alias, base type with generics as path (struct literal)`() = doTest("""
struct Struct<T> { t: T }
type Foo/*caret*/ = Struct<i32>;
fn func() {
let _ = Foo { t: 0 };
}
""", """
struct Struct<T> { t: T }
fn func() {
let _ = Struct::<i32> { t: 0 };
}
""")
fun `test simple alias, array type as base type`() = doTest("""
type Foo/*caret*/ = [i32];
fn func() {
let _: Foo;
}
""", """
fn func() {
let _: [i32];
}
""")
fun `test simple alias, array type as path`() = doTest("""
type Foo/*caret*/ = [i32];
fn func() {
Foo::new();
}
""", """
fn func() {
<[i32]>::new();
}
""")
fun `test simple alias, array type as path with type arguments`() = doTest("""
type Foo/*caret*/ = [i32];
fn func() {
Foo::get::<usize>();
}
""", """
fn func() {
<[i32]>::get::<usize>();
}
""")
fun `test local type alias`() = doTest("""
fn func() {
type Foo/*caret*/ = i32;
let _: Foo;
}
""", """
fn func() {
let _: i32;
}
""")
fun `test type alias used in other module with import`() = doTest("""
mod mod1 {
pub type Foo/*caret*/ = i32;
}
mod mod2 {
use crate::mod1::Foo;
fn func() {
let _: Foo;
}
}
""", """
mod mod1 {}
mod mod2 {
fn func() {
let _: i32;
}
}
""")
fun `test type alias used in other module without import`() = doTest("""
mod mod1 {
pub type Foo/*caret*/ = i32;
}
mod mod2 {
fn func() {
let _: crate::mod1::Foo;
}
}
""", """
mod mod1 {}
mod mod2 {
fn func() {
let _: i32;
}
}
""")
fun `test add imports`() = doTest("""
mod mod1 {
pub struct Struct1<T> { t : T }
pub struct Struct2 {}
pub type Foo/*caret*/ = Struct1<Struct2>;
}
mod mod2 {
fn func() {
let _: crate::mod1::Foo;
}
}
""", """
mod mod1 {
pub struct Struct1<T> { t : T }
pub struct Struct2 {}
}
mod mod2 {
use crate::mod1::{Struct1, Struct2};
fn func() {
let _: Struct1<Struct2>;
}
}
""")
fun `test add imports 2`() = doTest("""
mod mod1 {
pub mod inner {
pub struct Struct {}
}
pub type Foo/*caret*/ = inner::Struct;
}
mod mod2 {
fn func() {
let _: crate::mod1::Foo;
}
}
""", """
mod mod1 {
pub mod inner {
pub struct Struct {}
}
}
mod mod2 {
use crate::mod1::inner;
fn func() {
let _: inner::Struct;
}
}
""")
fun `test qualify path`() = expect<ComparisonFailure> {
doTest("""
mod mod1 {
pub struct Bar {}
pub type Foo/*caret*/ = Bar;
}
mod mod2 {
struct Bar {}
fn func() {
let _: crate::mod1::Foo;
}
}
""", """
mod mod1 {
pub struct Bar {}
}
mod mod2 {
struct Bar {}
fn func() {
let _: crate::mod1::Bar;
}
}
""")
}
fun `test inline called on reference`() = doTest("""
type Foo = i32;
fn func() {
let _: Foo/*caret*/;
}
""", """
fn func() {
let _: i32;
}
""")
fun `test generic type alias`() = doTest("""
type /*caret*/Foo<T> = [T];
fn func(_: Foo<i32>) {}
""", """
fn func(_: [i32]) {}
""")
fun `test generic type alias with complex inference`() = doTest("""
struct Bar<T>(T);
impl <T> Bar<T> {
fn new(t: T) -> Bar<T> { Bar(t) }
}
type Foo<T> = Bar<T>;
fn foo() {
let _ = Foo/*caret*/::new(1);
}
""", """
struct Bar<T>(T);
impl <T> Bar<T> {
fn new(t: T) -> Bar<T> { Bar(t) }
}
fn foo() {
let _ = Bar::<i32>::new(1);
}
""")
fun `test don't inline associated type`() = doUnavailableTest("""
fn func(_: <Struct as Trait>::Foo) {}
struct Struct {}
impl Trait for Struct {
type Foo/*caret*/ = i32;
}
trait Trait {
type Foo;
}
""")
fun `test don't inline type alias generated by macro`() = doUnavailableTest("""
macro_rules! gen {
() => {
pub type Foo = i32;
};
}
gen!();
fn func() {
let _: Foo/*caret*/;
}
""")
}
| mit | 3d961efa2537f3fc6ef3dc9a1916597a | 21.38835 | 92 | 0.375687 | 4.226023 | false | true | false | false |
data-gov/bumblebee | src/test/unit/kotlin/br/com/bumblebee/api/congressman/client/model/OpenDataResponseFixture.kt | 1 | 499 | package br.com.bumblebee.api.congressman.client.model
import br.com.bumblebee.api.congressman.client.model.LinkType.NEXT
val CONGRESSMAN_NEXT_LINK_FIXTURE = Link(NEXT,
"https://dadosabertos.camara.leg.br/api/v2/deputados?pagina=2&itens=100")
val OPEN_DATA_CONGRESSMAN_FIXTURE = OpenDataResponse(listOf(CONGRESSMAN_CLIENT_MODEL_FIXTURE))
val OPEN_DATA_CONGRESSMAN_WITH_NEXT_FIXTURE = OpenDataResponse(
listOf(CONGRESSMAN_CLIENT_MODEL_FIXTURE),
listOf(CONGRESSMAN_NEXT_LINK_FIXTURE)
)
| gpl-3.0 | 534e72d94b40875a1432b64ceae95972 | 37.384615 | 94 | 0.795591 | 2.988024 | false | false | false | false |
mhsjlw/AndroidSnap | app/src/main/java/me/keegan/snap/LoginActivity.kt | 1 | 3010 | package me.keegan.snap
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.Window
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.parse.LogInCallback
import com.parse.ParseException
import com.parse.ParseUser
class LoginActivity : Activity() {
protected lateinit var mUsername: EditText
protected lateinit var mPassword: EditText
protected lateinit var mLoginButton: Button
protected lateinit var mSignUpTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS)
setContentView(R.layout.activity_login)
mSignUpTextView = findViewById<View>(R.id.signUpText) as TextView
mSignUpTextView.setOnClickListener {
val intent = Intent(this@LoginActivity, SignUpActivity::class.java)
startActivity(intent)
}
mUsername = findViewById<View>(R.id.usernameField) as EditText
mPassword = findViewById<View>(R.id.passwordField) as EditText
mLoginButton = findViewById<View>(R.id.loginButton) as Button
mLoginButton.setOnClickListener {
var username = mUsername.text.toString()
var password = mPassword.text.toString()
username = username.trim { it <= ' ' }
password = password.trim { it <= ' ' }
if (username.isEmpty() || password.isEmpty()) {
val builder = AlertDialog.Builder(this@LoginActivity)
builder.setMessage(R.string.login_error_message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null)
val dialog = builder.create()
dialog.show()
} else {
// Login
setProgressBarIndeterminateVisibility(true)
ParseUser.logInInBackground(username, password) { user, e ->
setProgressBarIndeterminateVisibility(false)
if (e == null) {
// Success!
val intent = Intent(this@LoginActivity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
} else {
val builder = AlertDialog.Builder(this@LoginActivity)
builder.setMessage(e.message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null)
val dialog = builder.create()
dialog.show()
}
}
}
}
}
}
| mit | aa3b021e393dec5c543791f82d86f5f2 | 37.589744 | 89 | 0.600332 | 5.189655 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/controller/GuiaRestApi.kt | 1 | 4018 | package com.quijotelui.controller
import com.quijotelui.electronico.ejecutar.Electronica
import com.quijotelui.electronico.util.TipoComprobante
import com.quijotelui.model.Guia
import com.quijotelui.service.IElectronicoService
import com.quijotelui.service.IGuiaService
import com.quijotelui.service.IInformacionService
import com.quijotelui.service.IParametroService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.util.concurrent.TimeUnit
@RestController
@RequestMapping("/rest/v1")
class GuiaRestApi {
@Autowired
lateinit var guiaService: IGuiaService
@Autowired
lateinit var parametroService : IParametroService
@Autowired
lateinit var electronicoService : IElectronicoService
@Autowired
lateinit var informacionService : IInformacionService
@Value("\${key.property}")
lateinit var keyProperty: String
@GetMapping("/guia/codigo/{codigo}/numero/{numero}")
fun getGuia(@PathVariable(value = "codigo") codigo: String,
@PathVariable(value = "numero") numero: String): ResponseEntity<MutableList<Any>> {
val guia = guiaService.findContribuyenteByComprobante(codigo, numero)
return ResponseEntity<MutableList<Any>>(guia, HttpStatus.OK)
}
/*
* Genera, firma y envía el comprobante electrónico
*/
@GetMapping("/guiaEnviar/codigo/{codigo}/numero/{numero}")
fun enviaXml(@PathVariable(value = "codigo") codigo : String,
@PathVariable(value = "numero") numero : String) : ResponseEntity<MutableList<Guia>> {
if (codigo == null || numero == null) {
return ResponseEntity(HttpStatus.CONFLICT)
}
else {
val guia = guiaService.findByComprobante(codigo, numero)
if (guia.isEmpty()) {
return ResponseEntity(HttpStatus.NOT_FOUND)
}
else {
val genera = Electronica(guiaService, codigo, numero, parametroService, keyProperty ,electronicoService)
genera.enviar(TipoComprobante.GUIA)
return ResponseEntity<MutableList<Guia>>(guia, HttpStatus.OK)
}
}
}
/*
Envía y Autoriza el comprobante electrónico
*/
@CrossOrigin(value = "*")
@GetMapping("/guia_procesar/codigo/{codigo}/numero/{numero}")
fun procesarXml(@PathVariable(value = "codigo") codigo : String,
@PathVariable(value = "numero") numero : String) : ResponseEntity<MutableList<Any>> {
if (codigo == null || numero == null) {
return ResponseEntity(HttpStatus.CONFLICT)
}
else {
val guia = guiaService.findByComprobante(codigo, numero)
if (guia.isEmpty()) {
return ResponseEntity(HttpStatus.NOT_FOUND)
} else {
val genera = Electronica(guiaService, codigo, numero, parametroService, keyProperty ,electronicoService)
genera.enviar(TipoComprobante.GUIA)
println("Espere 3 segundos por favor hasta que el servicio del SRI autorice")
TimeUnit.SECONDS.sleep(3)
genera.comprobar(informacionService, TipoComprobante.GUIA)
val estado = guiaService.findEstadoByComprobante(codigo, numero)
return ResponseEntity<MutableList<Any>>(estado, HttpStatus.OK)
}
}
}
/*
Estado del comprobante
*/
@GetMapping("/estado_guia/codigo/{codigo}/numero/{numero}")
fun getEstado(@PathVariable(value = "codigo") codigo : String,
@PathVariable(value = "numero") numero : String) : ResponseEntity<MutableList<Any>> {
val guia = guiaService.findEstadoByComprobante(codigo, numero)
return ResponseEntity<MutableList<Any>>(guia, HttpStatus.OK)
}
} | gpl-3.0 | d8a00cc81717e53e0eeef86869b8e8e3 | 35.171171 | 120 | 0.670902 | 4.386885 | false | false | false | false |
androidx/androidx | benchmark/benchmark-common/src/main/java/androidx/benchmark/Profiler.kt | 3 | 9003 | /*
* 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.benchmark
import android.os.Build
import android.os.Debug
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.benchmark.BenchmarkState.Companion.TAG
import androidx.benchmark.Outputs.dateToFileName
import androidx.benchmark.simpleperf.ProfileSession
import androidx.benchmark.simpleperf.RecordOptions
/**
* Profiler abstraction used for the timing stage.
*
* Controlled externally by `androidx.benchmark.profiling.mode`
* Subclasses are objects, as these generally refer to device or process global state. For
* example, things like whether the simpleperf process is running, or whether the runtime is
* capturing method trace.
*
* Note: flags on this class would be simpler if we either had a 'Default'/'Noop' profiler, or a
* wrapper extension function (e.g. `fun Profiler? .requiresSingleMeasurementIteration`). We
* avoid these however, in order to avoid the runtime visiting a new class in the hot path, when
* switching from warmup -> timing phase, when [start] would be called.
*/
internal sealed class Profiler {
class ResultFile(
val label: String,
val outputRelativePath: String
)
abstract fun start(traceUniqueName: String): ResultFile?
abstract fun stop()
/**
* Measure exactly one loop (one repeat, one iteration).
*
* Generally only set for tracing profilers.
*/
open val requiresSingleMeasurementIteration = false
/**
* Generally only set for sampling profilers.
*/
open val requiresExtraRuntime = false
/**
* Currently, debuggable is required to support studio-connected profiling.
*
* Remove this once stable Studio supports profileable.
*/
open val requiresDebuggable = false
/**
* Connected modes don't need dir, since library isn't doing the capture.
*/
open val requiresLibraryOutputDir = true
companion object {
const val CONNECTED_PROFILING_SLEEP_MS = 20_000L
fun getByName(name: String): Profiler? = mapOf(
"MethodTracing" to MethodTracing,
"StackSampling" to if (Build.VERSION.SDK_INT >= 29) {
StackSamplingSimpleperf // only supported on 29+ without root/debug/sideload
} else {
StackSamplingLegacy
},
"ConnectedAllocation" to ConnectedAllocation,
"ConnectedSampling" to ConnectedSampling,
// Below are compat codepaths for old names. Remove before 1.1 stable.
"MethodSampling" to StackSamplingLegacy,
"MethodSamplingSimpleperf" to StackSamplingSimpleperf,
"Method" to MethodTracing,
"Sampled" to StackSamplingLegacy,
"ConnectedSampled" to ConnectedSampling
)
.mapKeys { it.key.lowercase() }[name.lowercase()]
fun traceName(traceUniqueName: String, traceTypeLabel: String): String {
return "$traceUniqueName-$traceTypeLabel-${dateToFileName()}.trace"
}
}
}
internal fun startRuntimeMethodTracing(
traceFileName: String,
sampled: Boolean
): Profiler.ResultFile {
val path = Outputs.testOutputFile(traceFileName).absolutePath
Log.d(TAG, "Profiling output file: $path")
InstrumentationResults.reportAdditionalFileToCopy("profiling_trace", path)
val bufferSize = 16 * 1024 * 1024
if (sampled &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
) {
startMethodTracingSampling(path, bufferSize, Arguments.profilerSampleFrequency)
} else {
Debug.startMethodTracing(path, bufferSize, 0)
}
return Profiler.ResultFile(
outputRelativePath = traceFileName,
label = if (sampled) "Stack Sampling (legacy) Trace" else "Method Trace"
)
}
internal fun stopRuntimeMethodTracing() {
Debug.stopMethodTracing()
}
internal object StackSamplingLegacy : Profiler() {
@get:RestrictTo(RestrictTo.Scope.TESTS)
var isRunning = false
override fun start(traceUniqueName: String): ResultFile {
isRunning = true
return startRuntimeMethodTracing(
traceFileName = traceName(traceUniqueName, "stackSamplingLegacy"),
sampled = true
)
}
override fun stop() {
stopRuntimeMethodTracing()
isRunning = false
}
override val requiresExtraRuntime: Boolean = true
}
internal object MethodTracing : Profiler() {
override fun start(traceUniqueName: String): ResultFile {
return startRuntimeMethodTracing(
traceFileName = traceName(traceUniqueName, "methodTracing"),
sampled = false
)
}
override fun stop() {
stopRuntimeMethodTracing()
}
override val requiresSingleMeasurementIteration: Boolean = true
}
internal object ConnectedAllocation : Profiler() {
override fun start(traceUniqueName: String): ResultFile? {
Thread.sleep(CONNECTED_PROFILING_SLEEP_MS)
return null
}
override fun stop() {
Thread.sleep(CONNECTED_PROFILING_SLEEP_MS)
}
override val requiresSingleMeasurementIteration: Boolean = true
override val requiresDebuggable: Boolean = true
override val requiresLibraryOutputDir: Boolean = false
}
internal object ConnectedSampling : Profiler() {
override fun start(traceUniqueName: String): ResultFile? {
Thread.sleep(CONNECTED_PROFILING_SLEEP_MS)
return null
}
override fun stop() {
Thread.sleep(CONNECTED_PROFILING_SLEEP_MS)
}
override val requiresDebuggable: Boolean = true
override val requiresLibraryOutputDir: Boolean = false
}
/**
* Simpleperf profiler.
*
* API 29+ currently, since it relies on the platform system image simpleperf.
*
* Could potentially lower, but that would require root or debuggable.
*/
internal object StackSamplingSimpleperf : Profiler() {
@RequiresApi(29)
private var session: ProfileSession? = null
/** "security.perf_harden" must be set to "0" during simpleperf capture */
@RequiresApi(29)
private val securityPerfHarden = PropOverride("security.perf_harden", "0")
var outputRelativePath: String? = null
@RequiresApi(29)
override fun start(traceUniqueName: String): ResultFile? {
session?.stopRecording() // stop previous
// for security perf harden, enable temporarily
securityPerfHarden.forceValue()
// for all other properties, simply set the values, as these don't have defaults
Shell.executeScriptSilent("setprop debug.perf_event_max_sample_rate 10000")
Shell.executeScriptSilent("setprop debug.perf_cpu_time_max_percent 25")
Shell.executeScriptSilent("setprop debug.perf_event_mlock_kb 32800")
outputRelativePath = traceName(traceUniqueName, "stackSampling")
session = ProfileSession().also {
// prepare simpleperf must be done as shell user, so do this here with other shell setup
// NOTE: this is sticky across reboots, so missing this will cause tests or profiling to
// fail, but only on devices that have not run this command since flashing (e.g. in CI)
Shell.executeScriptSilent(it.findSimpleperf() + " api-prepare")
it.startRecording(
RecordOptions()
.setSampleFrequency(Arguments.profilerSampleFrequency)
.recordDwarfCallGraph() // enable Java/Kotlin callstacks
.setEvent("cpu-clock") // Required on API 33 to enable traceOffCpu
.traceOffCpu() // track time sleeping
.setSampleCurrentThread() // sample stacks from this thread only
.setOutputFilename("simpleperf.data")
)
}
return ResultFile(
label = "Stack Sampling Trace",
outputRelativePath = outputRelativePath!!
)
}
@RequiresApi(29)
override fun stop() {
session!!.stopRecording()
Outputs.writeFile(
fileName = outputRelativePath!!,
reportKey = "simpleperf_trace"
) {
session!!.convertSimpleperfOutputToProto("simpleperf.data", it.absolutePath)
}
session = null
securityPerfHarden.resetIfOverridden()
}
override val requiresLibraryOutputDir: Boolean = false
}
| apache-2.0 | 4197877eec01ca68af4465707ef6c453 | 33.102273 | 100 | 0.679996 | 4.698852 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/main/kotlin/com/commonsense/android/kotlin/views/input/InputValidator.kt | 1 | 2277 | @file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.views.input
import com.commonsense.android.kotlin.base.*
/**
* Created by kasper on 21/08/2017.
*/
typealias ValidationCallback<T, U> = (T) -> U?
typealias ValidationFailedCallback<T, U> = (T, U) -> Unit
private typealias MutableRuleList<U> = MutableList<ValidationRule<*, U>>
private typealias RuleList<U> = List<ValidationRule<*, U>>
class InputValidator<U>
private constructor(
private val elementsToValidate: RuleList<U>,
private val onFailedValidation: FunctionUnit<U>?) {
fun validate(): Boolean {
return elementsToValidate.all { rule ->
rule.validate(onFailedValidation)
}
}
class Builder<U> {
private val elementsToValidate: MutableRuleList<U> = mutableListOf()
private var onFailedValidation: FunctionUnit<U>? = null
fun <T> add(objectToUse: T,
validationCallback: ValidationCallback<T, U>,
onValidationFailed: ValidationFailedCallback<T, U>? = null
) {
val rule = ValidationRule(objectToUse, validationCallback, onValidationFailed)
elementsToValidate.add(rule)
/* attachEvents?.invoke(objectToUse, {
//TODO something in this manner.
rule.validate(onFailedValidation)
})*/
}
fun addOnValidationFailedCallback(callback: FunctionUnit<U>) {
onFailedValidation = callback
}
fun addOnValidationCallback() {
}
fun build(): InputValidator<U> {
return InputValidator(elementsToValidate.toList(), onFailedValidation)
}
}
}
private class ValidationRule<T, U>(val theObject: T, val validationRules: ValidationCallback<T, U>,
val onValidationFailed: ValidationFailedCallback<T, U>?) {
fun validate(optErrorCallback: FunctionUnit<U>?): Boolean {
//if null then no errors , otherwise theres an error.
return validationRules(theObject)?.let {
onValidationFailed?.invoke(theObject, it)
optErrorCallback?.invoke(it)
false
} ?: true
}
}
| mit | 8acf06944c688a18e19f7e829fd47b30 | 28.192308 | 99 | 0.631094 | 4.628049 | false | false | false | false |
world-federation-of-advertisers/panel-exchange-client | src/main/kotlin/org/wfanet/panelmatch/common/beam/WriteShardedData.kt | 1 | 4256 | // Copyright 2021 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.panelmatch.common.beam
import com.google.protobuf.Message
import kotlin.math.abs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.transforms.DoFn
import org.apache.beam.sdk.transforms.GroupByKey
import org.apache.beam.sdk.transforms.PTransform
import org.apache.beam.sdk.transforms.ParDo
import org.apache.beam.sdk.values.KV
import org.apache.beam.sdk.values.PCollection
import org.apache.beam.sdk.values.PCollectionList
import org.apache.beam.sdk.values.PInput
import org.apache.beam.sdk.values.POutput
import org.apache.beam.sdk.values.PValue
import org.apache.beam.sdk.values.TupleTag
import org.wfanet.panelmatch.common.ShardedFileName
import org.wfanet.panelmatch.common.storage.StorageFactory
import org.wfanet.panelmatch.common.toDelimitedByteString
/** Writes input messages into blobs. */
class WriteShardedData<T : Message>(
private val fileSpec: String,
private val storageFactory: StorageFactory
) : PTransform<PCollection<T>, WriteShardedData.WriteResult>() {
/** [POutput] holding filenames written. */
class WriteResult(private val fileNames: PCollection<String>) : POutput {
override fun getPipeline(): Pipeline = fileNames.pipeline
override fun expand(): Map<TupleTag<*>, PValue> {
return mapOf(tag to fileNames)
}
override fun finishSpecifyingOutput(
transformName: String,
input: PInput,
transform: PTransform<*, *>
) {}
companion object {
private val tag = TupleTag<String>()
}
}
override fun expand(input: PCollection<T>): WriteResult {
val shardedFileName = ShardedFileName(fileSpec)
val shardCount = shardedFileName.shardCount
val groupedData: PCollection<KV<Int, Iterable<T>>> =
input
.keyBy("Key by Blob") { it.assignToShard(shardCount) }
.apply("Group by Blob", GroupByKey.create())
val allShardIndices =
groupedData.pipeline.createSequence(
name = "Missing Files Sequence",
n = shardCount,
parallelism = 1000
)
val missingFiles =
allShardIndices
.minus(groupedData.keys("Grouped Data Keys"))
.map("Missing Files Map") { fileIndex -> kvOf(fileIndex, emptyList<T>().asIterable()) }
.setCoder(groupedData.coder)
val filesWritten =
PCollectionList.of(groupedData)
.and(missingFiles)
.flatten("Flatten groupedData+missingFiles")
.setCoder(groupedData.coder)
.apply("Write $fileSpec", ParDo.of(WriteFilesFn(fileSpec, storageFactory)))
return WriteResult(filesWritten)
}
}
private class WriteFilesFn<T : Message>(
private val fileSpec: String,
private val storageFactory: StorageFactory
) : DoFn<KV<Int, Iterable<@JvmWildcard T>>, String>() {
@ProcessElement
fun processElement(context: ProcessContext) {
val pipelineOptions = context.getPipelineOptions()
val kv = context.element()
val blobKey = ShardedFileName(fileSpec).fileNameForShard(kv.key)
val storageClient = storageFactory.build(pipelineOptions)
val messageFlow = kv.value.asFlow().map { it.toDelimitedByteString() }
runBlocking(Dispatchers.IO) { storageClient.writeBlob(blobKey, messageFlow) }
context.output(blobKey)
}
}
/** Returns an [Int] shard index for [this]. */
fun Any.assignToShard(shardCount: Int): Int {
// The conversion to Long avoids the special case where abs(Int.MIN_VALUE) returns Int.MIN_VALUE.
val longShard = abs(hashCode().toLong()) % shardCount
return longShard.toInt()
}
| apache-2.0 | 448bb32767117baf7ad92a028a8c3169 | 35.067797 | 99 | 0.735432 | 4.003763 | false | false | false | false |
hidroh/tldroid | app/src/androidTest/kotlin/io/github/hidroh/tldroid/NetworkConnection.kt | 1 | 865 | package io.github.hidroh.tldroid
import java.io.IOException
import java.io.InputStream
class NetworkConnection(url: String) {
companion object {
private var responseCode: Int = 0
private var lastModified: Long = 0L
private var response: InputStream? = null
fun mockResponse(responseCode: Int, lastModified: Long, response: InputStream?) {
NetworkConnection.responseCode = responseCode
NetworkConnection.lastModified = lastModified
NetworkConnection.response = response
}
}
fun connect() {
}
fun disconnect() {
try { response?.close() } catch (e: IOException) { }
}
fun getResponseCode(): Int {
return responseCode
}
fun getInputStream(): InputStream? {
return response
}
fun setIfModifiedSince(ifModifiedSince: Long) {
}
fun getLastModified(): Long {
return lastModified
}
} | apache-2.0 | 9fe9563bc46f3b96ec79d32c46008435 | 20.65 | 85 | 0.698266 | 4.552632 | false | false | false | false |
arkon/LISTEN.moe-Unofficial-Android-App | app/src/main/java/me/echeung/moemoekyun/service/auto/AutoMediaBrowserService.kt | 1 | 2369 | package me.echeung.moemoekyun.service.auto
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaDescriptionCompat
import androidx.media.MediaBrowserServiceCompat
import me.echeung.moemoekyun.App
import me.echeung.moemoekyun.R
import me.echeung.moemoekyun.service.RadioService
class AutoMediaBrowserService : MediaBrowserServiceCompat(), ServiceConnection {
override fun onCreate() {
super.onCreate()
if (App.service != null) {
setSessionToken()
} else {
val intent = Intent(applicationContext, RadioService::class.java)
applicationContext.bindService(intent, this, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT)
}
}
override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? {
return BrowserRoot(MEDIA_ID_ROOT, null)
}
override fun onLoadChildren(parentId: String, result: Result<List<MediaBrowserCompat.MediaItem>>) {
val mediaItems = listOf(
createPlayableMediaItem(RadioService.LIBRARY_JPOP, resources.getString(R.string.jpop)),
createPlayableMediaItem(RadioService.LIBRARY_KPOP, resources.getString(R.string.kpop))
)
result.sendResult(mediaItems)
}
override fun onServiceConnected(className: ComponentName, service: IBinder) {
val binder = service as RadioService.ServiceBinder
val radioService = binder.service
App.service = radioService
setSessionToken()
}
override fun onServiceDisconnected(arg0: ComponentName) {
}
private fun setSessionToken() {
val mediaSession = App.service!!.mediaSession
sessionToken = mediaSession!!.sessionToken
}
private fun createPlayableMediaItem(mediaId: String, title: String): MediaBrowserCompat.MediaItem {
val builder = MediaDescriptionCompat.Builder()
.setMediaId(mediaId)
.setTitle(title)
return MediaBrowserCompat.MediaItem(builder.build(), MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)
}
companion object {
private const val MEDIA_ID_ROOT = "media_root"
}
}
| mit | 4e1840573a1a49b6b6fba1fddfeb6077 | 33.333333 | 108 | 0.721401 | 4.864476 | false | false | false | false |
dataloom/datastore | src/main/kotlin/com/openlattice/entitysets/controllers/EntitySetsController.kt | 1 | 27482 | /*
* Copyright (C) 2018. OpenLattice, Inc.
*
* 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/>.
*
* You can contact the owner of the copyright at [email protected]
*/
package com.openlattice.entitysets.controllers
import com.codahale.metrics.annotation.Timed
import com.google.common.base.Preconditions
import com.google.common.collect.ImmutableMap
import com.google.common.collect.Lists
import com.google.common.collect.Maps
import com.openlattice.auditing.AuditEventType
import com.openlattice.auditing.AuditRecordEntitySetsManager
import com.openlattice.auditing.AuditableEvent
import com.openlattice.auditing.AuditingComponent
import com.openlattice.auditing.AuditingManager
import com.openlattice.authorization.*
import com.openlattice.authorization.EdmAuthorizationHelper.READ_PERMISSION
import com.openlattice.authorization.securable.SecurableObjectType
import com.openlattice.authorization.util.getLastAclKeySafely
import com.openlattice.controllers.exceptions.ForbiddenException
import com.openlattice.controllers.exceptions.wrappers.BatchException
import com.openlattice.controllers.exceptions.wrappers.ErrorsDTO
import com.openlattice.controllers.util.ApiExceptions
import com.openlattice.data.DataDeletionManager
import com.openlattice.data.DataGraphManager
import com.openlattice.data.DeleteType
import com.openlattice.data.WriteEvent
import com.openlattice.data.storage.partitions.PartitionManager
import com.openlattice.datastore.services.EdmManager
import com.openlattice.datastore.services.EntitySetManager
import com.openlattice.edm.EntitySet
import com.openlattice.edm.requests.MetadataUpdate
import com.openlattice.edm.set.EntitySetFlag
import com.openlattice.edm.set.EntitySetPropertyMetadata
import com.openlattice.edm.type.PropertyType
import com.openlattice.entitysets.EntitySetsApi
import com.openlattice.entitysets.EntitySetsApi.Companion.ALL
import com.openlattice.entitysets.EntitySetsApi.Companion.BY_ID_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.BY_NAME_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.EXPIRATION_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.ID
import com.openlattice.entitysets.EntitySetsApi.Companion.IDS_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.ID_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.LINKING
import com.openlattice.entitysets.EntitySetsApi.Companion.METADATA_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.NAME
import com.openlattice.entitysets.EntitySetsApi.Companion.NAME_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.PARTITIONS_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.PROPERTIES_PATH
import com.openlattice.entitysets.EntitySetsApi.Companion.PROPERTY_TYPE_ID
import com.openlattice.entitysets.EntitySetsApi.Companion.PROPERTY_TYPE_ID_PATH
import com.openlattice.linking.util.PersonProperties
import com.openlattice.organizations.roles.SecurePrincipalsManager
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.OffsetDateTime
import java.util.*
import java.util.stream.Collectors
import javax.inject.Inject
import kotlin.streams.asSequence
@SuppressFBWarnings(
value = ["BC_BAD_CAST_TO_ABSTRACT_COLLECTION"],
justification = "Allowing kotlin collection mapping cast to List"
)
@RestController
@RequestMapping(EntitySetsApi.CONTROLLER)
class EntitySetsController @Inject
constructor(
private val authorizations: AuthorizationManager,
private val edmManager: EdmManager,
private val aresManager: AuditRecordEntitySetsManager,
private val auditingManager: AuditingManager,
private val dgm: DataGraphManager,
private val spm: SecurePrincipalsManager,
private val authzHelper: EdmAuthorizationHelper,
private val deletionManager: DataDeletionManager,
private val entitySetManager: EntitySetManager,
private val partitionManager: PartitionManager
) : EntitySetsApi, AuthorizingComponent, AuditingComponent {
override fun getAuditingManager(): AuditingManager {
return auditingManager
}
@Timed
@RequestMapping(path = [LINKING + ID_PATH], method = [RequestMethod.PUT])
override fun addEntitySetsToLinkingEntitySet(
@PathVariable(ID) linkingEntitySetId: UUID,
@RequestBody entitySetIds: Set<UUID>
): Int {
return addEntitySets(linkingEntitySetId, entitySetIds)
}
@Timed
@RequestMapping(path = [LINKING], method = [RequestMethod.POST])
override fun addEntitySetsToLinkingEntitySets(@RequestBody entitySetIds: Map<UUID, Set<UUID>>): Int {
return entitySetIds.map { addEntitySets(it.key, it.value) }.sum()
}
private fun addEntitySets(linkingEntitySetId: UUID, entitySetIds: Set<UUID>): Int {
ensureOwnerAccess(AclKey(linkingEntitySetId))
Preconditions.checkState(
entitySetManager.getEntitySet(linkingEntitySetId)!!.isLinking,
"Can't add linked entity sets to a not linking entity set"
)
checkLinkedEntitySets(entitySetIds)
ensureValidLinkedEntitySets(entitySetIds)
return entitySetManager.addLinkedEntitySets(linkingEntitySetId, entitySetIds)
}
@Timed
@RequestMapping(path = [LINKING + ID_PATH], method = [RequestMethod.DELETE])
override fun removeEntitySetsFromLinkingEntitySet(
@PathVariable(ID) linkingEntitySetId: UUID,
@RequestBody entitySetIds: Set<UUID>
): Int {
return removeEntitySets(linkingEntitySetId, entitySetIds)
}
@Timed
@RequestMapping(path = [LINKING], method = [RequestMethod.DELETE])
override fun removeEntitySetsFromLinkingEntitySets(@RequestBody entitySetIds: Map<UUID, Set<UUID>>): Int {
return entitySetIds.map { removeEntitySets(it.key, it.value) }.sum()
}
@Timed
@RequestMapping(
path = ["", "/"], method = [RequestMethod.POST],
consumes = [MediaType.APPLICATION_JSON_VALUE], produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun createEntitySets(@RequestBody entitySets: Set<EntitySet>): Map<String, UUID> {
checkPermissionsForCreate(entitySets)
val dto = ErrorsDTO()
val createdEntitySets = Maps.newHashMapWithExpectedSize<String, UUID>(entitySets.size)
val auditableEvents = Lists.newArrayListWithExpectedSize<AuditableEvent>(entitySets.size)
for (entitySet in entitySets) {
try {
// validity insurance is handled in this call
createdEntitySets[entitySet.name] = entitySetManager
.createEntitySet(Principals.getCurrentUser(), entitySet)
auditableEvents.add(
AuditableEvent(
spm.currentUserId,
AclKey(entitySet.id),
AuditEventType.CREATE_ENTITY_SET,
"Created entity set through EntitySetsApi.createEntitySets",
Optional.empty(),
ImmutableMap.of("entitySet", entitySet),
OffsetDateTime.now(),
Optional.empty()
)
)
} catch (e: Exception) {
deleteAuditEntitySetsForId(entitySet.id)
dto.addError(ApiExceptions.OTHER_EXCEPTION, entitySet.name + ": " + e.message)
}
}
recordEvents(auditableEvents)
if (!dto.isEmpty()) {
throw BatchException(dto)
}
return createdEntitySets
}
@Timed
@RequestMapping(path = ["", "/"], method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE])
override fun getEntitySets(): Set<EntitySet> {
val entitySetIds = authorizations.getAuthorizedObjectsOfType(
Principals.getCurrentPrincipals(),
SecurableObjectType.EntitySet,
EnumSet.of(Permission.READ)
)
.asSequence()
.mapNotNull { getLastAclKeySafely(it) }
.toSet()
return entitySetManager.getEntitySetsAsMap(entitySetIds).values.toSet()
}
@Timed
@RequestMapping(
path = [BY_ID_PATH],
method = [RequestMethod.POST],
consumes = [MediaType.APPLICATION_JSON_VALUE],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun getEntitySetsById(@RequestBody entitySetIds: Set<UUID>): Map<UUID, EntitySet> {
accessCheck(entitySetIds.map { AclKey(it) to EnumSet.of(Permission.READ) }.toMap())
val entitySets = entitySetManager.getEntitySetsAsMap(entitySetIds)
val now = OffsetDateTime.now()
val events = entitySets.map {
AuditableEvent(
spm.currentUserId,
AclKey(it.key),
AuditEventType.READ_ENTITY_SET,
"EntitySet read through EntitySetsApi.getEntitySetsById",
Optional.empty(),
ImmutableMap.of(),
now,
Optional.empty()
)
}.toList()
recordEvents(events)
return entitySets
}
@Timed
@RequestMapping(
path = [BY_NAME_PATH],
method = [RequestMethod.POST],
consumes = [MediaType.APPLICATION_JSON_VALUE],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun getEntitySetsByName(@RequestBody entitySetNames: Set<String>): Map<String, EntitySet> {
val entitySetIds = edmManager.getAclKeyIds(entitySetNames).values.toSet()
accessCheck(entitySetIds.map { AclKey(it) to EnumSet.of(Permission.READ) }.toMap())
val entitySets = entitySetManager.getEntitySetsAsMap(entitySetIds)
val now = OffsetDateTime.now()
val events = entitySets.map {
AuditableEvent(
spm.currentUserId,
AclKey(it.key),
AuditEventType.READ_ENTITY_SET,
"EntitySet read through EntitySetsApi.getEntitySetsByName",
Optional.empty(),
ImmutableMap.of(),
now,
Optional.empty()
)
}.toList()
recordEvents(events)
return entitySets.mapKeys { entry -> entry.value.name }
}
@Timed
@RequestMapping(path = [ALL + ID_PATH], method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE])
override fun getEntitySet(@PathVariable(ID) entitySetId: UUID): EntitySet {
ensureReadAccess(AclKey(entitySetId))
recordEvent(
AuditableEvent(
spm.currentUserId,
AclKey(entitySetId),
AuditEventType.READ_ENTITY_SET,
"Entity set read through EntitySetsApi.getEntitySet",
Optional.empty(),
ImmutableMap.of(),
OffsetDateTime.now(),
Optional.empty()
)
)
return entitySetManager.getEntitySet(entitySetId)!!
}
@Timed
@RequestMapping(path = [ALL + ID_PATH], method = [RequestMethod.DELETE])
override fun deleteEntitySet(@PathVariable(ID) entitySetId: UUID): Int {
val entitySet = checkPermissionsForDelete(entitySetId)
ensureEntitySetCanBeDeleted(entitySet)
/* Delete first entity set data */
val deleted = if (!entitySet.isLinking) {
// associations need to be deleted first, because edges are deleted in DataGraphManager.deleteEntitySet call
deletionManager.clearOrDeleteEntitySetIfAuthorized(
entitySet.id, DeleteType.Hard, Principals.getCurrentPrincipals()
)
} else {
// linking entitysets have no entities or associations
WriteEvent(System.currentTimeMillis(), 1)
}
deleteAuditEntitySetsForId(entitySetId)
entitySetManager.deleteEntitySet(entitySet)
recordEvent(
AuditableEvent(
spm.currentUserId,
AclKey(entitySetId),
AuditEventType.DELETE_ENTITY_SET,
"Entity set deleted through EntitySetsApi.deleteEntitySet",
Optional.empty(),
ImmutableMap.of(),
OffsetDateTime.now(),
Optional.empty()
)
)
return deleted.numUpdates
}
private fun deleteAuditEntitySetsForId(entitySetId: UUID) {
val aclKey = AclKey(entitySetId)
aresManager.getAuditEdgeEntitySets(aclKey).forEach {
val auditEdgeEntitySet = entitySetManager.getEntitySet(it)!!
deletionManager.clearOrDeleteEntitySet(it, DeleteType.Hard)
entitySetManager.deleteEntitySet(auditEdgeEntitySet)
}
aresManager.getAuditRecordEntitySets(aclKey).forEach {
val auditEntitySet = entitySetManager.getEntitySet(it)!!
deletionManager.clearOrDeleteEntitySet(it, DeleteType.Hard)
entitySetManager.deleteEntitySet(auditEntitySet)
}
aresManager.removeAuditRecordEntitySetConfiguration(aclKey)
}
@Timed
@RequestMapping(
path = [IDS_PATH + NAME_PATH],
method = [RequestMethod.GET],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun getEntitySetId(@PathVariable(NAME) entitySetName: String): UUID {
val esId = entitySetManager.getEntitySet(entitySetName)?.id
?: throw NullPointerException("Entity Set $entitySetName does not exists.")
ensureReadAccess(AclKey(esId))
return esId
}
@Timed
@RequestMapping(
path = [IDS_PATH],
method = [RequestMethod.POST],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun getEntitySetIds(@RequestBody entitySetNames: Set<String>): Map<String, UUID> {
val entitySetIds = edmManager.getAclKeyIds(entitySetNames)
entitySetIds.values.forEach { entitySetId -> ensureReadAccess(AclKey(entitySetId)) }
return entitySetIds
}
@Timed
@RequestMapping(
path = [ALL + ID_PATH + METADATA_PATH],
method = [RequestMethod.PATCH],
consumes = [MediaType.APPLICATION_JSON_VALUE]
)
override fun updateEntitySetMetadata(
@PathVariable(ID) entitySetId: UUID,
@RequestBody update: MetadataUpdate
): Int {
ensureOwnerAccess(AclKey(entitySetId))
entitySetManager.updateEntitySetMetadata(entitySetId, update)
recordEvent(
AuditableEvent(
spm.currentUserId,
AclKey(entitySetId),
AuditEventType.UPDATE_ENTITY_SET,
"Entity set metadata updated through EntitySetsApi.updateEntitySetMetadata",
Optional.empty(),
ImmutableMap.of("update", update),
OffsetDateTime.now(),
Optional.empty()
)
)
//TODO: Return number of fields updated? Low priority.
return 1
}
@Timed
@RequestMapping(
path = [ALL + METADATA_PATH],
method = [RequestMethod.POST],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun getPropertyMetadataForEntitySets(
@RequestBody entitySetIds: Set<UUID>
): Map<UUID, Map<UUID, EntitySetPropertyMetadata>> {
val accessChecks = entitySetIds.map { id -> AccessCheck(AclKey(id), EnumSet.of(Permission.READ)) }.toSet()
authorizations
.accessChecksForPrincipals(accessChecks, Principals.getCurrentPrincipals())
.forEach { authorization ->
if (!authorization.permissions.getValue(Permission.READ)) {
throw ForbiddenException(
"AclKey " + authorization.aclKey.toString() + " is not authorized."
)
}
}
return entitySetManager.getAllEntitySetPropertyMetadataForIds(entitySetIds)
}
@Timed
@RequestMapping(
path = [ALL + ID_PATH + METADATA_PATH],
method = [RequestMethod.GET],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun getAllEntitySetPropertyMetadata(
@PathVariable(ID) entitySetId: UUID
): Map<UUID, EntitySetPropertyMetadata> {
//You should be able to get properties without having read access
ensureReadAccess(AclKey(entitySetId))
return entitySetManager.getAllEntitySetPropertyMetadata(entitySetId)
}
@Timed
@RequestMapping(
path = [ALL + ID_PATH + PROPERTIES_PATH + PROPERTY_TYPE_ID_PATH],
method = [RequestMethod.GET],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun getEntitySetPropertyMetadata(
@PathVariable(ID) entitySetId: UUID,
@PathVariable(PROPERTY_TYPE_ID) propertyTypeId: UUID
): EntitySetPropertyMetadata {
ensureReadAccess(AclKey(entitySetId, propertyTypeId))
return entitySetManager.getEntitySetPropertyMetadata(entitySetId, propertyTypeId)
}
@Timed
@GetMapping(
value = [ALL + ID_PATH + PROPERTIES_PATH],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun getPropertyTypesForEntitySet(@PathVariable(ID) entitySetId: UUID): Map<UUID, PropertyType> {
//We only check for entity set metadata read access.
ensureReadAccess(AclKey(entitySetId))
return entitySetManager.getPropertyTypesForEntitySet(entitySetId)
}
@Timed
@RequestMapping(
path = [ALL + ID_PATH + PROPERTIES_PATH + PROPERTY_TYPE_ID_PATH],
method = [RequestMethod.POST],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun updateEntitySetPropertyMetadata(
@PathVariable(ID) entitySetId: UUID,
@PathVariable(PROPERTY_TYPE_ID) propertyTypeId: UUID,
@RequestBody update: MetadataUpdate
): Int {
ensureOwnerAccess(AclKey(entitySetId, propertyTypeId))
entitySetManager.updateEntitySetPropertyMetadata(entitySetId, propertyTypeId, update)
recordEvent(
AuditableEvent(
spm.currentUserId,
AclKey(entitySetId, propertyTypeId),
AuditEventType.UPDATE_ENTITY_SET_PROPERTY_METADATA,
"Entity set property metadata updated through EntitySetsApi.updateEntitySetPropertyMetadata",
Optional.empty(),
ImmutableMap.of("update", update),
OffsetDateTime.now(),
Optional.empty()
)
)
//TODO: Makes this return something more useful.
return 1
}
@Timed
@RequestMapping(
path = [ALL + ID_PATH + EXPIRATION_PATH],
method = [RequestMethod.PATCH],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
override fun removeDataExpirationPolicy(
@PathVariable(ID) entitySetId: UUID
): Int {
ensureOwnerAccess(AclKey(entitySetId))
entitySetManager.removeDataExpirationPolicy(entitySetId)
recordEvent(
AuditableEvent(
spm.currentUserId,
AclKey(entitySetId),
AuditEventType.UPDATE_ENTITY_SET,
"Entity set data expiration policy removed through EntitySetsApi.removeDataExpirationPolicy",
Optional.empty(),
ImmutableMap.of("entitySetId", entitySetId),
OffsetDateTime.now(),
Optional.empty()
)
)
return 1
}
@Timed
@RequestMapping(
path = [ALL + ID_PATH + EXPIRATION_PATH],
method = [RequestMethod.POST]
)
override fun getExpiringEntitiesFromEntitySet(
@PathVariable(ID) entitySetId: UUID,
@RequestBody dateTime: String
): Set<UUID> {
ensureReadAccess(AclKey(entitySetId))
val es = entitySetManager.getEntitySet(entitySetId)!!
check(es.hasExpirationPolicy()) { "Entity set ${es.name} does not have an expiration policy" }
val expirationPolicy = es.expiration!!
val expirationPT = expirationPolicy.startDateProperty.map { edmManager.getPropertyType(it) }
recordEvent(
AuditableEvent(
spm.currentUserId,
AclKey(entitySetId),
AuditEventType.READ_ENTITY_SET,
"EntitySetsApi.getExpiringEntitiesFromEntitySet() returned entity key ids",
Optional.empty(),
ImmutableMap.of("entitySetId", entitySetId),
OffsetDateTime.now(),
Optional.empty()
)
)
return dgm.getExpiringEntitiesFromEntitySet(
entitySetId,
expirationPolicy,
OffsetDateTime.parse(dateTime),
expirationPolicy.deleteType,
expirationPT
).toSet()
}
private fun removeEntitySets(linkingEntitySetId: UUID, entitySetIds: Set<UUID>): Int {
ensureOwnerAccess(AclKey(linkingEntitySetId))
Preconditions.checkState(
entitySetManager.getEntitySet(linkingEntitySetId)!!.isLinking,
"Can't remove linked entity sets from a not linking entity set"
)
checkLinkedEntitySets(entitySetIds)
return entitySetManager.removeLinkedEntitySets(linkingEntitySetId, entitySetIds)
}
private fun checkLinkedEntitySets(entitySetIds: Set<UUID>) {
Preconditions.checkState(entitySetIds.isNotEmpty(), "Linked entity sets is empty")
}
private fun ensureValidLinkedEntitySets(entitySetIds: Set<UUID>) {
val entityTypeId = edmManager.getEntityType(PersonProperties.PERSON_TYPE_FQN).id
Preconditions.checkState(
entitySetIds.stream()
.map { entitySetManager.getEntitySet(it)!!.entityTypeId }
.allMatch { entityTypeId == it },
"Linked entity sets are of differing entity types than %s :{}",
PersonProperties.PERSON_TYPE_FQN.fullQualifiedNameAsString, entitySetIds
)
Preconditions.checkState(
entitySetIds.all { !entitySetManager.getEntitySet(it)!!.isLinking },
"Cannot add linking entity set as linked entity set."
)
}
private fun ensureEntitySetCanBeDeleted(entitySet: EntitySet) {
val entitySetId = entitySet.id
ensureObjectCanBeDeleted(entitySetId)
if (entitySet.flags.contains(EntitySetFlag.AUDIT)) {
throw ForbiddenException("You cannot delete entity set $entitySetId because it is an audit entity set.")
}
}
private fun checkPermissionsForCreate(entitySets: Set<EntitySet>) {
// check read on organization
val organizationIds = entitySets.map { it.organizationId }.toSet()
val authorizedOrganizationIds = authorizations
.accessChecksForPrincipals(
organizationIds.map { AccessCheck(AclKey(it), READ_PERMISSION) }.toSet(),
Principals.getCurrentPrincipals()
)
.filter { it.permissions.contains(Permission.READ) }
.map { it.aclKey[0] }
.collect(Collectors.toSet())
if (authorizedOrganizationIds.size < organizationIds.size) {
throw ForbiddenException(
"Can't create entity sets, missing read permissions on organizations with ids " +
"${organizationIds.subtract(authorizedOrganizationIds)}"
)
}
// if it's a linking entity set, check link on linked entity sets
val linkedEntitySetIds = entitySets.filter { it.isLinking }.flatMap { it.linkedEntitySets }.toSet()
val authorizedLinkedEntitySetIds = authorizations
.accessChecksForPrincipals(
linkedEntitySetIds.map { AccessCheck(AclKey(it), EnumSet.of(Permission.LINK)) }.toSet(),
Principals.getCurrentPrincipals()
)
.filter { it.permissions.contains(Permission.LINK) }
.map { it.aclKey[0] }
.collect(Collectors.toSet())
if (authorizedLinkedEntitySetIds.size < linkedEntitySetIds.size) {
throw ForbiddenException(
"Can't create linking entity entity sets, missing link permissions on linked entity sets with " +
"ids ${linkedEntitySetIds.subtract(authorizedLinkedEntitySetIds)}"
)
}
}
private fun checkPermissionsForDelete(entitySetId: UUID): EntitySet {
ensureOwnerAccess(AclKey(entitySetId))
val entitySet = entitySetManager.getEntitySet(entitySetId)!!
val entityType = edmManager.getEntityType(entitySet.entityTypeId)
val authorizedPropertyTypes = authzHelper
.getAuthorizedPropertyTypes(entitySetId, EdmAuthorizationHelper.OWNER_PERMISSION)
val missingPropertyTypes = entityType.properties.subtract(authorizedPropertyTypes.keys)
if (missingPropertyTypes.isNotEmpty()) {
throw ForbiddenException(
"Cannot delete entity set. Missing ${Permission.OWNER} permission for property " +
"types $missingPropertyTypes."
)
}
return entitySet
}
@Timed
@PutMapping(value = [ID_PATH + PARTITIONS_PATH])
override fun repartitionEntitySet(@PathVariable(ID) entitySetId: UUID, @RequestBody partitions: Set<Int>): UUID {
ensureAdminAccess()
require ( entitySetManager.exists( entitySetId ) ) { "Entity set must exist."}
val oldPartitions = partitionManager.getEntitySetPartitions(entitySetId)
return dgm.repartitionEntitySet(entitySetId, oldPartitions, partitions)
}
override fun getAuthorizationManager(): AuthorizationManager {
return authorizations
}
} | gpl-3.0 | 64085cc25c630c2d9b749b66515d6b59 | 39.958271 | 120 | 0.641875 | 5.132985 | false | false | false | false |
tasomaniac/OpenLinkWith | resolver/src/main/kotlin/com/tasomaniac/openwith/util/IntentFixer.kt | 1 | 2049 | package com.tasomaniac.openwith.util
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import com.tasomaniac.openwith.extensions.extractAmazonASIN
object IntentFixer {
private val INTENT_FIXERS = arrayOf<Fixer>(
AmazonFixer()
)
@JvmStatic
fun fixIntents(context: Context, originalIntent: Intent): Intent {
var intent = originalIntent
for (intentFixer in INTENT_FIXERS) {
val fixedIntent = intentFixer.fix(context, intent)
if (context.packageManager.hasHandler(fixedIntent)) {
intent = fixedIntent
}
}
return intent
}
/**
* Queries on-device packages for a handler for the supplied [intent].
*/
private fun PackageManager.hasHandler(intent: Intent) = queryIntentActivities(intent, 0).isNotEmpty()
internal interface Fixer {
fun fix(context: Context, intent: Intent): Intent
}
private class AmazonFixer : Fixer {
/**
* If link contains amazon and it has ASIN in it, create a specific intent to open Amazon App.
*
* @param intent Original Intent with amazon link in it.
* @return Specific Intent for Amazon app.
*/
override fun fix(context: Context, intent: Intent): Intent {
val dataString = intent.dataString
if (dataString != null && dataString.contains("amazon")) {
val asin = extractAmazonASIN(dataString)
if (asin != null) {
return if ("0000000000" == asin) {
context.packageManager.getLaunchIntentForPackage(intent.component!!.packageName)!!
} else Intent(Intent.ACTION_VIEW).setDataAndType(
Uri.parse("mshop://featured?ASIN=$asin"),
"vnd.android.cursor.item/vnd.amazon.mShop.featured"
)
}
}
return intent
}
}
}
| apache-2.0 | ae41d82457415f74b2662ecffef8931f | 33.728814 | 106 | 0.601269 | 4.832547 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/segregated/AddCyclewaySegregation.kt | 1 | 1484 | package de.westnordost.streetcomplete.quests.segregated
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.ANYTHING_PAVED
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.ktx.toYesNo
class AddCyclewaySegregation : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
ways with
(
(highway = path and bicycle = designated and foot = designated)
or (highway = footway and bicycle = designated)
or (highway = cycleway and foot ~ designated|yes)
)
and surface ~ ${ANYTHING_PAVED.joinToString("|")}
and area != yes
and !sidewalk
and (!segregated or segregated older today -8 years)
"""
override val commitMessage = "Add segregated status for combined footway with cycleway"
override val wikiLink = "Key:segregated"
override val icon = R.drawable.ic_quest_path_segregation
override val isSplitWayEnabled = true
override fun getTitle(tags: Map<String, String>) = R.string.quest_segregated_title
override fun createForm() = AddCyclewaySegregationForm()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("segregated", answer.toYesNo())
}
}
| gpl-3.0 | 6877a46e6b28f054fb74e60d0b18907b | 38.052632 | 91 | 0.734501 | 4.681388 | false | false | false | false |
FelixKlauke/mercantor | client/src/main/kotlin/de/d3adspace/mercantor/client/util/RoundRobinList.kt | 1 | 935 | package de.d3adspace.mercantor.client.util
/**
* @author Felix Klauke <[email protected]>
*/
class RoundRobinList<ContentType>(private var content: MutableList<ContentType>) {
private var currentPosition: Int = 0
val isEmpty: Boolean
get() = content.isEmpty()
fun getContent(): List<ContentType> = content
fun setContent(content: MutableList<ContentType>) {
this.content = content
}
fun size(): Int = content.size
fun add(element: ContentType): Boolean = content.add(element)
fun remove(element: ContentType) = content.remove(element)
fun get(): ContentType {
if (content.isEmpty()) {
throw IllegalStateException("I don't have any elements.")
}
if (currentPosition == content.size) {
currentPosition = 0
}
val element = content[currentPosition]
currentPosition++
return element
}
}
| mit | 1e5574a98d08d95d8560eb845ff209f7 | 22.974359 | 82 | 0.638503 | 4.516908 | false | false | false | false |
ScheNi/android-material-stepper | sample/src/main/java/com/stepstone/stepper/sample/step/view/StepViewSample.kt | 2 | 2228 | package com.stepstone.stepper.sample.step.view
import android.content.Context
import android.text.Html
import android.view.LayoutInflater
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.FrameLayout
import com.stepstone.stepper.Step
import com.stepstone.stepper.VerificationError
import com.stepstone.stepper.sample.OnNavigationBarListener
import com.stepstone.stepper.sample.R
/**
* Created by leonardo on 18/12/16.
*/
class StepViewSample(context: Context) : FrameLayout(context), Step {
companion object {
private const val TAP_THRESHOLD = 2
}
private var i = 0
private var onNavigationBarListener: OnNavigationBarListener? = null
private var button: Button? = null
init {
init(context)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val c = context
if (c is OnNavigationBarListener) {
this.onNavigationBarListener = c
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
this.onNavigationBarListener = null
}
@Suppress("DEPRECATION")
private fun init(context: Context) {
val v = LayoutInflater.from(context).inflate(R.layout.fragment_step, this, true)
button = v.findViewById(R.id.button) as Button
updateNavigationBar()
button = v.findViewById(R.id.button) as Button
button?.text = Html.fromHtml("Taps: <b>$i</b>")
button?.setOnClickListener {
button?.text = Html.fromHtml("Taps: <b>${++i}</b>")
updateNavigationBar()
}
}
private val isAboveThreshold: Boolean
get() = i >= TAP_THRESHOLD
override fun verifyStep(): VerificationError? {
return if (isAboveThreshold) null else VerificationError("Click ${TAP_THRESHOLD - i} more times!")
}
private fun updateNavigationBar() {
onNavigationBarListener?.onChangeEndButtonsEnabled(isAboveThreshold)
}
override fun onSelected() {
updateNavigationBar()
}
override fun onError(error: VerificationError) {
button?.startAnimation(AnimationUtils.loadAnimation(context, R.anim.shake_error))
}
}
| apache-2.0 | f6076d34487403892b6cb722dfc004e3 | 26.170732 | 106 | 0.682226 | 4.482897 | false | false | false | false |
apollostack/apollo-android | apollo-normalized-cache-api/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/CacheKey.kt | 1 | 658 | package com.apollographql.apollo3.cache.normalized
import kotlin.jvm.JvmField
import kotlin.jvm.JvmStatic
/**
* A key for a [Record] used for normalization in a [NormalizedCache].
* If the json object which the [Record] corresponds to does not have a suitable
* key, return use [NO_KEY].
*/
class CacheKey(val key: String) {
override fun equals(other: Any?): Boolean {
return key == (other as? CacheKey)?.key
}
override fun hashCode(): Int = key.hashCode()
override fun toString(): String = key
companion object {
@JvmField
val NO_KEY = CacheKey("")
@JvmStatic
fun from(key: String): CacheKey = CacheKey(key)
}
}
| mit | 7ae78069712a9b17c977302ba43235bd | 20.933333 | 80 | 0.68541 | 3.870588 | false | false | false | false |
almapp/uc-access-android-old | app/src/main/java/com/lopezjuri/uc_accesss/WebPageDetailFragment.kt | 1 | 2198 | package com.lopezjuri.uc_accesss
import android.app.Activity
import android.support.design.widget.CollapsingToolbarLayout
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.lopezjuri.uc_accesss.dummy.DummyContent
/**
* A fragment representing a single WebPage detail screen.
* This fragment is either contained in a [WebPageListActivity]
* in two-pane mode (on tablets) or a [WebPageDetailActivity]
* on handsets.
*/
class WebPageDetailFragment : Fragment() {
/**
* The dummy content this fragment is presenting.
*/
private var mItem: DummyContent.DummyItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments.containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem = DummyContent.ITEM_MAP[arguments.getString(ARG_ITEM_ID)]
val activity = this.activity
val appBarLayout = activity.findViewById(R.id.toolbar_layout) as CollapsingToolbarLayout
if (appBarLayout != null) {
appBarLayout.title = mItem!!.content
}
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater!!.inflate(R.layout.webpage_detail, container, false)
// Show the dummy content as text in a TextView.
if (mItem != null) {
(rootView.findViewById(R.id.webpage_detail) as TextView).text = mItem!!.details
}
return rootView
}
companion object {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
val ARG_ITEM_ID = "item_id"
}
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
| gpl-3.0 | 577bd8135e9d1ba33988a3872ab8292b | 31.80597 | 100 | 0.666515 | 4.579167 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingResponsePacket.kt | 1 | 1398 | package info.nightscout.androidaps.diaconn.packet
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.diaconn.DiaconnG8Pump
import info.nightscout.shared.logging.LTag
import javax.inject.Inject
/**
* SoundSettingResponsePacket
*/
class SoundSettingResponsePacket(
injector: HasAndroidInjector
) : DiaconnG8Packet(injector ) {
@Inject lateinit var diaconnG8Pump: DiaconnG8Pump
var result = 0
init {
msgType = 0x8D.toByte()
aapsLogger.debug(LTag.PUMPCOMM, "SoundSettingResponsePacket init")
}
override fun handleMessage(data: ByteArray?) {
val defectCheck = defect(data)
if (defectCheck != 0) {
aapsLogger.debug(LTag.PUMPCOMM, "SoundSettingResponsePacket Got some Error")
failed = true
return
} else failed = false
val bufferData = prefixDecode(data)
result = getByteToInt(bufferData)
if(!isSuccSettingResponseResult(result)) {
diaconnG8Pump.resultErrorCode = result
failed = true
return
}
diaconnG8Pump.otpNumber = getIntToInt(bufferData)
aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result")
aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}")
}
override fun getFriendlyName(): String {
return "PUMP_SOUND_SETTING_RESPONSE"
}
} | agpl-3.0 | 3bbbb67b61798833d183e6f7292cbfab | 28.765957 | 88 | 0.674535 | 4.613861 | false | false | false | false |
wesamhaboush/kotlin-algorithms | src/main/kotlin/algorithms/coded-triangle-words.kt | 1 | 1419 | package algorithms
import java.io.File
/*
Coded triangle numbers
Problem 42
The nth term of the sequence of triangle numbers is given by, t(n) = (1/2)(n)(n+1);
so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical position
and adding these values we form a word value. For example, the word value for SKY is
19 + 11 + 25 = 55 = t(10).
If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly
two-thousand common English words, how many are triangle words?
*/
fun readFile(): Sequence<String> =
File(ClassLoader.getSystemResource("p042_words.txt").file)
.bufferedReader()
.lineSequence()
fun fileAsWords(): Sequence<String> = readFile()
.flatMap { it.split(',').asSequence() }
fun letterToNumber(letter: Char): Int = letter.toLowerCase().toInt() - 96
fun wordToNumber(word: String): Int = word.map { letterToNumber(it) }.sum()
fun countNumberOfTriangularWords(): Int = fileAsWords()
.map { unquote(it) }
.filter { isTriangularNumber(wordToNumber(it).toLong()) }
// .onEach { println("word: $it, number: ${wordToNumber(it)}") }
.count()
fun unquote(word: String) = word.substring(1, word.length - 1)
| gpl-3.0 | bf5ee9739f17d720b15386067b32abc6 | 33.609756 | 93 | 0.679352 | 3.647815 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/sub.kt | 1 | 277 | package venus.riscv.insts
import venus.riscv.insts.dsl.RTypeInstruction
val sub = RTypeInstruction(
name = "sub",
opcode = 0b0110011,
funct3 = 0b000,
funct7 = 0b0100000,
eval32 = { a, b -> a - b },
eval64 = { a, b -> a - b }
)
| mit | 7b03dcf09630ee6a4e28d667c02a8298 | 22.083333 | 45 | 0.548736 | 3.11236 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/favorite/FavoriteButton.kt | 1 | 1752 | package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.favorite
import android.content.Context
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.widget.ImageView
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.ui.dialogs.showExceptionDialog
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import javax.inject.Inject
abstract class FavoriteButton : ImageView, FavoriteButtonView {
constructor(context: Context) : super(context, null, R.attr.MirkoButtonStyle)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs, R.attr.MirkoButtonStyle)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@Inject lateinit var userManager : UserManagerApi
init {
WykopApp.uiInjector.inject(this)
setBackgroundResource(R.drawable.button_background_state_list)
isVisible = userManager.isUserAuthorized()
}
override var isFavorite : Boolean
get() = isSelected
set(value) {
if (value) {
isSelected = true
setImageDrawable(
ContextCompat.getDrawable(context, R.drawable.ic_favorite_selected)
)
} else {
isSelected = false
setImageDrawable(
ContextCompat.getDrawable(context, R.drawable.ic_favorite)
)
}
}
override fun showErrorDialog(e: Throwable) =
context.showExceptionDialog(e)
} | mit | 999b3901ae88d13eae856f46a0de9803 | 36.297872 | 111 | 0.700913 | 4.949153 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/navigationbar/NavigationBarModule.kt | 2 | 6923 | package abi44_0_0.expo.modules.navigationbar
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowInsets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsControllerCompat
import abi44_0_0.expo.modules.core.ExportedModule
import abi44_0_0.expo.modules.core.ModuleRegistry
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.errors.CurrentActivityNotFoundException
import abi44_0_0.expo.modules.core.interfaces.ActivityProvider
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
import abi44_0_0.expo.modules.core.interfaces.services.EventEmitter
class NavigationBarModule(context: Context) : ExportedModule(context) {
private lateinit var mActivityProvider: ActivityProvider
private lateinit var mEventEmitter: EventEmitter
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
?: throw IllegalStateException("Could not find implementation for ActivityProvider.")
mEventEmitter = moduleRegistry.getModule(EventEmitter::class.java) ?: throw IllegalStateException("Could not find implementation for EventEmitter.")
}
// Ensure that rejections are passed up to JS rather than terminating the native client.
private fun safeRunOnUiThread(promise: Promise, block: (activity: Activity) -> Unit) {
val activity = mActivityProvider.currentActivity
if (activity == null) {
promise.reject(CurrentActivityNotFoundException())
return
}
activity.runOnUiThread {
block(activity)
}
}
@ExpoMethod
fun setBackgroundColorAsync(color: Int, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBackgroundColor(it, color, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBackgroundColorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
val color = colorToHex(it.window.navigationBarColor)
promise.resolve(color)
}
}
@ExpoMethod
fun setBorderColorAsync(color: Int, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBorderColor(it, color, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBorderColorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val color = colorToHex(it.window.navigationBarDividerColor)
promise.resolve(color)
} else {
promise.reject(ERROR_TAG, "'getBorderColorAsync' is only available on Android API 28 or higher")
}
}
}
@ExpoMethod
fun setButtonStyleAsync(buttonStyle: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setButtonStyle(
it, buttonStyle,
{
promise.resolve(null)
},
{ m -> promise.reject(ERROR_TAG, m) }
)
}
}
@ExpoMethod
fun getButtonStyleAsync(promise: Promise) {
safeRunOnUiThread(promise) {
WindowInsetsControllerCompat(it.window, it.window.decorView).let { controller ->
val style = if (controller.isAppearanceLightNavigationBars) "dark" else "light"
promise.resolve(style)
}
}
}
@ExpoMethod
fun setVisibilityAsync(visibility: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setVisibility(it, visibility, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getVisibilityAsync(promise: Promise) {
safeRunOnUiThread(promise) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val visibility = if (it.window.decorView.rootWindowInsets.isVisible(WindowInsets.Type.navigationBars())) "visible" else "hidden"
promise.resolve(visibility)
} else {
// TODO: Verify this works
@Suppress("DEPRECATION") val visibility = if ((View.SYSTEM_UI_FLAG_HIDE_NAVIGATION and it.window.decorView.systemUiVisibility) == 0) "visible" else "hidden"
promise.resolve(visibility)
}
}
}
@ExpoMethod
fun setPositionAsync(position: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setPosition(it, position, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun unstable_getPositionAsync(promise: Promise) {
safeRunOnUiThread(promise) {
val position = if (ViewCompat.getFitsSystemWindows(it.window.decorView)) "relative" else "absolute"
promise.resolve(position)
}
}
@ExpoMethod
fun setBehaviorAsync(behavior: String, promise: Promise) {
safeRunOnUiThread(promise) {
NavigationBar.setBehavior(it, behavior, { promise.resolve(null) }, { m -> promise.reject(ERROR_TAG, m) })
}
}
@ExpoMethod
fun getBehaviorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
WindowInsetsControllerCompat(it.window, it.window.decorView).let { controller ->
val behavior = when (controller.systemBarsBehavior) {
// TODO: Maybe relative / absolute
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE -> "overlay-swipe"
WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE -> "inset-swipe"
// WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH -> "inset-touch"
else -> "inset-touch"
}
promise.resolve(behavior)
}
}
}
/* Events */
@ExpoMethod
fun startObserving(promise: Promise) {
safeRunOnUiThread(promise) {
val decorView = it.window.decorView
@Suppress("DEPRECATION")
decorView.setOnSystemUiVisibilityChangeListener { visibility: Int ->
var isNavigationBarVisible = (visibility and View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
var stringVisibility = if (isNavigationBarVisible) "visible" else "hidden"
mEventEmitter.emit(
VISIBILITY_EVENT_NAME,
Bundle().apply {
putString("visibility", stringVisibility)
putInt("rawVisibility", visibility)
}
)
}
promise.resolve(null)
}
}
@ExpoMethod
fun stopObserving(promise: Promise) {
safeRunOnUiThread(promise) {
val decorView = it.window.decorView
@Suppress("DEPRECATION")
decorView.setOnSystemUiVisibilityChangeListener(null)
promise.resolve(null)
}
}
companion object {
private const val NAME = "ExpoNavigationBar"
private const val VISIBILITY_EVENT_NAME = "ExpoNavigationBar.didChange"
private const val ERROR_TAG = "ERR_NAVIGATION_BAR"
fun colorToHex(color: Int): String {
return String.format("#%02x%02x%02x", Color.red(color), Color.green(color), Color.blue(color))
}
}
}
| bsd-3-clause | 38b75af9f22083ee149d14cfe7eb03e1 | 32.936275 | 164 | 0.700708 | 4.278739 | false | false | false | false |
notsyncing/lightfur | lightfur-integration-jdbc-ql/src/main/kotlin/io/github/notsyncing/lightfur/integration/jdbc/ql/JdbcRawQueryProcessor.kt | 1 | 1868 | package io.github.notsyncing.lightfur.integration.jdbc.ql
import io.github.notsyncing.lightfur.DataSession
import io.github.notsyncing.lightfur.entity.dsl.EntitySelectDSL
import io.github.notsyncing.lightfur.integration.jdbc.JdbcDataSession
import io.github.notsyncing.lightfur.ql.RawQueryProcessor
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.future.future
import java.sql.Array
import java.sql.ResultSet
import java.util.concurrent.CompletableFuture
class JdbcRawQueryProcessor : RawQueryProcessor {
private lateinit var db: JdbcDataSession
private fun currentRowToMap(rs: ResultSet): Map<String, Any?> {
val count = rs.metaData.columnCount
val map = mutableMapOf<String, Any?>()
for (i in 1..count) {
map.put(rs.metaData.getColumnLabel(i), rs.getObject(i))
}
return map
}
override fun resultSetToList(resultSet: Any?): List<Map<String, Any?>> {
if (resultSet is ResultSet) {
val list = mutableListOf<Map<String, Any?>>()
while (resultSet.next()) {
list.add(currentRowToMap(resultSet))
}
return list
} else {
throw UnsupportedOperationException("$resultSet is not an ${ResultSet::class.java}")
}
}
override fun processValue(value: Any?): Any? {
if (value is Array) {
return value.array
}
return value
}
override fun query(dsl: EntitySelectDSL<*>) = future {
db = DataSession.start()
try {
dsl.queryRaw(db).await()
} catch (e: Exception) {
e.printStackTrace()
db.end().await()
throw e
}
}
override fun end(): CompletableFuture<Unit> {
return db.end()
.thenApply { }
}
} | gpl-3.0 | 61eb48e99d48499cdbafcdcce2640feb | 26.895522 | 96 | 0.630086 | 4.447619 | false | false | false | false |
thatadamedwards/kotlin-koans | src/iv_properties/_32_Properties_.kt | 1 | 638 | package iv_properties
import util.TODO
import util.doc32
class PropertyExample {
var counter = 0
private var _propertyWithCounter: Int? = 0
var propertyWithCounter: Int?
get() = _propertyWithCounter
set(value) {
counter++
_propertyWithCounter = value
}
}
fun todoTask32(): Nothing = TODO(
"""
Task 32.
Add a custom setter to PropertyExample.propertyWithCounter so that
the 'counter' property is incremented every time 'propertyWithCounter' is assigned to.
""",
documentation = doc32(),
references = { PropertyExample() }
)
| mit | 78dd0a09198583edc81976fbf94f0754 | 24.52 | 94 | 0.626959 | 4.656934 | false | false | false | false |
ThoseGrapefruits/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustTraitMethodImplMixin.kt | 1 | 979 | package org.rust.lang.core.psi.impl.mixin
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.Iconable
import org.rust.lang.core.psi.RustTraitMethod
import org.rust.lang.core.psi.RustTypeMethod
import org.rust.lang.core.psi.impl.RustCompositeElementImpl
import org.rust.lang.icons.*
import javax.swing.Icon
abstract class RustTraitMethodImplMixin(node: ASTNode) : RustCompositeElementImpl(node), RustTraitMethod {
override fun getIcon(flags: Int): Icon? {
var icon = if (isAbstract()) RustIcons.ABSTRACT_METHOD else RustIcons.METHOD
if (isStatic())
icon = icon.addStaticMark()
if ((flags and Iconable.ICON_FLAG_VISIBILITY) == 0)
return icon;
return icon.addVisibilityIcon(isPublic())
}
fun isPublic(): Boolean {
return vis != null;
}
fun isAbstract(): Boolean {
return this is RustTypeMethod;
}
fun isStatic(): Boolean {
return self == null;
}
} | mit | ee6299faee0a1832d311c573dd111e1f | 27 | 106 | 0.687436 | 4.012295 | false | false | false | false |
JetBrains/ideavim | src/test/java/ui/pages/WelcomeFrame.kt | 1 | 1529 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package ui.pages
import com.intellij.remoterobot.RemoteRobot
import com.intellij.remoterobot.data.RemoteComponent
import com.intellij.remoterobot.fixtures.CommonContainerFixture
import com.intellij.remoterobot.fixtures.ComponentFixture
import com.intellij.remoterobot.fixtures.DefaultXpath
import com.intellij.remoterobot.fixtures.FixtureName
import com.intellij.remoterobot.search.locators.byXpath
import java.time.Duration
fun RemoteRobot.welcomeFrame(function: WelcomeFrame.() -> Unit) {
find(WelcomeFrame::class.java, Duration.ofSeconds(10)).apply(function)
}
@FixtureName("Welcome Frame")
@DefaultXpath("type", "//div[@class='FlatWelcomeFrame']")
class WelcomeFrame(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) :
CommonContainerFixture(remoteRobot, remoteComponent) {
val createNewProjectLink
get() = actionLink(
byXpath(
"New Project",
"//div[(@class='MainButton' and @text='New Project') or (@accessiblename='New Project' and @class='JButton')]"
)
)
@Suppress("unused")
val moreActions
get() = button(byXpath("More Action", "//div[@accessiblename='More Actions' and @class='ActionButton']"))
@Suppress("unused")
val heavyWeightPopup
get() = remoteRobot.find(ComponentFixture::class.java, byXpath("//div[@class='HeavyWeightWindow']"))
}
| mit | 3f45f81faf5f37e719ec778d000aa0c6 | 34.55814 | 118 | 0.752126 | 4.002618 | false | false | false | false |
Turbo87/intellij-rust | src/main/kotlin/org/rust/lang/core/RustParserDefinition.kt | 1 | 1777 | package org.rust.lang.core
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import org.rust.lang.RustLanguage
import org.rust.lang.core.lexer.RustLexer
import org.rust.lang.core.lexer.RustTokenElementTypes
import org.rust.lang.core.lexer.RustTokenElementTypes.*
import org.rust.lang.core.parser.RustParser
import org.rust.lang.core.psi.RustCompositeElementTypes
import org.rust.lang.core.psi.impl.RustFileImpl
public class RustParserDefinition : ParserDefinition {
override fun createFile(viewProvider: FileViewProvider): PsiFile? =
RustFileImpl(viewProvider)
override fun spaceExistanceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements? {
// TODO(kudinkin): Fix
return ParserDefinition.SpaceRequirements.MUST
}
override fun getFileNodeType(): IFileElementType? = RustFileElementType
override fun getStringLiteralElements(): TokenSet =
TokenSet.create(STRING_LITERAL)
override fun getWhitespaceTokens(): TokenSet =
TokenSet.create(TokenType.WHITE_SPACE)
override fun getCommentTokens() = RustTokenElementTypes.COMMENTS_TOKEN_SET
override fun createElement(node: ASTNode?): PsiElement =
RustCompositeElementTypes.Factory.createElement(node)
override fun createLexer(project: Project?): Lexer = RustLexer()
override fun createParser(project: Project?): PsiParser = RustParser()
}
| mit | fe0de54ff3b64646b07d9c01477aca23 | 36.020833 | 120 | 0.792909 | 4.568123 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/reader/services/discover/ReaderDiscoverService.kt | 1 | 2438 | package org.wordpress.android.ui.reader.services.discover
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import org.wordpress.android.WordPress
import org.wordpress.android.ui.reader.services.ServiceCompletionListener
import org.wordpress.android.ui.reader.services.discover.ReaderDiscoverLogic.DiscoverTasks
import org.wordpress.android.ui.reader.services.discover.ReaderDiscoverServiceStarter.ARG_DISCOVER_TASK
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T.READER
import org.wordpress.android.util.LocaleManager
import javax.inject.Inject
import javax.inject.Named
import kotlin.coroutines.CoroutineContext
/**
* Service which updates data for discover tab in Reader, relies on EventBus to notify of changes.
*/
class ReaderDiscoverService : Service(), ServiceCompletionListener, CoroutineScope {
@Inject @field:Named("IO_THREAD") lateinit var ioDispatcher: CoroutineDispatcher
private lateinit var readerDiscoverLogic: ReaderDiscoverLogic
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = ioDispatcher + job
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleManager.setLocale(newBase))
}
override fun onCreate() {
super.onCreate()
val component = (application as WordPress).component()
component.inject(this)
readerDiscoverLogic = ReaderDiscoverLogic(this, this, component)
AppLog.i(READER, "reader discover service > created")
}
override fun onDestroy() {
AppLog.i(READER, "reader discover service > destroyed")
job.cancel()
super.onDestroy()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null && intent.hasExtra(ARG_DISCOVER_TASK)) {
val task = intent.getSerializableExtra(ARG_DISCOVER_TASK) as DiscoverTasks
readerDiscoverLogic.performTasks(task, null)
}
return START_NOT_STICKY
}
override fun onCompleted(companion: Any?) {
AppLog.i(READER, "reader discover service > all tasks completed")
stopSelf()
}
}
| gpl-2.0 | a82f0b9aaeaf9aa097a23a67479755d2 | 35.38806 | 103 | 0.742002 | 4.634981 | false | false | false | false |
theScrabi/NewPipe | app/src/main/java/org/schabi/newpipe/ktx/OffsetDateTime.kt | 1 | 1045 | package org.schabi.newpipe.ktx
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.time.temporal.ChronoField
import java.util.Calendar
import java.util.Date
import java.util.GregorianCalendar
import java.util.TimeZone
// This method is a modified version of GregorianCalendar.from(ZonedDateTime).
// Math.addExact() and Math.multiplyExact() are desugared even though lint displays a warning.
@SuppressWarnings("NewApi")
fun OffsetDateTime.toCalendar(): Calendar {
val cal = GregorianCalendar(TimeZone.getTimeZone("UTC"))
val offsetDateTimeUTC = withOffsetSameInstant(ZoneOffset.UTC)
cal.gregorianChange = Date(Long.MIN_VALUE)
cal.firstDayOfWeek = Calendar.MONDAY
cal.minimalDaysInFirstWeek = 4
try {
cal.timeInMillis = Math.addExact(
Math.multiplyExact(offsetDateTimeUTC.toEpochSecond(), 1000),
offsetDateTimeUTC[ChronoField.MILLI_OF_SECOND].toLong()
)
} catch (ex: ArithmeticException) {
throw IllegalArgumentException(ex)
}
return cal
}
| gpl-3.0 | 5320dc8ee44183c58f6726a19d7abcf8 | 35.034483 | 94 | 0.749282 | 4.390756 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/ModifiableRootModelBridgeTest.kt | 2 | 3965 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.ide
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.module.EmptyModuleType
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.impl.RootConfigurationAccessor
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.toBuilder
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
class ModifiableRootModelBridgeTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule(true)
@Test(expected = Test.None::class)
fun `removing module with modifiable model`() {
runWriteActionAndWait {
val module = projectModel.createModule()
val moduleRootManager = ModuleRootManager.getInstance(module) as ModuleRootComponentBridge
val diff = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.toBuilder()
val modifiableModel = moduleRootManager.getModifiableModel(diff,
RootConfigurationAccessor.DEFAULT_INSTANCE) as ModifiableRootModelBridge
(ModuleManager.getInstance(projectModel.project) as ModuleManagerBridgeImpl).getModifiableModel(diff).disposeModule(module)
modifiableModel.prepareForCommit()
modifiableModel.postCommit()
}
}
@Test(expected = Test.None::class)
fun `getting module root model from modifiable module`() {
runWriteActionAndWait {
val moduleModifiableModel = ModuleManager.getInstance(projectModel.project).getModifiableModel()
val newModule = moduleModifiableModel.newModule(projectModel.projectRootDir.resolve("myModule/myModule.iml"),
EmptyModuleType.EMPTY_MODULE) as ModuleBridge
val moduleRootManager = ModuleRootManager.getInstance(newModule) as ModuleRootComponentBridge
// Assert no exceptions
val model = moduleRootManager.getModifiableModel(newModule.diff!! as MutableEntityStorage,
RootConfigurationAccessor.DEFAULT_INSTANCE)
model.dispose()
moduleModifiableModel.dispose()
}
}
@Test(expected = Test.None::class)
fun `get modifiable models of renamed module`() {
runWriteActionAndWait {
val moduleModifiableModel = ModuleManager.getInstance(projectModel.project).getModifiableModel()
val newModule = moduleModifiableModel.newModule(projectModel.projectRootDir.resolve("myModule/myModule.iml"),
EmptyModuleType.EMPTY_MODULE) as ModuleBridge
moduleModifiableModel.commit()
val builder = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.toBuilder()
val anotherModifiableModel = (ModuleManager.getInstance(projectModel.project) as ModuleManagerBridgeImpl).getModifiableModel(builder)
anotherModifiableModel.renameModule(newModule, "newName")
val moduleRootManager = ModuleRootManager.getInstance(newModule) as ModuleRootComponentBridge
// Assert no exceptions
val model = moduleRootManager.getModifiableModel(builder, RootConfigurationAccessor.DEFAULT_INSTANCE)
anotherModifiableModel.dispose()
}
}
}
| apache-2.0 | f07329cda20566b0903152fe2b641294 | 44.056818 | 139 | 0.757629 | 5.83947 | false | true | false | false |
SneakSpeak/sp-android | app/src/main/kotlin/io/sneakspeak/sneakspeak/adapters/UserListAdapter.kt | 1 | 1956 | package io.sneakspeak.sneakspeak.adapters
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.sneakspeak.sneakspeak.R
import io.sneakspeak.sneakspeak.activities.ChatActivity
import io.sneakspeak.sneakspeak.data.User
import kotlinx.android.synthetic.main.item_user.view.*
class UserListAdapter(ctx: Context) : RecyclerView.Adapter<UserListAdapter.ViewHolder>(),
View.OnClickListener {
val TAG = "UserListAdapter"
val context = ctx
class ViewHolder(userView: View) : RecyclerView.ViewHolder(userView) {
val name = userView.name
}
private var users: List<User>? = null
fun setUsers(userList: List<User>) {
users = userList
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val context = parent.context
val inflater = LayoutInflater.from(context)
// Inflate the custom layout
val userItem = inflater.inflate(R.layout.item_user, parent, false)
userItem.setOnClickListener(this)
// Return a new holder instance
return ViewHolder(userItem)
}
// Involves populating data into the item through holder
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
val user = users?.get(position)
with(viewHolder) {
name.text = user?.name
}
}
override fun getItemCount() = users?.size ?: 0
override fun onClick(view: View?) {
val name = view?.name ?: return
Log.d(TAG, name.text.toString())
val intent = Intent(context, ChatActivity::class.java)
val bundle = Bundle()
bundle.putString("name", name.text.toString())
intent.putExtras(bundle)
context.startActivity(intent)
}
}
| mit | 23a886f7837ebe535682dcb9db6caf1a | 28.19403 | 89 | 0.69274 | 4.41535 | false | false | false | false |
thaapasa/jalkametri-android | app/src/main/java/fi/tuska/jalkametri/gui/IconAdapter.kt | 1 | 1090 | package fi.tuska.jalkametri.gui
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import fi.tuska.jalkametri.R
import fi.tuska.jalkametri.dao.NamedIcon
import fi.tuska.jalkametri.gui.DrinkIconUtils.getDrinkIconRes
class IconAdapter<out T : NamedIcon>(c: Context, icons: List<T>, defaultIconRes: Int) :
NamedIconAdapter<T>(c, icons, defaultIconRes) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view: LinearLayout = convertView as LinearLayout? ?: (inflater().inflate(R.layout.icon_area, null) as LinearLayout).apply {
val size = resources.getDimension(R.dimen.icon_area_size).toInt()
layoutParams = ViewGroup.LayoutParams(size, size)
}
val imageView = view.findViewById(R.id.icon) as ImageView
val icon = getItem(position)
val res = getDrinkIconRes(icon.icon)
imageView.setImageResource(if (res != 0) res else defaultIconRes)
return view
}
}
| mit | 969ffb35a47d010345048a71fc5a6a6e | 36.586207 | 135 | 0.721101 | 3.771626 | false | false | false | false |
jonathanlermitage/tikione-c2e | src/main/kotlin/fr/tikione/c2e/core/model/web/Magazine.kt | 1 | 451 | package fr.tikione.c2e.core.model.web
/**
* CanardPC web magazine.
*/
class Magazine {
var number: String = ""
var title: String? = null
var login: String? = null
var edito: Edito? = null
var toc = ArrayList<TocCategory>()
var authorsPicture: Map<String, AuthorPicture> = HashMap()
override fun toString(): String {
return "Magazine(number=$number, title=$title, login=$login, edito=$edito, toc=$toc)"
}
}
| mit | dbafdedeb8a43a705fd927236918f2e4 | 24.055556 | 93 | 0.643016 | 3.442748 | false | false | false | false |
mdanielwork/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/util/GithubApiUrlQueryBuilder.kt | 4 | 1120 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.util
import com.intellij.util.io.URLUtil
import org.jetbrains.plugins.github.api.requests.GithubRequestPagination
@DslMarker
private annotation class UrlQueryDsl
@UrlQueryDsl
class GithubApiUrlQueryBuilder {
private val builder = StringBuilder()
fun param(name: String, value: String?) {
if (value != null) append("$name=${URLUtil.encodeURIComponent(value)}")
}
fun param(pagination: GithubRequestPagination?) {
if (pagination != null) {
param("page", pagination.pageNumber.toString())
param("per_page", pagination.pageSize.toString())
}
}
private fun append(part: String) {
if (builder.isEmpty()) builder.append("?") else builder.append("&")
builder.append(part)
}
companion object {
@JvmStatic
fun urlQuery(init: GithubApiUrlQueryBuilder.() -> Unit) : String {
val query = GithubApiUrlQueryBuilder()
init(query)
return query.builder.toString()
}
}
} | apache-2.0 | 232779ff90860321bb7ba879c58331e9 | 28.5 | 140 | 0.709821 | 4.258555 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinClassesWithAnnotatedMembersSearcher.kt | 2 | 1969 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.search.ideaExtensions
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ClassesWithAnnotatedMembersSearch
import com.intellij.psi.search.searches.ScopedQueryExecutor
import com.intellij.util.Processor
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.util.allScope
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
class KotlinClassesWithAnnotatedMembersSearcher : ScopedQueryExecutor<PsiClass, ClassesWithAnnotatedMembersSearch.Parameters> {
override fun getScope(param: ClassesWithAnnotatedMembersSearch.Parameters): GlobalSearchScope {
return GlobalSearchScope.getScopeRestrictedByFileTypes(param.annotationClass.project.allScope(), KotlinFileType.INSTANCE)
}
override fun execute(queryParameters: ClassesWithAnnotatedMembersSearch.Parameters, consumer: Processor<in PsiClass>): Boolean {
val processed = hashSetOf<KtClassOrObject>()
return KotlinAnnotatedElementsSearcher.processAnnotatedMembers(queryParameters.annotationClass,
queryParameters.scope,
{ it.getNonStrictParentOfType<KtClassOrObject>() !in processed }) { declaration ->
val ktClass = declaration.getNonStrictParentOfType<KtClassOrObject>()
if (ktClass != null && processed.add(ktClass)) {
val lightClass = ktClass.toLightClass()
if (lightClass != null) consumer.process(lightClass) else true
} else
true
}
}
}
| apache-2.0 | ea78e11bf7f78b98ff0b60ecd6af36b8 | 56.911765 | 158 | 0.726257 | 5.562147 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToStringTemplateIntention.kt | 1 | 7181 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.util.PsiUtilCore
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ConvertToStringTemplateInspection : IntentionBasedInspection<KtBinaryExpression>(
ConvertToStringTemplateIntention::class,
ConvertToStringTemplateIntention::shouldSuggestToConvert,
problemText = KotlinBundle.message("convert.concatenation.to.template.before.text")
), CleanupLocalInspectionTool
open class ConvertToStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("convert.concatenation.to.template")
) {
override fun isApplicableTo(element: KtBinaryExpression): Boolean {
if (!isApplicableToNoParentCheck(element)) return false
val parent = element.parent
if (parent is KtBinaryExpression && isApplicableToNoParentCheck(parent)) return false
return true
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val replacement = buildReplacement(element)
runWriteActionIfPhysical(element) {
element.replaced(replacement)
}
}
companion object {
fun shouldSuggestToConvert(expression: KtBinaryExpression): Boolean {
val entries = buildReplacement(expression).entries
return entries.none { it is KtBlockStringTemplateEntry }
&& !entries.all { it is KtLiteralStringTemplateEntry || it is KtEscapeStringTemplateEntry }
&& entries.count { it is KtLiteralStringTemplateEntry } >= 1
&& !expression.textContains('\n')
}
@JvmStatic
fun buildReplacement(expression: KtBinaryExpression): KtStringTemplateExpression {
val rightText = buildText(expression.right, false)
return fold(expression.left, rightText, KtPsiFactory(expression))
}
private fun fold(left: KtExpression?, right: String, factory: KtPsiFactory): KtStringTemplateExpression {
val forceBraces = right.isNotEmpty() && right.first() != '$' && right.first().isJavaIdentifierPart()
return if (left is KtBinaryExpression && isApplicableToNoParentCheck(left)) {
val leftRight = buildText(left.right, forceBraces)
fold(left.left, leftRight + right, factory)
} else {
val leftText = buildText(left, forceBraces)
factory.createExpression("\"$leftText$right\"") as KtStringTemplateExpression
}
}
fun buildText(expr: KtExpression?, forceBraces: Boolean): String {
if (expr == null) return ""
val expression = KtPsiUtil.safeDeparenthesize(expr).let {
when {
(it as? KtDotQualifiedExpression)?.isToString() == true && it.receiverExpression !is KtSuperExpression ->
it.receiverExpression
it is KtLambdaExpression && it.parent is KtLabeledExpression -> expr
else -> it
}
}
val expressionText = expression.text
when (expression) {
is KtConstantExpression -> {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val type = bindingContext.getType(expression)!!
val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext)
if (constant != null) {
val stringValue = constant.getValue(type).toString()
if (KotlinBuiltIns.isChar(type) || stringValue == expressionText) {
return buildString {
StringUtil.escapeStringCharacters(stringValue.length, stringValue, if (forceBraces) "\"$" else "\"", this)
}
}
}
}
is KtStringTemplateExpression -> {
val base = if (expressionText.startsWith("\"\"\"") && expressionText.endsWith("\"\"\"")) {
val unquoted = expressionText.substring(3, expressionText.length - 3)
StringUtil.escapeStringCharacters(unquoted)
} else {
StringUtil.unquoteString(expressionText)
}
if (forceBraces) {
if (base.endsWith('$')) {
return base.dropLast(1) + "\\$"
} else {
val lastPart = expression.children.lastOrNull()
if (lastPart is KtSimpleNameStringTemplateEntry) {
return base.dropLast(lastPart.textLength) + "\${" + lastPart.text.drop(1) + "}"
}
}
}
return base
}
is KtNameReferenceExpression ->
return "$" + (if (forceBraces) "{$expressionText}" else expressionText)
is KtThisExpression ->
return "$" + (if (forceBraces || expression.labelQualifier != null) "{$expressionText}" else expressionText)
}
return "\${$expressionText}"
}
private fun isApplicableToNoParentCheck(expression: KtBinaryExpression): Boolean {
if (expression.operationToken != KtTokens.PLUS) return false
val expressionType = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL).getType(expression)
if (!KotlinBuiltIns.isString(expressionType)) return false
return isSuitable(expression)
}
private fun isSuitable(expression: KtExpression): Boolean {
if (expression is KtBinaryExpression && expression.operationToken == KtTokens.PLUS) {
return isSuitable(expression.left ?: return false) && isSuitable(expression.right ?: return false)
}
if (PsiUtilCore.hasErrorElementChild(expression)) return false
if (expression.textContains('\n')) return false
return true
}
}
}
| apache-2.0 | 5889014a05efe8c493cb4183b984baea | 46.873333 | 158 | 0.62554 | 6.034454 | false | false | false | false |
MarkusAmshove/Kluent | jvm/src/main/kotlin/org/amshove/kluent/CharSequenceBacktick.kt | 1 | 3481 | package org.amshove.kluent
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
infix fun <T : CharSequence> T.`should start with`(expected: CharSequence) = this.shouldStartWith(expected)
infix fun <T : CharSequence> T.`should end with`(expected: CharSequence) = this.shouldEndWith(expected)
infix fun <T : CharSequence> T.`should contain`(char: Char) = this.shouldContain(char)
infix fun <T : CharSequence> T.`should contain some`(things: Iterable<CharSequence>) = this.shouldContainSome(things)
infix fun <T : CharSequence> T.`should contain none`(things: Iterable<CharSequence>) = this.shouldContainNone(things)
infix fun <T : CharSequence> T.`should contain`(expected: CharSequence) = this.shouldContain(expected)
infix fun <T : CharSequence> T.`should not contain`(char: Char) = this.shouldNotContain(char)
infix fun <T : CharSequence> T.`should not contain any`(things: Iterable<CharSequence>) =
this.shouldNotContainAny(things)
infix fun <T : CharSequence> T.`should match`(regex: String) = this.shouldMatch(regex)
infix fun <T : CharSequence> T.`should match`(regex: Regex) = this.shouldMatch(regex)
fun <T : CharSequence> T.`should be empty`() = this.shouldBeEmpty()
fun <T : CharSequence> T?.`should be null or empty`() = this.shouldBeNullOrEmpty()
fun <T : CharSequence> T.`should be blank`() = this.shouldBeBlank()
fun <T : CharSequence> T?.`should be null or blank`() = this.shouldBeNullOrBlank()
@Deprecated("Use #`should be equal to`", ReplaceWith("this.`should be equal to`(expected)"))
infix fun String.`should equal to`(expected: String) = this.`should be equal to`(expected)
infix fun String.`should be equal to`(expected: String) = this.shouldBeEqualTo(expected)
@Deprecated("Use #`should not be equal to`", ReplaceWith("this.`should not be equal to`(expected)"))
infix fun String.`should not equal to`(expected: String) = this.`should not be equal to`(expected)
infix fun String.`should not be equal to`(expected: String) = this.shouldNotBeEqualTo(expected)
infix fun <T : CharSequence> T.`should not start with`(expected: CharSequence) = this.shouldNotStartWith(expected)
infix fun <T : CharSequence> T.`should not end with`(expected: CharSequence) = this.shouldNotEndWith(expected)
infix fun <T : CharSequence> T.`should not contain`(expected: CharSequence) = this.shouldNotContain(expected)
infix fun <T : CharSequence> T.`should not match`(regex: String) = this.shouldNotMatch(regex)
infix fun <T : CharSequence> T.`should not match`(regex: Regex) = this.shouldNotMatch(regex)
fun <T : CharSequence> T.`should not be empty`(): T = this.shouldNotBeEmpty()
@UseExperimental(ExperimentalContracts::class)
fun <T : CharSequence> T?.`should not be null or empty`(): T {
contract {
returns() implies (this@`should not be null or empty` != null)
}
return this.shouldNotBeNullOrEmpty()
}
fun <T : CharSequence> T.`should not be blank`(): T = this.shouldNotBeBlank()
@UseExperimental(ExperimentalContracts::class)
fun <T : CharSequence> T?.`should not be null or blank`(): T {
contract {
returns() implies (this@`should not be null or blank` != null)
}
return this.shouldNotBeNullOrBlank()
}
infix fun <T : CharSequence> T.`should contain all`(items: Iterable<CharSequence>): CharSequence =
this.shouldContainAll(items)
infix fun <T : CharSequence> T.`should not contain all`(items: Iterable<CharSequence>): CharSequence =
this.shouldNotContainAll(items)
| mit | 5ce98b7da19e5cb7a9f11e9aba1c4938 | 41.975309 | 117 | 0.735995 | 3.973744 | false | false | false | false |
elpassion/el-space-android | el-space-app/src/main/java/pl/elpassion/elspace/hub/report/add/ReportAddController.kt | 1 | 5081 | package pl.elpassion.elspace.hub.report.add
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.withLatestFrom
import pl.elpassion.elspace.common.CurrentTimeProvider
import pl.elpassion.elspace.common.SchedulersSupplier
import pl.elpassion.elspace.common.extensions.catchOnError
import pl.elpassion.elspace.common.extensions.getDateString
import pl.elpassion.elspace.common.extensions.getTimeFrom
import pl.elpassion.elspace.hub.project.Project
import pl.elpassion.elspace.hub.project.last.LastSelectedProjectRepository
import pl.elpassion.elspace.hub.report.PaidVacationsViewModel
import pl.elpassion.elspace.hub.report.RegularViewModel
import pl.elpassion.elspace.hub.report.ReportType
import pl.elpassion.elspace.hub.report.ReportViewModel
class ReportAddController(private val date: String?,
private val view: ReportAdd.View,
private val api: ReportAdd.Api,
private val repository: LastSelectedProjectRepository,
private val schedulers: SchedulersSupplier) {
private val subscriptions = CompositeDisposable()
fun onCreate() {
repository.getLastProject()?.let {
view.showSelectedProject(it)
}
view.showDate(date ?: getCurrentDatePerformedAtString())
view.projectClickEvents()
.subscribe { view.openProjectChooser() }
.addTo(subscriptions)
addReportClicks()
.subscribe()
.addTo(subscriptions)
}
fun onDestroy() {
subscriptions.clear()
}
fun onDateChanged(date: String) {
view.showDate(date)
}
fun onProjectChanged(project: Project) {
view.showSelectedProject(project)
}
private fun getCurrentDatePerformedAtString() = getTimeFrom(timeInMillis = CurrentTimeProvider.get()).getDateString()
private fun addReportClicks() = view.addReportClicks()
.withLatestFrom(reportTypeChanges(), { model, handler -> model to handler })
.switchMap { callApi(it) }
.doOnNext { view.close() }
private fun reportTypeChanges() = view.reportTypeChanges()
.doOnNext { onReportTypeChanged(it) }
.startWith(ReportType.REGULAR)
.map { chooseReportHandler(it) }
private fun chooseReportHandler(reportType: ReportType) = when (reportType) {
ReportType.REGULAR -> regularReportHandler
ReportType.PAID_VACATIONS -> paidVacationReportHandler
ReportType.UNPAID_VACATIONS -> unpaidVacationReportHandler
ReportType.SICK_LEAVE -> sickLeaveReportHandler
ReportType.PAID_CONFERENCE -> paidConferenceReportHandler
}
private fun callApi(modelCallPair: Pair<ReportViewModel, (ReportViewModel) -> Observable<Unit>>) = modelCallPair.second(modelCallPair.first)
.subscribeOn(schedulers.backgroundScheduler)
.observeOn(schedulers.uiScheduler)
.addLoader()
.catchOnError { view.showError(it) }
private val regularReportHandler = { model: ReportViewModel ->
(model as RegularViewModel).run {
when {
hasNoProject() -> {
view.showEmptyProjectError()
Observable.empty()
}
hasNoDescription() -> {
view.showEmptyDescriptionError()
Observable.empty()
}
else -> addRegularReportObservable(this)
}
}
}
private fun addRegularReportObservable(model: RegularViewModel) =
api.addRegularReport(model.selectedDate, model.project!!.id, model.hours, model.description)
private val paidVacationReportHandler = { model: ReportViewModel ->
api.addPaidVacationsReport(model.selectedDate, (model as PaidVacationsViewModel).hours)
}
private val unpaidVacationReportHandler = { model: ReportViewModel ->
api.addUnpaidVacationsReport(model.selectedDate)
}
private val sickLeaveReportHandler = { model: ReportViewModel ->
api.addSickLeaveReport(model.selectedDate)
}
private val paidConferenceReportHandler = { model: ReportViewModel ->
api.addPaidConferenceReport(model.selectedDate)
}
private fun onReportTypeChanged(reportType: ReportType) = when (reportType) {
ReportType.REGULAR -> view.showRegularForm()
ReportType.PAID_VACATIONS -> view.showPaidVacationsForm()
ReportType.UNPAID_VACATIONS -> view.showUnpaidVacationsForm()
ReportType.SICK_LEAVE -> view.showSickLeaveForm()
ReportType.PAID_CONFERENCE -> view.showPaidConferenceForm()
}
private fun RegularViewModel.hasNoDescription() = description.isBlank()
private fun RegularViewModel.hasNoProject() = project == null
private fun Observable<Unit>.addLoader() = this
.doOnSubscribe { view.showLoader() }
.doFinally { view.hideLoader() }
}
| gpl-3.0 | f35da81ab603eb962843916749471287 | 38.387597 | 144 | 0.680968 | 4.730912 | false | false | false | false |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/contents/Text.kt | 1 | 2736 | // Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// PdfLayoutMgr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.contents
import com.planbase.pdf.lm2.attributes.TextStyle
import com.planbase.pdf.lm2.lineWrapping.LineWrappable
import com.planbase.pdf.lm2.lineWrapping.LineWrapper
import org.organicdesign.indented.StringUtils.stringify
/**
Represents styled text kind of like a #Text node in HTML.
*/
data class Text(val textStyle: TextStyle,
private val initialText: String = "") : LineWrappable {
constructor(textStyle: TextStyle) : this(textStyle, "")
// This removes all tabs, transforms all line-terminators into "\n", and removes all runs of spaces that
// precede line terminators. This should simplify the subsequent line-breaking algorithm.
val text: String = cleanStr(initialText)
fun avgCharsForWidth(width: Double): Int = (width * 1220.0 / textStyle.avgCharWidth).toInt()
fun maxWidth(): Double = textStyle.stringWidthInDocUnits(text.trim())
override fun toString() = "Text($textStyle, ${stringify(text)})"
override fun lineWrapper(): LineWrapper = TextLineWrapper(this)
companion object {
// From: https://docs.google.com/document/d/1vpbFYqfW7XmJplSwwLLo7zSPOztayO7G4Gw5_EHfpfI/edit#
//
// 1. Remove all tabs. There is no way to make a good assumption about how to turn them into spaces.
//
// 2. Transform all line-terminators into "\n". Also remove spaces before every line terminator (hard break).
//
// The wrapping algorithm will remove all consecutive spaces on an automatic line-break. Otherwise, we want
// to preserve consecutive spaces within a line.
//
// Non-breaking spaces are ignored here.
fun cleanStr(s:String):String = s.replace(Regex("\t"), "")
.replace(Regex("[ ]*(\r\n|[\r\n\u0085\u2028\u2029])"), "\n")
}
}
| agpl-3.0 | 55911877b9a50169d328cfdfd60eb35a | 43.852459 | 118 | 0.710161 | 4.029455 | false | false | false | false |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/PdfLayoutMgr.kt | 1 | 14793 | // Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// PdfLayoutMgr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2
import com.planbase.pdf.lm2.attributes.Orientation
import com.planbase.pdf.lm2.attributes.Orientation.LANDSCAPE
import com.planbase.pdf.lm2.attributes.PageArea
import com.planbase.pdf.lm2.contents.ScaledImage.WrappedImage
import com.planbase.pdf.lm2.pages.PageGrouping
import com.planbase.pdf.lm2.pages.SinglePage
import com.planbase.pdf.lm2.utils.Dim
import org.apache.fontbox.ttf.TTFParser
import org.apache.fontbox.ttf.TrueTypeFont
import org.apache.pdfbox.cos.COSArray
import org.apache.pdfbox.cos.COSString
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.PDDocumentInformation
import org.apache.pdfbox.pdmodel.PDPage
import org.apache.pdfbox.pdmodel.PDPageContentStream
import org.apache.pdfbox.pdmodel.font.PDType0Font
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace
import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject
import org.apache.pdfbox.util.Matrix
import java.awt.image.BufferedImage
import java.io.File
import java.io.IOException
import java.io.OutputStream
import java.lang.IllegalArgumentException
import java.util.HashMap
/**
* Manages a PDF document. You need one of these to do almost anything useful.
*
* ## Usage (Example taken from TestBasics.kt)
* ```kotlin
* // Make a manager with the given color model and starting page size.
* val pageMgr = PdfLayoutMgr(PDDeviceCMYK.INSTANCE, Dim(LETTER))
*
* // Declare a text style to use.
* val bodyText = TextStyle(TIMES_ITALIC, 36.0, CMYK_BLACK)
*
* // Start a bunch of pages (add more text to use more than one)
* val lp = pageMgr.startPageGrouping(PORTRAIT, letterPortraitBody)
*
* // Stick some text on the page(s)
* lp.appendCell(0.0, CellStyle(Align.TOP_LEFT_JUSTIFY, BoxStyle.NO_PAD_NO_BORDER),
* listOf(Text(bodyText, "\"Darkness within darkness: the gateway to all" +
* " understanding.\" — Lao Tzu")))
*
* // Commit all your work and write it to a file
* pageMgr.commit()
* pageMgr.save(FileOutputStream("helloWorld.pdf"))
* ```
*
* # Note:
*
* Because this class buffers and writes to an underlying stream, it is mutable, has side effects,
* and is NOT thread-safe!
*
* @param colorSpace the color-space for the document. Often PDDeviceCMYK.INSTANCE or PDDeviceRGB.INSTANCE
* @param pageDim Returns the width and height of the paper-size where THE HEIGHT IS ALWAYS THE LONGER DIMENSION.
* You may need to swap these for landscape: `pageDim().swapWh()`. For this reason, it's not a
* good idea to use this directly. Use the corrected values through a [PageGrouping] instead.
* @param pageReactor Takes a page number and returns an x-offset for that page. Use this for effects like page
* numbering or different offsets or headers/footers for even and odd pages or the start of a chapter.
*/
class PdfLayoutMgr(private val colorSpace: PDColorSpace,
val pageDim: Dim,
private var pageReactor:((Int, SinglePage) -> Double)? = null) {
private val doc = PDDocument()
init {
val docInf = PDDocumentInformation()
docInf.producer = "PlanBase PdfLayoutMgr2"
doc.documentInformation = docInf
}
/**
* This returns the wrapped PDDocument instance. This is a highly mutable data structure.
* Accessing it directly while also using PdfLayoutMgr is inherently unsafe and untested.
* This method is provided so you can do things like add encryption or use other features of PDFBox not yet
* directly supported by PdfLayoutMgr.
*/
@Suppress("unused") // Required part of public API
fun getPDDocButBeCareful(): PDDocument = doc
// You can have many PDImageXObject backed by only a few images - it is a flyweight, and this
// hash map keeps track of the few underlying images, even as instances of PDImageXObject
// represent all the places where these images are used.
// CRITICAL: This means that the the set of PDImageXObject must be thrown out and created anew for each
// document!
private val imageCache = HashMap<BufferedImage, PDImageXObject>()
private val pages:MutableList<SinglePage> = mutableListOf()
private val uncommittedPageGroupings:MutableList<PageGrouping> = mutableListOf()
class TrueAndZeroFonts(val trueType:TrueTypeFont, val typeZero:PDType0Font)
private val openFontFiles: MutableMap<File,TrueAndZeroFonts> = mutableMapOf()
// pages.size() counts the first page as 1, so 0 is the appropriate sentinel value
private var unCommittedPageIdx:Int = 0
fun unCommittedPageIdx():Int = unCommittedPageIdx
internal fun ensureCached(sj: WrappedImage): PDImageXObject {
val bufferedImage = sj.bufferedImage
var temp: PDImageXObject? = imageCache[bufferedImage]
if (temp == null) {
val problems:MutableList<Throwable> = mutableListOf()
temp = try {
LosslessFactory.createFromImage(doc, bufferedImage)
} catch (t: Throwable) {
problems.plus(t)
try {
JPEGFactory.createFromImage(doc, bufferedImage)
} catch (u: Throwable) {
if (problems.isEmpty()) {
throw Exception("Caught exception creating a JPEG from a bufferedImage", u)
} else {
problems.plus(u)
throw Exception("Caught exceptions creating Lossless/JPEG PDImageXObjects from" +
" a bufferedImage: $problems")
}
}
}
imageCache[bufferedImage] = temp!!
}
return temp
}
// TODO: Is this a good idea?
fun numPages():Int = pages.size
fun hasAnyPages():Boolean = pages.size > 0
fun page(idx:Int):SinglePage = pages[idx]
/**
* Allows inserting a single page before already created pages.
* @param page the page to insert
* @param idx the index to insert at (shifting the pages currently at that index and all greater indices up one.
* This must be >= 0, <= pages.size, and >= the unCommittedPageIdx.
* The last means that you cannot insert before already committed pages.
*/
fun insertPageAt(page:SinglePage, idx:Int) {
if (idx < 0) {
throw IllegalArgumentException("Insert index cannot be less than 0")
}
if (idx > pages.size) {
throw IllegalArgumentException("Insert index cannot be greater than the number" +
" of pages (if index == pages.size it's a legal" +
" append, but not technically an insert).")
}
if (idx < unCommittedPageIdx) {
throw IllegalStateException("Can't insert page at $idx before already" +
" committed pages at $unCommittedPageIdx.")
}
pages.add(idx, page)
}
fun ensurePageIdx(idx:Int, body:PageArea) {
while (pages.size <= idx) {
pages.add(SinglePage(pages.size + 1, this, pageReactor, body))
}
}
/**
* Call this to commit the PDF information to the underlying stream after it is completely built.
* This also frees any open font file descriptors (that were opened by PdfLayoutMgr2).
*/
@Throws(IOException::class)
fun save(os: OutputStream) {
doc.save(os)
doc.close()
openFontFiles.values.forEach { ttt0 ->
ttt0.trueType.close()
}
openFontFiles.clear()
}
/**
* Tells this PdfLayoutMgr that you want to start a new logical page (which may be broken across
* two or more physical pages) in the requested page orientation.
*/
// Part of end-user public interface
fun startPageGrouping(orientation: Orientation,
body:PageArea,
pr: ((Int, SinglePage) -> Double)? = null): PageGrouping {
pageReactor = pr
val pb = SinglePage(pages.size + 1, this, pageReactor, body)
pages.add(pb)
val pg = PageGrouping(this, orientation, body)
uncommittedPageGroupings.add(pg)
return pg
}
// private fun pageArea(o: Orientation, margins:Padding = Padding(DEFAULT_MARGIN)):PageArea {
// val bodyDim:Dim = margins.subtractFrom(if (o == Orientation.PORTRAIT) {
// pageDim
// } else {
// pageDim.swapWh()
// })
// return PageArea(Coord(margins.left, margins.bottom + bodyDim.height),
// bodyDim)
// }
// fun startPageGrouping(orientation: Orientation,
// body:PageArea): PageGrouping = startPageGrouping(orientation, body, null)
/**
* Loads a TrueType font and automatically embeds (the part you use?) into the document from the given file,
* returning a PDType0Font object. The underlying TrueTypeFont object holds the file descriptor open while you
* are working, presumably to embed only the glyphs you need. PdfLayoutMgr2 will explicitly close the file
* descriptor when you call [save]. Calling this method twice on the same PdfLayoutMgr with the same file will
* return the same (already open) font.
*/
@Throws(IOException::class)
fun loadTrueTypeFont(fontFile: File): PDType0Font {
var ttt0:TrueAndZeroFonts? = openFontFiles[fontFile]
if (ttt0 == null) {
val tt = TTFParser().parse(fontFile)
val t0 = PDType0Font.load(doc, tt, true)
ttt0 = TrueAndZeroFonts(tt, t0)
openFontFiles[fontFile] = ttt0
}
return ttt0.typeZero
}
fun commit() {
uncommittedPageGroupings.forEach { logicalPageEnd(it) }
uncommittedPageGroupings.clear()
}
/** Returns a COSArray of two COSString's. See [setFileIdentifiers] for details */
fun getFileIdentifiers() : COSArray? = doc.document.documentID
/**
* This an optional value in the PDF spec designed to hold two hashcode for later file compares.
* The first represents the original state of the file, the second the latest.
* If left null, PDFBox fills it in with an md5 hash of the file info plus timestamp.
* Construct a COSString like: COSString("Whatever".toByteArray(Charsets.ISO_8859_1))
* or just by passing it a byte array directly.
*/
fun setFileIdentifiers(original: COSString, latest: COSString) {
val ca = COSArray()
ca.add(original)
ca.add(latest)
doc.document.documentID = ca
}
/**
* Call this when you are through with your current set of pages to commit all pending text and
* drawing operations. This is the only method that throws an IOException because the purpose of
* PdfLayoutMgr is to buffer all operations until a page is complete so that it can safely be
* written to the underlying stream. This method turns the potential pages into real output.
* Call when you need a page break, or your document is done and you need to write it out.
*
* Once you call this method, you cannot insert or modify earlier pages.
*
* @throws IOException if there is a failure writing to the underlying stream.
*/
@Throws(IOException::class)
private fun logicalPageEnd(lp: PageGrouping) {
// Write out all uncommitted pages.
while (unCommittedPageIdx < pages.size) {
val pdPage = PDPage(pageDim.toRect())
if (lp.orientation === LANDSCAPE) {
pdPage.rotation = 90
}
var stream: PDPageContentStream? = null
try {
stream = PDPageContentStream(doc, pdPage)
doc.addPage(pdPage)
if (lp.orientation === LANDSCAPE) {
stream.transform(Matrix(0f, 1f, -1f, 0f, pageDim.width.toFloat(), 0f))
}
stream.setStrokingColor(colorSpace.initialColor)
stream.setNonStrokingColor(colorSpace.initialColor)
val pb = pages[unCommittedPageIdx]
pb.commit(stream)
lp.commitBorderItems(stream)
stream.close()
// Set to null to show that no exception was thrown and no need to close again.
stream = null
} finally {
// Let it throw an exception if the closing doesn't work.
stream?.close()
}
unCommittedPageIdx++
}
lp.invalidate()
}
override fun equals(other: Any?): Boolean {
// First, the obvious...
if (this === other) {
return true
}
if ( (other == null) ||
(other !is PdfLayoutMgr) ) {
return false
}
// Details...
return this.doc == other.doc && this.pages == other.pages
}
override fun hashCode(): Int = doc.hashCode() + pages.hashCode()
companion object {
/**
* If you use no scaling when printing the output PDF, PDFBox shows approximately 72
* Document-Units Per Inch. This makes one pixel on an average desktop monitor correspond to
* roughly one document unit. This is a useful constant for page layout math.
*/
const val DOC_UNITS_PER_INCH: Double = 72.0
/**
* Some printers need at least 1/2" of margin (36 "pixels") in order to accept a print job.
* This amount seems to accommodate all printers.
*/
const val DEFAULT_MARGIN: Double = 37.0
// private val DEFAULT_DOUBLE_MARGIN_DIM = Dim(DEFAULT_MARGIN * 2, DEFAULT_MARGIN * 2)
}
}
| agpl-3.0 | 80b180b00d9c09b6d91667d5a39337bb | 40.90085 | 116 | 0.650666 | 4.29846 | false | false | false | false |
cd1/motofretado | app/src/main/java/com/gmail/cristiandeives/motofretado/TrackBusFragment.kt | 1 | 10346 | package com.gmail.cristiandeives.motofretado
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.support.annotation.MainThread
import android.support.annotation.UiThread
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.app.LoaderManager
import android.support.v4.content.ContextCompat
import android.support.v4.content.Loader
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import com.gmail.cristiandeives.motofretado.http.Bus
import kotlinx.android.synthetic.main.fragment_track_bus.*
import java.util.Arrays
@MainThread
internal class TrackBusFragment : Fragment(), LoaderManager.LoaderCallbacks<TrackBusMvp.Presenter>, TrackBusMvp.View, AddBusDialogFragment.OnClickListener {
companion object {
private val TAG = TrackBusFragment::class.java.simpleName
private const val REQUEST_PERMISSION_LOCATION_UPDATE = 0
private const val REQUEST_PERMISSION_ACTIVITY_DETECTION = 1
private const val TRACK_BUS_LOADER_ID = 0
}
private lateinit var mSpinnerAdapter: BusSpinnerAdapter
private var mPresenter: TrackBusMvp.Presenter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
Log.v(TAG, "> onCreateView(inflater=$inflater, container=$container, savedInstanceState=$savedInstanceState)")
val rootView = inflater.inflate(R.layout.fragment_track_bus, container, false)
mSpinnerAdapter = BusSpinnerAdapter(context)
mPresenter = null;
Log.v(TAG, "< onCreateView(inflater=$inflater, container=$container, savedInstanceState=$savedInstanceState): $rootView")
return rootView
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
Log.v(TAG, "> onViewCreated(view=$view, savedInstanceState=$savedInstanceState)")
spinnerBusID.adapter = mSpinnerAdapter
buttonAddBus.setOnClickListener {
val fragment = AddBusDialogFragment()
fragment.setTargetFragment(this@TrackBusFragment, 0)
fragment.show(fragmentManager, AddBusDialogFragment::class.java.name)
}
buttonEnterBus.setOnClickListener(this::buttonEnterBusClick)
buttonLeaveBus.setOnClickListener { mPresenter?.stopLocationUpdate() }
switchDetectAutomatically.setOnCheckedChangeListener(this::switchDetectAutomaticallyChange)
disableBusId()
Log.v(TAG, "< onViewCreated(view=$view, savedInstanceState=$savedInstanceState)")
}
override fun onDestroyView() {
Log.v(TAG, "> onDestroyView()")
super.onDestroyView()
mPresenter?.onDetach()
Log.v(TAG, "< onDestroyView()")
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
Log.v(TAG, "> onActivityCreated(savedInstanceState=$savedInstanceState)")
super.onActivityCreated(savedInstanceState)
loaderManager.initLoader(TRACK_BUS_LOADER_ID, null, this)
Log.v(TAG, "< onActivityCreated(savedInstanceState=$savedInstanceState)")
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "> onRequestPermissionsResult(requestCode=$requestCode, permissions=${Arrays.toString(permissions)}, grantResults=${Arrays.toString(grantResults)})")
}
when (requestCode) {
REQUEST_PERMISSION_LOCATION_UPDATE, REQUEST_PERMISSION_ACTIVITY_DETECTION -> {
if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "user granted permission")
mPresenter?.let { presenter ->
when (requestCode) {
REQUEST_PERMISSION_LOCATION_UPDATE -> presenter.startLocationUpdate()
REQUEST_PERMISSION_ACTIVITY_DETECTION -> presenter.startActivityDetection()
}
}
} else {
uncheckSwitchDetectAutomatically()
if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
Log.d(TAG, "user did NOT grant permission")
displayMessage(getString(R.string.fine_location_permission_rationale))
} else {
view?.let { rootView ->
val snackIntent = Intent().apply {
action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.parse("package:${activity.packageName}")
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
Snackbar.make(rootView, R.string.fine_location_permission_rationale, Snackbar.LENGTH_LONG)
.setAction(R.string.snackbar_action_settings) { startActivity(snackIntent) }
.show()
}
}
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "> onRequestPermissionsResult(requestCode=$requestCode, permissions=${Arrays.toString(permissions)}, grantResults=${Arrays.toString(grantResults)})")
}
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<TrackBusMvp.Presenter> {
Log.v(TAG, "> onCreateLoader(id=$id, args=$args)")
val loader = TrackBusPresenterLoader(context.applicationContext)
Log.v(TAG, "< onCreateLoader(id=$id, args=$args): $loader")
return loader
}
override fun onLoaderReset(loader: Loader<TrackBusMvp.Presenter>) {
Log.v(TAG, "> onLoaderReset(loader=$loader)")
mPresenter?.let { presenter ->
presenter.onDetach()
mPresenter = null
}
Log.v(TAG, "< onLoaderReset(loader=$loader)")
}
override fun onLoadFinished(loader: Loader<TrackBusMvp.Presenter>, data: TrackBusMvp.Presenter) {
Log.v(TAG, "> onLoadFinished(loader=$loader, data=$data)")
mPresenter = data
data.onAttach(this)
Log.v(TAG, "< onLoadFinished(loader=$loader, data=$data)")
}
@UiThread
override fun getBusId(): String? {
return if (mSpinnerAdapter.hasActualBusData()) {
spinnerBusID.selectedItem.toString()
} else {
null
}
}
@UiThread
override fun displayMessage(text: String) {
Log.d(TAG, "displaying message: $text")
context.toast(text)
}
@UiThread
override fun enableBusId() {
spinnerBusID.isEnabled = true
buttonAddBus.isEnabled = true
buttonAddBus.setImageDrawable(context.getDrawable(R.drawable.ic_add))
}
@UiThread
override fun disableBusId() {
spinnerBusID.isEnabled = false
buttonAddBus.isEnabled = false
// change button icon to grayscale
val drawable = context.getDrawable(R.drawable.ic_add).mutate()
drawable.setColorFilter(Color.LTGRAY, PorterDuff.Mode.SRC_IN)
buttonAddBus.setImageDrawable(drawable)
}
@UiThread
override fun uncheckSwitchDetectAutomatically() {
switchDetectAutomatically.isChecked = false
}
@UiThread
override fun setAvailableBuses(buses: List<Bus>, selectedBusId: String?) {
mSpinnerAdapter.clear()
mSpinnerAdapter.addAll(buses)
if (!selectedBusId.isNullOrEmpty()) {
val selectedBusIndex = buses.indexOfFirst { it.id == selectedBusId }
spinnerBusID.setSelection(selectedBusIndex)
}
}
@UiThread
override fun setBusError(errorMessage: String) {
mSpinnerAdapter.setErrorMessage(errorMessage)
spinnerBusID.adapter = mSpinnerAdapter
mSpinnerAdapter.notifyDataSetChanged()
disableBusId()
}
@UiThread
override fun onPositiveButtonClick(text: String) {
mPresenter?.createBus(Bus(id = text))
}
@UiThread
private fun buttonEnterBusClick(view: View) {
if (getBusId().isNullOrEmpty()) {
Log.d(TAG, "empty bus ID; cannot trigger location updates")
displayMessage(getString(R.string.empty_bus_id_message))
return
}
mPresenter?.let { presenter ->
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
presenter.startLocationUpdate()
} else {
Log.d(TAG, "the app doesn't have location permission; requesting it to the user")
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION_LOCATION_UPDATE)
}
}
}
@UiThread
private fun switchDetectAutomaticallyChange(buttonView: CompoundButton, isChecked: Boolean) {
mPresenter?.let { presenter ->
if (isChecked && getBusId().isNullOrEmpty()) {
Log.d(TAG, "empty bus ID; cannot trigger activity detection")
displayMessage(getString(R.string.empty_bus_id_message))
uncheckSwitchDetectAutomatically()
return
}
if (isChecked) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
presenter.startActivityDetection()
} else {
Log.d(TAG, "the app doesn't have location permission; requesting it to the user")
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION_ACTIVITY_DETECTION)
}
} else {
presenter.stopActivityDetection()
}
}
}
} | gpl-3.0 | f926ad740729dc94ba949116fe49d4d8 | 38.492366 | 172 | 0.647013 | 4.986024 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinMethodSmartStepTarget.kt | 2 | 3228 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto
import com.intellij.debugger.engine.MethodFilter
import com.intellij.psi.PsiElement
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.util.Range
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
import org.jetbrains.kotlin.renderer.PropertyAccessorRenderingPolicy
import javax.swing.Icon
class KotlinMethodSmartStepTarget(
lines: Range<Int>,
highlightElement: PsiElement,
label: String,
declaration: KtDeclaration?,
val ordinal: Int,
val methodInfo: CallableMemberInfo
) : KotlinSmartStepTarget(label, highlightElement, false, lines) {
companion object {
private val renderer = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE
withoutReturnType = true
propertyAccessorRenderingPolicy = PropertyAccessorRenderingPolicy.PRETTY
startFromName = true
modifiers = emptySet()
}
fun calcLabel(descriptor: DeclarationDescriptor): String {
return renderer.render(descriptor)
}
}
private val declarationPtr = declaration?.let(SourceNavigationHelper::getNavigationElement)?.createSmartPointer()
init {
assert(declaration != null || methodInfo.isInvoke)
}
override fun getIcon(): Icon = if (methodInfo.isExtension) KotlinIcons.EXTENSION_FUNCTION else KotlinIcons.FUNCTION
fun getDeclaration(): KtDeclaration? =
declarationPtr.getElementInReadAction()
override fun createMethodFilter(): MethodFilter {
val declaration = declarationPtr.getElementInReadAction()
return KotlinMethodFilter(declaration, callingExpressionLines, methodInfo)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is KotlinMethodSmartStepTarget) return false
if (methodInfo.isInvoke && other.methodInfo.isInvoke) {
// Don't allow to choose several invoke targets in smart step into as we can't distinguish them reliably during debug
return true
}
return highlightElement === other.highlightElement
}
override fun hashCode(): Int {
if (methodInfo.isInvoke) {
// Predefined value to make all FunctionInvokeDescriptor targets equal
return 42
}
return highlightElement.hashCode()
}
}
internal fun <T : PsiElement> SmartPsiElementPointer<T>?.getElementInReadAction(): T? =
this?.let { runReadAction { element } }
| apache-2.0 | 165c1a79a66a7d529f3acbfda0109d1e | 39.35 | 158 | 0.740397 | 5.353234 | false | false | false | false |
pattyjogal/MusicScratchpad | app/src/main/java/com/viviose/musicscratchpad/EditorView.kt | 2 | 9913 | package com.viviose.musicscratchpad
import android.annotation.TargetApi
import android.content.Context
import android.graphics.*
import android.graphics.drawable.VectorDrawable
import android.media.MediaPlayer
import android.net.Uri
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
/**
* Created by Patrick on 2/2/2016.
*/
class EditorView : View {
fun pxdp(dp: Float): Float {
val px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics)
return px
}
internal var DEBUG_TAG = "MusicDebug"
internal var navigationBarHeight = 0
internal var conx: Context
val NOTE_WIDTH = 150f
val NOTE_HEIGHT = 100f
internal var paint = Paint()
private val mBitmap: Bitmap? = null
private val mCanvas: Canvas? = null
internal var metrics = context.resources.displayMetrics
internal var density = metrics.density
internal var x: Float = 0.toFloat()
internal var y: Float = 0.toFloat()
internal var ma = context as MainActivity
private var mDetector: GestureDetector? = null
internal var accidental = 0
internal var renderableNote: Note = Note(0f,0f,0)
internal var touchX: Float = 0.toFloat()
internal var touchY: Float = 0.toFloat()
internal var drawNote: Boolean = false
//Loading note images
internal var qnh: Bitmap? = null
internal var hnh: Bitmap? = null
internal var drawDot: Boolean = false
constructor(con: Context) : super(con) {
conx = con
isFocusable = true
isFocusableInTouchMode = true
paint.color = Color.BLACK
}
constructor(con: Context, attrs: AttributeSet) : super(con, attrs) {
conx = con
isFocusable = true
isFocusableInTouchMode = true
paint.color = Color.BLACK
}
constructor(con: Context, attrs: AttributeSet, defStyle: Int) : super(con, attrs, defStyle) {
conx = con
isFocusable = true
isFocusableInTouchMode = true
paint.color = Color.BLACK
}
@TargetApi(21)
public override fun onDraw(c: Canvas) {
// navigation bar height
mDetector = GestureDetector(this.context, mListener())
val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
if (resourceId > 0) {
navigationBarHeight = resources.getDimensionPixelSize(resourceId)
DensityMetrics.navBarHeight = (navigationBarHeight.toFloat())
}
x = width.toFloat()
y = height.toFloat()
DensityMetrics.spaceHeight = ((y - DensityMetrics.getToolbarHeight()) / 8)
paint.strokeWidth = 10f
for (i in 2..6) {
c.drawLine(20f, DensityMetrics.spaceHeight * i + DensityMetrics.getToolbarHeight(), x - 20, DensityMetrics.spaceHeight * i + DensityMetrics.getToolbarHeight(), paint)
}
val altoClef = DensityMetrics.getToolbarHeight() + 2 * DensityMetrics.spaceHeight
if (ClefSetting.clef == Clef.ALTO) {
val b = BitmapFactory.decodeResource(resources, R.drawable.alto_clef)
c.drawBitmap(Bitmap.createScaledBitmap(b, (4 * DensityMetrics.spaceHeight.toInt() / 1.5).toInt(), 4 * DensityMetrics.spaceHeight.toInt(), true), 20f, altoClef, paint)
} else if (ClefSetting.clef == Clef.TREBLE) {
val b = BitmapFactory.decodeResource(resources, R.drawable.treble_clef)
c.drawBitmap(Bitmap.createScaledBitmap(b, 420, 1200, true), 1f, 380f, paint)
} else if (ClefSetting.clef == Clef.BASS) {
val b = BitmapFactory.decodeResource(resources, R.drawable.bass_clef)
c.drawBitmap(Bitmap.createScaledBitmap(b, 420, 610, true), 20f, 500f, paint)
}
if (drawNote) {
drawNoteHead(renderableNote, c)
drawNote = false
}
}
//TODO: Make noteheads for different note values AND stack x values
override fun onTouchEvent(event: MotionEvent): Boolean {
val result = mDetector!!.onTouchEvent(event)
if (!result) {
Log.d("What", "is this gesture?")
}
val x = event.x
val y = event.y - DensityMetrics.getToolbarHeight()
//rhythmBar.setVisibility(View.GONE);
when (event.action) {
MotionEvent.ACTION_DOWN -> {
touchX = x
touchY = y
}
MotionEvent.ACTION_UP -> {
drawNote = true
invalidate()
renderableNote = Note(touchX, touchY, accidental)
var renderNote = true
for (note in MusicStore.activeNotes) {
if (renderableNote.name == note.name && renderableNote.octave == note.octave) {
renderNote = false
Log.d("Note", "Dupe note skipped!")
}
}
if (renderNote) {
MusicStore.activeNotes.add(renderableNote)
}
if (Settings.piano) {
val main = MainActivity()
main.nextInput()
}
}
}
return result
}
@TargetApi(21)
private fun drawNoteHead(note: Note, canvas: Canvas) {
val mediaPlayer = MediaPlayer()
try {
mediaPlayer.setDataSource(context, Uri.parse("android.resource://com.viviose.musicscratchpad/raw/" + note.name.toString() + Integer.toString(note.octave)))
} catch (e: Exception) {
}
Log.i("Media Playing:", "Player created!")
mediaPlayer.setOnPreparedListener { player -> player.start() }
mediaPlayer.setOnCompletionListener { mp -> mp.release() }
try {
mediaPlayer.prepareAsync()
} catch (e: Exception) {
}
//Gotta love gradle build times. Thanks Kotlin lmao
if (note.y - DensityMetrics.getToolbarHeight() <= DensityMetrics.spaceHeight * 2) {
canvas.drawLine(note.x - 200, DensityMetrics.spaceHeight + DensityMetrics.getToolbarHeight(), note.x + 200, DensityMetrics.spaceHeight + DensityMetrics.getToolbarHeight(), paint)
}
if (note.y - DensityMetrics.getToolbarHeight() >= DensityMetrics.spaceHeight * 6) {
canvas.drawLine(note.x - 200, DensityMetrics.spaceHeight * 7 + DensityMetrics.getToolbarHeight(), note.x + 200, DensityMetrics.spaceHeight * 7 + DensityMetrics.getToolbarHeight(), paint)
}
//canvas.drawOval(note.x - NOTE_WIDTH, note.y - DensityMetrics.spaceHeight / 2, note.x + NOTE_WIDTH, note.y + DensityMetrics.spaceHeight / 2, paint);
val headBmap: Bitmap
if (note.rhythm == 2.0) {
headBmap = NoteBitmap.hnh
} else {
headBmap = NoteBitmap.qnh
}
canvas.drawBitmap(Bitmap.createScaledBitmap(headBmap, (DensityMetrics.spaceHeight * 1.697).toInt(), DensityMetrics.spaceHeight.toInt(), true), (note.x - DensityMetrics.spaceHeight * 1.697 / 2).toInt().toFloat(), note.y - DensityMetrics.spaceHeight / 2, paint)
if (LastRhythm.dot) {
//TODO: I don't want these hardcoded obviously
canvas.drawCircle(note.x + 20, note.y + 20, 5f, paint)
LastRhythm.dot = false
}
if ((accidental == 1 && note.name != Note.NoteName.b && note.name != Note.NoteName.e) || note.accidental == 1) {
val vd = ContextCompat.getDrawable(context, R.drawable.sharp) as VectorDrawable
val b = NoteBitmap.getBitmap(vd)
canvas.drawBitmap(Bitmap.createScaledBitmap(b, (NOTE_HEIGHT * 3 / 2).toInt(), NOTE_HEIGHT.toInt() * 3, true), note.x - NOTE_WIDTH * 2, note.y - NOTE_HEIGHT * 3 / 2, paint)
}else if (accidental == -1 && note.name != Note.NoteName.f && note.name != Note.NoteName.c){
val vd = ContextCompat.getDrawable(context, R.drawable.flat) as VectorDrawable
val b = NoteBitmap.getBitmap(vd)
canvas.drawBitmap(Bitmap.createScaledBitmap(b, (NOTE_HEIGHT * 1.35).toInt(), NOTE_HEIGHT.toInt() * 3, true), note.x - NOTE_WIDTH * 2, note.y - NOTE_HEIGHT * 3 / 2, paint)
}
accidental = 0
//Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.alto_clef);
//c.drawBitmap(Bitmap.createScaledBitmap(b, (int) ((4 * (int) DensityMetrics.spaceHeight) / 1.5), 4 * (int) DensityMetrics.spaceHeight, true), 20, altoClef, paint);
}
internal inner class mListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(event: MotionEvent): Boolean {
Log.d(DEBUG_TAG, "onDown: " + event.toString())
return true
}
override fun onFling(ev1: MotionEvent, ev2: MotionEvent, velX: Float, velY: Float): Boolean {
if (velY > 5000) {
accidental = -1
}
if (velY < -5000) {
accidental = 1
}
if (velX < -5000) {
LastRhythm.dot = true;
}
return true
}
override fun onLongPress(event: MotionEvent) {
Log.d(DEBUG_TAG, "onLongPress: " + event.toString())
}
override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float,
distanceY: Float): Boolean {
return true
}
override fun onShowPress(event: MotionEvent) {
Log.d(DEBUG_TAG, "onShowPress: " + event.toString())
}
override fun onSingleTapUp(event: MotionEvent): Boolean {
Log.d(DEBUG_TAG, "onSingleTapUp: " + event.toString())
return true
}
}
companion object {
private val TAG = "EditorView"
}
} | gpl-3.0 | 4bc0a2d3dc4a9188eb4cee491bafde7b | 36.984674 | 267 | 0.610814 | 4.227292 | false | false | false | false |
matrix-org/matrix-android-sdk | matrix-sdk/src/androidTest/java/org/matrix/androidsdk/crypto/CryptoStoreTest.kt | 1 | 3984 | /*
* Copyright 2018 New Vector 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 org.matrix.androidsdk.crypto
import org.junit.Assert.*
import org.junit.Test
import org.matrix.androidsdk.crypto.cryptostore.IMXCryptoStore
import org.matrix.androidsdk.crypto.data.MXOlmSession
import org.matrix.olm.OlmAccount
import org.matrix.olm.OlmManager
import org.matrix.olm.OlmSession
private const val DUMMY_DEVICE_KEY = "DeviceKey"
class CryptoStoreTest {
private val cryptoStoreHelper = CryptoStoreHelper()
@Test
fun test_metadata_file_ok() {
test_metadata_ok(false)
}
@Test
fun test_metadata_realm_ok() {
test_metadata_ok(true)
}
private fun test_metadata_ok(useRealm: Boolean) {
val cryptoStore: IMXCryptoStore = cryptoStoreHelper.createStore(useRealm)
assertFalse(cryptoStore.hasData())
cryptoStore.open()
assertEquals("deviceId_sample", cryptoStore.deviceId)
assertTrue(cryptoStore.hasData())
// Cleanup
cryptoStore.close()
cryptoStore.deleteStore()
}
@Test
fun test_lastSessionUsed() {
// Ensure Olm is initialized
OlmManager()
val cryptoStore: IMXCryptoStore = cryptoStoreHelper.createStore(true)
assertNull(cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
val olmAccount1 = OlmAccount().apply {
generateOneTimeKeys(1)
}
val olmSession1 = OlmSession().apply {
initOutboundSession(olmAccount1,
olmAccount1.identityKeys()[OlmAccount.JSON_KEY_IDENTITY_KEY],
olmAccount1.oneTimeKeys()[OlmAccount.JSON_KEY_ONE_TIME_KEY]?.values?.first())
}
val sessionId1 = olmSession1.sessionIdentifier()
val mxOlmSession1 = MXOlmSession(olmSession1)
cryptoStore.storeSession(mxOlmSession1, DUMMY_DEVICE_KEY)
assertEquals(sessionId1, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
val olmAccount2 = OlmAccount().apply {
generateOneTimeKeys(1)
}
val olmSession2 = OlmSession().apply {
initOutboundSession(olmAccount2,
olmAccount2.identityKeys()[OlmAccount.JSON_KEY_IDENTITY_KEY],
olmAccount2.oneTimeKeys()[OlmAccount.JSON_KEY_ONE_TIME_KEY]?.values?.first())
}
val sessionId2 = olmSession2.sessionIdentifier()
val mxOlmSession2 = MXOlmSession(olmSession2)
cryptoStore.storeSession(mxOlmSession2, DUMMY_DEVICE_KEY)
// Ensure sessionIds are distinct
assertNotEquals(sessionId1, sessionId2)
// Note: we cannot be sure what will be the result of getLastUsedSessionId() here
mxOlmSession2.onMessageReceived()
cryptoStore.storeSession(mxOlmSession2, DUMMY_DEVICE_KEY)
// sessionId2 is returned now
assertEquals(sessionId2, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
Thread.sleep(2)
mxOlmSession1.onMessageReceived()
cryptoStore.storeSession(mxOlmSession1, DUMMY_DEVICE_KEY)
// sessionId1 is returned now
assertEquals(sessionId1, cryptoStore.getLastUsedSessionId(DUMMY_DEVICE_KEY))
// Cleanup
olmSession1.releaseSession()
olmSession2.releaseSession()
olmAccount1.releaseAccount()
olmAccount2.releaseAccount()
}
companion object {
private const val LOG_TAG = "CryptoStoreTest"
}
} | apache-2.0 | 3b61d26bb5d1460508f53d303de6ae15 | 29.653846 | 97 | 0.684237 | 4.077789 | false | true | false | false |
stevesea/RPGpad | adventuresmith-core/src/test/java/org/stevesea/adventuresmith/core/TestHelpers.kt | 2 | 1651 | /*
* Copyright (c) 2016 Steve Christensen
*
* This file is part of Adventuresmith.
*
* Adventuresmith 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.
*
* Adventuresmith 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 Adventuresmith. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.stevesea.adventuresmith.core
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.bind
import com.github.salomonbrys.kodein.instance
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import java.security.SecureRandom
import java.util.Random
fun getMockRandom(mockRandomVal: Int = 1) : Random {
val mockRandom : Random = mock()
whenever(mockRandom.nextInt(any())).thenReturn(mockRandomVal)
return mockRandom
}
fun getKodein(random: Random) = Kodein {
import(adventureSmithModule)
bind<Random>(overrides = true) with instance (random)
}
fun getGenerator(genName: String, mockRandomVal: Int = -1) : Generator {
if (mockRandomVal < 0)
return getKodein(SecureRandom()).instance(genName)
return getKodein(getMockRandom(mockRandomVal)).instance(genName)
}
| gpl-3.0 | c18425237d8cf7ffbbe9903c03a02726 | 34.12766 | 74 | 0.75954 | 3.866511 | false | false | false | false |
romannurik/muzei | extensions/src/main/java/com/google/android/apps/muzei/util/FlowExt.kt | 1 | 2342 | /*
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.util
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* A convenience wrapper around [androidx.lifecycle.LifecycleCoroutineScope.launch]
* that calls [collect] with [action], all wrapped in a lifecycle-aware
* [repeatOnLifecycle]. Think of it as [kotlinx.coroutines.flow.launchIn], but for
* collecting.
*
* ```
* uiStateFlow.collectIn(owner) { uiState ->
* updateUi(uiState)
* }
* ```
*/
inline fun <T> Flow<T>.collectIn(
owner: LifecycleOwner,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
coroutineContext: CoroutineContext = EmptyCoroutineContext,
crossinline action: suspend (T) -> Unit
) = owner.lifecycleScope.launch(coroutineContext) {
owner.lifecycle.repeatOnLifecycle(minActiveState) {
collect { action(it) }
}
}
/**
* A convenience wrapper around [androidx.lifecycle.LifecycleCoroutineScope.launch]
* that calls [collect], all wrapped in a lifecycle-aware
* [repeatOnLifecycle]. Think of it as [kotlinx.coroutines.flow.launchIn], but for
* collecting.
*
* ```
* uiStateFlow.collectIn(owner)
* ```
*/
fun <T> Flow<T>.collectIn(
owner: LifecycleOwner,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
coroutineContext: CoroutineContext = EmptyCoroutineContext
) = owner.lifecycleScope.launch(coroutineContext) {
owner.lifecycle.repeatOnLifecycle(minActiveState) {
collect()
}
} | apache-2.0 | bc3cc0714071fe0dcc8d6cfec023c2b9 | 32.471429 | 83 | 0.75064 | 4.313076 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineEventComponentFactoryImpl.kt | 1 | 10335 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.timeline
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent
import com.intellij.ui.ColorUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.GithubIcons
import org.intellij.lang.annotations.Language
import org.jetbrains.plugins.github.api.data.GHLabel
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHGitRefName
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestState
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.*
import org.jetbrains.plugins.github.pullrequest.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.ui.timeline.GHPRTimelineItemComponentFactory.Item
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import org.jetbrains.plugins.github.util.GithubUIUtil
import javax.swing.Icon
class GHPRTimelineEventComponentFactoryImpl(private val avatarIconsProvider: GHAvatarIconsProvider)
: GHPRTimelineEventComponentFactory<GHPRTimelineEvent> {
private val simpleEventDelegate = SimpleEventComponentFactory()
private val stateEventDelegate = StateEventComponentFactory()
private val branchEventDelegate = BranchEventComponentFactory()
private val complexEventDelegate = ComplexEventComponentFactory()
override fun createComponent(event: GHPRTimelineEvent): Item {
return when (event) {
is GHPRTimelineEvent.Simple -> simpleEventDelegate.createComponent(event)
is GHPRTimelineEvent.State -> stateEventDelegate.createComponent(event)
is GHPRTimelineEvent.Branch -> branchEventDelegate.createComponent(event)
is GHPRTimelineEvent.Complex -> complexEventDelegate.createComponent(event)
else -> throwUnknownType(event)
}
}
private fun throwUnknownType(item: GHPRTimelineEvent): Nothing {
throw IllegalStateException("""Unknown event type "${item.javaClass.canonicalName}"""")
}
private abstract inner class EventComponentFactory<T : GHPRTimelineEvent> : GHPRTimelineEventComponentFactory<T> {
protected fun eventItem(item: GHPRTimelineEvent, @Language("HTML") titleHTML: String): Item {
return eventItem(GithubIcons.Timeline, item, titleHTML)
}
protected fun eventItem(markerIcon: Icon,
item: GHPRTimelineEvent,
@Language("HTML") titleHTML: String): Item {
return Item(markerIcon, GHPRTimelineItemComponentFactory.actionTitle(avatarIconsProvider, item.actor, titleHTML, item.createdAt))
}
}
private inner class SimpleEventComponentFactory : EventComponentFactory<GHPRTimelineEvent.Simple>() {
override fun createComponent(event: GHPRTimelineEvent.Simple): Item {
return when (event) {
is GHPRAssignedEvent ->
eventItem(event, assigneesHTML(assigned = listOf(event.user)))
is GHPRUnassignedEvent ->
eventItem(event, assigneesHTML(unassigned = listOf(event.user)))
is GHPRReviewRequestedEvent ->
eventItem(event, reviewersHTML(added = listOf(event.requestedReviewer)))
is GHPRReviewUnrequestedEvent ->
eventItem(event, reviewersHTML(removed = listOf(event.requestedReviewer)))
is GHPRLabeledEvent ->
eventItem(event, labelsHTML(added = listOf(event.label)))
is GHPRUnlabeledEvent ->
eventItem(event, labelsHTML(removed = listOf(event.label)))
is GHPRRenamedTitleEvent ->
eventItem(event, renameHTML(event.previousTitle, event.currentTitle))
is GHPRTimelineMergedSimpleEvents -> {
val builder = StringBuilder()
.appendParagraph(labelsHTML(event.addedLabels, event.removedLabels))
.appendParagraph(assigneesHTML(event.assignedPeople, event.unassignedPeople))
.appendParagraph(reviewersHTML(event.addedReviewers, event.removedReviewers))
.appendParagraph(event.rename?.let { renameHTML(it.first, it.second) }.orEmpty())
Item(GithubIcons.Timeline, GHPRTimelineItemComponentFactory.actionTitle(avatarIconsProvider, event.actor, "", event.createdAt),
HtmlEditorPane(builder.toString()).apply {
border = JBUI.Borders.emptyLeft(28)
foreground = UIUtil.getContextHelpForeground()
})
}
else -> throwUnknownType(event)
}
}
private fun assigneesHTML(assigned: Collection<GHUser> = emptyList(), unassigned: Collection<GHUser> = emptyList()): String {
val builder = StringBuilder()
if (assigned.isNotEmpty()) {
builder.append(assigned.joinToString(prefix = "assigned ") { "<b>${it.login}</b>" })
}
if (unassigned.isNotEmpty()) {
if (builder.isNotEmpty()) builder.append(" and ")
builder.append(unassigned.joinToString(prefix = "unassigned ") { "<b>${it.login}</b>" })
}
return builder.toString()
}
private fun reviewersHTML(added: Collection<GHPullRequestRequestedReviewer> = emptyList(),
removed: Collection<GHPullRequestRequestedReviewer> = emptyList()): String {
val builder = StringBuilder()
if (added.isNotEmpty()) {
builder.append(added.joinToString(prefix = "requested a review from ") { "<b>${it.shortName}</b>" })
}
if (removed.isNotEmpty()) {
if (builder.isNotEmpty()) builder.append(" and ")
builder.append(removed.joinToString(prefix = "removed review request from ") { "<b>${it.shortName}</b>" })
}
return builder.toString()
}
private fun labelsHTML(added: Collection<GHLabel> = emptyList(), removed: Collection<GHLabel> = emptyList()): String {
val builder = StringBuilder()
if (added.isNotEmpty()) {
if (added.size > 1) {
builder.append(added.joinToString(prefix = "added labels ") { labelHTML(it) })
}
else {
builder.append("added the ").append(labelHTML(added.first())).append(" label")
}
}
if (removed.isNotEmpty()) {
if (builder.isNotEmpty()) builder.append(" and ")
if (removed.size > 1) {
builder.append(removed.joinToString(prefix = "removed labels ") { labelHTML(it) })
}
else {
builder.append("removed the ").append(labelHTML(removed.first())).append(" label")
}
}
return builder.toString()
}
private fun labelHTML(label: GHLabel): String {
val background = GithubUIUtil.getLabelBackground(label)
val foreground = GithubUIUtil.getLabelForeground(background)
//language=HTML
return """<span style='color: #${ColorUtil.toHex(foreground)}; background: #${ColorUtil.toHex(background)}'>
${StringUtil.escapeXmlEntities(label.name)} </span>"""
}
private fun renameHTML(oldName: String, newName: String) = "renamed this from <b>$oldName</b> to <b>$newName</b>"
}
private inner class StateEventComponentFactory : EventComponentFactory<GHPRTimelineEvent.State>() {
override fun createComponent(event: GHPRTimelineEvent.State): Item {
val icon = when (event.newState) {
GHPullRequestState.CLOSED -> GithubIcons.PullRequestClosed
GHPullRequestState.MERGED -> GithubIcons.PullRequestMerged
GHPullRequestState.OPEN -> GithubIcons.PullRequestOpen
}
val text = when (event.newState) {
GHPullRequestState.CLOSED -> "closed this"
GHPullRequestState.MERGED -> "merged this"
GHPullRequestState.OPEN -> "reopened this"
}
return eventItem(icon, event, text)
}
}
private inner class BranchEventComponentFactory : EventComponentFactory<GHPRTimelineEvent.Branch>() {
override fun createComponent(event: GHPRTimelineEvent.Branch): Item {
return when (event) {
is GHPRBaseRefChangedEvent ->
eventItem(event, "changed the base branch")
is GHPRBaseRefForcePushedEvent ->
eventItem(event, "force-pushed the ${branchHTML(event.ref) ?: "base"} branch")
is GHPRHeadRefForcePushedEvent ->
eventItem(event, "force-pushed the ${branchHTML(event.ref) ?: "head"} branch")
is GHPRHeadRefDeletedEvent ->
eventItem(event, "deleted the ${branchHTML(event.headRefName)} branch")
is GHPRHeadRefRestoredEvent ->
eventItem(event, "restored head branch")
else -> throwUnknownType(event)
}
}
private fun branchHTML(ref: GHGitRefName?) = ref?.name?.let { branchHTML(it) }
//language=HTML
private fun branchHTML(name: String): String {
val foreground = CurrentBranchComponent.TEXT_COLOR
val background = CurrentBranchComponent.getBranchPresentationBackground(UIUtil.getListBackground())
return """<span style='color: #${ColorUtil.toHex(foreground)}; background: #${ColorUtil.toHex(background)}'>
<icon-inline src='GithubIcons.Branch'/>$name </span>"""
}
}
private inner class ComplexEventComponentFactory : EventComponentFactory<GHPRTimelineEvent.Complex>() {
override fun createComponent(event: GHPRTimelineEvent.Complex): Item {
return when (event) {
is GHPRReviewDismissedEvent ->
Item(GithubIcons.Timeline, GHPRTimelineItemComponentFactory.actionTitle(avatarIconsProvider, event.actor,
"dismissed <b>${event.reviewAuthor?.login}</b>`s stale review",
event.createdAt),
event.dismissalMessageHTML?.let {
HtmlEditorPane(it).apply {
border = JBUI.Borders.emptyLeft(28)
}
})
else -> throwUnknownType(event)
}
}
}
companion object {
private fun StringBuilder.appendParagraph(text: String): StringBuilder {
if (text.isNotEmpty()) this.append("<p>").append(text).append("</p>")
return this
}
}
}
| apache-2.0 | 3824737dc1fb30b7bd00be615d8b66f3 | 44.528634 | 145 | 0.683019 | 4.881908 | false | false | false | false |
googlecodelabs/android-performance | benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/home/cart/Cart.kt | 1 | 19783 | /*
* 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.
*/
package com.example.macrobenchmark_codelab.ui.home.cart
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.macrobenchmark_codelab.R
import com.example.macrobenchmark_codelab.model.OrderLine
import com.example.macrobenchmark_codelab.model.SnackCollection
import com.example.macrobenchmark_codelab.model.SnackRepo
import com.example.macrobenchmark_codelab.ui.components.JetsnackButton
import com.example.macrobenchmark_codelab.ui.components.JetsnackDivider
import com.example.macrobenchmark_codelab.ui.components.JetsnackSurface
import com.example.macrobenchmark_codelab.ui.components.QuantitySelector
import com.example.macrobenchmark_codelab.ui.components.SnackCollection
import com.example.macrobenchmark_codelab.ui.components.SnackImage
import com.example.macrobenchmark_codelab.ui.home.DestinationBar
import com.example.macrobenchmark_codelab.ui.theme.AlphaNearOpaque
import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme
import com.example.macrobenchmark_codelab.ui.utils.formatPrice
@Composable
fun Cart(
onSnackClick: (Long) -> Unit,
modifier: Modifier = Modifier,
viewModel: CartViewModel = viewModel(factory = CartViewModel.provideFactory())
) {
val orderLines by viewModel.orderLines.collectAsState()
val inspiredByCart = remember { SnackRepo.getInspiredByCart() }
Cart(
orderLines = orderLines,
removeSnack = viewModel::removeSnack,
increaseItemCount = viewModel::increaseSnackCount,
decreaseItemCount = viewModel::decreaseSnackCount,
inspiredByCart = inspiredByCart,
onSnackClick = onSnackClick,
modifier = modifier
)
}
@Composable
fun Cart(
orderLines: List<OrderLine>,
removeSnack: (Long) -> Unit,
increaseItemCount: (Long) -> Unit,
decreaseItemCount: (Long) -> Unit,
inspiredByCart: SnackCollection,
onSnackClick: (Long) -> Unit,
modifier: Modifier = Modifier
) {
JetsnackSurface(modifier = modifier.fillMaxSize()) {
Box {
CartContent(
orderLines = orderLines,
removeSnack = removeSnack,
increaseItemCount = increaseItemCount,
decreaseItemCount = decreaseItemCount,
inspiredByCart = inspiredByCart,
onSnackClick = onSnackClick,
modifier = Modifier.align(Alignment.TopCenter)
)
DestinationBar(modifier = Modifier.align(Alignment.TopCenter))
CheckoutBar(modifier = Modifier.align(Alignment.BottomCenter))
}
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
private fun CartContent(
orderLines: List<OrderLine>,
removeSnack: (Long) -> Unit,
increaseItemCount: (Long) -> Unit,
decreaseItemCount: (Long) -> Unit,
inspiredByCart: SnackCollection,
onSnackClick: (Long) -> Unit,
modifier: Modifier = Modifier
) {
val resources = LocalContext.current.resources
val snackCountFormattedString = remember(orderLines.size, resources) {
resources.getQuantityString(
R.plurals.cart_order_count,
orderLines.size, orderLines.size
)
}
LazyColumn(modifier) {
item {
Spacer(
Modifier.windowInsetsTopHeight(
WindowInsets.statusBars.add(WindowInsets(top = 56.dp))
)
)
Text(
text = stringResource(R.string.cart_order_header, snackCountFormattedString),
style = MaterialTheme.typography.h6,
color = JetsnackTheme.colors.brand,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.heightIn(min = 56.dp)
.padding(horizontal = 24.dp, vertical = 4.dp)
.wrapContentHeight()
)
}
items(orderLines) { orderLine ->
SwipeDismissItem(
background = { offsetX ->
/*Background color changes from light gray to red when the
swipe to delete with exceeds 160.dp*/
val backgroundColor = if (offsetX < -160.dp) {
JetsnackTheme.colors.error
} else {
JetsnackTheme.colors.uiFloated
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(backgroundColor),
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.Center
) {
// Set 4.dp padding only if offset is bigger than 160.dp
val padding: Dp by animateDpAsState(
if (offsetX > -160.dp) 4.dp else 0.dp
)
Box(
Modifier
.width(offsetX * -1)
.padding(padding)
) {
// Height equals to width removing padding
val height = (offsetX + 8.dp) * -1
Surface(
modifier = Modifier
.fillMaxWidth()
.height(height)
.align(Alignment.Center),
shape = CircleShape,
color = JetsnackTheme.colors.error
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
// Icon must be visible while in this width range
if (offsetX < -40.dp && offsetX > -152.dp) {
// Icon alpha decreases as it is about to disappear
val iconAlpha: Float by animateFloatAsState(
if (offsetX < -120.dp) 0.5f else 1f
)
Icon(
imageVector = Icons.Filled.DeleteForever,
modifier = Modifier
.size(16.dp)
.graphicsLayer(alpha = iconAlpha),
tint = JetsnackTheme.colors.uiBackground,
contentDescription = null,
)
}
/*Text opacity increases as the text is supposed to appear in
the screen*/
val textAlpha by animateFloatAsState(
if (offsetX > -144.dp) 0.5f else 1f
)
if (offsetX < -120.dp) {
Text(
text = stringResource(id = R.string.remove_item),
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.uiBackground,
textAlign = TextAlign.Center,
modifier = Modifier
.graphicsLayer(
alpha = textAlpha
)
)
}
}
}
}
}
},
) {
CartItem(
orderLine = orderLine,
removeSnack = removeSnack,
increaseItemCount = increaseItemCount,
decreaseItemCount = decreaseItemCount,
onSnackClick = onSnackClick
)
}
}
item {
SummaryItem(
subtotal = orderLines.map { it.snack.price * it.count }.sum(),
shippingCosts = 369
)
}
item {
SnackCollection(
snackCollection = inspiredByCart,
onSnackClick = onSnackClick,
highlight = false
)
Spacer(Modifier.height(56.dp))
}
}
}
@Composable
fun CartItem(
orderLine: OrderLine,
removeSnack: (Long) -> Unit,
increaseItemCount: (Long) -> Unit,
decreaseItemCount: (Long) -> Unit,
onSnackClick: (Long) -> Unit,
modifier: Modifier = Modifier
) {
val snack = orderLine.snack
ConstraintLayout(
modifier = modifier
.fillMaxWidth()
.clickable { onSnackClick(snack.id) }
.background(JetsnackTheme.colors.uiBackground)
.padding(horizontal = 24.dp)
) {
val (divider, image, name, tag, priceSpacer, price, remove, quantity) = createRefs()
createVerticalChain(name, tag, priceSpacer, price, chainStyle = ChainStyle.Packed)
SnackImage(
imageUrl = snack.imageUrl,
contentDescription = null,
modifier = Modifier
.size(100.dp)
.constrainAs(image) {
top.linkTo(parent.top, margin = 16.dp)
bottom.linkTo(parent.bottom, margin = 16.dp)
start.linkTo(parent.start)
}
)
Text(
text = snack.name,
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.textSecondary,
modifier = Modifier.constrainAs(name) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = remove.start,
endMargin = 16.dp,
bias = 0f
)
}
)
IconButton(
onClick = { removeSnack(snack.id) },
modifier = Modifier
.constrainAs(remove) {
top.linkTo(parent.top)
end.linkTo(parent.end)
}
.padding(top = 12.dp)
) {
Icon(
imageVector = Icons.Filled.Close,
tint = JetsnackTheme.colors.iconSecondary,
contentDescription = stringResource(R.string.label_remove)
)
}
Text(
text = snack.tagline,
style = MaterialTheme.typography.body1,
color = JetsnackTheme.colors.textHelp,
modifier = Modifier.constrainAs(tag) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = parent.end,
endMargin = 16.dp,
bias = 0f
)
}
)
Spacer(
Modifier
.height(8.dp)
.constrainAs(priceSpacer) {
linkTo(top = tag.bottom, bottom = price.top)
}
)
Text(
text = formatPrice(snack.price),
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.textPrimary,
modifier = Modifier.constrainAs(price) {
linkTo(
start = image.end,
end = quantity.start,
startMargin = 16.dp,
endMargin = 16.dp,
bias = 0f
)
}
)
QuantitySelector(
count = orderLine.count,
decreaseItemCount = { decreaseItemCount(snack.id) },
increaseItemCount = { increaseItemCount(snack.id) },
modifier = Modifier.constrainAs(quantity) {
baseline.linkTo(price.baseline)
end.linkTo(parent.end)
}
)
JetsnackDivider(
Modifier.constrainAs(divider) {
linkTo(start = parent.start, end = parent.end)
top.linkTo(parent.bottom)
}
)
}
}
@Composable
fun SummaryItem(
subtotal: Long,
shippingCosts: Long,
modifier: Modifier = Modifier
) {
Column(modifier) {
Text(
text = stringResource(R.string.cart_summary_header),
style = MaterialTheme.typography.h6,
color = JetsnackTheme.colors.brand,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.padding(horizontal = 24.dp)
.heightIn(min = 56.dp)
.wrapContentHeight()
)
Row(modifier = Modifier.padding(horizontal = 24.dp)) {
Text(
text = stringResource(R.string.cart_subtotal_label),
style = MaterialTheme.typography.body1,
modifier = Modifier
.weight(1f)
.wrapContentWidth(Alignment.Start)
.alignBy(LastBaseline)
)
Text(
text = formatPrice(subtotal),
style = MaterialTheme.typography.body1,
modifier = Modifier.alignBy(LastBaseline)
)
}
Row(modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) {
Text(
text = stringResource(R.string.cart_shipping_label),
style = MaterialTheme.typography.body1,
modifier = Modifier
.weight(1f)
.wrapContentWidth(Alignment.Start)
.alignBy(LastBaseline)
)
Text(
text = formatPrice(shippingCosts),
style = MaterialTheme.typography.body1,
modifier = Modifier.alignBy(LastBaseline)
)
}
Spacer(modifier = Modifier.height(8.dp))
JetsnackDivider()
Row(modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) {
Text(
text = stringResource(R.string.cart_total_label),
style = MaterialTheme.typography.body1,
modifier = Modifier
.weight(1f)
.padding(end = 16.dp)
.wrapContentWidth(Alignment.End)
.alignBy(LastBaseline)
)
Text(
text = formatPrice(subtotal + shippingCosts),
style = MaterialTheme.typography.subtitle1,
modifier = Modifier.alignBy(LastBaseline)
)
}
JetsnackDivider()
}
}
@Composable
private fun CheckoutBar(modifier: Modifier = Modifier) {
Column(
modifier.background(
JetsnackTheme.colors.uiBackground.copy(alpha = AlphaNearOpaque)
)
) {
JetsnackDivider()
Row {
Spacer(Modifier.weight(1f))
JetsnackButton(
onClick = { /* todo */ },
shape = RectangleShape,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 8.dp)
.weight(1f)
) {
Text(
text = stringResource(id = R.string.cart_checkout),
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Left,
maxLines = 1
)
}
}
}
}
@Preview("default")
@Preview("dark theme", uiMode = UI_MODE_NIGHT_YES)
@Preview("large font", fontScale = 2f)
@Composable
private fun CartPreview() {
JetsnackTheme {
Cart(
orderLines = SnackRepo.getCart(),
removeSnack = {},
increaseItemCount = {},
decreaseItemCount = {},
inspiredByCart = SnackRepo.getInspiredByCart(),
onSnackClick = {}
)
}
}
| apache-2.0 | bd15a1dc92d824718b4caa9a26aedcc0 | 38.174257 | 97 | 0.544862 | 5.393402 | false | false | false | false |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/collections/Collections.kt | 2 | 89873 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.collections
import kotlin.comparisons.*
internal object EmptyIterator : ListIterator<Nothing> {
override fun hasNext(): Boolean = false
override fun hasPrevious(): Boolean = false
override fun nextIndex(): Int = 0
override fun previousIndex(): Int = -1
override fun next(): Nothing = throw NoSuchElementException()
override fun previous(): Nothing = throw NoSuchElementException()
}
internal object EmptyList : List<Nothing>, RandomAccess {
override fun equals(other: Any?): Boolean = other is List<*> && other.isEmpty()
override fun hashCode(): Int = 1
override fun toString(): String = "[]"
override val size: Int get() = 0
override fun isEmpty(): Boolean = true
override fun contains(element: Nothing): Boolean = false
override fun containsAll(elements: Collection<Nothing>): Boolean = elements.isEmpty()
override fun get(index: Int): Nothing = throw IndexOutOfBoundsException("Empty list doesn't contain element at index $index.")
override fun indexOf(element: Nothing): Int = -1
override fun lastIndexOf(element: Nothing): Int = -1
override fun iterator(): Iterator<Nothing> = EmptyIterator
override fun listIterator(): ListIterator<Nothing> = EmptyIterator
override fun listIterator(index: Int): ListIterator<Nothing> {
if (index != 0) throw IndexOutOfBoundsException("Index: $index")
return EmptyIterator
}
override fun subList(fromIndex: Int, toIndex: Int): List<Nothing> {
if (fromIndex == 0 && toIndex == 0) return this
throw IndexOutOfBoundsException("fromIndex: $fromIndex, toIndex: $toIndex")
}
private fun readResolve(): Any = EmptyList
}
internal fun <T> Array<out T>.asCollection(): Collection<T> = ArrayAsCollection(this, isVarargs = false)
private class ArrayAsCollection<T>(val values: Array<out T>, val isVarargs: Boolean): Collection<T> {
override val size: Int get() = values.size
override fun isEmpty(): Boolean = values.isEmpty()
override fun contains(element: T): Boolean = values.contains(element)
override fun containsAll(elements: Collection<T>): Boolean = elements.all { contains(it) }
override fun iterator(): Iterator<T> = values.iterator()
// override hidden toArray implementation to prevent copying of values array
public fun toArray(): Array<out Any?> = values.copyToArrayOfAny(isVarargs)
}
/** Returns an empty read-only list. */
public fun <T> emptyList(): List<T> = EmptyList
/** Returns a new read-only list of given elements. */
public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elements.asList() else emptyList()
/** Returns an empty read-only list. */
@kotlin.internal.InlineOnly
public inline fun <T> listOf(): List<T> = emptyList()
/** Returns a new [MutableList] with the given elements. */
public fun <T> mutableListOf(vararg elements: T): MutableList<T>
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
// This part is from generated _Collections.kt.
/** Returns a new [ArrayList] with the given elements. */
public fun <T> arrayListOf(vararg elements: T): ArrayList<T>
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
/** Returns a new read-only list either of single given element, if it is not null,
* or empty list it the element is null.*/
public fun <T : Any> listOfNotNull(element: T?): List<T> =
if (element != null) listOf(element) else emptyList()
/** Returns a new read-only list only of those given elements, that are not null. */
public fun <T : Any> listOfNotNull(vararg elements: T?): List<T> = elements.filterNotNull()
/**
* Creates a new read-only list with the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns a list element given its index.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T> = MutableList(size, init)
/**
* Creates a new mutable list with the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns a list element given its index.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> {
val list = ArrayList<T>(size)
repeat(size) { index -> list.add(init(index)) }
return list
}
/**
* Returns an [IntRange] of the valid indices for this collection.
*/
public val Collection<*>.indices: IntRange
get() = 0..size - 1
/**
* Returns the index of the last item in the list or -1 if the list is empty.
*
* @sample samples.collections.Collections.Lists.lastIndexOfList
*/
public val <T> List<T>.lastIndex: Int
get() = this.size - 1
/** Returns `true` if the collection is not empty. */
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.isNotEmpty(): Boolean = !isEmpty()
/** Returns this Collection if it's not `null` and the empty list otherwise. */
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>?.orEmpty(): Collection<T> = this ?: emptyList()
@kotlin.internal.InlineOnly
public inline fun <T> List<T>?.orEmpty(): List<T> = this ?: emptyList()
/**
* Checks if all elements in the specified collection are contained in this collection.
*
* Allows to overcome type-safety restriction of `containsAll` that requires to pass a collection of type `Collection<E>`.
*/
@kotlin.internal.InlineOnly
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public inline fun <@kotlin.internal.OnlyInputTypes T> Collection<T>.containsAll(
elements: Collection<T>): Boolean = this.containsAll(elements)
// copies typed varargs array to array of objects
// TODO: generally wrong, wrt specialization.
@FixmeSpecialization
private fun <T> Array<out T>.copyToArrayOfAny(isVarargs: Boolean): Array<Any?> =
if (isVarargs)
// if the array came from varargs and already is array of Any, copying isn't required.
@Suppress("UNCHECKED_CAST") (this as Array<Any?>)
else
@Suppress("UNCHECKED_CAST") (this.copyOfUninitializedElements(this.size) as Array<Any?>)
/**
* Classes that inherit from this interface can be represented as a sequence of elements that can
* be iterated over.
* @param T the type of element being iterated over.
*/
public interface Iterable<out T> {
/**
* Returns an iterator over the elements of this object.
*/
public operator fun iterator(): Iterator<T>
}
/**
* Classes that inherit from this interface can be represented as a sequence of elements that can
* be iterated over and that supports removing elements during iteration.
*/
public interface MutableIterable<out T> : Iterable<T> {
/**
* Returns an iterator over the elementrs of this sequence that supports removing elements during iteration.
*/
override fun iterator(): MutableIterator<T>
}
public fun <T> Array<out T>.asList(): List<T> {
return object : AbstractList<T>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: T): Boolean = [email protected](element)
override fun get(index: Int): T = this@asList[index]
override fun indexOf(element: T): Int = [email protected](element)
override fun lastIndexOf(element: T): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun ByteArray.asList(): List<Byte> {
return object : AbstractList<Byte>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Byte): Boolean = [email protected](element)
override fun get(index: Int): Byte = this@asList[index]
override fun indexOf(element: Byte): Int = [email protected](element)
override fun lastIndexOf(element: Byte): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun ShortArray.asList(): List<Short> {
return object : AbstractList<Short>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Short): Boolean = [email protected](element)
override fun get(index: Int): Short = this@asList[index]
override fun indexOf(element: Short): Int = [email protected](element)
override fun lastIndexOf(element: Short): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun IntArray.asList(): List<Int> {
return object : AbstractList<Int>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Int): Boolean = [email protected](element)
override fun get(index: Int): Int = this@asList[index]
override fun indexOf(element: Int): Int = [email protected](element)
override fun lastIndexOf(element: Int): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun LongArray.asList(): List<Long> {
return object : AbstractList<Long>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Long): Boolean = [email protected](element)
override fun get(index: Int): Long = this@asList[index]
override fun indexOf(element: Long): Int = [email protected](element)
override fun lastIndexOf(element: Long): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun FloatArray.asList(): List<Float> {
return object : AbstractList<Float>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Float): Boolean = [email protected](element)
override fun get(index: Int): Float = this@asList[index]
override fun indexOf(element: Float): Int = [email protected](element)
override fun lastIndexOf(element: Float): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun DoubleArray.asList(): List<Double> {
return object : AbstractList<Double>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Double): Boolean = [email protected](element)
override fun get(index: Int): Double = this@asList[index]
override fun indexOf(element: Double): Int = [email protected](element)
override fun lastIndexOf(element: Double): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun BooleanArray.asList(): List<Boolean> {
return object : AbstractList<Boolean>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Boolean): Boolean = [email protected](element)
override fun get(index: Int): Boolean = this@asList[index]
override fun indexOf(element: Boolean): Int = [email protected](element)
override fun lastIndexOf(element: Boolean): Int = [email protected](element)
}
}
/**
* Returns a [List] that wraps the original array.
*/
public fun CharArray.asList(): List<Char> {
return object : AbstractList<Char>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: Char): Boolean = [email protected](element)
override fun get(index: Int): Char = this@asList[index]
override fun indexOf(element: Char): Int = [email protected](element)
override fun lastIndexOf(element: Char): Int = [email protected](element)
}
}
@Fixme
internal fun <T> List<T>.optimizeReadOnlyList() = this
/**
* Searches this list or its range for the provided [element] using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the Comparable natural ordering of its elements,
* otherwise the result is undefined.
*
* If the list contains multiple elements equal to the specified [element], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public fun <T: Comparable<T>> List<T?>.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int {
rangeCheck(size, fromIndex, toIndex)
var lowBorder = fromIndex
var highBorder = toIndex - 1
while (lowBorder <= highBorder) {
val middleIndex = (lowBorder + highBorder).ushr(1) // safe from overflows
val middleValue = get(middleIndex)
val comparisonResult = compareValues(middleValue, element)
if (comparisonResult < 0)
lowBorder = middleIndex + 1
else if (comparisonResult > 0)
highBorder = middleIndex - 1
else
return middleIndex // key found
}
return -(lowBorder + 1) // key not found
}
/**
* Searches this list or its range for the provided [element] using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the specified [comparator],
* otherwise the result is undefined.
*
* If the list contains multiple elements equal to the specified [element], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted according to the specified [comparator].
*/
public fun <T> List<T>.binarySearch(element: T, comparator: Comparator<in T>, fromIndex: Int = 0, toIndex: Int = size): Int {
rangeCheck(size, fromIndex, toIndex)
var lowBorder = fromIndex
var highBorder = toIndex - 1
while (lowBorder <= highBorder) {
val middleIndex = (lowBorder + highBorder).ushr(1) // safe from overflows
val middleValue = get(middleIndex)
val comparisonResult = comparator.compare(middleValue, element)
if (comparisonResult < 0)
lowBorder = middleIndex + 1
else if (comparisonResult > 0)
highBorder = middleIndex - 1
else
return middleIndex // key found
}
return -(lowBorder + 1) // key not found
}
/**
* Searches this list or its range for an element having the key returned by the specified [selector] function
* equal to the provided [key] value using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the Comparable natural ordering of keys of its elements.
* otherwise the result is undefined.
*
* If the list contains multiple elements with the specified [key], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element with the specified [key], if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size, crossinline selector: (T) -> K?): Int =
binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) }
/**
* Searches this list or its range for an element for which [comparison] function returns zero using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the provided [comparison],
* otherwise the result is undefined.
*
* If the list contains multiple elements for which [comparison] returns zero, there is no guarantee which one will be found.
*
* @param comparison function that compares an element of the list with the element being searched.
*
* @return the index of the found element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public fun <T> List<T>.binarySearch(fromIndex: Int = 0, toIndex: Int = size, comparison: (T) -> Int): Int {
rangeCheck(size, fromIndex, toIndex)
var lowBorder = fromIndex
var highBorder = toIndex - 1
while (lowBorder <= highBorder) {
val middleIndex = (lowBorder + highBorder).ushr(1) // safe from overflows
val middleValue = get(middleIndex)
val comparisonResult = comparison(middleValue)
if (comparisonResult < 0)
lowBorder = middleIndex + 1
else if (comparisonResult > 0)
highBorder = middleIndex - 1
else
return middleIndex // key found
}
return -(lowBorder + 1) // key not found
}
/**
* Checks that `from` and `to` are in
* the range of [0..size] and throws an appropriate exception, if they aren't.
*/
private fun rangeCheck(size: Int, fromIndex: Int, toIndex: Int) {
when {
fromIndex > toIndex -> throw IllegalArgumentException("fromIndex ($fromIndex) is greater than toIndex ($toIndex).")
fromIndex < 0 -> throw IndexOutOfBoundsException("fromIndex ($fromIndex) is less than zero.")
toIndex > size -> throw IndexOutOfBoundsException("toIndex ($toIndex) is greater than size ($size).")
}
}
// From generated _Collections.kt.
/////////
/**
* Returns 1st *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component1(): T {
return get(0)
}
/**
* Returns 2nd *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component2(): T {
return get(1)
}
/**
* Returns 3rd *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component3(): T {
return get(2)
}
/**
* Returns 4th *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component4(): T {
return get(3)
}
/**
* Returns 5th *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun <T> List<T>.component5(): T {
return get(4)
}
/**
* Returns `true` if [element] is found in the collection.
*/
public operator fun <@kotlin.internal.OnlyInputTypes T> Iterable<T>.contains(element: T): Boolean {
if (this is Collection)
return contains(element)
return indexOf(element) >= 0
}
/**
* Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this collection.
*/
public fun <T> Iterable<T>.elementAt(index: Int): T {
if (this is List)
return get(index)
return elementAtOrElse(index) { throw IndexOutOfBoundsException("Collection doesn't contain element at index $index.") }
}
/**
* Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this list.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.elementAt(index: Int): T {
return get(index)
}
/**
* Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this collection.
*/
public fun <T> Iterable<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
if (this is List)
return this.getOrElse(index, defaultValue)
if (index < 0)
return defaultValue(index)
val iterator = iterator()
var count = 0
while (iterator.hasNext()) {
val element = iterator.next()
if (index == count++)
return element
}
return defaultValue(index)
}
/**
* Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this list.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}
/**
* Returns an element at the given [index] or `null` if the [index] is out of bounds of this collection.
*/
public fun <T> Iterable<T>.elementAtOrNull(index: Int): T? {
if (this is List)
return this.getOrNull(index)
if (index < 0)
return null
val iterator = iterator()
var count = 0
while (iterator.hasNext()) {
val element = iterator.next()
if (index == count++)
return element
}
return null
}
/**
* Returns an element at the given [index] or `null` if the [index] is out of bounds of this list.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.elementAtOrNull(index: Int): T? {
return this.getOrNull(index)
}
/**
* Returns the first element matching the given [predicate], or `null` if no such element was found.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.find(predicate: (T) -> Boolean): T? {
return firstOrNull(predicate)
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.findLast(predicate: (T) -> Boolean): T? {
return lastOrNull(predicate)
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.findLast(predicate: (T) -> Boolean): T? {
return lastOrNull(predicate)
}
/**
* Returns first element.
* @throws [NoSuchElementException] if the collection is empty.
*/
public fun <T> Iterable<T>.first(): T {
when (this) {
is List -> return this.first()
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty.")
return iterator.next()
}
}
}
/**
* Returns first element.
* @throws [NoSuchElementException] if the list is empty.
*/
public fun <T> List<T>.first(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[0]
}
/**
* Returns the first element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
public inline fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T {
for (element in this) if (predicate(element)) return element
throw NoSuchElementException("Collection contains no element matching the predicate.")
}
/**
* Returns the first element, or `null` if the collection is empty.
*/
public fun <T> Iterable<T>.firstOrNull(): T? {
when (this) {
is List -> {
if (isEmpty())
return null
else
return this[0]
}
else -> {
val iterator = iterator()
if (!iterator.hasNext())
return null
return iterator.next()
}
}
}
/**
* Returns the first element, or `null` if the list is empty.
*/
public fun <T> List<T>.firstOrNull(): T? {
return if (isEmpty()) null else this[0]
}
/**
* Returns the first element matching the given [predicate], or `null` if element was not found.
*/
public inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this list.
*/
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.getOrElse(index: Int, defaultValue: (Int) -> T): T {
return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}
/**
* Returns an element at the given [index] or `null` if the [index] is out of bounds of this list.
*/
public fun <T> List<T>.getOrNull(index: Int): T? {
return if (index >= 0 && index <= lastIndex) get(index) else null
}
/**
* Returns first index of [element], or -1 if the collection does not contain element.
*/
public fun <@kotlin.internal.OnlyInputTypes T> Iterable<T>.indexOf(element: T): Int {
if (this is List) return this.indexOf(element)
var index = 0
for (item in this) {
if (element == item)
return index
index++
}
return -1
}
/**
* Returns first index of [element], or -1 if the list does not contain element.
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun <@kotlin.internal.OnlyInputTypes T> List<T>.indexOf(element: T): Int {
return indexOf(element)
}
/**
* Returns index of the first element matching the given [predicate], or -1 if the collection does not contain such element.
*/
public inline fun <T> Iterable<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
var index = 0
for (item in this) {
if (predicate(item))
return index
index++
}
return -1
}
/**
* Returns index of the first element matching the given [predicate], or -1 if the list does not contain such element.
*/
public inline fun <T> List<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
var index = 0
for (item in this) {
if (predicate(item))
return index
index++
}
return -1
}
/**
* Returns index of the last element matching the given [predicate], or -1 if the collection does not contain such element.
*/
public inline fun <T> Iterable<T>.indexOfLast(predicate: (T) -> Boolean): Int {
var lastIndex = -1
var index = 0
for (item in this) {
if (predicate(item))
lastIndex = index
index++
}
return lastIndex
}
/**
* Returns index of the last element matching the given [predicate], or -1 if the list does not contain such element.
*/
public inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (predicate(iterator.previous())) {
return iterator.nextIndex()
}
}
return -1
}
/**
* Returns the last element.
* @throws [NoSuchElementException] if the collection is empty.
*/
public fun <T> Iterable<T>.last(): T {
when (this) {
is List -> return this.last()
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty.")
var last = iterator.next()
while (iterator.hasNext())
last = iterator.next()
return last
}
}
}
/**
* Returns the last element.
* @throws [NoSuchElementException] if the list is empty.
*/
public fun <T> List<T>.last(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[lastIndex]
}
/**
* Returns the last element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
public inline fun <T> Iterable<T>.last(predicate: (T) -> Boolean): T {
var last: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
last = element
found = true
}
}
if (!found) throw NoSuchElementException("Collection contains no element matching the predicate.")
@Suppress("UNCHECKED_CAST")
return last as T
}
/**
* Returns the last element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
public inline fun <T> List<T>.last(predicate: (T) -> Boolean): T {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
throw NoSuchElementException("List contains no element matching the predicate.")
}
/**
* Returns last index of [element], or -1 if the collection does not contain element.
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun <@kotlin.internal.OnlyInputTypes T> Iterable<T>.lastIndexOf(element: T): Int {
if (this is List) return this.lastIndexOf(element)
var lastIndex = -1
var index = 0
for (item in this) {
if (element == item)
lastIndex = index
index++
}
return lastIndex
}
/**
* Returns last index of [element], or -1 if the list does not contain element.
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun <@kotlin.internal.OnlyInputTypes T> List<T>.lastIndexOf(element: T): Int {
return lastIndexOf(element)
}
/**
* Returns the last element, or `null` if the collection is empty.
*/
public fun <T> Iterable<T>.lastOrNull(): T? {
when (this) {
is List -> return if (isEmpty()) null else this[size - 1]
else -> {
val iterator = iterator()
if (!iterator.hasNext())
return null
var last = iterator.next()
while (iterator.hasNext())
last = iterator.next()
return last
}
}
}
/**
* Returns the last element, or `null` if the list is empty.
*/
public fun <T> List<T>.lastOrNull(): T? {
return if (isEmpty()) null else this[size - 1]
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
public inline fun <T> Iterable<T>.lastOrNull(predicate: (T) -> Boolean): T? {
var last: T? = null
for (element in this) {
if (predicate(element)) {
last = element
}
}
return last
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
public inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
return null
}
/**
* Returns the single element, or throws an exception if the collection is empty or has more than one element.
*/
public fun <T> Iterable<T>.single(): T {
when (this) {
is List -> return this.single()
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty.")
val single = iterator.next()
if (iterator.hasNext())
throw IllegalArgumentException("Collection has more than one element.")
return single
}
}
}
/**
* Returns the single element, or throws an exception if the list is empty or has more than one element.
*/
public fun <T> List<T>.single(): T {
return when (size) {
0 -> throw NoSuchElementException("List is empty.")
1 -> this[0]
else -> throw IllegalArgumentException("List has more than one element.")
}
}
/**
* Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element.
*/
public inline fun <T> Iterable<T>.single(predicate: (T) -> Boolean): T {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) throw IllegalArgumentException("Collection contains more than one matching element.")
single = element
found = true
}
}
if (!found) throw NoSuchElementException("Collection contains no element matching the predicate.")
@Suppress("UNCHECKED_CAST")
return single as T
}
/**
* Returns single element, or `null` if the collection is empty or has more than one element.
*/
public fun <T> Iterable<T>.singleOrNull(): T? {
when (this) {
is List -> return if (size == 1) this[0] else null
else -> {
val iterator = iterator()
if (!iterator.hasNext())
return null
val single = iterator.next()
if (iterator.hasNext())
return null
return single
}
}
}
/**
* Returns single element, or `null` if the list is empty or has more than one element.
*/
public fun <T> List<T>.singleOrNull(): T? {
return if (size == 1) this[0] else null
}
/**
* Returns the single element matching the given [predicate], or `null` if element was not found or more than one element was found.
*/
public inline fun <T> Iterable<T>.singleOrNull(predicate: (T) -> Boolean): T? {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) return null
single = element
found = true
}
}
if (!found) return null
return single
}
/**
* Returns a list containing all elements except first [n] elements.
*/
public fun <T> Iterable<T>.drop(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return toList()
val list: ArrayList<T>
if (this is Collection<*>) {
val resultSize = size - n
if (resultSize <= 0)
return emptyList()
if (resultSize == 1)
return listOf(last())
list = ArrayList<T>(resultSize)
if (this is List<T>) {
if (this is RandomAccess) {
for (index in n..size - 1)
list.add(this[index])
} else {
for (item in this.listIterator(n))
list.add(item)
}
return list
}
}
else {
list = ArrayList<T>()
}
var count = 0
for (item in this) {
if (count++ >= n) list.add(item)
}
return list.optimizeReadOnlyList()
}
/**
* Returns a list containing all elements except last [n] elements.
*/
public fun <T> List<T>.dropLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return take((size - n).coerceAtLeast(0))
}
/**
* Returns a list containing all elements except last elements that satisfy the given [predicate].
*/
public inline fun <T> List<T>.dropLastWhile(predicate: (T) -> Boolean): List<T> {
if (!isEmpty()) {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
return take(iterator.nextIndex() + 1)
}
}
}
return emptyList()
}
/**
* Returns a list containing all elements except first elements that satisfy the given [predicate].
*/
public inline fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean): List<T> {
var yielding = false
val list = ArrayList<T>()
for (item in this)
if (yielding)
list.add(item)
else if (!predicate(item)) {
list.add(item)
yielding = true
}
return list
}
/**
* Returns a list containing only elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing only elements matching the given [predicate].
* @param [predicate] function that takes the index of an element and the element itself
* and returns the result of predicate evaluation on the element.
*/
public inline fun <T> Iterable<T>.filterIndexed(predicate: (Int, T) -> Boolean): List<T> {
return filterIndexedTo(ArrayList<T>(), predicate)
}
/**
* Appends all elements matching the given [predicate] to the given [destination].
* @param [predicate] function that takes the index of an element and the element itself
* and returns the result of predicate evaluation on the element.
*/
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterIndexedTo(destination: C, predicate: (Int, T) -> Boolean): C {
forEachIndexed { index, element ->
if (predicate(index, element)) destination.add(element)
}
return destination
}
/**
* Returns a list containing all elements that are instances of specified type parameter R.
*/
public inline fun <reified R> Iterable<*>.filterIsInstance(): List<@kotlin.internal.NoInfer R> {
return filterIsInstanceTo(ArrayList<R>())
}
/**
* Appends all elements that are instances of specified type parameter R to the given [destination].
*/
public inline fun <reified R, C : MutableCollection<in R>> Iterable<*>.filterIsInstanceTo(destination: C): C {
for (element in this) if (element is R) destination.add(element)
return destination
}
/**
* Returns a list containing all elements not matching the given [predicate].
*/
public inline fun <T> Iterable<T>.filterNot(predicate: (T) -> Boolean): List<T> {
return filterNotTo(ArrayList<T>(), predicate)
}
/**
* Returns a list containing all elements that are not `null`.
*/
public fun <T : Any> Iterable<T?>.filterNotNull(): List<T> {
return filterNotNullTo(ArrayList<T>())
}
/**
* Appends all elements that are not `null` to the given [destination].
*/
public fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo(destination: C): C {
for (element in this) if (element != null) destination.add(element)
return destination
}
/**
* Appends all elements not matching the given [predicate] to the given [destination].
*/
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (!predicate(element)) destination.add(element)
return destination
}
/**
* Appends all elements matching the given [predicate] to the given [destination].
*/
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (predicate(element)) destination.add(element)
return destination
}
/**
* Returns a list containing elements at indices in the specified [indices] range.
*/
public fun <T> List<T>.slice(indices: IntRange): List<T> {
if (indices.isEmpty()) return listOf()
return this.subList(indices.start, indices.endInclusive + 1).toList()
}
/**
* Returns a list containing elements at specified [indices].
*/
public fun <T> List<T>.slice(indices: Iterable<Int>): List<T> {
val size = indices.collectionSizeOrDefault(10)
if (size == 0) return emptyList()
val list = ArrayList<T>(size)
for (index in indices) {
list.add(get(index))
}
return list
}
/**
* Returns a list containing first [n] elements.
*/
public fun <T> Iterable<T>.take(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
if (this is Collection<T>) {
if (n >= size) return toList()
if (n == 1) return listOf(first())
}
var count = 0
val list = ArrayList<T>(n)
for (item in this) {
if (count++ == n)
break
list.add(item)
}
return list.optimizeReadOnlyList()
}
/**
* Returns a list containing last [n] elements.
*/
public fun <T> List<T>.takeLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
val size = size
if (n >= size) return toList()
if (n == 1) return listOf(last())
val list = ArrayList<T>(n)
if (this is RandomAccess) {
for (index in size - n .. size - 1)
list.add(this[index])
} else {
for (item in this.listIterator(n))
list.add(item)
}
return list
}
/**
* Returns a list containing last elements satisfying the given [predicate].
*/
public inline fun <T> List<T>.takeLastWhile(predicate: (T) -> Boolean): List<T> {
if (isEmpty())
return emptyList()
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
iterator.next()
val expectedSize = size - iterator.nextIndex()
if (expectedSize == 0) return emptyList()
return ArrayList<T>(expectedSize).apply {
while (iterator.hasNext())
add(iterator.next())
}
}
}
return toList()
}
/**
* Returns a list containing first elements satisfying the given [predicate].
*/
public inline fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
if (!predicate(item))
break
list.add(item)
}
return list
}
/**
* Reverses elements in the list in-place.
*/
public fun <T> MutableList<T>.reverse(): Unit {
val median = size / 2
var leftIndex = 0
var rightIndex = size - 1
while (leftIndex < median) {
val tmp = this[leftIndex]
this[leftIndex] = this[rightIndex]
this[rightIndex] = tmp
leftIndex++
rightIndex--
}
}
/**
* Returns a list with elements in reversed order.
*/
public fun <T> Iterable<T>.reversed(): List<T> {
if (this is Collection && size <= 1) return toList()
val list = toMutableList()
list.reverse()
return list
}
/**
* Sorts elements in the list in-place according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) -> R?): Unit {
if (size > 1) sortWith(compareBy(selector))
}
/**
* Sorts elements in the list in-place descending according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> MutableList<T>.sortByDescending(crossinline selector: (T) -> R?): Unit {
if (size > 1) sortWith(compareByDescending(selector))
}
/**
* Sorts elements in the list in-place descending according to their natural sort order.
*/
public fun <T : Comparable<T>> MutableList<T>.sortDescending(): Unit {
sortWith(reverseOrder())
}
/**
* Replaces each element in the list with a result of a transformation specified.
*/
public fun <T> MutableList<T>.replaceAll(transformation: (T) -> T) {
val it = listIterator()
while (it.hasNext()) {
val element = it.next()
it.set(transformation(element))
}
}
/**
* Returns a list of all elements sorted according to their natural sort order.
*/
public fun <T : Comparable<T>> Iterable<T>.sorted(): List<T> {
if (this is Collection) {
if (size <= 1) return this.toList()
@Suppress("UNCHECKED_CAST")
return (toTypedArray<Comparable<T>>() as Array<T>).apply { sort() }.asList()
}
return toMutableList().apply { sort() }
}
/**
* Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
return sortedWith(compareBy(selector))
}
/**
* Returns a list of all elements sorted descending according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(crossinline selector: (T) -> R?): List<T> {
return sortedWith(compareByDescending(selector))
}
/**
* Returns a list of all elements sorted descending according to their natural sort order.
*/
public fun <T : Comparable<T>> Iterable<T>.sortedDescending(): List<T> {
return sortedWith(reverseOrder())
}
/**
* Returns a list of all elements sorted according to the specified [comparator].
*/
public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T> {
if (this is Collection) {
if (size <= 1) return this.toList()
@Suppress("UNCHECKED_CAST")
return (toTypedArray<Any?>() as Array<T>).apply { sortWith(comparator) }.asList()
}
return toMutableList().apply { sortWith(comparator) }
}
/**
* Returns an array of Boolean containing all of the elements of this collection.
*/
public fun Collection<Boolean>.toBooleanArray(): BooleanArray {
val result = BooleanArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Byte containing all of the elements of this collection.
*/
public fun Collection<Byte>.toByteArray(): ByteArray {
val result = ByteArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Char containing all of the elements of this collection.
*/
public fun Collection<Char>.toCharArray(): CharArray {
val result = CharArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Double containing all of the elements of this collection.
*/
public fun Collection<Double>.toDoubleArray(): DoubleArray {
val result = DoubleArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Float containing all of the elements of this collection.
*/
public fun Collection<Float>.toFloatArray(): FloatArray {
val result = FloatArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Int containing all of the elements of this collection.
*/
public fun Collection<Int>.toIntArray(): IntArray {
val result = IntArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Long containing all of the elements of this collection.
*/
public fun Collection<Long>.toLongArray(): LongArray {
val result = LongArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns an array of Short containing all of the elements of this collection.
*/
public fun Collection<Short>.toShortArray(): ShortArray {
val result = ShortArray(size)
var index = 0
for (element in this)
result[index++] = element
return result
}
/**
* Returns a [Map] containing key-value pairs provided by [transform] function
* applied to elements of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
public inline fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V> {
val capacity = mapCapacity(collectionSizeOrDefault(10)).coerceAtLeast(16)
return associateTo(LinkedHashMap<K, V>(capacity), transform)
}
/**
* Returns a [Map] containing the elements from the given collection indexed by the key
* returned from [keySelector] function applied to each element.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
public inline fun <T, K> Iterable<T>.associateBy(keySelector: (T) -> K): Map<K, T> {
val capacity = mapCapacity(collectionSizeOrDefault(10)).coerceAtLeast(16)
return associateByTo(LinkedHashMap<K, T>(capacity), keySelector)
}
/**
* Returns a [Map] containing the values provided by [valueTransform] and indexed by [keySelector] functions applied to elements of the given collection.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original collection.
*/
public inline fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V> {
val capacity = mapCapacity(collectionSizeOrDefault(10)).coerceAtLeast(16)
return associateByTo(LinkedHashMap<K, V>(capacity), keySelector, valueTransform)
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function applied to each element of the given collection
* and value is the element itself.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*/
public inline fun <T, K, M : MutableMap<in K, in T>> Iterable<T>.associateByTo(destination: M, keySelector: (T) -> K): M {
for (element in this) {
destination.put(keySelector(element), element)
}
return destination
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function and
* and value is provided by the [valueTransform] function applied to elements of the given collection.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*/
public inline fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateByTo(destination: M, keySelector: (T) -> K, valueTransform: (T) -> V): M {
for (element in this) {
destination.put(keySelector(element), valueTransform(element))
}
return destination
}
/**
* Populates and returns the [destination] mutable map with key-value pairs
* provided by [transform] function applied to each element of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map.
*/
public inline fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateTo(destination: M, transform: (T) -> Pair<K, V>): M {
for (element in this) {
destination += transform(element)
}
return destination
}
/**
* Appends all elements to the given [destination] collection.
*/
public fun <T, C : MutableCollection<in T>> Iterable<T>.toCollection(destination: C): C {
for (item in this) {
destination.add(item)
}
return destination
}
/**
* Returns a [HashSet] of all elements.
*/
public fun <T> Iterable<T>.toHashSet(): HashSet<T> {
return toCollection(HashSet<T>(mapCapacity(collectionSizeOrDefault(12))))
}
/**
* Returns a [List] containing all elements.
*/
public fun <T> Iterable<T>.toList(): List<T> {
if (this is Collection) {
return when (size) {
0 -> emptyList()
1 -> listOf(if (this is List) get(0) else iterator().next())
else -> this.toMutableList()
}
}
return this.toMutableList().optimizeReadOnlyList()
}
/**
* Returns a [MutableList] filled with all elements of this collection.
*/
public fun <T> Iterable<T>.toMutableList(): MutableList<T> {
if (this is Collection<T>)
return this.toMutableList()
return toCollection(ArrayList<T>())
}
/**
* Returns a [MutableList] filled with all elements of this collection.
*/
public fun <T> Collection<T>.toMutableList(): MutableList<T> {
return ArrayList(this)
}
/**
* Returns a [Set] of all elements.
*
* The returned set preserves the element iteration order of the original collection.
*/
public fun <T> Iterable<T>.toSet(): Set<T> {
if (this is Collection) {
return when (size) {
0 -> emptySet()
1 -> setOf(if (this is List) this[0] else iterator().next())
else -> toCollection(LinkedHashSet<T>(mapCapacity(size)))
}
}
return toCollection(LinkedHashSet<T>()).optimizeReadOnlySet()
}
/**
* Returns a [SortedSet] of all elements.
*/
//public fun <T: Comparable<T>> Iterable<T>.toSortedSet(): SortedSet<T> {
// return toCollection(TreeSet<T>())
//}
/**
* Returns a [SortedSet] of all elements.
*
* Elements in the set returned are sorted according to the given [comparator].
*/
//public fun <T> Iterable<T>.toSortedSet(comparator: Comparator<in T>): SortedSet<T> {
// return toCollection(TreeSet<T>(comparator))
//}
/**
* Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
*/
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination].
*/
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) -> Iterable<R>): C {
for (element in this) {
val list = transform(element)
destination.addAll(list)
}
return destination
}
/**
* Groups elements of the original collection by the key returned by the given [keySelector] function
* applied to each element and returns a map where each group key is associated with a list of corresponding elements.
*
* The returned map preserves the entry iteration order of the keys produced from the original collection.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
public inline fun <T, K> Iterable<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>> {
return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
}
/**
* Groups values returned by the [valueTransform] function applied to each element of the original collection
* by the key returned by the given [keySelector] function applied to the element
* and returns a map where each group key is associated with a list of corresponding values.
*
* The returned map preserves the entry iteration order of the keys produced from the original collection.
*
* @sample samples.collections.Collections.Transformations.groupByKeysAndValues
*/
public inline fun <T, K, V> Iterable<T>.groupBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, List<V>> {
return groupByTo(LinkedHashMap<K, MutableList<V>>(), keySelector, valueTransform)
}
/**
* Groups elements of the original collection by the key returned by the given [keySelector] function
* applied to each element and puts to the [destination] map each group key associated with a list of corresponding elements.
*
* @return The [destination] map.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return destination
}
/**
* Groups values returned by the [valueTransform] function applied to each element of the original collection
* by the key returned by the given [keySelector] function applied to the element
* and puts to the [destination] map each group key associated with a list of corresponding values.
*
* @return The [destination] map.
*
* @sample samples.collections.Collections.Transformations.groupByKeysAndValues
*/
public inline fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K, valueTransform: (T) -> V): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<V>() }
list.add(valueTransform(element))
}
return destination
}
/**
* Creates a [Grouping] source from a collection to be used later with one of group-and-fold operations
* using the specified [keySelector] function to extract a key from each element.
*
* @sample samples.collections.Collections.Transformations.groupingByEachCount
*/
@SinceKotlin("1.1")
public inline fun <T, K> Iterable<T>.groupingBy(crossinline keySelector: (T) -> K): Grouping<T, K> {
return object : Grouping<T, K> {
override fun sourceIterator(): Iterator<T> = [email protected]()
override fun keyOf(element: T): K = keySelector(element)
}
}
/**
* Returns a list containing the results of applying the given [transform] function
* to each element in the original collection.
*/
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
/**
* Returns a list containing the results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R> Iterable<T>.mapIndexed(transform: (Int, T) -> R): List<R> {
@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE")
return mapIndexedTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element and its index in the original collection.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R : Any> Iterable<T>.mapIndexedNotNull(transform: (Int, T) -> R?): List<R> {
return mapIndexedNotNullTo(ArrayList<R>(), transform)
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends only the non-null results to the given [destination].
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapIndexedNotNullTo(destination: C, transform: (Int, T) -> R?): C {
forEachIndexed { index, element -> transform(index, element)?.let { destination.add(it) } }
return destination
}
/**
* Applies the given [transform] function to each element and its index in the original collection
* and appends the results to the given [destination].
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo(destination: C, transform: (Int, T) -> R): C {
var index = 0
for (item in this)
destination.add(transform(index++, item))
return destination
}
/**
* Returns a list containing only the non-null results of applying the given [transform] function
* to each element in the original collection.
*/
public inline fun <T, R : Any> Iterable<T>.mapNotNull(transform: (T) -> R?): List<R> {
return mapNotNullTo(ArrayList<R>(), transform)
}
/**
* Applies the given [transform] function to each element in the original collection
* and appends only the non-null results to the given [destination].
*/
public inline fun <T, R : Any, C : MutableCollection<in R>> Iterable<T>.mapNotNullTo(destination: C, transform: (T) -> R?): C {
forEach { element -> transform(element)?.let { destination.add(it) } }
return destination
}
/**
* Applies the given [transform] function to each element of the original collection
* and appends the results to the given [destination].
*/
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) -> R): C {
for (item in this)
destination.add(transform(item))
return destination
}
/**
* Returns a lazy [Iterable] of [IndexedValue] for each element of the original collection.
*/
public fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> {
return IndexingIterable { iterator() }
}
/**
* Returns a list containing only distinct elements from the given collection.
*
* The elements in the resulting list are in the same order as they were in the source collection.
*/
public fun <T> Iterable<T>.distinct(): List<T> {
return this.toMutableSet().toList()
}
/**
* Returns a list containing only elements from the given collection
* having distinct keys returned by the given [selector] function.
*
* The elements in the resulting list are in the same order as they were in the source collection.
*/
public inline fun <T, K> Iterable<T>.distinctBy(selector: (T) -> K): List<T> {
val set = HashSet<K>()
val list = ArrayList<T>()
for (e in this) {
val key = selector(e)
if (set.add(key))
list.add(e)
}
return list
}
/**
* Returns a set containing all elements that are contained by both this set and the specified collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
public infix fun <T> Iterable<T>.intersect(other: Iterable<T>): Set<T> {
val set = this.toMutableSet()
set.retainAll(other)
return set
}
/**
* Returns a set containing all elements that are contained by this collection and not contained by the specified collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
public infix fun <T> Iterable<T>.subtract(other: Iterable<T>): Set<T> {
val set = this.toMutableSet()
set.removeAll(other)
return set
}
/**
* Returns a mutable set containing all distinct elements from the given collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
public fun <T> Iterable<T>.toMutableSet(): MutableSet<T> {
return when (this) {
is Collection<T> -> LinkedHashSet(this)
else -> toCollection(LinkedHashSet<T>())
}
}
/**
* Returns a set containing all distinct elements from both collections.
*
* The returned set preserves the element iteration order of the original collection.
* Those elements of the [other] collection that are unique are iterated in the end
* in the order of the [other] collection.
*/
public infix fun <T> Iterable<T>.union(other: Iterable<T>): Set<T> {
val set = this.toMutableSet()
set.addAll(other)
return set
}
/**
* Returns `true` if all elements match the given [predicate].
*/
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns `true` if collection has at least one element.
*/
public fun <T> Iterable<T>.any(): Boolean {
for (element in this) return true
return false
}
/**
* Returns `true` if at least one element matches the given [predicate].
*/
public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Returns the number of elements in this collection.
* Returns the number of elements in this collection.
*/
public fun <T> Iterable<T>.count(): Int {
var count = 0
for (element in this) count++
return count
}
/**
* Returns the number of elements in this collection.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.count(): Int {
return size
}
/**
* Returns the number of elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <T, R> Iterable<T>.fold(initial: R, operation: (R, T) -> R): R {
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right
* to current accumulator value and each element with its index in the original collection.
* @param [operation] function that takes the index of an element, current accumulator value
* and the element itself, and calculates the next accumulator value.
*/
public inline fun <T, R> Iterable<T>.foldIndexed(initial: R, operation: (Int, R, T) -> R): R {
var index = 0
var accumulator = initial
for (element in this) accumulator = operation(index++, accumulator, element)
return accumulator
}
/**
* Accumulates value starting with [initial] value and applying [operation] from right to left to each element and current accumulator value.
*/
public inline fun <T, R> List<T>.foldRight(initial: R, operation: (T, R) -> R): R {
var accumulator = initial
if (!isEmpty()) {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
}
return accumulator
}
/**
* Accumulates value starting with [initial] value and applying [operation] from right to left
* to each element with its index in the original list and current accumulator value.
* @param [operation] function that takes the index of an element, the element itself
* and current accumulator value, and calculates the next accumulator value.
*/
public inline fun <T, R> List<T>.foldRightIndexed(initial: R, operation: (Int, T, R) -> R): R {
var accumulator = initial
if (!isEmpty()) {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
}
return accumulator
}
/**
* Performs the given [action] on each element.
*/
@kotlin.internal.HidesMembers
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
/**
* Performs the given [action] on each element, providing sequential index with the element.
* @param [action] function that takes the index of an element and the element itself
* and performs the desired action on the element.
*/
public inline fun <T> Iterable<T>.forEachIndexed(action: (Int, T) -> Unit): Unit {
var index = 0
for (item in this) action(index++, item)
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
public fun Iterable<Double>.max(): Double? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
if (max.isNaN()) return max
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (max < e) max = e
}
return max
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
public fun Iterable<Float>.max(): Float? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
if (max.isNaN()) return max
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (max < e) max = e
}
return max
}
/**
* Returns the largest element or `null` if there are no elements.
*/
public fun <T : Comparable<T>> Iterable<T>.max(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or `null` if there are no elements.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
var maxValue = selector(maxElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the first element having the largest value according to the provided [comparator] or `null` if there are no elements.
*/
public fun <T> Iterable<T>.maxWith(comparator: Comparator<in T>): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (comparator.compare(max, e) < 0) max = e
}
return max
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
public fun Iterable<Double>.min(): Double? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
if (min.isNaN()) return min
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (min > e) min = e
}
return min
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
@SinceKotlin("1.1")
public fun Iterable<Float>.min(): Float? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
if (min.isNaN()) return min
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (min > e) min = e
}
return min
}
/**
* Returns the smallest element or `null` if there are no elements.
*/
public fun <T : Comparable<T>> Iterable<T>.min(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or `null` if there are no elements.
*/
public inline fun <T, R : Comparable<R>> Iterable<T>.minBy(selector: (T) -> R): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var minValue = selector(minElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Returns the first element having the smallest value according to the provided [comparator] or `null` if there are no elements.
*/
public fun <T> Iterable<T>.minWith(comparator: Comparator<in T>): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (comparator.compare(min, e) > 0) min = e
}
return min
}
/**
* Returns `true` if the collection has no elements.
*/
public fun <T> Iterable<T>.none(): Boolean {
for (element in this) return false
return true
}
/**
* Returns `true` if no elements match the given [predicate].
*/
public inline fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return false
return true
}
/**
* Performs the given [action] on each element and returns the collection itself afterwards.
*/
@SinceKotlin("1.1")
public inline fun <T, C : Iterable<T>> C.onEach(action: (T) -> Unit): C {
return apply { for (element in this) action(element) }
}
/**
* Accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <S, T: S> Iterable<T>.reduce(operation: (S, T) -> S): S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
}
/**
* Accumulates value starting with the first element and applying [operation] from left to right
* to current accumulator value and each element with its index in the original collection.
* @param [operation] function that takes the index of an element, current accumulator value
* and the element itself and calculates the next accumulator value.
*/
public inline fun <S, T: S> Iterable<T>.reduceIndexed(operation: (Int, S, T) -> S): S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
var index = 1
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(index++, accumulator, iterator.next())
}
return accumulator
}
/**
* Accumulates value starting with last element and applying [operation] from right to left to each element and current accumulator value.
*/
public inline fun <S, T: S> List<T>.reduceRight(operation: (T, S) -> S): S {
val iterator = listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
return accumulator
}
/**
* Accumulates value starting with last element and applying [operation] from right to left
* to each element with its index in the original list and current accumulator value.
* @param [operation] function that takes the index of an element, the element itself
* and current accumulator value, and calculates the next accumulator value.
*/
public inline fun <S, T: S> List<T>.reduceRightIndexed(operation: (Int, T, S) -> S): S {
val iterator = this.listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
return accumulator
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
public inline fun <T> Iterable<T>.sumBy(selector: (T) -> Int): Int {
var sum: Int = 0
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
public inline fun <T> Iterable<T>.sumByDouble(selector: (T) -> Double): Double {
var sum: Double = 0.0
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Returns an original collection containing all the non-`null` elements, throwing an [IllegalArgumentException] if there are any `null` elements.
*/
public fun <T : Any> Iterable<T?>.requireNoNulls(): Iterable<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this.")
}
}
@Suppress("UNCHECKED_CAST")
return this as Iterable<T>
}
/**
* Returns an original collection containing all the non-`null` elements, throwing an [IllegalArgumentException] if there are any `null` elements.
*/
public fun <T : Any> List<T?>.requireNoNulls(): List<T> {
for (element in this) {
if (element == null) {
throw IllegalArgumentException("null element found in $this.")
}
}
@Suppress("UNCHECKED_CAST")
return this as List<T>
}
/**
* Returns a list containing all elements of the original collection without the first occurrence of the given [element].
*/
public operator fun <T> Iterable<T>.minus(element: T): List<T> {
val result = ArrayList<T>(collectionSizeOrDefault(10))
var removed = false
return this.filterTo(result) { if (!removed && it == element) { removed = true; false } else true }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] array.
*/
public operator fun <T> Iterable<T>.minus(elements: Array<out T>): List<T> {
if (elements.isEmpty()) return this.toList()
val other = elements.toHashSet()
return this.filterNot { it in other }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] collection.
*/
public operator fun <T> Iterable<T>.minus(elements: Iterable<T>): List<T> {
val other = elements.convertToSetForSetOperationWith(this)
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
}
/**
* Returns a list containing all elements of the original collection except the elements contained in the given [elements] sequence.
*/
public operator fun <T> Iterable<T>.minus(elements: Sequence<T>): List<T> {
val other = elements.toHashSet()
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
}
/**
* Returns a list containing all elements of the original collection without the first occurrence of the given [element].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.minusElement(element: T): List<T> {
return minus(element)
}
/**
* Splits the original collection into pair of lists,
* where *first* list contains elements for which [predicate] yielded `true`,
* while *second* list contains elements for which [predicate] yielded `false`.
*/
public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
public operator fun <T> Iterable<T>.plus(element: T): List<T> {
if (this is Collection) return this.plus(element)
val result = ArrayList<T>()
result.addAll(this)
result.add(element)
return result
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
public operator fun <T> Collection<T>.plus(element: T): List<T> {
val result = ArrayList<T>(size + 1)
result.addAll(this)
result.add(element)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] array.
*/
public operator fun <T> Iterable<T>.plus(elements: Array<out T>): List<T> {
if (this is Collection) return this.plus(elements)
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] array.
*/
public operator fun <T> Collection<T>.plus(elements: Array<out T>): List<T> {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] collection.
*/
public operator fun <T> Iterable<T>.plus(elements: Iterable<T>): List<T> {
if (this is Collection) return this.plus(elements)
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] collection.
*/
public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
if (elements is Collection) {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
} else {
val result = ArrayList<T>(this)
result.addAll(elements)
return result
}
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] sequence.
*/
public operator fun <T> Iterable<T>.plus(elements: Sequence<T>): List<T> {
val result = ArrayList<T>()
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] sequence.
*/
public operator fun <T> Collection<T>.plus(elements: Sequence<T>): List<T> {
val result = ArrayList<T>(this.size + 10)
result.addAll(this)
result.addAll(elements)
return result
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.plusElement(element: T): List<T> {
return plus(element)
}
/**
* Returns a list containing all elements of the original collection and then the given [element].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.plusElement(element: T): List<T> {
return plus(element)
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public infix fun <T, R> Iterable<T>.zip(other: Array<out R>): List<Pair<T, R>> {
return zip(other) { t1, t2 -> t1 to t2 }
}
@Suppress("NOTHING_TO_INLINE")
inline fun min(x1: Int, x2: Int) = if (x1 < x2) x1 else x2
/**
* Returns a list of values built from elements of both collections with same indexes using provided [transform]. List has length of shortest collection.
*/
public inline fun <T, R, V> Iterable<T>.zip(other: Array<out R>, transform: (T, R) -> V): List<V> {
val arraySize = other.size
val list = ArrayList<V>(min(collectionSizeOrDefault(10), arraySize))
var i = 0
for (element in this) {
if (i >= arraySize) break
list.add(transform(element, other[i++]))
}
return list
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public infix fun <T, R> Iterable<T>.zip(other: Iterable<R>): List<Pair<T, R>> {
return zip(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of values built from elements of both collections with same indexes using provided [transform]. List has length of shortest collection.
*/
public inline fun <T, R, V> Iterable<T>.zip(other: Iterable<R>, transform: (T, R) -> V): List<V> {
val first = iterator()
val second = other.iterator()
val list = ArrayList<V>(min(collectionSizeOrDefault(10), other.collectionSizeOrDefault(10)))
while (first.hasNext() && second.hasNext()) {
list.add(transform(first.next(), second.next()))
}
return list
}
/**
* Appends the string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T, A : Appendable> Iterable<T>.joinTo(buffer: A, separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): A {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
if (transform != null)
buffer.append(transform(element))
else
buffer.append(if (element == null) "null" else element.toString())
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
return buffer
}
/**
* Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T> Iterable<T>.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): String {
return joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated, transform).toString()
}
/**
* Returns this collection as an [Iterable].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Iterable<T>.asIterable(): Iterable<T> {
return this
}
/**
* Creates a [Sequence] instance that wraps the original collection returning its elements when being iterated.
*/
public fun <T> Iterable<T>.asSequence(): Sequence<T> {
return Sequence { this.iterator() }
}
/**
* Returns a list containing all elements that are instances of specified class.
*/
//public fun <R> Iterable<*>.filterIsInstance(klass: Class<R>): List<R> {
// return filterIsInstanceTo(ArrayList<R>(), klass)
//}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Byte>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Short>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Int>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Long>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Float>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns an average value of elements in the collection.
*/
public fun Iterable<Double>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Byte>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Short>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Int>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Long>.sum(): Long {
var sum: Long = 0L
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Float>.sum(): Float {
var sum: Float = 0.0f
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the collection.
*/
public fun Iterable<Double>.sum(): Double {
var sum: Double = 0.0
for (element in this) {
sum += element
}
return sum
}
| apache-2.0 | b32a6b6c92742f592250991a7504dd0b | 32.6603 | 244 | 0.665728 | 4.004322 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/primitiveTypes/comparisonWithNaN.kt | 2 | 1841 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// This test checks that our bytecode is consistent with javac bytecode
fun _assert(condition: Boolean) {
if (!condition) throw AssertionError("Fail")
}
fun _assertFalse(condition: Boolean) = _assert(!condition)
fun box(): String {
var dnan = java.lang.Double.NaN
if (System.nanoTime() < 0) dnan = 3.14 // To avoid possible compile-time const propagation
_assertFalse(0.0 < dnan)
_assertFalse(0.0 > dnan)
_assertFalse(0.0 <= dnan)
_assertFalse(0.0 >= dnan)
_assertFalse(0.0 == dnan)
_assertFalse(dnan < 0.0)
_assertFalse(dnan > 0.0)
_assertFalse(dnan <= 0.0)
_assertFalse(dnan >= 0.0)
_assertFalse(dnan == 0.0)
_assertFalse(dnan < dnan)
_assertFalse(dnan > dnan)
_assertFalse(dnan <= dnan)
_assertFalse(dnan >= dnan)
_assertFalse(dnan == dnan)
// Double.compareTo: "NaN is considered by this method to be equal to itself and greater than all other values"
_assert(0.0.compareTo(dnan) == -1)
_assert(dnan.compareTo(0.0) == 1)
_assert(dnan.compareTo(dnan) == 0)
var fnan = java.lang.Float.NaN
if (System.nanoTime() < 0) fnan = 3.14f
_assertFalse(0.0f < fnan)
_assertFalse(0.0f > fnan)
_assertFalse(0.0f <= fnan)
_assertFalse(0.0f >= fnan)
_assertFalse(0.0f == fnan)
_assertFalse(fnan < 0.0f)
_assertFalse(fnan > 0.0f)
_assertFalse(fnan <= 0.0f)
_assertFalse(fnan >= 0.0f)
_assertFalse(fnan == 0.0f)
_assertFalse(fnan < fnan)
_assertFalse(fnan > fnan)
_assertFalse(fnan <= fnan)
_assertFalse(fnan >= fnan)
_assertFalse(fnan == fnan)
_assert(0.0.compareTo(fnan) == -1)
_assert(fnan.compareTo(0.0) == 1)
_assert(fnan.compareTo(fnan) == 0)
return "OK"
}
| apache-2.0 | 6d8575c1df8688eea77370409a040f81 | 29.180328 | 115 | 0.630092 | 3.022989 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.