repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mktiti/Battleship
src/main/java/hu/titi/battleship/activity/MainActivity.kt
1
1562
package hu.titi.battleship.activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import hu.titi.battleship.R import hu.titi.battleship.model.GameType import org.jetbrains.anko.button import org.jetbrains.anko.sdk23.coroutines.onClick import org.jetbrains.anko.startActivity import org.jetbrains.anko.textResource import org.jetbrains.anko.verticalLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) verticalLayout { button { textResource = R.string.start_pvp onClick { startActivity<LocalGameActivity>("type" to GameType.PVP) } } button { textResource = R.string.start_pvcpu onClick { startActivity<LocalGameActivity>("type" to GameType.BOT) } } button { textResource = R.string.connect_to_game onClick { startActivity<ConnectActivity>() } } button { textResource = R.string.host_game onClick { startActivity<HostActivity>() } } /* button { text = "Setup" onClick { startActivity<MapSetupActivity>("maps" to 2) } } */ } } }
gpl-3.0
5e1ee8628303be9a67a4468876e022d1
25.948276
76
0.526889
5.22408
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/vo/platform/users/StaffVo.kt
1
774
package top.zbeboy.isy.web.vo.platform.users import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size /** * Created by zbeboy 2017-11-19 . **/ open class StaffVo { @NotNull @Pattern(regexp = "^[\\d]{8,}$") var staffNumber: String? = null var birthday: String? = null var sex: String? = null var idCard: String? = null var familyResidence: String? = null var politicalLandscapeId: Int? = null var nationId: Int? = null var academicTitleId: Int? = null var post: String? = null var departmentId: Int? = null @NotNull var username: String? = null @NotNull @Size(max = 30) var realName: String? = null var avatar: String? = null }
mit
90809e6b1533a3f83898a8dd8aac9a2d
25.724138
44
0.666667
3.6
false
false
false
false
nibarius/opera-park-android
app/src/main/java/se/barsk/park/mainui/SpecifyServerDialog.kt
1
3724
package se.barsk.park.mainui import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Bundle import androidx.fragment.app.DialogFragment import androidx.appcompat.app.AlertDialog import android.text.Editable import android.text.TextWatcher import android.util.Patterns import android.view.View import android.view.WindowManager import android.widget.EditText import com.google.android.material.dialog.MaterialAlertDialogBuilder import se.barsk.park.ParkApp import se.barsk.park.R import se.barsk.park.utils.Utils // OK to ignore on Alert dialogs // https://wundermanthompsonmobile.com/2013/05/layout-inflation-as-intended/ @SuppressLint("InflateParams") class SpecifyServerDialog : DialogFragment() { interface SpecifyServerDialogListener { fun parkServerChanged() } companion object { fun newInstance(): SpecifyServerDialog = SpecifyServerDialog() } private lateinit var listener: SpecifyServerDialogListener private val dialogView: View by lazy { requireActivity().layoutInflater.inflate(R.layout.specify_server_dialog, null) as View } private val editText: EditText by lazy { dialogView.findViewById<EditText>(R.id.server_url_input) } override fun onAttach(context: Context) { super.onAttach(context) listener = try { // Instantiate the NoticeDialogListener so we can send events to the host activity as SpecifyServerDialogListener } catch (e: ClassCastException) { // The activity doesn't implement the interface, throw exception throw ClassCastException(activity.toString() + " must implement SpecifyServerDialogListener") } } override fun onStart() { super.onStart() updatePositiveButton() editText.addTextChangedListener(DialogTextWatcher()) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.specify_server_dialog_title) .setView(dialogView) .setNegativeButton(R.string.dialog_button_cancel) { _, _ -> requireDialog().cancel() } .setPositiveButton(R.string.dialog_button_ok) { _, _: Int -> ParkApp.storageManager.setServer(editText.text.toString()) listener.parkServerChanged() } .create() editText.setOnEditorActionListener { _, _, _ -> dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() false } editText.setText(ParkApp.storageManager.getServer()) // The activity is visible when the dialog is created so the window should never be null dialog.window!!.let { it.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams .FLAG_ALT_FOCUSABLE_IM) it.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) } return dialog } private fun updatePositiveButton() { val canSave = Patterns.WEB_URL.matcher(Utils.fixUrl(editText.text.toString())).matches() (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = canSave } inner class DialogTextWatcher : TextWatcher { override fun afterTextChanged(s: Editable?) = updatePositiveButton() override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit } }
mit
949cfd73e03deccabfe38a8149a1aecf
39.053763
125
0.693878
4.958722
false
false
false
false
chrislo27/Tickompiler
src/main/kotlin/rhmodding/tickompiler/cli/PackCommand.kt
2
5664
package rhmodding.tickompiler.cli import com.google.gson.Gson import picocli.CommandLine import rhmodding.tickompiler.gameputter.GamePutter import rhmodding.tickompiler.objectify.ManifestObj import rhmodding.tickompiler.objectify.TFOBJ_PACKER_VERSION import rhmodding.tickompiler.util.getDirectories import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.charset.Charset import java.nio.file.Files import java.util.zip.ZipFile @CommandLine.Command(name = "pack", aliases = ["p"], description = ["Pack binary, tempo, and/or tfobj files from a specified directory into the output file, using the specified base file.", "The base file can be obtained from extraction.", "Files must have the file extension .bin (little-endian), .tempo, or .tfobj.", "The output file will be overwritten without warning.", "If the output file name is not specified, it will default to \"C00.bin\"."], mixinStandardHelpOptions = true) class PackCommand : Runnable { @CommandLine.Parameters(index = "0", arity = "1", description = ["input directory"]) lateinit var inputFile: File @CommandLine.Parameters(index = "1", arity = "1", description = ["base file"]) lateinit var baseFile: File @CommandLine.Parameters(index = "2", arity = "0..1", description = ["output file"]) var outputFile: File? = null override fun run() { val dirs = getDirectories(inputFile, baseFile, { it.endsWith(".bin") || it.endsWith(".tempo") }, "", true).input val base = Files.readAllBytes(baseFile.toPath()) var index = base.size val baseBuffer = ByteBuffer.wrap(base).order(ByteOrder.LITTLE_ENDIAN) val out = ByteArrayOutputStream() val putter = GamePutter val lookIn = dirs.map { PackTarget(it, it.name) }.toMutableList() val tmpFiles = mutableListOf<File>() val tfObjs: List<File> = inputFile.listFiles { _, name -> name.endsWith(".tfobj") }?.toList() ?: listOf() if (tfObjs.isNotEmpty()) { println("Detected ${tfObjs.size} .tfobj files, extracting those first...") tfObjs.forEach { f -> println("\tExtracting from tfobj ${f.name}...") val zipFile = ZipFile(f) val manifestEntry = zipFile.getEntry("manifest.json") val manifest = Gson().fromJson(zipFile.getInputStream(manifestEntry).let { val res = it.readBytes().toString(Charsets.UTF_8) it.close() res }, ManifestObj::class.java) if (manifest.version <= 0) { error("${f.path} - Manifest version is invalid (${manifest.version})") } else if (manifest.version > TFOBJ_PACKER_VERSION) { error("${f.path} - Manifest version is too high (${manifest.version}, max $TFOBJ_PACKER_VERSION). Update Tickompiler by using the 'updates' command") } // Version 1 parsing if (manifest.version <= 1) { for (i in 0 until manifest.bin.size) { lookIn += PackTarget(File.createTempFile("Tickompiler_tmp-", ".bin").apply { zipFile.getInputStream(zipFile.getEntry("bin/bin_$i.bin")).also { stream -> val fos = FileOutputStream(this) stream.copyTo(fos) fos.close() stream.close() } deleteOnExit() tmpFiles += this }, "${f.name}[bin_$i.bin]") } for (i in 0 until manifest.tempo.size) { lookIn += PackTarget(File.createTempFile("Tickompiler_tmp-", ".tempo").apply { zipFile.getInputStream(zipFile.getEntry("tempo/tempo_$i.tempo")).also { stream -> val fos = FileOutputStream(this) stream.copyTo(fos) fos.close() stream.close() } deleteOnExit() tmpFiles += this }, "${f.name}[tempo_$i.tempo]") } } zipFile.close() } } for ((file, descriptor) in lookIn) { println("Packing $descriptor...") val contents = Files.readAllBytes(file.toPath()) val ints = if (file.path.endsWith(".bin")) { putter.putGame(baseBuffer, ByteBuffer.wrap(contents).order(ByteOrder.LITTLE_ENDIAN), index) } else { putter.putTempo(baseBuffer, contents.toString(Charset.forName("UTF-8")), index) } index += ints.size * 4 val byteBuffer = ByteBuffer.allocate(ints.size * 4).order(ByteOrder.LITTLE_ENDIAN) val intBuf = byteBuffer.asIntBuffer() intBuf.put(ints.toIntArray()) val arr = ByteArray(ints.size * 4) byteBuffer[arr, 0, ints.size * 4] out.write(arr) } val file = outputFile ?: File("C00.bin") val fos = FileOutputStream(file) fos.write(baseBuffer.array()) fos.write(out.toByteArray()) fos.close() tmpFiles.forEach { it.delete() } println("Done.") } } data class PackTarget(val file: File, val descriptor: String)
mit
33fd488d13043cb3e789bc6fde96f7d8
44.312
189
0.557556
4.650246
false
false
false
false
CobaltVO/2048-Neural-network
src/main/java/ru/falseteam/neural2048/gnn/mutations/MutationWeights.kt
1
1131
package ru.falseteam.neural2048.gnn.mutations import ru.falseteam.neural2048.ga.MutatorCrossover import ru.falseteam.neural2048.nn.NeuralNetwork import java.util.* class MutationWeights : MutatorCrossover.Mutation<NeuralNetwork> { private val random = Random() override fun mutate(chromosome: NeuralNetwork): NeuralNetwork { val weights = chromosome.weightsOfLinks val weightsSize = weights.size var itersCount = this.random.nextInt(weightsSize) if (itersCount == 0) { itersCount = 1 } val used = HashSet<Int>() for (iter in 0 until itersCount) { var i = this.random.nextInt(weightsSize) if (weightsSize > 1) { while (used.contains(i)) { i = this.random.nextInt(weightsSize) } } var w = weights[i] w += (this.random.nextGaussian() - this.random.nextGaussian()) * 1 //TODO weights[i] = w used.add(i) } val clone = chromosome.clone() clone.weightsOfLinks = weights return clone } }
gpl-3.0
27f2f920e828c4d3e57acdc2434fb3c0
31.342857
85
0.59328
4.204461
false
false
false
false
square/okhttp
okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureAndroidTrustManager.kt
7
2351
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.tls.internal import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.security.cert.Certificate import java.security.cert.CertificateException import java.security.cert.X509Certificate import javax.net.ssl.X509TrustManager /** This extends [X509TrustManager] for Android to disable verification for a set of hosts. */ internal class InsecureAndroidTrustManager( private val delegate: X509TrustManager, private val insecureHosts: List<String> ) : X509TrustManager { private val checkServerTrustedMethod: Method? = try { delegate::class.java.getMethod("checkServerTrusted", Array<X509Certificate>::class.java, String::class.java, String::class.java) } catch (_: NoSuchMethodException) { null } /** Android method to clean and sort certificates, called via reflection. */ @Suppress("unused", "UNCHECKED_CAST") fun checkServerTrusted( chain: Array<out X509Certificate>, authType: String, host: String ): List<Certificate> { if (host in insecureHosts) return listOf() try { val method = checkServerTrustedMethod ?: throw CertificateException("Failed to call checkServerTrusted") return method.invoke(delegate, chain, authType, host) as List<Certificate> } catch (e: InvocationTargetException) { throw e.targetException } } override fun getAcceptedIssuers(): Array<X509Certificate> = delegate.acceptedIssuers override fun checkClientTrusted(chain: Array<out X509Certificate>, authType: String?) = throw CertificateException("Unsupported operation") override fun checkServerTrusted(chain: Array<out X509Certificate>, authType: String) = throw CertificateException("Unsupported operation") }
apache-2.0
9cdb5752800b43fb859a7f807f3835e7
37.540984
94
0.75117
4.512476
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/introspection/IntrospectionSchema.kt
1
5440
package com.apollographql.apollo3.compiler.introspection import com.apollographql.apollo3.compiler.fromJson import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonReader import dev.zacsweers.moshix.sealed.annotations.TypeLabel import okio.Buffer import okio.BufferedSource import okio.ByteString.Companion.decodeHex import okio.buffer import okio.source import java.io.File @JsonClass(generateAdapter = true) data class IntrospectionSchema( val __schema: Schema, ) { @JsonClass(generateAdapter = true) data class Schema( val queryType: QueryType, val mutationType: MutationType?, val subscriptionType: SubscriptionType?, val types: List<Type>, ) { @JsonClass(generateAdapter = true) data class QueryType(val name: String) @JsonClass(generateAdapter = true) data class MutationType(val name: String) @JsonClass(generateAdapter = true) data class SubscriptionType(val name: String) @JsonClass(generateAdapter = true, generator = "sealed:kind") sealed class Type { abstract val name: String abstract val description: String? @TypeLabel("SCALAR") @JsonClass(generateAdapter = true) data class Scalar( override val name: String, override val description: String?, ) : Type() @TypeLabel("OBJECT") @JsonClass(generateAdapter = true) data class Object( override val name: String, override val description: String?, val fields: List<Field>?, ) : Type() @TypeLabel("INTERFACE") @JsonClass(generateAdapter = true) data class Interface( override val name: String, override val description: String?, val fields: List<Field>?, val possibleTypes: List<TypeRef>?, ) : Type() @TypeLabel("UNION") @JsonClass(generateAdapter = true) data class Union( override val name: String, override val description: String?, val fields: List<Field>?, val possibleTypes: List<TypeRef>?, ) : Type() @TypeLabel("ENUM") @JsonClass(generateAdapter = true) data class Enum( override val name: String, override val description: String?, val enumValues: List<Value>, ) : Type() { @JsonClass(generateAdapter = true) data class Value( val name: String, val description: String?, val isDeprecated: Boolean = false, val deprecationReason: String?, ) } @TypeLabel("INPUT_OBJECT") @JsonClass(generateAdapter = true) data class InputObject( override val name: String, override val description: String?, val inputFields: List<InputField>, ) : Type() } @JsonClass(generateAdapter = true) data class InputField( val name: String, val description: String?, val isDeprecated: Boolean = false, val deprecationReason: String?, val type: TypeRef, val defaultValue: Any?, ) @JsonClass(generateAdapter = true) data class Field( val name: String, val description: String?, val isDeprecated: Boolean = false, val deprecationReason: String?, val type: TypeRef, val args: List<Argument> = emptyList(), ) { @JsonClass(generateAdapter = true) data class Argument( val name: String, val description: String?, val isDeprecated: Boolean = false, val deprecationReason: String?, val type: TypeRef, val defaultValue: Any?, ) } /** * An introspection TypeRef */ @JsonClass(generateAdapter = true) data class TypeRef( val kind: Kind, val name: String? = "", val ofType: TypeRef? = null, ) enum class Kind { ENUM, INTERFACE, OBJECT, INPUT_OBJECT, SCALAR, NON_NULL, LIST, UNION } } } /** * */ fun BufferedSource.toIntrospectionSchema(origin: String = ""): IntrospectionSchema { val bom = "EFBBBF".decodeHex() if (rangeEquals(0, bom)) { skip(bom.size.toLong()) } return JsonReader.of(this).use { try { IntrospectionSchema(__schema = it.locateSchemaRootNode().fromJson()) } catch (e: Exception) { throw RuntimeException("Cannot decode introspection $origin", e) } } } fun File.toIntrospectionSchema() = inputStream().source().buffer().toIntrospectionSchema("from `$this`") fun String.toIntrospectionSchema() = Buffer().writeUtf8(this).toIntrospectionSchema() private fun JsonReader.locateSchemaRootNode(): JsonReader { beginObject() var schemaJsonReader: JsonReader? = null try { while (schemaJsonReader == null && hasNext()) { when (nextName()) { "data" -> beginObject() "__schema" -> schemaJsonReader = peekJson() else -> skipValue() } } } catch (e: Exception) { throw IllegalArgumentException("Failed to locate schema root node `__schema`", e) } return schemaJsonReader ?: throw IllegalArgumentException("Failed to locate schema root node `__schema`") } fun IntrospectionSchema.normalize(): IntrospectionSchema { return copy( __schema = __schema.normalize() ) } fun IntrospectionSchema.Schema.normalize(): IntrospectionSchema.Schema { return copy( types = types.sortedBy { it.name } ) }
mit
5fe77fbdfa4a657ca0d62b151db40881
26.2
107
0.633456
4.556114
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/db/room/RemoteReadMarkDao.kt
1
1682
package com.nononsenseapps.feeder.db.room import androidx.room.ColumnInfo import androidx.room.Dao import androidx.room.Delete import androidx.room.Ignore import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.nononsenseapps.feeder.db.COL_ID import java.net.URL import org.threeten.bp.Instant @Dao interface RemoteReadMarkDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(readMark: RemoteReadMark): Long @Delete suspend fun delete(readMark: RemoteReadMark): Int @Query( """ DELETE FROM remote_read_mark WHERE timestamp < :oldestTimestamp """ ) suspend fun deleteStaleRemoteReadMarks(oldestTimestamp: Instant): Int @Query( """ SELECT remote_read_mark.id as id, fi.id as feed_item_id FROM remote_read_mark INNER JOIN feed_items fi ON remote_read_mark.guid = fi.guid INNER JOIN feeds f on f.id = fi.feed_id WHERE f.url IS remote_read_mark.feed_url AND fi.unread = 1 """ ) suspend fun getRemoteReadMarksReadyToBeApplied(): List<RemoteReadMarkReadyToBeApplied> @Query( """ SELECT remote_read_mark.guid FROM remote_read_mark WHERE remote_read_mark.feed_url = :feedUrl """ ) suspend fun getGuidsWhichAreSyncedAsReadInFeed(feedUrl: URL): List<String> } data class RemoteReadMarkReadyToBeApplied @Ignore constructor( @ColumnInfo(name = COL_ID) var id: Long = ID_UNSET, @ColumnInfo(name = "feed_item_id") var feedItemId: Long = ID_UNSET ) { constructor() : this(id = ID_UNSET) }
gpl-3.0
705ec1f86382638cd0ec832a37762342
29.035714
90
0.67717
3.93911
false
false
false
false
glodanif/BluetoothChat
app/src/main/kotlin/com/glodanif/bluetoothchat/data/model/BluetoothScannerImpl.kt
1
4387
package com.glodanif.bluetoothchat.data.model import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Handler import com.glodanif.bluetoothchat.data.model.BluetoothScanner.ScanningListener import java.lang.Exception class BluetoothScannerImpl(val context: Context) : BluetoothScanner { private var listener: ScanningListener? = null private var isDiscovering: Boolean = false private val handler: Handler = Handler() private val adapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter() private val foundDevices = HashMap<String, BluetoothDevice>() private var isListeningForDiscoverableStatus = false private val foundDeviceFilter = IntentFilter(BluetoothDevice.ACTION_FOUND) private val foundDeviceReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (BluetoothDevice.ACTION_FOUND == intent.action) { val device = intent .getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) foundDevices[device.address] = device listener?.onDeviceFind(device) } } } private val discoverableStateFilter = IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED) private val discoverableStateReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.SCAN_MODE_NONE) if (scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { listener?.onDiscoverableStart() } else { listener?.onDiscoverableFinish() isListeningForDiscoverableStatus = false context.unregisterReceiver(this) } } } private val scanningFinishedTask = Runnable { listener?.onDiscoveryFinish() isDiscovering = false try { context.unregisterReceiver(foundDeviceReceiver) } catch (e: IllegalArgumentException) { e.printStackTrace() } if (adapter != null && adapter.isDiscovering) { adapter.cancelDiscovery() } } override fun getMyDeviceName() = try { adapter?.name ?: "?" } catch (e: Exception) { "?" } override fun scanForDevices(seconds: Int) { adapter?.startDiscovery() listener?.onDiscoveryStart(seconds) isDiscovering = true handler.postDelayed(scanningFinishedTask, seconds.toLong() * 1000) context.registerReceiver(foundDeviceReceiver, foundDeviceFilter) } override fun stopScanning() { handler.removeCallbacks(scanningFinishedTask) scanningFinishedTask.run() } override fun getBondedDevices(): List<BluetoothDevice> { val devices = adapter?.bondedDevices return if (devices == null) ArrayList() else ArrayList<BluetoothDevice>(devices) } override fun getDeviceByAddress(address: String): BluetoothDevice? { val pairedDevice = getBondedDevices() .filter { it.address.equals(address, ignoreCase = true) } return if (!pairedDevice.isEmpty()) pairedDevice.first() else foundDevices[address] } override fun isBluetoothAvailable() = adapter != null override fun isBluetoothEnabled() = adapter?.isEnabled ?: false override fun isDiscoverable() = adapter?.scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE override fun isDiscovering() = isDiscovering override fun listenDiscoverableStatus() { isListeningForDiscoverableStatus = true context.registerReceiver(discoverableStateReceiver, discoverableStateFilter) } override fun stopListeningDiscoverableStatus() { if (isListeningForDiscoverableStatus) { context.unregisterReceiver(discoverableStateReceiver) isListeningForDiscoverableStatus = false } } override fun setScanningListener(listener: ScanningListener) { this.listener = listener } }
apache-2.0
4a5dd6a51b453b9dc0c2bb89a2fd3d0f
32.746154
112
0.680647
5.272837
false
false
false
false
spring-projects/spring-framework
spring-webflux/src/test/kotlin/org/springframework/web/reactive/function/server/RouterFunctionDslTests.kt
1
9483
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.function.server import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.jupiter.api.Test import org.springframework.core.io.ClassPathResource import org.springframework.http.HttpHeaders.* import org.springframework.http.HttpMethod.* import org.springframework.http.HttpStatus import org.springframework.http.MediaType.* import org.springframework.web.reactive.function.server.support.ServerRequestWrapper import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest.* import org.springframework.web.testfixture.server.MockServerWebExchange import org.springframework.web.reactive.function.server.AttributesTestVisitor import reactor.core.publisher.Mono import reactor.test.StepVerifier import java.security.Principal /** * Tests for [RouterFunctionDsl]. * * @author Sebastien Deleuze */ class RouterFunctionDslTests { @Test fun header() { val mockRequest = get("https://example.com") .header("bar","bar").build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun accept() { val mockRequest = get("https://example.com/content") .header(ACCEPT, APPLICATION_ATOM_XML_VALUE).build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun acceptAndPOST() { val mockRequest = post("https://example.com/api/foo/") .header(ACCEPT, APPLICATION_JSON_VALUE) .build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun acceptAndPOSTWithRequestPredicate() { val mockRequest = post("https://example.com/api/bar/") .header(CONTENT_TYPE, APPLICATION_JSON_VALUE) .build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun contentType() { val mockRequest = get("https://example.com/content/") .header(CONTENT_TYPE, APPLICATION_OCTET_STREAM_VALUE) .build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun resourceByPath() { val mockRequest = get("https://example.com/org/springframework/web/reactive/function/response.txt") .build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun method() { val mockRequest = patch("https://example.com/") .build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun path() { val mockRequest = get("https://example.com/baz").build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun resource() { val mockRequest = get("https://example.com/response.txt").build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .expectNextCount(1) .verifyComplete() } @Test fun noRoute() { val mockRequest = get("https://example.com/bar") .header(ACCEPT, APPLICATION_PDF_VALUE) .header(CONTENT_TYPE, APPLICATION_PDF_VALUE) .build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request)) .verifyComplete() } @Test fun rendering() { val mockRequest = get("https://example.com/rendering").build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(sampleRouter().route(request).flatMap { it.handle(request) }) .expectNextMatches { it is RenderingResponse} .verifyComplete() } @Test fun emptyRouter() { assertThatExceptionOfType(IllegalStateException::class.java).isThrownBy { router { } } } @Test fun attributes() { val visitor = AttributesTestVisitor() attributesRouter.accept(visitor) assertThat(visitor.routerFunctionsAttributes()).containsExactly( listOf(mapOf("foo" to "bar", "baz" to "qux")), listOf(mapOf("foo" to "bar", "baz" to "qux")), listOf(mapOf("foo" to "bar"), mapOf("foo" to "n1")), listOf(mapOf("baz" to "qux"), mapOf("foo" to "n1")), listOf(mapOf("foo" to "n3"), mapOf("foo" to "n2"), mapOf("foo" to "n1")) ); assertThat(visitor.visitCount()).isEqualTo(7); } @Test fun acceptFilterAndPOST() { val mockRequest = post("https://example.com/filter") .header(ACCEPT, APPLICATION_JSON_VALUE) .build() val request = DefaultServerRequest(MockServerWebExchange.from(mockRequest), emptyList()) StepVerifier.create(filteredRouter.route(request).flatMap { it.handle(request) }) .expectNextCount(1) .verifyComplete() } private val filteredRouter = router { POST("/filter", ::handleRequestWrapper) filter (TestFilterProvider.provide()) before { it } after { _, response -> response } onError({it is IllegalStateException}) { _, _ -> ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build() } onError<IllegalStateException> { _, _ -> ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build() } } private class TestServerRequestWrapper(delegate: ServerRequest, private val principalOverride: String = "foo"): ServerRequestWrapper(delegate) { override fun principal(): Mono<out Principal> = Mono.just(Principal { principalOverride }) } private object TestFilterProvider { fun provide(): (ServerRequest, (ServerRequest) -> Mono<ServerResponse>) -> Mono<ServerResponse> = { request, next -> next(TestServerRequestWrapper(request)) } } private fun handleRequestWrapper(req: ServerRequest): Mono<ServerResponse> { return req.principal() .flatMap { assertThat(it.name).isEqualTo("foo") ServerResponse.ok().build() } } private fun sampleRouter() = router { (GET("/foo/") or GET("/foos/")) { req -> handle(req) } "/api".nest { POST("/foo/", ::handleFromClass) POST("/bar/", contentType(APPLICATION_JSON), ::handleFromClass) PUT("/foo/", :: handleFromClass) PATCH("/foo/") { ok().build() } "/foo/" { handleFromClass(it) } } "/content".nest { accept(APPLICATION_ATOM_XML, ::handle) contentType(APPLICATION_OCTET_STREAM, ::handle) } method(PATCH, ::handle) headers { it.accept().contains(APPLICATION_JSON) }.nest { GET("/api/foo/", ::handle) } headers({ it.header("bar").isNotEmpty() }, ::handle) resources("/org/springframework/web/reactive/function/**", ClassPathResource("/org/springframework/web/reactive/function/response.txt")) resources { if (it.path() == "/response.txt") { Mono.just(ClassPathResource("/org/springframework/web/reactive/function/response.txt")) } else { Mono.empty() } } path("/baz", ::handle) GET("/rendering") { RenderingResponse.create("index").build() } add(otherRouter) } private val otherRouter = router { "/other" { ok().build() } filter { request, next -> next(request) } before { it } after { _, response -> response } onError({it is IllegalStateException}) { _, _ -> ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build() } onError<IllegalStateException> { _, _ -> ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).build() } } private val attributesRouter = router { GET("/atts/1") { ok().build() } withAttribute("foo", "bar") withAttribute("baz", "qux") GET("/atts/2") { ok().build() } withAttributes { atts -> atts["foo"] = "bar" atts["baz"] = "qux" } "/atts".nest { GET("/3") { ok().build() } withAttribute("foo", "bar") GET("/4") { ok().build() } withAttribute("baz", "qux") "/5".nest { GET { ok().build() } withAttribute("foo", "n3") } withAttribute("foo", "n2") } withAttribute("foo", "n1") } @Suppress("UNUSED_PARAMETER") private fun handleFromClass(req: ServerRequest) = ServerResponse.ok().build() } @Suppress("UNUSED_PARAMETER") private fun handle(req: ServerRequest) = ServerResponse.ok().build()
apache-2.0
6560ed0a4d8aa5181226a3c3d930b37c
29.104762
145
0.705789
3.585255
false
true
false
false
leafclick/intellij-community
platform/util/testSrc/com/intellij/util/lang/JavaVersionTest.kt
1
8988
// 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 com.intellij.util.lang import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.Test class JavaVersionTest { @Test fun `1_0`() = doTest("1.0", 0) @Test fun `1_2`() = doTest("1.2", 2) @Test fun `1_4_0`() = doTest("1.4.0", 4) @Test fun `1_4_2_30`() = doTest("1.4.2_30", 4, 2, 30, 0) @Test fun `1_4_2_30-b03`() = doTest("1.4.2_30-b03", 4, 2, 30, 3) @Test fun `1_8_0_152`() = doTest("1.8.0_152", 8, 0, 152, 0) @Test fun `1_8_0_152-b16`() = doTest("1.8.0_152-b16", 8, 0, 152, 16) @Test fun `1_8_0_162-ea`() = doTest("1.8.0_162-ea", 8, 0, 162, 0, true) @Test fun `1_8_0_162-ea-b03`() = doTest("1.8.0_162-ea-b03", 8, 0, 162, 3, true) @Test fun `1_8_0_152-jb`() = doTest("1.8.0_152-release", 8, 0, 152, 0) @Test fun `1_8_0_152-jb-b13`() = doTest("1.8.0_152-release-1056-b13", 8, 0, 152, 13) @Test fun `1_8_0_151-debian-b12`() = doTest("1.8.0_151-8u151-b12-0ubuntu0.17.10.2-b12", 8, 0, 151, 12) @Test fun `1_8_0_45-internal`() = doTest("1.8.0_45-internal", 8, 0, 45, 0, true) @Test fun `1_8_0_121-2-whatever-b11`() = doTest("1.8.0_121-2-whatever-b11", 8, 0, 121, 11) @Test fun `1_8_0_121-(big-number)-b11`() = doTest("1.8.0_121-99${Long.MAX_VALUE}-b11", 8, 0, 121, 11) @Test fun `1_10`() = doTest("1.10", 10) @Test fun `5`() = doTest("5", 5) @Test fun `9`() = doTest("9", 9) @Test fun `9-ea`() = doTest("9-ea", 9, 0, 0, 0, true) @Test fun `9-internal`() = doTest("9-internal", 9, 0, 0, 0, true) @Test fun `9-ea+165`() = doTest("9-ea+165", 9, 0, 0, 165, true) @Test fun `9+181`() = doTest("9+181", 9, 0, 0, 181) @Test fun `9_0_1`() = doTest("9.0.1", 9, 0, 1, 0) @Test fun `9_1_2`() = doTest("9.1.2", 9, 1, 2, 0) @Test fun `9_0_1+11`() = doTest("9.0.1+11", 9, 0, 1, 11) @Test fun `9_0_3-ea`() = doTest("9.0.3-ea", 9, 0, 3, 0, true) @Test fun `9_0_3-ea+9`() = doTest("9.0.3-ea+9", 9, 0, 3, 9, true) @Test fun `9-Ubuntu`() = doTest("9-Ubuntu", 9) @Test fun `9-Ubuntu+0-9b181-4`() = doTest("9-Ubuntu+0-9b181-4", 9) @Test fun `10`() = doTest("10", 10) @Test fun `10-ea`() = doTest("10-ea", 10, 0, 0, 0, true) @Test fun `10-ea+36`() = doTest("10-ea+36", 10, 0, 0, 36, true) @Test fun `10-ea+0-valhalla`() = doTest("10-mvt_ea+0-2017-12-11-1328177.valhalla", 10) @Test fun empty() = doFailTest("") @Test fun spaces() = doFailTest(" ") @Test fun randomWord() = doFailTest("whatever") @Test fun incomplete1() = doFailTest("1") @Test fun incomplete2() = doFailTest("-1") @Test fun incomplete3() = doFailTest("1.") @Test fun outOfRange1() = doFailTest("0") @Test fun outOfRange2() = doFailTest("4") @Test fun outOfRange3() = doFailTest("99${Long.MAX_VALUE}") @Test fun ibmRt() = doFailTest("pxa6480sr3fp10-20160720_02 (SR3 FP10)") @Test fun current() { val current = JavaVersion.current() assertThat(current.feature).isGreaterThanOrEqualTo(8) assertThat(current.minor).isEqualTo(0) assertThat(current.build).isGreaterThan(0) } @Test fun comparing() { assertThat(JavaVersion.compose(9, 0, 0, 0, false)).isGreaterThan(JavaVersion.compose(8, 0, 0, 0, false)) assertThat(JavaVersion.compose(8, 1, 0, 0, false)).isGreaterThan(JavaVersion.compose(8, 0, 0, 0, false)) assertThat(JavaVersion.compose(8, 0, 1, 0, false)).isGreaterThan(JavaVersion.compose(8, 0, 0, 0, false)) assertThat(JavaVersion.compose(8, 0, 0, 1, false)).isGreaterThan(JavaVersion.compose(8, 0, 0, 0, false)) assertThat(JavaVersion.compose(8, 0, 0, 0, false)).isGreaterThan(JavaVersion.compose(8, 0, 0, 0, true)) } @Test fun formatting() { assertThat(JavaVersion.compose(8, 0, 0, 0, false).toString()).isEqualTo("1.8") assertThat(JavaVersion.compose(8, 1, 0, 0, false).toString()).isEqualTo("1.8.1") assertThat(JavaVersion.compose(8, 0, 1, 0, false).toString()).isEqualTo("1.8.0_1") assertThat(JavaVersion.compose(8, 0, 0, 1, false).toString()).isEqualTo("1.8.0-b1") assertThat(JavaVersion.compose(8, 0, 0, 0, true).toString()).isEqualTo("1.8.0-ea") assertThat(JavaVersion.compose(8, 1, 2, 3, true).toString()).isEqualTo("1.8.1_2-ea-b3") assertThat(JavaVersion.compose(9, 0, 0, 0, false).toString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 1, 0, 0, false).toString()).isEqualTo("9.1") assertThat(JavaVersion.compose(9, 0, 1, 0, false).toString()).isEqualTo("9.0.1") assertThat(JavaVersion.compose(9, 0, 0, 1, false).toString()).isEqualTo("9+1") assertThat(JavaVersion.compose(9, 0, 0, 0, true).toString()).isEqualTo("9-ea") assertThat(JavaVersion.compose(9, 1, 2, 3, true).toString()).isEqualTo("9.1.2-ea+3") } @Test fun formattingFeatureMinorUpdate() { assertThat(JavaVersion.compose(8, 0, 0, 0, false).toFeatureMinorUpdateString()).isEqualTo("1.8") assertThat(JavaVersion.compose(8, 1, 0, 0, false).toFeatureMinorUpdateString()).isEqualTo("1.8.1") assertThat(JavaVersion.compose(8, 0, 1, 0, false).toFeatureMinorUpdateString()).isEqualTo("1.8.0_1") assertThat(JavaVersion.compose(8, 0, 0, 1, false).toFeatureMinorUpdateString()).isEqualTo("1.8.0") assertThat(JavaVersion.compose(8, 0, 0, 0, true).toFeatureMinorUpdateString()).isEqualTo("1.8.0") assertThat(JavaVersion.compose(8, 1, 2, 3, true).toFeatureMinorUpdateString()).isEqualTo("1.8.1_2") assertThat(JavaVersion.compose(9, 0, 0, 0, false).toFeatureMinorUpdateString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 1, 0, 0, false).toFeatureMinorUpdateString()).isEqualTo("9.1") assertThat(JavaVersion.compose(9, 0, 1, 0, false).toFeatureMinorUpdateString()).isEqualTo("9.0.1") assertThat(JavaVersion.compose(9, 0, 0, 1, false).toFeatureMinorUpdateString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 0, 0, 0, true).toFeatureMinorUpdateString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 1, 2, 3, true).toFeatureMinorUpdateString()).isEqualTo("9.1.2") } @Test fun formattingProductOnly() { assertThat(JavaVersion.compose(8, 0, 0, 0, false).toFeatureString()).isEqualTo("1.8") assertThat(JavaVersion.compose(8, 1, 0, 0, false).toFeatureString()).isEqualTo("1.8") assertThat(JavaVersion.compose(8, 0, 1, 0, false).toFeatureString()).isEqualTo("1.8") assertThat(JavaVersion.compose(8, 0, 0, 1, false).toFeatureString()).isEqualTo("1.8") assertThat(JavaVersion.compose(8, 0, 0, 0, true).toFeatureString()).isEqualTo("1.8") assertThat(JavaVersion.compose(8, 1, 2, 3, true).toFeatureString()).isEqualTo("1.8") assertThat(JavaVersion.compose(9, 0, 0, 0, false).toFeatureString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 1, 0, 0, false).toFeatureString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 0, 1, 0, false).toFeatureString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 0, 0, 1, false).toFeatureString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 0, 0, 0, true).toFeatureString()).isEqualTo("9") assertThat(JavaVersion.compose(9, 1, 2, 3, true).toFeatureString()).isEqualTo("9") } private fun doTest(versionString: String, feature: Int, minor: Int = 0, update: Int = 0, build: Int = 0, ea: Boolean = false) { val expected = JavaVersion.compose(feature, minor, update, build, ea) val parsed = JavaVersion.parse(versionString) assertThat(parsed).isEqualTo(expected) val reparsed = JavaVersion.parse(parsed.toString()) assertThat(reparsed).isEqualTo(expected) sequenceOf( // "java -version", 1st line "java version \"$versionString\"", // 1.0 - 9 "openjdk version \"$versionString\"", "java version \"$versionString\" 2018-03-20", // 10+ "openjdk version \"$versionString\" 2018-03-20", // "java -version", 2nd line "Classic VM (build JDK-$versionString, native threads, jit)", // 1.2 "Java(TM) 2 Runtime Environment, Standard Edition (build $versionString)", // 1.3 - 1.5 "Java(TM) SE Runtime Environment (build $versionString)", // 1.6 - 9 "OpenJDK Runtime Environment (build $versionString)", "Java(TM) SE Runtime Environment 18.3 (build $versionString)", // 10+ "OpenJDK Runtime Environment 18.3 (build $versionString)", // "java --full-version" (9+) "java $versionString", "openjdk $versionString", // `release` file (1.7+) "JAVA_VERSION=\"$versionString\"" ).forEach { assertThat(JavaVersion.parse(it)).describedAs(it).isEqualTo(expected) } } private fun doFailTest(versionString: String) { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { JavaVersion.parse(versionString) } .withMessage(versionString) } }
apache-2.0
fe64303990f0d36c0de5a093e4caca79
57.37013
140
0.639186
3.062351
false
true
false
false
zdary/intellij-community
python/src/com/jetbrains/python/inspections/PyRelativeImportInspection.kt
3
5761
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.command.undo.BasicUndoableAction import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.PyBundle import com.jetbrains.python.PyPsiBundle import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.namespacePackages.PyNamespacePackagesService import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyElementGenerator import com.jetbrains.python.psi.PyFromImportStatement import com.jetbrains.python.psi.PyUtil class PyRelativeImportInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { if (!PyNamespacePackagesService.isEnabled() || LanguageLevel.forElement(holder.file).isOlderThan(LanguageLevel.PYTHON34)) { return PsiElementVisitor.EMPTY_VISITOR } return Visitor(holder, session) } private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyFromImportStatement(node: PyFromImportStatement) { val directory = node.containingFile?.containingDirectory ?: return if (node.relativeLevel > 0 && !PyUtil.isExplicitPackage(directory) && !isInsideOrdinaryPackage(directory)) { handleRelativeImportNotInsidePackage(node, directory) } } private fun isInsideOrdinaryPackage(directory: PsiDirectory): Boolean { var curDir: PsiDirectory? = directory while (curDir != null) { if (PyUtil.isOrdinaryPackage(curDir)) return true curDir = curDir.parentDirectory } return false } private fun handleRelativeImportNotInsidePackage(node: PyFromImportStatement, directory: PsiDirectory) { val fixes = mutableListOf<LocalQuickFix>() getMarkAsNamespacePackageQuickFix(directory) ?.let { fixes.add(it) } if (node.relativeLevel == 1) { fixes.add(PyChangeToSameDirectoryImportQuickFix()) } val message = PyPsiBundle.message("INSP.relative.import.relative.import.outside.package") registerProblem(node, message, *fixes.toTypedArray()) } private fun getMarkAsNamespacePackageQuickFix(directory: PsiDirectory): PyMarkAsNamespacePackageQuickFix? { val module = ModuleUtilCore.findModuleForPsiElement(directory) ?: return null var curDir: PsiDirectory? = directory while (curDir != null) { val virtualFile = curDir.virtualFile if (PyUtil.isRoot(curDir)) return null val parentDir = curDir.parentDirectory if (parentDir != null && (PyUtil.isRoot(parentDir) || PyUtil.isOrdinaryPackage(parentDir))) { return PyMarkAsNamespacePackageQuickFix(module, virtualFile) } curDir = parentDir } return null } } private class PyMarkAsNamespacePackageQuickFix(val module: Module, val directory: VirtualFile) : LocalQuickFix { override fun getFamilyName(): String = PyBundle.message("QFIX.mark.as.namespace.package", directory.name) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val document = PsiDocumentManager.getInstance(project).getDocument(descriptor.psiElement.containingFile) val undoableAction = object: BasicUndoableAction(document) { override fun undo() { PyNamespacePackagesService.getInstance(module).toggleMarkingAsNamespacePackage(directory) } override fun redo() { PyNamespacePackagesService.getInstance(module).toggleMarkingAsNamespacePackage(directory) } } undoableAction.redo() UndoManager.getInstance(project).undoableActionPerformed(undoableAction) } } private class PyChangeToSameDirectoryImportQuickFix : LocalQuickFix { override fun getFamilyName(): String = PyBundle.message("QFIX.change.to.same.directory.import") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val oldImport = descriptor.psiElement as? PyFromImportStatement ?: return assert(oldImport.relativeLevel == 1) val qualifier = oldImport.importSource if (qualifier != null) { val possibleDot = PsiTreeUtil.prevVisibleLeaf(qualifier) assert(possibleDot != null && possibleDot.node.elementType == PyTokenTypes.DOT) possibleDot?.delete() } else { replaceByImportStatements(oldImport) } } private fun replaceByImportStatements(oldImport: PyFromImportStatement) { val project = oldImport.project val generator = PyElementGenerator.getInstance(project) val names = oldImport.importElements.map { it.text } if (names.isEmpty()) return val langLevel = LanguageLevel.forElement(oldImport) for (name in names.reversed()) { val newImport = generator.createImportStatement(langLevel, name, null) oldImport.parent.addAfter(newImport, oldImport) } oldImport.delete() } } }
apache-2.0
8615361b9b7ee0254414ca0cf5a0d2c4
42
140
0.7431
4.841176
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/modcrafters/mclib/ingredients/implementations/RegistrationItemIngredient.kt
1
1053
package net.modcrafters.mclib.ingredients.implementations import net.minecraft.item.Item import net.minecraft.item.ItemStack class RegistrationItemIngredient(val modId: String, pathMask: String, override val amount: Int, val meta: Int) : BaseFilterItemIngredient(pathMask) { private val lazyItemStacks by lazy { Item.REGISTRY.keys.filter { this.isMatch(it.toString()) }.map { ItemStack(Item.REGISTRY.getObject(it)!!, this.amount, this.meta) } } override fun getStringsFor(stack: ItemStack) = listOf<String>( stack.item.registryName?.toString() ?: "" ) override fun isMatch(info: String): Boolean { if (info.contains(':')) { val (modId, path) = info.indexOf(':').let { info.substring(0 .. (it - 1)) to info.substring(it + 1) } return (this.modId == modId) && super.isMatch(path) } return super.isMatch(info) } override val itemStacks: List<ItemStack> get() = this.lazyItemStacks }
mit
0fbf00a8f4fd6ef46f1f27d14ecb4df7
32.967742
149
0.624881
4.113281
false
false
false
false
JuliusKunze/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/GraphAlgorithms.kt
1
3226
/* * 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 org.jetbrains.kotlin.backend.konan internal interface DirectedGraphNode<out K> { val key: K val directEdges: List<K> val reversedEdges: List<K> } internal interface DirectedGraph<K, out N: DirectedGraphNode<K>> { val nodes: Collection<N> fun get(key: K): N } internal class DirectedGraphMultiNode<out K>(val nodes: Set<K>) internal class DirectedGraphCondensation<out K>(val topologicalOrder: List<DirectedGraphMultiNode<K>>) internal class DirectedGraphCondensationBuilder<K, out N: DirectedGraphNode<K>>(private val graph: DirectedGraph<K, N>) { private val visited = mutableSetOf<K>() private val order = mutableListOf<N>() private val nodeToMultiNodeMap = mutableMapOf<N, DirectedGraphMultiNode<K>>() private val multiNodesOrder = mutableListOf<DirectedGraphMultiNode<K>>() fun build(): DirectedGraphCondensation<K> { // First phase. graph.nodes.forEach { if (!visited.contains(it.key)) findOrder(it) } // Second phase. visited.clear() val multiNodes = mutableListOf<DirectedGraphMultiNode<K>>() order.reversed().forEach { if (!visited.contains(it.key)) { val nodes = mutableSetOf<K>() paint(it, nodes) multiNodes += DirectedGraphMultiNode(nodes) } } // Topsort of built condensation. multiNodes.forEach { multiNode -> multiNode.nodes.forEach { nodeToMultiNodeMap.put(graph.get(it), multiNode) } } visited.clear() multiNodes.forEach { if (!visited.contains(it.nodes.first())) findMultiNodesOrder(it) } return DirectedGraphCondensation(multiNodesOrder) } private fun findOrder(node: N) { visited += node.key node.directEdges.forEach { if (!visited.contains(it)) findOrder(graph.get(it)) } order += node } private fun paint(node: N, multiNode: MutableSet<K>) { visited += node.key multiNode += node.key node.reversedEdges.forEach { if (!visited.contains(it)) paint(graph.get(it), multiNode) } } private fun findMultiNodesOrder(node: DirectedGraphMultiNode<K>) { visited.addAll(node.nodes) node.nodes.forEach { graph.get(it).directEdges.forEach { if (!visited.contains(it)) findMultiNodesOrder(nodeToMultiNodeMap[graph.get(it)]!!) } } multiNodesOrder += node } }
apache-2.0
1db1a725c4599f333eb308a059569f7a
31.585859
121
0.631742
4.18961
false
false
false
false
kpi-ua/ecampus-client-android
app/src/main/java/com/goldenpiedevs/schedule/app/core/dao/timetable/DaoRoomModel.kt
1
663
package com.goldenpiedevs.schedule.app.core.dao.timetable import com.google.gson.annotations.SerializedName import io.realm.RealmObject import io.realm.annotations.PrimaryKey import io.realm.annotations.RealmClass import org.osmdroid.util.GeoPoint @RealmClass open class DaoRoomModel : RealmObject() { @PrimaryKey @SerializedName("room_id") var roomId: String = "" @SerializedName("room_longitude") var roomLongitude: Double = 0.0 @SerializedName("room_name") var roomName: String = "" @SerializedName("room_latitude") var roomLatitude: Double = 0.0 fun getGeoPoint(): GeoPoint = GeoPoint(roomLatitude, roomLongitude) }
apache-2.0
0578a11bfcedc7b6b51153e6f46a2202
27.869565
71
0.748115
4.14375
false
false
false
false
Flank/flank
test_projects/android/parameterizedTests/src/androidTest/java/com/flank/parameterizedtestsapplication/parameterized/SampleParameterizedTestSmall.kt
1
814
package com.flank.parameterizedtestsapplication.parameterized import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class SampleParameterizedTestSmall { companion object { @JvmStatic @Parameterized.Parameters fun inputs() = listOf( arrayOf( 0, "0" ), arrayOf( 1, "1" ) ) } @Parameterized.Parameter(value = 0) @JvmField var mTestInteger = 0 @Parameterized.Parameter(value = 1) @JvmField var mTestString: String? = null @Test fun sample_parseValue() { assertEquals(mTestString!!.toInt(), mTestInteger) } }
apache-2.0
fe950a5ba9f5da68a5cffe33408c4cbc
19.871795
61
0.590909
4.625
false
true
false
false
zdary/intellij-community
plugins/ide-features-trainer/src/training/statistic/LearnProjectStateListener.kt
1
2719
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.statistic import com.intellij.ide.RecentProjectsManagerBase import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.wm.impl.CloseProjectWindowHelper import training.lang.LangManager import training.util.isLearningProject import training.util.trainerPluginConfigName internal class LearnProjectStateListener : ProjectManagerListener { override fun projectOpened(project: Project) { val langSupport = LangManager.getInstance().getLangSupport() ?: return if (isLearningProject(project, langSupport)) { CloseProjectWindowHelper.SHOW_WELCOME_FRAME_FOR_PROJECT.set(project, true) removeFromRecentProjects(project) } else { val learnProjectState = LearnProjectState.instance val way = learnProjectState.firstTimeOpenedWay if (way != null) { StatisticBase.logNonLearningProjectOpened(way) learnProjectState.firstTimeOpenedWay = null } } } override fun projectClosingBeforeSave(project: Project) { val langSupport = LangManager.getInstance().getLangSupport() ?: return if (isLearningProject(project, langSupport)) { StatisticBase.isLearnProjectClosing = true StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.CLOSE_PROJECT) } } override fun projectClosed(project: Project) { val langSupport = LangManager.getInstance().getLangSupport() ?: return if (isLearningProject(project, langSupport)) { StatisticBase.isLearnProjectClosing = false removeFromRecentProjects(project) } } private fun removeFromRecentProjects(project: Project) { val manager = RecentProjectsManagerBase.instanceEx manager.getProjectPath(project)?.let { manager.removePath(it) } } } @State(name = "LearnProjectState", storages = [Storage(value = trainerPluginConfigName)]) internal class LearnProjectState : PersistentStateComponent<LearnProjectState> { var firstTimeOpenedWay: StatisticBase.LearnProjectOpeningWay? = null override fun getState(): LearnProjectState = this override fun loadState(state: LearnProjectState) { firstTimeOpenedWay = state.firstTimeOpenedWay } companion object { internal val instance: LearnProjectState get() = ApplicationManager.getApplication().getService(LearnProjectState::class.java) } }
apache-2.0
c8a601f29d3004861077046a0f4e38bb
38.42029
140
0.78117
4.907942
false
false
false
false
stefanmedack/cccTV
app/src/main/java/de/stefanmedack/ccctv/util/AndroidExtensions.kt
1
1557
package de.stefanmedack.ccctv.util import android.app.Activity import android.content.pm.PackageManager.PERMISSION_GRANTED import android.support.v17.leanback.widget.ArrayObjectAdapter import android.support.v17.leanback.widget.Row import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentTransaction fun Activity.hasPermission(permission: String) : Boolean = PERMISSION_GRANTED == this.packageManager.checkPermission(permission, this.packageName) operator fun ArrayObjectAdapter.plusAssign(items: List<*>?) { items?.forEach { this.add(it) } } operator fun ArrayObjectAdapter.plusAssign(row: Row) = this.add(row) inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) { beginTransaction().func().commit() } fun FragmentActivity.addFragmentInTransaction( fragment: Fragment, containerId: Int, tag: String? = null, addToBackStack: Boolean = false ) { supportFragmentManager.inTransaction { add(containerId, fragment, tag).also { if (addToBackStack) addToBackStack(tag) } } } fun FragmentActivity.replaceFragmentInTransaction( fragment: Fragment, containerId: Int, tag: String? = null, addToBackStack: Boolean = false ) { supportFragmentManager.inTransaction { replace(containerId, fragment, tag).also { if (addToBackStack) addToBackStack(tag) } } }
apache-2.0
ff588396dfc3b097211526b639f3f2e3
30.795918
95
0.73025
4.579412
false
false
false
false
jwren/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/FileState.kt
1
1574
package com.intellij.settingsSync import com.intellij.util.io.readBytes import com.intellij.util.io.systemIndependentPath import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.nio.file.Path import kotlin.io.path.relativeTo internal sealed class FileState(open val file: String) { class Modified(override val file: String, val content: ByteArray, val size: Int) : FileState(file) { override fun toString(): String = "file='$file', content:\n${String(content, StandardCharsets.UTF_8)}" override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Modified if (file != other.file) return false if (!content.contentEquals(other.content)) return false if (size != other.size) return false return true } override fun hashCode(): Int { var result = file.hashCode() result = 31 * result + content.contentHashCode() result = 31 * result + size return result } } data class Deleted(override val file: String): FileState(file) } internal fun getFileStateFromFileWithDeletedMarker(file: Path, storageBasePath: Path): FileState { val bytes = file.readBytes() val text = String(bytes, Charset.defaultCharset()) val fileSpec = file.relativeTo(storageBasePath).systemIndependentPath return if (text == DELETED_FILE_MARKER) { FileState.Deleted(fileSpec) } else { FileState.Modified(fileSpec, bytes, bytes.size) } } internal const val DELETED_FILE_MARKER = "DELETED"
apache-2.0
4140ad11a0f3fb832d02d412e575b122
30.5
106
0.714104
4.153034
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/pool/create/CreateLvmPoolTest.kt
2
4095
package com.github.kerubistan.kerub.planner.steps.storage.lvm.pool.create import com.github.kerubistan.kerub.model.LvmStorageCapability import com.github.kerubistan.kerub.model.config.HostConfiguration import com.github.kerubistan.kerub.model.config.LvmPoolConfiguration import com.github.kerubistan.kerub.model.dynamic.HostDynamic import com.github.kerubistan.kerub.model.dynamic.HostStatus import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep import com.github.kerubistan.kerub.planner.steps.OperationalStepVerifications import com.github.kerubistan.kerub.testHost import com.github.kerubistan.kerub.testHostCapabilities import com.github.kerubistan.kerub.testOtherHost import io.github.kerubistan.kroki.size.TB import org.junit.Test import org.junit.jupiter.api.assertThrows import java.util.UUID.randomUUID import kotlin.test.assertFalse import kotlin.test.assertTrue class CreateLvmPoolTest : OperationalStepVerifications() { @Test fun validations() { assertThrows<IllegalStateException>("Pool bigger than the VG") { val capability = LvmStorageCapability( id = randomUUID(), size = 8.TB, volumeGroupName = "test-vg", physicalVolumes = mapOf("/dev/sda" to 4.TB, "/dev/sdb" to 4.TB) ) CreateLvmPool( host = testHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf( capability ) ) ), size = 10.TB, vgName = capability.volumeGroupName, name = randomUUID().toString() ) } } @Test fun isLikeStep() { val step = CreateLvmPool( host = testHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf( LvmStorageCapability( id = randomUUID(), size = 8.TB, volumeGroupName = "test-vg", physicalVolumes = mapOf("/dev/sda" to 4.TB, "/dev/sdb" to 4.TB) ) ) ) ), size = 2.TB, vgName = "test-vg", name = "pool-1") val otherStep = CreateLvmPool( host = testOtherHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf( LvmStorageCapability( id = randomUUID(), size = 8.TB, volumeGroupName = "test-vg", physicalVolumes = mapOf("/dev/sda" to 4.TB, "/dev/sdb" to 4.TB) ) ) ) ), size = 2.TB, vgName = "test-vg", name = "pool-1") assertTrue(step.isLikeStep(step)) assertFalse(step.isLikeStep(otherStep)) } override val step: AbstractOperationalStep get() = CreateLvmPool( host = testHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf( LvmStorageCapability( id = randomUUID(), size = 8.TB, volumeGroupName = "test-vg", physicalVolumes = mapOf("/dev/sda" to 4.TB, "/dev/sdb" to 4.TB) ) ) ) ), size = 2.TB, vgName = "test-vg", name = "pool-1") @Test fun take() { val host = testHost.copy( capabilities = testHostCapabilities.copy( storageCapabilities = listOf( LvmStorageCapability( id = randomUUID(), size = 8.TB, volumeGroupName = "test-vg", physicalVolumes = mapOf("/dev/sda" to 4.TB, "/dev/sdb" to 4.TB) ) ) ) ) val state = CreateLvmPool(host = host, size = 2.TB, vgName = "test-vg", name = "pool-1").take( OperationalState.fromLists( hosts = listOf( host ), hostDyns = listOf( HostDynamic( id = host.id, status = HostStatus.Up ) ), hostCfgs = listOf( HostConfiguration( id = host.id, storageConfiguration = listOf() ) ) ) ) assertTrue { val poolConfig = (state.hosts.getValue(testHost.id).config!!.storageConfiguration.single() as LvmPoolConfiguration) poolConfig.poolName == "pool-1" && poolConfig.size == 2.TB && poolConfig.vgName == "test-vg" } } }
apache-2.0
a5ea92423efa0837ed108f4231787d26
29.340741
118
0.636874
3.830683
false
true
false
false
dahlstrom-g/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/strategy/impl/RuleGroup.kt
8
1300
// 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 com.intellij.grazie.grammar.strategy.impl import com.intellij.grazie.utils.LinkedSet @Suppress("DEPRECATION") @Deprecated( replaceWith = ReplaceWith("com.intellij.grazie.text.RuleGroup"), message = "Use a non-impl class" ) class RuleGroup(rules: LinkedSet<String>): com.intellij.grazie.text.RuleGroup(rules) { constructor(vararg rules: String) : this(LinkedSet<String>(rules.toSet())) companion object { val EMPTY = RuleGroup() /** Rule for checking double whitespaces */ @Deprecated("Use getStealthyRanges() in GrammarCheckingStrategy and StrategyUtils.indentIndexes()") val WHITESPACES = RuleGroup("WHITESPACE_RULE") /** Rules for checking casing errors */ val CASING = RuleGroup("UPPERCASE_SENTENCE_START") /** Rules for checking punctuation errors */ val PUNCTUATION = RuleGroup("PUNCTUATION_PARAGRAPH_END", "UNLIKELY_OPENING_PUNCTUATION") /** Rules that are usually disabled for literal strings */ val LITERALS = CASING + PUNCTUATION } fun getRules(): LinkedSet<String> = LinkedSet(rules) operator fun plus(other: RuleGroup) = RuleGroup((rules + other.rules) as LinkedSet<String>) }
apache-2.0
5229e198fcd9ef5b3f55c17f366d8419
37.235294
140
0.736923
4.012346
false
false
false
false
sheungon/SotwtmSupportLib
lib-sotwtm-support/src/main/kotlin/com/sotwtm/support/util/databinding/ViewHelpfulBindingAdapter.kt
1
1982
package com.sotwtm.support.util.databinding import androidx.databinding.BindingAdapter import androidx.databinding.adapters.ListenerUtil import androidx.annotation.DrawableRes import com.google.android.material.snackbar.Snackbar import android.view.View import com.sotwtm.support.R import com.sotwtm.support.activity.AppHelpfulActivity import com.sotwtm.support.util.createSnackbar import com.sotwtm.util.Log object ViewHelpfulBindingAdapter { @JvmStatic @BindingAdapter("menuId") fun showAllMenu( view: View, menuId: Int? ) { (view.context as? AppHelpfulActivity)?.apply { menuResId = menuId invalidateOptionsMenu() } } @JvmStatic @BindingAdapter("backgroundResource") fun setBackgroundRes( view: View, @DrawableRes resId: Int? ) { if (resId == null) { view.background = null } else { view.setBackgroundResource(resId) } } @JvmStatic @BindingAdapter( value = ["snackbarMsg", "snackbarDuration", "snackbarActionMsg", "snackbarAction"], requireAll = false ) fun showSnackbar( view: View, msg: String?, duration: Int?, actionMsg: String?, action: View.OnClickListener? ) { ListenerUtil.getListener<Snackbar?>(view, R.id.snackbar)?.dismiss() if (duration != Snackbar.LENGTH_SHORT && duration != Snackbar.LENGTH_LONG && duration != Snackbar.LENGTH_INDEFINITE ) { Log.e("Show snackbar with an invalid time : $duration") return } if (msg == null) return val snackbar = view.createSnackbar(msg, duration) if (actionMsg != null && action != null) { snackbar.setAction(actionMsg, action) } snackbar.show() ListenerUtil.trackListener(view, snackbar, R.id.snackbar) } }
apache-2.0
212051a184cf39de41de2ade67f0a3f5
25.797297
75
0.612008
4.641686
false
false
false
false
GunoH/intellij-community
java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProviderBase.kt
3
5899
// 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.packaging.impl.run import com.intellij.execution.BeforeRunTaskProvider import com.intellij.execution.RunManagerEx import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.impl.ConfigurationSettingsEditorWrapper import com.intellij.execution.impl.ExecutionManagerImpl import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.compiler.JavaCompilerBundle import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Key import com.intellij.packaging.artifacts.* import com.intellij.task.ProjectTask import com.intellij.task.ProjectTaskContext import com.intellij.task.ProjectTaskManager import com.intellij.task.impl.ProjectTaskManagerImpl import com.intellij.util.ui.JBUI import javax.swing.JComponent @Suppress("FINITE_BOUNDS_VIOLATION_IN_JAVA") abstract class BuildArtifactsBeforeRunTaskProviderBase<T : BuildArtifactsBeforeRunTaskBase<*>>( private val taskClass: Class<T>, private val project: Project ) : BeforeRunTaskProvider<T>() { init { project.messageBus.connect().subscribe(ArtifactManager.TOPIC, MyArtifactListener(project, id)) } override fun isConfigurable() = true @Suppress("OVERRIDE_DEPRECATION") override fun configureTask(runConfiguration: RunConfiguration, task: T): Boolean { val artifacts = ArtifactManager.getInstance(project).artifacts val pointers = HashSet<ArtifactPointer>() if (artifacts.isNotEmpty()) { val artifactPointerManager = ArtifactPointerManager.getInstance(project) for (artifact in artifacts) { pointers.add(artifactPointerManager.createPointer(artifact!!)) } } pointers.addAll(task.artifactPointers) val chooser = ArtifactChooser(pointers.toList()) chooser.markElements(task.artifactPointers) chooser.preferredSize = JBUI.size(400, 300) val builder = DialogBuilder(project) builder.setTitle(JavaCompilerBundle.message("build.artifacts.before.run.selector.title")) builder.setDimensionServiceKey("#BuildArtifactsBeforeRunChooser") builder.addOkAction() builder.addCancelAction() builder.setCenterPanel(chooser) builder.setPreferredFocusComponent(chooser) if (builder.show() == DialogWrapper.OK_EXIT_CODE) { task.artifactPointers = chooser.markedElements return true } return false } override fun createTask(runConfiguration: RunConfiguration): T? { return if (project.isDefault) null else doCreateTask(project) } override fun canExecuteTask(configuration: RunConfiguration, task: T): Boolean { return task.artifactPointers.any { it.artifact != null } } override fun executeTask(context: DataContext, configuration: RunConfiguration, env: ExecutionEnvironment, task: T): Boolean { val artifacts = ArrayList<Artifact>() ApplicationManager.getApplication().runReadAction { for (pointer in task.artifactPointers) { pointer.artifact?.let(artifacts::add) } } if (project.isDisposed) { return false } val artifactsBuildProjectTask = createProjectTask(project, artifacts) val sessionId = ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env) val projectTaskContext = ProjectTaskContext(sessionId) env.copyUserDataTo(projectTaskContext) val resultPromise = ProjectTaskManager.getInstance(project).run(projectTaskContext, artifactsBuildProjectTask) val taskResult = ProjectTaskManagerImpl.waitForPromise(resultPromise) return taskResult != null && !taskResult.isAborted && !taskResult.hasErrors() } protected fun setBuildArtifactBeforeRunOption(runConfigurationEditorComponent: JComponent, artifact: Artifact, enable: Boolean) { val dataContext = DataManager.getInstance().getDataContext(runConfigurationEditorComponent) val editor = ConfigurationSettingsEditorWrapper.CONFIGURATION_EDITOR_KEY.getData(dataContext) ?: return val tasks: List<BuildArtifactsBeforeRunTaskBase<*>> = editor.stepsBeforeLaunch .mapNotNull { if (taskClass.isInstance(it)) it as BuildArtifactsBeforeRunTaskBase else null } if (enable && tasks.isEmpty()) { val task = doCreateTask(project) task.addArtifact(artifact) task.isEnabled = true editor.addBeforeLaunchStep(task) } else { for (task in tasks) { if (enable) { task.addArtifact(artifact) task.setEnabled(true) } else { task.removeArtifact(artifact) if (task.artifactPointers.isEmpty()) { task.isEnabled = false } } } } } protected abstract fun doCreateTask(project: Project?): T protected abstract fun createProjectTask(project: Project, artifacts: List<Artifact>): ProjectTask } @Suppress("FINITE_BOUNDS_VIOLATION_IN_JAVA") private class MyArtifactListener<T : BuildArtifactsBeforeRunTaskBase<*>>( private val project: Project, private val providerId: Key<T> ) : ArtifactListener { override fun artifactRemoved(artifact: Artifact) { val runManager = RunManagerEx.getInstanceEx(project) for (configuration in runManager.allConfigurationsList) { val tasks = runManager.getBeforeRunTasks(configuration, providerId) for (task in tasks) { val artifactName = artifact.name for (pointer in task.artifactPointers.toList()) { if (pointer.artifactName == artifactName && ArtifactManager.getInstance(project).findArtifact(artifactName) == null) { task.removeArtifact(pointer) } } } } } }
apache-2.0
54f753575c66d3f8d086dbc927436d1a
39.689655
131
0.753348
4.700398
false
true
false
false
GunoH/intellij-community
platform/platform-util-netty/src/org/jetbrains/io/IdeaNettyLogger.kt
12
2427
// 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.io import com.intellij.openapi.diagnostic.Logger import io.netty.util.internal.logging.AbstractInternalLogger internal class IdeaNettyLogger : AbstractInternalLogger("netty") {//NON-NLS private fun getLogger() = Logger.getInstance("netty") override fun isInfoEnabled() = false override fun info(msg: String?) { } override fun info(format: String?, arg: Any?) { } override fun info(format: String?, argA: Any?, argB: Any?) { } override fun info(format: String?, vararg arguments: Any?) { } override fun info(msg: String?, t: Throwable?) { } override fun isWarnEnabled() = true override fun warn(msg: String?) { getLogger().warn(msg) } override fun warn(format: String?, arg: Any?) { getLogger().warn("$format $arg") } override fun warn(format: String?, vararg arguments: Any?) { getLogger().warn("$format $arguments") } override fun warn(format: String?, argA: Any?, argB: Any?) { getLogger().warn("$format $argA $argB") } override fun warn(msg: String?, t: Throwable?) { getLogger().warn(msg, t) } override fun isErrorEnabled() = true override fun error(msg: String?) { getLogger().error(msg) } override fun error(format: String?, arg: Any?) { getLogger().error("$format $arg") } override fun error(format: String?, argA: Any?, argB: Any?) { getLogger().error("$format $argA $argB") } override fun error(format: String?, vararg arguments: Any?) { getLogger().error("$format $arguments") } override fun error(msg: String?, t: Throwable?) { getLogger().error(msg, t) } override fun isDebugEnabled() = false override fun debug(msg: String?) { } override fun debug(format: String?, arg: Any?) { } override fun debug(format: String?, argA: Any?, argB: Any?) { } override fun debug(format: String?, vararg arguments: Any?) { } override fun debug(msg: String?, t: Throwable?) { } override fun isTraceEnabled() = false override fun trace(msg: String?) { } override fun trace(format: String?, arg: Any?) { } override fun trace(format: String?, argA: Any?, argB: Any?) { } override fun trace(format: String?, vararg arguments: Any?) { } override fun trace(msg: String?, t: Throwable?) { } }
apache-2.0
43bc8184cde4d85b09819aa0d921b2a0
22.346154
140
0.657602
3.751159
false
false
false
false
siosio/intellij-community
platform/platform-util-io/src/com/intellij/util/io/netty.kt
1
11437
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.io import com.google.common.net.InetAddresses import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Conditions import com.intellij.openapi.util.NlsSafe import com.intellij.util.Url import com.intellij.util.Urls import com.intellij.util.net.NetUtils import io.netty.bootstrap.Bootstrap import io.netty.bootstrap.BootstrapUtil import io.netty.bootstrap.ServerBootstrap import io.netty.buffer.ByteBuf import io.netty.channel.* import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.ServerSocketChannel import io.netty.channel.socket.nio.NioServerSocketChannel import io.netty.handler.codec.http.HttpHeaderNames import io.netty.handler.codec.http.HttpMethod import io.netty.handler.codec.http.HttpRequest import io.netty.handler.ssl.SslHandler import io.netty.resolver.ResolvedAddressTypes import io.netty.util.concurrent.GenericFutureListener import org.jetbrains.io.NettyUtil import java.io.IOException import java.net.InetAddress import java.net.InetSocketAddress import java.net.NetworkInterface import java.net.Socket import java.util.concurrent.TimeUnit import java.util.function.Consumer inline fun Bootstrap.handler(crossinline task: (Channel) -> Unit): Bootstrap { handler(object : ChannelInitializer<Channel>() { override fun initChannel(channel: Channel) { task(channel) } }) return this } fun serverBootstrap(group: EventLoopGroup): ServerBootstrap { val bootstrap = ServerBootstrap() .group(group) .channel(group.serverSocketChannelClass()) bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) return bootstrap } @Suppress("DEPRECATION") private fun EventLoopGroup.serverSocketChannelClass(): Class<out ServerSocketChannel> { return when (this) { is NioEventLoopGroup -> NioServerSocketChannel::class.java is io.netty.channel.oio.OioEventLoopGroup -> io.netty.channel.socket.oio.OioServerSocketChannel::class.java // SystemInfo.isMacOSSierra && this is KQueueEventLoopGroup -> KQueueServerSocketChannel::class.java else -> throw Exception("Unknown event loop group type: ${this.javaClass.name}") } } inline fun ChannelFuture.addChannelListener(crossinline listener: (future: ChannelFuture) -> Unit) { addListener(GenericFutureListener<ChannelFuture> { listener(it) }) } // if NIO, so, it is shared and we must not shutdown it fun EventLoop.shutdownIfOio() { @Suppress("DEPRECATION") (parent() as? io.netty.channel.oio.OioEventLoopGroup)?.shutdownGracefully(1L, 2L, TimeUnit.NANOSECONDS) } // Event loop will be shut downed only if OIO fun Channel.closeAndShutdownEventLoop() { val eventLoop = eventLoop() try { close().awaitUninterruptibly() } finally { eventLoop.shutdownIfOio() } } /** * Synchronously connects to remote address. */ @JvmOverloads fun Bootstrap.connectRetrying(remoteAddress: InetSocketAddress, maxAttemptCount: Int = NettyUtil.DEFAULT_CONNECT_ATTEMPT_COUNT, stopCondition: Condition<Void>? = null): ConnectToChannelResult { try { return doConnect(this, remoteAddress, maxAttemptCount, stopCondition ?: Conditions.alwaysFalse<Void>()) } catch (e: Throwable) { return ConnectToChannelResult(e) } } private fun doConnect(bootstrap: Bootstrap, remoteAddress: InetSocketAddress, maxAttemptCount: Int, stopCondition: Condition<Void>): ConnectToChannelResult { if (ApplicationManager.getApplication().isDispatchThread) { Logger.getInstance("com.intellij.util.io.netty").error("Synchronous connection to socket shouldn't be performed on EDT.") } var attemptCount = 0 @Suppress("DEPRECATION") if (bootstrap.config().group() !is io.netty.channel.oio.OioEventLoopGroup) { return connectNio(bootstrap, remoteAddress, maxAttemptCount, stopCondition, attemptCount) } bootstrap.validate() while (true) { try { @Suppress("DEPRECATION") val channel = io.netty.channel.socket.oio.OioSocketChannel(Socket(remoteAddress.address, remoteAddress.port)) BootstrapUtil.initAndRegister(channel, bootstrap).sync() return ConnectToChannelResult(channel) } catch (e: IOException) { when { stopCondition.value(null) -> return ConnectToChannelResult() maxAttemptCount == -1 -> { sleep(300)?.let { return ConnectToChannelResult(it) } attemptCount++ } ++attemptCount < maxAttemptCount -> { sleep(attemptCount * NettyUtil.MIN_START_TIME)?.let { return ConnectToChannelResult(it) } } else -> return ConnectToChannelResult(e) } } } } private fun connectNio(bootstrap: Bootstrap, remoteAddress: InetSocketAddress, maxAttemptCount: Int, stopCondition: Condition<Void>, _attemptCount: Int): ConnectToChannelResult { var attemptCount = _attemptCount Logger.getInstance("com.intellij.util.io.netty").debug("connectNio: ${Thread.currentThread()} #$attemptCount, max:#$maxAttemptCount to $remoteAddress") while (true) { Logger.getInstance("com.intellij.util.io.netty").debug("Connection attempt #$attemptCount to $remoteAddress") val future = bootstrap.connect(remoteAddress).awaitUninterruptibly() if (future.isSuccess) { if (!future.channel().isOpen) { Logger.getInstance("com.intellij.util.io.netty").debug("connectNio: !future.channel().isOpen") } return ConnectToChannelResult(future.channel()) } else if (stopCondition.value(null)) { return ConnectToChannelResult() } else if (maxAttemptCount == -1) { sleep(300)?.let { return ConnectToChannelResult(it) } attemptCount++ } else if (++attemptCount < maxAttemptCount) { sleep(attemptCount * NettyUtil.MIN_START_TIME)?.let { return ConnectToChannelResult(it) } } else { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") val cause = future.cause() if (cause == null) { return ConnectToChannelResult(IdeUtilIoBundle.message("error.message.cannot.connect.unknown.error")) } else { return ConnectToChannelResult(cause) } } } } private fun sleep(time: Int): String? { try { //noinspection BusyWait Thread.sleep(time.toLong()) } catch (ignored: InterruptedException) { return IdeUtilIoBundle.message("error.message.interrupted") } return null } val Channel.uriScheme: String @NlsSafe get() = if (pipeline().get(SslHandler::class.java) == null) "http" else "https" val HttpRequest.host: String? get() = headers().getAsString(HttpHeaderNames.HOST) fun getHostName(httpRequest: HttpRequest): String? { val hostAndPort = httpRequest.headers().getAsString(HttpHeaderNames.HOST)?.ifBlank { null } ?: return null val portIndex = hostAndPort.lastIndexOf(':') return if (portIndex > 0) hostAndPort.substring(0, portIndex).ifBlank { null } else hostAndPort } val HttpRequest.origin: String? get() = headers().getAsString(HttpHeaderNames.ORIGIN) val HttpRequest.referrer: String? get() = headers().getAsString(HttpHeaderNames.REFERER) val HttpRequest.userAgent: String? @NlsSafe get() = headers().getAsString(HttpHeaderNames.USER_AGENT) inline fun <T> ByteBuf.releaseIfError(task: () -> T): T { try { return task() } catch (e: Exception) { try { release() } finally { throw e } } } fun isLocalHost(host: String, onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false): Boolean { if (NetUtils.isLocalhost(host)) { return true } // if IP address, it is safe to use getByName (not affected by DNS rebinding) if (onlyAnyOrLoopback && !InetAddresses.isInetAddress(host)) { return false } fun InetAddress.isLocal() = isAnyLocalAddress || isLoopbackAddress || NetworkInterface.getByInetAddress(this) != null try { val address = InetAddress.getByName(host) if (!address.isLocal()) { return false } // be aware - on windows hosts file doesn't contain localhost // hosts can contain remote addresses, so, we check it if (hostsOnly && !InetAddresses.isInetAddress(host)) { return io.netty.resolver.HostsFileEntriesResolver.DEFAULT.address(host, ResolvedAddressTypes.IPV4_PREFERRED).let { it != null && it.isLocal() } } else { return true } } catch (ignored: IOException) { return false } } @JvmOverloads fun HttpRequest.isLocalOrigin(onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false): Boolean { return parseAndCheckIsLocalHost(origin, onlyAnyOrLoopback, hostsOnly) && parseAndCheckIsLocalHost(referrer, onlyAnyOrLoopback, hostsOnly) } @Suppress("SpellCheckingInspection") private fun isTrustedChromeExtension(@NlsSafe url: Url): Boolean { return url.scheme == "chrome-extension" && (url.authority == "hmhgeddbohgjknpmjagkdomcpobmllji" || url.authority == "offnedcbhjldheanlbojaefbfbllddna" || System.getProperty("idea.trusted.chrome.extension.id")?.equals(url.authority) ?: false ) } private val Url.host: String? get() = authority?.let { val portIndex = it.indexOf(':') if (portIndex > 0) it.substring(0, portIndex) else it } @JvmOverloads fun parseAndCheckIsLocalHost(@NlsSafe uri: String?, onlyAnyOrLoopback: Boolean = true, hostsOnly: Boolean = false): Boolean { if (uri == null || uri == "about:blank") { return true } try { val parsedUri = Urls.parse(uri, false) ?: return false val host = parsedUri.host return host != null && (isTrustedChromeExtension(parsedUri) || isLocalHost(host, onlyAnyOrLoopback, hostsOnly)) } catch (ignored: Exception) { } return false } fun HttpRequest.isRegularBrowser(): Boolean = userAgent?.startsWith("Mozilla/5.0") ?: false // forbid POST requests from browser without Origin fun HttpRequest.isWriteFromBrowserWithoutOrigin(): Boolean { val method = method() return origin.isNullOrEmpty() && isRegularBrowser() && (method == HttpMethod.POST || method == HttpMethod.PATCH || method == HttpMethod.PUT || method == HttpMethod.DELETE) } fun ByteBuf.readUtf8(): String = toString(Charsets.UTF_8) class ConnectToChannelResult { val channel: Channel? private val message: String? private val throwable: Throwable? constructor(channel: Channel? = null) : this(channel, null, null) constructor(message: String): this(null, message, null) constructor(error: Throwable) : this(null, null, error) private constructor(channel: Channel?, message: String?, throwable: Throwable?) { this.channel = channel this.message = message this.throwable = throwable } fun handleError(consumer: Consumer<String>) : ConnectToChannelResult { if (message != null) { consumer.accept(message) } return this } fun handleThrowable(consumer: Consumer<Throwable>) : ConnectToChannelResult { if (throwable != null) { consumer.accept(throwable) } return this } }
apache-2.0
1ea08ce2c0e4019221152c18e5217af3
32.542522
173
0.709015
4.462349
false
false
false
false
siosio/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/secondStep/ModuleDependenciesComponent.kt
1
6591
// 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.tools.projectWizard.wizard.ui.secondStep import com.intellij.openapi.actionSystem.ActionToolbarPosition import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.ui.ColoredListCellRenderer import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.ToolbarDecorator import com.intellij.ui.popup.PopupFactoryImpl import com.intellij.util.ui.JBUI import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.withAllSubModules import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.* import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.awt.Dimension import javax.swing.Icon import javax.swing.JComponent import javax.swing.JPanel import kotlin.reflect.KFunction0 class ModuleDependenciesComponent( context: Context ) : TitledComponent(context) { override val title: String = KotlinNewProjectWizardUIBundle.message("module.dependencies.module.dependencies") private val dependenciesList = ModuleDependenciesList(::possibleDependencies) override val alignment: TitleComponentAlignment get() = TitleComponentAlignment.AlignAgainstSpecificComponent(dependenciesList) override val additionalComponentPadding: Int = 1 override val maximumWidth: Int = 500 private val toolbarDecorator: ToolbarDecorator = ToolbarDecorator.createDecorator(dependenciesList).apply { setToolbarPosition(ActionToolbarPosition.BOTTOM) setAddAction { button -> AddModulesPopUp.create( possibleDependencies(), dependenciesList::addDependency ).show(button.preferredPopupPoint!!) } setAddActionName(KotlinNewProjectWizardUIBundle.message("module.dependencies.add.module.dependency")) setAddActionUpdater { e -> e.presentation.apply { isEnabled = possibleDependencies().isNotEmpty() } e.presentation.isEnabled } setRemoveAction { dependenciesList.removeSelected() } setRemoveActionName(KotlinNewProjectWizardUIBundle.message("module.dependencies.remove.module.dependency")) setMoveDownAction(null) setMoveUpAction(null) } var module: Module? = null set(value) { field = value dependenciesList.module = value } private fun possibleDependencies(): List<Module> = read { KotlinPlugin.modules.settingValue }.withAllSubModules().toMutableList().apply { module?.let(::remove) removeAll( module ?.dependencies ?.filterIsInstance<ModuleReference.ByModule>() ?.map(ModuleReference.ByModule::module) .orEmpty() ) }.filter { to -> ModuleDependencyType.isDependencyPossible(module!!, to) } override fun shouldBeShow(): Boolean = module?.let { it.dependencies.isEmpty() && possibleDependencies().isEmpty() } != true override val component: JPanel = toolbarDecorator.createPanelWithPopupHandler(dependenciesList).apply { preferredSize = Dimension(preferredSize.width, 200) addBorder(JBUI.Borders.empty(0, 3)) } } private class AddModulesPopUp( modules: List<Module>, private val onChosenCallBack: (Module) -> Unit ) : BaseListPopupStep<Module>(null, modules) { override fun getIconFor(value: Module?): Icon? = value?.icon override fun getTextFor(value: Module): String = value.fullTextHtml override fun onChosen(selectedValue: Module?, finalChoice: Boolean): PopupStep<*>? { if (selectedValue != null) { onChosenCallBack(selectedValue) } return PopupStep.FINAL_CHOICE } companion object { fun create(modules: List<Module>, onChosen: (Module) -> Unit) = PopupFactoryImpl.getInstance().createListPopup(AddModulesPopUp(modules, onChosen)) } } private class ModuleDependenciesList(getDependencies: () -> List<Module>) : AbstractSingleSelectableListWithIcon<Module>() { init { emptyText.apply { clear() appendText(KotlinNewProjectWizardUIBundle.message("module.settings.dependencies.empty")) appendSecondaryText( KotlinNewProjectWizardUIBundle.message("module.settings.dependencies.empty.suggest.add"), SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES ) { AddModulesPopUp.create( getDependencies(), ::addDependency ).showInCenterOf(this@ModuleDependenciesList) } val shortcutText = KeymapUtil.getFirstKeyboardShortcutText(CommonShortcuts.getNewForDialogs()) if (shortcutText.isNotEmpty()) { appendSecondaryText(" ($shortcutText)", SimpleTextAttributes.GRAYED_ATTRIBUTES, null) } } } override fun ColoredListCellRenderer<Module>.render(value: Module) { renderModule(value) } var module: Module? = null set(value) { field = value updateValues( value?.dependencies?.mapNotNull { it.safeAs<ModuleReference.ByModule>()?.module } ?: return ) updateUI() } fun addDependency(dependency: Module) { model.addElement(dependency) module?.let { it.dependencies += ModuleReference.ByModule(dependency) } } fun removeSelected() { val index = selectedIndex model.removeElementAt(selectedIndex) module?.dependencies?.removeAt(index) if (model.size() > 0) { selectedIndex = index.coerceAtMost(model.size - 1) } } } private fun ColoredListCellRenderer<Module>.renderModule(module: Module) { append(module.path.asString()) append(" ") module.greyText?.let { append(it, SimpleTextAttributes.GRAYED_ATTRIBUTES) } icon = module.icon }
apache-2.0
76db43ebeeeb9195eec56a67cf943c1b
38.238095
158
0.685935
5.133178
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinFunctionCallInstruction.kt
1
8895
// 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.inspections.dfa import com.intellij.codeInspection.dataFlow.* import com.intellij.codeInspection.dataFlow.interpreter.DataFlowInterpreter import com.intellij.codeInspection.dataFlow.java.JavaDfaHelpers import com.intellij.codeInspection.dataFlow.jvm.SpecialField import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState import com.intellij.codeInspection.dataFlow.lang.ir.ExpressionPushingInstruction import com.intellij.codeInspection.dataFlow.lang.ir.Instruction import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState import com.intellij.codeInspection.dataFlow.types.DfType import com.intellij.codeInspection.dataFlow.types.DfTypes import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue import com.intellij.codeInspection.dataFlow.value.DfaValue import com.intellij.codeInspection.dataFlow.value.DfaValueFactory import com.intellij.codeInspection.dataFlow.value.RelationType import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.KotlinExpressionAnchor import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.source.PsiSourceElement // TODO: support Java contracts // TODO: support Kotlin contracts class KotlinFunctionCallInstruction( private val call: KtExpression, private val argCount: Int, private val qualifierOnStack: Boolean = false, private val exceptionTransfer: DfaControlTransferValue? ) : ExpressionPushingInstruction(KotlinExpressionAnchor(call)) { override fun bindToFactory(factory: DfaValueFactory): Instruction = if (exceptionTransfer == null) this else KotlinFunctionCallInstruction((dfaAnchor as KotlinExpressionAnchor).expression, argCount, qualifierOnStack, exceptionTransfer.bindToFactory(factory)) override fun accept(interpreter: DataFlowInterpreter, stateBefore: DfaMemoryState): Array<DfaInstructionState> { val arguments = popArguments(stateBefore, interpreter) val factory = interpreter.factory val (resultValue, pure) = getMethodReturnValue(factory, stateBefore, arguments) if (!pure || JavaDfaHelpers.mayLeakFromType(resultValue.dfType)) { arguments.arguments.forEach { arg -> JavaDfaHelpers.dropLocality(arg, stateBefore) } val qualifier = arguments.qualifier if (qualifier != null) { JavaDfaHelpers.dropLocality(qualifier, stateBefore) } } if (!pure) { stateBefore.flushFields() } val result = mutableListOf<DfaInstructionState>() if (exceptionTransfer != null) { val exceptional = stateBefore.createCopy() result += exceptionTransfer.dispatch(exceptional, interpreter) } if (resultValue.dfType != DfType.BOTTOM) { pushResult(interpreter, stateBefore, resultValue) result += nextState(interpreter, stateBefore) } return result.toTypedArray() } data class MethodEffect(val dfaValue: DfaValue, val pure: Boolean) private fun getMethodReturnValue( factory: DfaValueFactory, stateBefore: DfaMemoryState, arguments: DfaCallArguments ): MethodEffect { val method = getPsiMethod() val pure = MutationSignature.fromMethod(method).isPure if (method != null && arguments.arguments.size == method.parameterList.parametersCount) { val handler = CustomMethodHandlers.find(method) if (handler != null) { val dfaValue = handler.getMethodResultValue(arguments, stateBefore, factory, method) if (dfaValue != null) { return MethodEffect(dfaValue, pure) } } } val descriptor = call.resolveToCall()?.resultingDescriptor if (descriptor != null) { val type = fromKnownDescriptor(descriptor, arguments, stateBefore) if (type != null) return MethodEffect(factory.fromDfType(type.meet(getExpressionDfType(call))), true) } return MethodEffect(factory.fromDfType(getExpressionDfType(call)), pure) } private fun fromKnownDescriptor(descriptor: CallableDescriptor, arguments: DfaCallArguments, state: DfaMemoryState): DfType? { val name = descriptor.name.asString() val containingPackage = (descriptor.containingDeclaration as? PackageFragmentDescriptor)?.fqName?.asString() ?: return null if (containingPackage == "kotlin.collections") { val args = arguments.arguments if (args.size > 1) return null val size = if (args.isEmpty()) DfTypes.intValue(0) else state.getDfType(SpecialField.ARRAY_LENGTH.createValue(args[0].factory, args[0])) return when (name) { "arrayOf", "booleanArrayOf", "byteArrayOf", "shortArrayOf", "charArrayOf", "floatArrayOf", "intArrayOf", "doubleArrayOf", "longArrayOf" -> SpecialField.ARRAY_LENGTH.asDfType(size) "emptyList", "emptySet", "emptyMap" -> SpecialField.COLLECTION_SIZE.asDfType(DfTypes.intValue(0)) .meet(Mutability.UNMODIFIABLE.asDfType()) "listOf" -> SpecialField.COLLECTION_SIZE.asDfType(size) .meet(Mutability.UNMODIFIABLE.asDfType()) "listOfNotNull", "setOfNotNull", "mapOfNotNull" -> SpecialField.COLLECTION_SIZE.asDfType( size.fromRelation(RelationType.LE).meet(DfTypes.intValue(0).fromRelation(RelationType.GE)) ) .meet(Mutability.UNMODIFIABLE.asDfType()) "setOf", "mapOf" -> SpecialField.COLLECTION_SIZE.asDfType(size.toSetSize()) .meet(Mutability.UNMODIFIABLE.asDfType()) "mutableListOf", "arrayListOf" -> SpecialField.COLLECTION_SIZE.asDfType(size) .meet(DfTypes.LOCAL_OBJECT) "mutableSetOf", "linkedSetOf", "hashSetOf", "hashMapOf", "linkedMapOf" -> SpecialField.COLLECTION_SIZE.asDfType(size.toSetSize()).meet(DfTypes.LOCAL_OBJECT) else -> null } } return null } private fun DfType.toSetSize(): DfType { val minValue = if (DfTypes.intValue(0).isSuperType(this)) 0 else 1 return fromRelation(RelationType.LE).meet(DfTypes.intValue(minValue).fromRelation(RelationType.GE)) } private fun popArguments(stateBefore: DfaMemoryState, interpreter: DataFlowInterpreter): DfaCallArguments { val args = mutableListOf<DfaValue>() repeat(argCount) { args += stateBefore.pop() } val qualifier: DfaValue = if (qualifierOnStack) stateBefore.pop() else interpreter.factory.unknown return DfaCallArguments(qualifier, args.toTypedArray(), MutationSignature.unknown()) } private fun getPsiMethod(): PsiMethod? { return when (val source = (call.resolveToCall()?.resultingDescriptor?.source as? PsiSourceElement)?.psi) { is KtNamedFunction -> source.toLightMethods().singleOrNull() is PsiMethod -> source else -> null } } private fun getExpressionDfType(expr: KtExpression): DfType { val constructedClassName = (expr.resolveToCall()?.resultingDescriptor as? ConstructorDescriptor)?.constructedClass?.fqNameOrNull() if (constructedClassName != null) { // Set exact class type for constructor val psiClass = JavaPsiFacade.getInstance(expr.project).findClass(constructedClassName.asString(), expr.resolveScope) if (psiClass != null) { return TypeConstraints.exactClass(psiClass).asDfType().meet(DfTypes.NOT_NULL_OBJECT) } } return expr.getKotlinType().toDfType(expr) } override fun getSuccessorIndexes(): IntArray { return if (exceptionTransfer == null) intArrayOf(index + 1) else exceptionTransfer.possibleTargetIndices + (index + 1) } override fun toString(): String { return "CALL " + call.text } }
apache-2.0
7ec70569a4ca9e3fe5a2a8811b1970d5
50.126437
158
0.683867
5.097421
false
false
false
false
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/test/org/jetbrains/uast/test/common/kotlin/IndentedPrintingVisitor.kt
4
1320
// 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.uast.test.common.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import org.jetbrains.uast.UFile import kotlin.reflect.KClass abstract class IndentedPrintingVisitor(val shouldIndent: (PsiElement) -> Boolean) : PsiElementVisitor() { constructor(vararg kClasses: KClass<*>) : this({ psi -> kClasses.any { it.isInstance(psi) } }) private val builder = StringBuilder() var level = 0 private set override fun visitElement(element: PsiElement) { val charSequence = render(element) if (charSequence != null) { builder.append(" ".repeat(level)) builder.append(charSequence) builder.appendLine() } val shouldIndent = shouldIndent(element) if (shouldIndent) level++ element.acceptChildren(this) if (shouldIndent) level-- } protected abstract fun render(element: PsiElement): CharSequence? val result: String get() = builder.toString() } fun IndentedPrintingVisitor.visitUFileAndGetResult(uFile: UFile): String { uFile.sourcePsi.accept(this) return result }
apache-2.0
4eaa4edd41b812020f05676f24890cc9
32
158
0.693939
4.489796
false
false
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/lang/AbstractLangSupport.kt
5
4009
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package training.lang import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.vfs.VirtualFile import training.learn.exceptons.NoSdkException import training.project.FileUtils import training.project.ProjectUtils import training.project.ReadMeCreator import training.util.OnboardingFeedbackData import java.io.File import java.io.FileFilter import java.io.PrintWriter import java.nio.charset.StandardCharsets import java.nio.file.Path abstract class AbstractLangSupport : LangSupport { override val contentRootDirectoryName: String get() = "LearnProject" override fun getProjectFilePath(projectName: String): String { return ProjectUtil.getBaseDir() + File.separator + projectName } override var onboardingFeedbackData: OnboardingFeedbackData? = null override fun installAndOpenLearningProject(contentRoot: Path, projectToClose: Project?, postInitCallback: (learnProject: Project) -> Unit) { ProjectUtils.simpleInstallAndOpenLearningProject(contentRoot, this, OpenProjectTask { this.projectToClose = projectToClose }, postInitCallback) } override fun openOrImportLearningProject(projectRootDirectory: VirtualFile, openProjectTask: OpenProjectTask): Project { val nioPath = projectRootDirectory.toNioPath() return ProjectUtil.openOrImport(nioPath, openProjectTask) ?: error("Cannot create project for ${primaryLanguage} at $nioPath") } override fun copyLearningProjectFiles(projectDirectory: File, destinationFilter: FileFilter?): Boolean { val inputUrl = ProjectUtils.learningProjectUrl(this) return FileUtils.copyResourcesRecursively(inputUrl, projectDirectory, destinationFilter).also { if (it) copyGeneratedFiles(projectDirectory, destinationFilter) } } private fun copyGeneratedFiles(projectDirectory: File, destinationFilter: FileFilter?) { val generator = readMeCreator if (generator != null) { val readme = File(projectDirectory, "README.md") if (destinationFilter == null || destinationFilter.accept(readme)) { PrintWriter(readme, StandardCharsets.UTF_8).use { it.print(generator.createReadmeMdText()) } } } } open val readMeCreator: ReadMeCreator? = null override fun getSdkForProject(project: Project, selectedSdk: Sdk?): Sdk? { try { // Use no SDK if it's a valid for this language checkSdk(null, project) return null } catch (e: Throwable) { } return ApplicationManager.getApplication().runReadAction(ThrowableComputable<Sdk, NoSdkException> { val sdkOrNull = ProjectJdkTable.getInstance().allJdks.find { try { checkSdk(it, project) true } catch (e: Throwable) { false } } sdkOrNull ?: throw NoSdkException() }) } override fun applyProjectSdk(sdk: Sdk, project: Project) { CommandProcessor.getInstance().executeCommand(project, { ApplicationManager.getApplication().runWriteAction { val rootManager = ProjectRootManagerEx.getInstanceEx(project) rootManager.projectSdk = sdk } }, null, null) } override fun cleanupBeforeLessons(project: Project) { ProjectUtils.restoreProject(this, project) } override fun toString(): String = primaryLanguage }
apache-2.0
5ef23162345c2a600f7d75c261b7ec4e
36.476636
130
0.717885
4.998753
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/gradle/commonizerImportAndCheckHighlighting/withPosix/p1/src/linuxX64Main/kotlin/LinuxX64Main.kt
16
789
@file:Suppress("unused") import kotlinx.cinterop.pointed import platform.posix.stat import withPosix.getMyStructPointer import withPosix.getStructFromPosix import withPosix.getStructPointerFromPosix object LinuxX64Main { val structFromPosix = getStructFromPosix() val structPointerFromPosix = getStructPointerFromPosix() object MyStruct { val struct = getMyStructPointer()?.pointed ?: error("Missing my struct") val posixProperty: stat = struct.posixProperty val longProperty: Long = struct.longProperty val doubleProperty: Double = struct.doubleProperty val int32tProperty: Int = struct.int32tProperty val int64TProperty: Long = struct.int64tProperty val linuxOnlyProperty: Boolean = struct.linuxOnlyProperty } }
apache-2.0
6afa91328bbc74f3d262c3d544f0037d
34.863636
80
0.756654
4.13089
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ArrayInDataClassInspection.kt
1
4089
// 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.inspections import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateEqualsAndHashcodeAction import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.classVisitor import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.util.OperatorNameConventions class ArrayInDataClassInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return classVisitor { klass -> if (!klass.isData()) return@classVisitor val constructor = klass.primaryConstructor ?: return@classVisitor if (hasOverriddenEqualsAndHashCode(klass)) return@classVisitor val context = constructor.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) for (parameter in constructor.valueParameters) { if (!parameter.hasValOrVar()) continue val type = context.get(BindingContext.TYPE, parameter.typeReference) ?: continue if (KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type)) { holder.registerProblem( parameter, KotlinBundle.message("array.property.in.data.class.it.s.recommended.to.override.equals.hashcode"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, GenerateEqualsAndHashcodeFix() ) } } } } private fun hasOverriddenEqualsAndHashCode(klass: KtClass): Boolean { var overriddenEquals = false var overriddenHashCode = false for (declaration in klass.declarations) { if (declaration !is KtFunction) continue if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) continue if (declaration.nameAsName == OperatorNameConventions.EQUALS && declaration.valueParameters.size == 1) { val type = (declaration.resolveToDescriptorIfAny() as? FunctionDescriptor)?.valueParameters?.singleOrNull()?.type if (type != null && KotlinBuiltIns.isNullableAny(type)) { overriddenEquals = true } } if (declaration.name == "hashCode" && declaration.valueParameters.size == 0) { overriddenHashCode = true } } return overriddenEquals && overriddenHashCode } class GenerateEqualsAndHashcodeFix : LocalQuickFix { override fun getName() = KotlinBundle.message("generate.equals.and.hashcode.fix.text") override fun getFamilyName() = name override fun startInWriteAction() = false override fun applyFix(project: Project, descriptor: ProblemDescriptor) { if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.psiElement)) return descriptor.psiElement.getNonStrictParentOfType<KtClass>()?.run { KotlinGenerateEqualsAndHashcodeAction().doInvoke(project, descriptor.psiElement.findExistingEditor(), this) } } } }
apache-2.0
4357411e1e7674357e6da97dbe631f9f
50.1125
158
0.708242
5.4375
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/WaitActionType.kt
1
805
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO import kotlin.time.Duration.Companion.milliseconds class WaitActionType : BaseActionType() { override val type = TYPE override fun fromDTO(actionDTO: ActionDTO) = WaitAction( duration = (actionDTO.getInt(0)?.takeIf { it > 0 } ?: 0).milliseconds, ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, functionNameAliases = setOf(FUNCTION_NAME_ALIAS), parameters = 1, ) companion object { private const val TYPE = "wait" private const val FUNCTION_NAME = "wait" private const val FUNCTION_NAME_ALIAS = "sleep" } }
mit
bfec89e1426593514cbc3a0cf0d3022c
29.961538
78
0.696894
4.107143
false
false
false
false
emilybache/Parrot-Refactoring-Kata
Kotlin/src/test/kotlin/parrot/ParrotTest.kt
1
1385
package parrot import org.junit.Test import org.junit.Assert.assertEquals class ParrotTest { @Test fun getSpeedOfEuropeanParrot() { val parrot = Parrot(ParrotTypeEnum.EUROPEAN, 0, 0.0, false) assertEquals(12.0, parrot.speed, 0.0) } @Test fun getSpeedOfAfricanParrot_With_One_Coconut() { val parrot = Parrot(ParrotTypeEnum.AFRICAN, 1, 0.0, false) assertEquals(3.0, parrot.speed, 0.0) } @Test fun getSpeedOfAfricanParrot_With_Two_Coconuts() { val parrot = Parrot(ParrotTypeEnum.AFRICAN, 2, 0.0, false) assertEquals(0.0, parrot.speed, 0.0) } @Test fun getSpeedOfAfricanParrot_With_No_Coconuts() { val parrot = Parrot(ParrotTypeEnum.AFRICAN, 0, 0.0, false) assertEquals(12.0, parrot.speed, 0.0) } @Test fun getSpeedNorwegianBlueParrot_nailed() { val parrot = Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 1.5, true) assertEquals(0.0, parrot.speed, 0.0) } @Test fun getSpeedNorwegianBlueParrot_not_nailed() { val parrot = Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 1.5, false) assertEquals(18.0, parrot.speed, 0.0) } @Test fun getSpeedNorwegianBlueParrot_not_nailed_high_voltage() { val parrot = Parrot(ParrotTypeEnum.NORWEGIAN_BLUE, 0, 4.0, false) assertEquals(24.0, parrot.speed, 0.0) } }
mit
aa3eaf8795feb84c463146cc942d60a6
26.7
73
0.648375
2.940552
false
true
false
false
h31/LibraryMigration
src/main/kotlin/ru/spbstu/kspt/librarymigration/parser/Postprocessor.kt
1
2597
package ru.spbstu.kspt.librarymigration.parser import ru.spbstu.kspt.librarymigration.* import ru.spbstu.kspt.librarymigration.Action import ru.spbstu.kspt.librarymigration.State class Postprocessor { val machines = mutableMapOf<String, StateMachine>() val functions = mutableMapOf<Pair<String, String>, FunctionDecl>() // val entities get() = machines + types fun process(libraryDecl: LibraryDecl): Library { libraryDecl.types.map { StateMachine(name = it.semanticType) }.associateByTo(machines, StateMachine::name) libraryDecl.functions.associateByTo(functions, { Pair(it.entity, it.name) }) for (fsm in libraryDecl.automata) { val machine = machines[fsm.name]!! for (state in fsm.states) { State(name = state.name, machine = machine) } for (shift in fsm.shifts) { for (func in shift.functions) { encodeFunction(machine = machine, functionDecl = functions[fsm.name to func]!!, shift = shift) } } } for (conv in libraryDecl.converters) { val machine = machines[conv.entity]!! val args = Regex("<(w+)>").findAll(conv.expression) .map { it.groupValues[1] }.map { it to machines[it]!!.getConstructedState() }.toMap() TemplateEdge(machine = machine, src = machine.getInitState(), dst = machine.getConstructedState(), template = conv.expression, templateParams = args) } val types = libraryDecl.types.map { machines[it.semanticType]!! to it.codeType }.toMap() return ru.spbstu.kspt.librarymigration.Library(name = libraryDecl.name, stateMachines = machines.values.toList(), machineTypes = types) } fun encodeFunction(machine: StateMachine, functionDecl: FunctionDecl, shift: ShiftDecl): Edge { val dst = if (shift.to == "self") shift.from else shift.to val actionParams = functionDecl.actions.flatMap { it.args }.map { ActionParam(it) } return CallEdge(machine = machine, src = machine.stateByName(shift.from), dst = machine.stateByName(dst), methodName = functionDecl.name, param = functionDecl.args.map { EntityParam(machine = checkNotNull(machines[it.type])) } + actionParams, actions = functionDecl.actions.map { Action(name = it.name) }) } fun StateMachine.stateByName(name: String): State { return states.first { it.name == name } } }
mit
24ceabb1fb9870532ca59cb6466f396c
48.018868
120
0.623027
4.257377
false
false
false
false
marktony/ZhiHuDaily
app/src/main/java/com/marktony/zhihudaily/favorites/FavoritesPresenter.kt
1
2349
/* * Copyright 2016 lizhaotailang * * 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.marktony.zhihudaily.favorites import com.marktony.zhihudaily.data.source.Result import com.marktony.zhihudaily.data.source.repository.DoubanMomentNewsRepository import com.marktony.zhihudaily.data.source.repository.GuokrHandpickNewsRepository import com.marktony.zhihudaily.data.source.repository.ZhihuDailyNewsRepository import com.marktony.zhihudaily.util.launchSilent import kotlinx.coroutines.experimental.android.UI import kotlin.coroutines.experimental.CoroutineContext /** * Created by lizhaotailang on 2017/6/6. * * Listens the actions from UI ([FavoritesFragment]), * retrieves the data and update the UI as required. */ class FavoritesPresenter( private val mView: FavoritesContract.View, private val mZhihuRepository: ZhihuDailyNewsRepository, private val mDoubanRepository: DoubanMomentNewsRepository, private val mGuokrRepository: GuokrHandpickNewsRepository, private val uiContext: CoroutineContext = UI ) : FavoritesContract.Presenter { init { mView.mPresenter = this } override fun start() { } override fun loadFavorites() = launchSilent(uiContext) { val zhihuResult = mZhihuRepository.getFavorites() val doubanResult = mDoubanRepository.getFavorites() val guokrResult = mGuokrRepository.getFavorites() if (mView.isActive) { mView.showFavorites( (zhihuResult as? Result.Success)?.data?.toMutableList() ?: mutableListOf(), (doubanResult as? Result.Success)?.data?.toMutableList() ?: mutableListOf(), (guokrResult as? Result.Success)?.data?.toMutableList() ?: mutableListOf()) mView.setLoadingIndicator(false) } } }
apache-2.0
16798f648b1f5220a1ec91e2db57b1ec
36.285714
96
0.727118
4.633136
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/domain/NoteDiffer.kt
1
2698
package com.ivanovsky.passnotes.domain import com.ivanovsky.passnotes.data.entity.Note import com.ivanovsky.passnotes.data.entity.Property import com.ivanovsky.passnotes.domain.NoteDiffer.NoteField.* class NoteDiffer { enum class NoteField { UID, GROUP_UID, CREATED, MODIFIED, TITLE, PROPERTIES } fun isEqualsByFields(lhs: Note, rhs: Note, fields: List<NoteField>): Boolean { for (field in fields) { val isEquals = when (field) { UID -> isUidEquals(lhs, rhs) GROUP_UID -> isGroupUidEquals(lhs, rhs) CREATED -> isCreatedEquals(lhs, rhs) MODIFIED -> isModifiedEquals(lhs, rhs) TITLE -> isTitleEquals(lhs, rhs) PROPERTIES -> isPropertiesEquals(lhs, rhs) } if (!isEquals) { return false } } return true } private fun isUidEquals(lhs: Note, rhs: Note): Boolean { return lhs.uid == rhs.uid } private fun isGroupUidEquals(lhs: Note, rhs: Note): Boolean { return lhs.groupUid == rhs.groupUid } private fun isCreatedEquals(lhs: Note, rhs: Note): Boolean { return lhs.created == rhs.created } private fun isModifiedEquals(lhs: Note, rhs: Note): Boolean { return lhs.modified == rhs.modified } private fun isTitleEquals(lhs: Note, rhs: Note): Boolean { return lhs.title == rhs.title } private fun isPropertiesEquals(lhs: Note, rhs: Note): Boolean { val equalsProperties = mutableListOf<Property>() for (lhsProp in lhs.properties) { if (rhs.properties.contains(lhsProp)) { equalsProperties.add(lhsProp) } } val lhsProps = lhs.properties.filter { property -> !equalsProperties.contains(property) } val rhsProps = rhs.properties.filter { property -> !equalsProperties.contains(property) } val lhsPropMap = lhsProps.map { property -> property.name to property } .toMap() val rhsPropMap = rhsProps.map { property -> property.name to property } .toMap() if (lhsPropMap.size != rhsPropMap.size) { return false } for (lhsProp in lhsPropMap.values) { val rhsProp = rhsPropMap[lhsProp.name] if (lhsProp != rhsProp) { return false } } // TODO: add comparision for properties with type == null return true } companion object { val ALL_FIELDS_WITHOUT_MODIFIED = listOf(UID, GROUP_UID, CREATED, TITLE, PROPERTIES) } }
gpl-2.0
58bd58e56e9fc5bc47e42fe2bff2838f
27.702128
97
0.583766
4.337621
false
false
false
false
hazuki0x0/YuzuBrowser
module/bookmark/src/main/java/jp/hazuki/yuzubrowser/bookmark/view/AddBookmarkSiteDialog.kt
1
1816
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.bookmark.view import android.content.Context import android.view.View import jp.hazuki.yuzubrowser.bookmark.item.BookmarkSite import jp.hazuki.yuzubrowser.bookmark.repository.BookmarkManager import jp.hazuki.yuzubrowser.bookmark.util.BookmarkIdGenerator import jp.hazuki.yuzubrowser.ui.extensions.decodePunyCodeUrl class AddBookmarkSiteDialog : AddBookmarkDialog<BookmarkSite, String> { constructor(context: Context, manager: BookmarkManager, item: BookmarkSite) : super(context, manager, item, item.title, item.url) constructor(context: Context, title: String, url: String) : super(context, null, null, title, url) override fun initView(view: View, title: String?, url: String) { super.initView(view, title, url) titleEditText.setText(title ?: url) urlEditText.setText(url.decodePunyCodeUrl()) } override fun makeItem(item: BookmarkSite?, title: String, url: String): BookmarkSite? { return if (item == null) { BookmarkSite(title, url.trim { it <= ' ' }, BookmarkIdGenerator.getNewId()) } else { item.title = title item.url = url.trim { it <= ' ' } null } } }
apache-2.0
265eb2abab70a6b9878bab3b39afb30c
38.478261
133
0.710903
4.117914
false
false
false
false
AlmasB/Zephyria
src/main/kotlin/com/almasb/zeph/character/npc/NPCData.kt
1
1172
package com.almasb.zeph.character.npc import com.almasb.zeph.Description import com.almasb.zeph.DescriptionBuilder import com.almasb.zeph.character.DataDSL import com.almasb.zeph.emptyDescription /** * * @author Almas Baimagambetov ([email protected]) */ @DataDSL class NPCDataBuilder( var description: Description = emptyDescription, var dialogueName: String = "", var textureNameFull: String = "" ) { fun desc(setup: DescriptionBuilder.() -> Unit) { val builder = DescriptionBuilder() builder.setup() description = builder.build() } fun build(): NPCData { if (textureNameFull.isEmpty()) { textureNameFull = description.textureName.replace(".png", "_full.png") } return NPCData( description, dialogueName, textureNameFull ) } } @DataDSL fun npc(setup: NPCDataBuilder.() -> Unit): NPCData { val builder = NPCDataBuilder() builder.setup() return builder.build() } data class NPCData( val description: Description, val dialogueName: String, val textureNameFull: String )
gpl-2.0
b53fd23877e3bf60335c9d1d3f03cf07
22.46
82
0.635666
4.324723
false
false
false
false
wuan/bo-android
app/src/main/java/org/blitzortung/android/data/provider/LocalData.kt
1
1014
package org.blitzortung.android.data.provider import android.location.Location import org.blitzortung.android.data.LocalReference import org.blitzortung.android.data.Parameters import javax.inject.Inject import javax.inject.Singleton @Singleton class LocalData @Inject constructor() { fun updateParameters(parameters: Parameters, location: Location?): Parameters { return if (parameters.region == LOCAL_REGION) { if (location != null) { val x = calculateLocalRegion(location.longitude) val y = calculateLocalRegion(location.latitude) parameters.copy(localReference = LocalReference(x, y)) } else { parameters.copy(region = GLOBAL_REGION) } } else { parameters } } private fun calculateLocalRegion(value: Double): Int { return (value / 5).toInt() - if (value < 0) 1 else 0 } } internal const val LOCAL_REGION = -1 internal const val GLOBAL_REGION = 0
apache-2.0
892d374593849122e3a09f91a1ce94f0
31.709677
83
0.655819
4.486726
false
false
false
false
grote/Liberario
app/src/main/java/de/grobox/transportr/networks/PickTransportNetworkActivity.kt
1
4990
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.networks import android.content.Intent import android.os.Bundle import android.os.PersistableBundle import android.view.MenuItem import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.mikepenz.fastadapter.IItem import com.mikepenz.fastadapter.ISelectionListener import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter import com.mikepenz.fastadapter.expandable.ExpandableExtension import de.grobox.transportr.R import de.grobox.transportr.TransportrActivity import de.grobox.transportr.map.MapActivity class PickTransportNetworkActivity : TransportrActivity(), ISelectionListener<IItem<*, *>> { private lateinit var adapter: FastItemAdapter<IItem<*, *>> private lateinit var expandableExtension: ExpandableExtension<IItem<*, *>> private lateinit var list: RecyclerView private var firstStart: Boolean = false private var selectAllowed = false companion object { const val FORCE_NETWORK_SELECTION = "ForceNetworkSelection" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_pick_transport_network) setUpCustomToolbar(false) if (intent.getBooleanExtra(FORCE_NETWORK_SELECTION, false)) { firstStart = true supportActionBar?.setDisplayHomeAsUpEnabled(false) findViewById<View>(R.id.firstRunTextView).visibility = VISIBLE } else { firstStart = false supportActionBar?.setDisplayHomeAsUpEnabled(true) findViewById<View>(R.id.firstRunTextView).visibility = GONE } setResult(RESULT_CANCELED) adapter = FastItemAdapter() adapter.withSelectable(true) adapter.withSelectionListener(this) expandableExtension = ExpandableExtension() expandableExtension.withOnlyOneExpandedItem(false) adapter.addExtension(expandableExtension) list = findViewById(R.id.list) list.layoutManager = LinearLayoutManager(this) list.adapter = adapter for (c in getContinentItems(this)) { adapter.add(c) } if (savedInstanceState != null) adapter.withSavedInstanceState(savedInstanceState) selectItem() } override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) { val newState = adapter.saveInstanceState(outState) super.onSaveInstanceState(newState, outPersistentState) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == android.R.id.home) { onBackPressed() true } else { false } } override fun onSelectionChanged(item: IItem<*, *>?, selected: Boolean) { if (item == null || !selectAllowed || !selected) return selectAllowed = false val networkItem = item as TransportNetworkItem manager.setTransportNetwork(networkItem.transportNetwork) setResult(RESULT_OK) if (firstStart) { // MapActivity was closed val intent = Intent(this, MapActivity::class.java) startActivity(intent) } supportFinishAfterTransition() } private fun selectItem() { val network = manager.transportNetwork.value if (network == null) { selectAllowed = true return } val (continentPos, countryPos, networkPos) = getTransportNetworkPositions(this, network) if (continentPos != -1) { expandableExtension.expand(continentPos) if (countryPos != -1) { expandableExtension.expand(continentPos + countryPos + 1) if (networkPos != -1) { val selectPos = continentPos + countryPos + networkPos + 2 adapter.select(selectPos, false) list.scrollToPosition(selectPos) list.smoothScrollBy(0, -75) selectAllowed = true } } } } }
gpl-3.0
a39bb1270fd2d1984d206802d04321f5
34.899281
97
0.674349
4.935707
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/codegen/testutil/Util.kt
1
1591
/* * 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.codegen.testutil import com.google.android.libraries.pcc.chronicle.codegen.FieldCategory import com.google.android.libraries.pcc.chronicle.codegen.Type fun Type.withoutFields(vararg exclude: String) = copy(fields = this.fields.filter { it.name !in exclude }) fun Type.withForeignReference( foreignRef: String, schemaName: String, hard: Boolean, additionalName: String? = null ) = copy( fields = this.fields.flatMap { if (it.name == foreignRef) { if (additionalName != null) { listOf( it, it.copy( name = additionalName, sourceName = it.name, category = FieldCategory.ForeignReference(schemaName, hard) ), ) } else { listOf(it.copy(category = FieldCategory.ForeignReference(schemaName, hard))) } } else { listOf(it) } } )
apache-2.0
a2fb891fddf6b7b38a5ecca9e42c9fdb
30.196078
88
0.64802
4.220159
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/ActivatorComponent.kt
1
1495
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dsl.components import com.almasb.fxgl.entity.components.BooleanComponent /** * When added, the component is set to non-activated. * * @author Almas Baimagambetov ([email protected]) */ class ActivatorComponent @JvmOverloads constructor( var canBeDeactivated: Boolean = true, /** * This count is only honored when calling [activate] or [deactivate]. * Setting the value of [isActivated] directly ignores this count. */ var numTimesCanBeActivated: Int = Int.MAX_VALUE ): BooleanComponent(false) { private var numTimesActivated = 0 var isActivated: Boolean get() = value set(v) { value = v } /** * If not activated calls [activate], otherwise calls [deactivate]. */ fun press() { if (isActivated) { deactivate() } else { activate() } } fun activate() { if (!isActivated && numTimesActivated < numTimesCanBeActivated) { isActivated = true numTimesActivated++ } } /** * Deactivates this component so that it can be activated again. */ fun deactivate() { if (canBeDeactivated && isActivated) { isActivated = false } } override fun isComponentInjectionRequired(): Boolean = false }
mit
70bde067dadbff6ddbfb2049921c1a2e
23.52459
78
0.608696
4.462687
false
false
false
false
AlmasB/FXGL
fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/ViewComponent.kt
1
8193
/* * 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.View import com.almasb.fxgl.entity.component.Component import com.almasb.fxgl.entity.component.CoreComponent import javafx.beans.property.* import javafx.event.Event import javafx.event.EventHandler import javafx.event.EventType import javafx.scene.Group import javafx.scene.Node import javafx.scene.Parent import javafx.scene.input.MouseEvent import javafx.scene.transform.Rotate import javafx.scene.transform.Scale /** * Represents visual aspect of an entity. * * @author Almas Baimagambetov ([email protected]) */ @CoreComponent class ViewComponent : Component() { private val viewRoot = Group() // no scale or rotate is applied private val viewRootNoTransform = Group() private val devRoot = Group() private val updatableViews = arrayListOf<View>() /** * This node is managed by FXGL and is part of active scene graph, do NOT modify children. */ val parent: Parent = Group() @get:JvmName("zIndexProperty") val zIndexProperty = SimpleIntegerProperty(0) @get:JvmName("opacityProperty") val opacityProperty = SimpleDoubleProperty(1.0) var opacity: Double get() = opacityProperty.value set(value) { opacityProperty.value = value } var zIndex: Int get() = zIndexProperty.value set(value) { zIndexProperty.value = value } @get:JvmName("visibleProperty") val visibleProperty: BooleanProperty get() = parent.visibleProperty() /** * If made invisible, all events (e.g. mouse) go through the entity * and do not register on the entity. * In contrast, changing opacity to 0 still allows the entity to receive * events (e.g. mouse clicks). */ var isVisible: Boolean get() = parent.isVisible set(value) { parent.isVisible = value } /** * @return all view children (the order is transform applied first, then without transforms) */ val children: List<Node> get() = viewRoot.children + viewRootNoTransform.children init { viewRoot.opacityProperty().bind(opacityProperty) viewRootNoTransform.opacityProperty().bind(viewRoot.opacityProperty()) } override fun onAdded() { viewRoot.translateXProperty().bind(entity.xProperty().subtract(entity.transformComponent.positionOriginXProperty())) viewRoot.translateYProperty().bind(entity.yProperty().subtract(entity.transformComponent.positionOriginYProperty())) viewRoot.translateZProperty().bind(entity.zProperty().subtract(entity.transformComponent.positionOriginZProperty())) viewRootNoTransform.translateXProperty().bind(viewRoot.translateXProperty()) viewRootNoTransform.translateYProperty().bind(viewRoot.translateYProperty()) viewRootNoTransform.translateZProperty().bind(viewRoot.translateZProperty()) devRoot.translateXProperty().bind(viewRoot.translateXProperty()) devRoot.translateYProperty().bind(viewRoot.translateYProperty()) devRoot.translateZProperty().bind(viewRoot.translateZProperty()) val scale = Scale() scale.xProperty().bind(entity.transformComponent.scaleXProperty()) scale.yProperty().bind(entity.transformComponent.scaleYProperty()) scale.zProperty().bind(entity.transformComponent.scaleZProperty()) scale.pivotXProperty().bind(entity.transformComponent.scaleOriginXProperty()) scale.pivotYProperty().bind(entity.transformComponent.scaleOriginYProperty()) scale.pivotZProperty().bind(entity.transformComponent.scaleOriginZProperty()) val rz = Rotate() rz.axis = Rotate.Z_AXIS rz.angleProperty().bind(entity.transformComponent.angleProperty()) rz.pivotXProperty().bind(entity.transformComponent.rotationOriginXProperty()) rz.pivotYProperty().bind(entity.transformComponent.rotationOriginYProperty()) rz.pivotZProperty().bind(entity.transformComponent.rotationOriginZProperty()) val ry = Rotate(0.0, Rotate.Y_AXIS) ry.angleProperty().bind(entity.transformComponent.rotationYProperty()) ry.pivotXProperty().bind(entity.transformComponent.rotationOriginXProperty()) ry.pivotYProperty().bind(entity.transformComponent.rotationOriginYProperty()) ry.pivotZProperty().bind(entity.transformComponent.rotationOriginZProperty()) val rx = Rotate(0.0, Rotate.X_AXIS) rx.angleProperty().bind(entity.transformComponent.rotationXProperty()) rx.pivotXProperty().bind(entity.transformComponent.rotationOriginXProperty()) rx.pivotYProperty().bind(entity.transformComponent.rotationOriginYProperty()) rx.pivotZProperty().bind(entity.transformComponent.rotationOriginZProperty()) viewRoot.transforms.addAll(rz, ry, rx, scale) devRoot.transforms.addAll(rz, ry, rx, scale) } override fun onUpdate(tpf: Double) { updatableViews.forEach { it.onUpdate(tpf) } } override fun onRemoved() { (parent as Group).children.clear() clearChildren() } /** * Register event handler for event type that occurs on this view. */ fun <T : Event> addEventHandler(eventType: EventType<T>, eventHandler: EventHandler<in T>) { parent.addEventHandler(eventType, eventHandler) } fun addOnClickHandler(eventHandler: EventHandler<MouseEvent>) { addEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler) } /** * Remove event handler for event type that occurs on this view. */ fun <T : Event> removeEventHandler(eventType: EventType<T>, eventHandler: EventHandler<in T>) { parent.removeEventHandler(eventType, eventHandler) } fun removeOnClickHandler(eventHandler: EventHandler<MouseEvent>) { removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler) } /** * Add a child node to this view. */ @JvmOverloads fun addChild(node: Node, isTransformApplied: Boolean = true) { if (isTransformApplied) { addToGroup(viewRoot, node) } else { addToGroup(viewRootNoTransform, node) } if (node is View) updatableViews += node } /** * @return a child node at given [index] which is then cast into [type] */ fun <T : Node> getChild(index: Int, type: Class<T>): T { return type.cast(children[index]) } /** * Remove a child from this view. */ fun removeChild(node: Node) { removeFromGroup(viewRoot, node) removeFromGroup(viewRootNoTransform, node) if (node is View) updatableViews -= node } /** * Internal use only. */ fun addDevChild(node: Node) { addToGroup(devRoot, node, true) } /** * Internal use only. */ fun removeDevChild(node: Node) { removeFromGroup(devRoot, node) } private fun addToGroup(group: Group, child: Node, addLast: Boolean = false) { if (!(parent as Group).children.contains(group)) { if (addLast) { parent.children += group } else { parent.children.add(0, group) } } group.children += child } private fun removeFromGroup(group: Group, child: Node) { group.children -= child if (group.children.isEmpty()) { (parent as Group).children -= group } } /** * Remove all (with and without transforms) children. */ fun clearChildren() { viewRoot.children.forEach { if (it is View) { updatableViews -= it it.dispose() } } viewRootNoTransform.children.forEach { if (it is View) { updatableViews -= it it.dispose() } } viewRoot.children.clear() viewRootNoTransform.children.clear() } override fun isComponentInjectionRequired(): Boolean = false }
mit
b957e6c2d72aa627b7f2e0393a037d53
31.383399
124
0.665446
4.452717
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/settings/fragment/DownloadingPreferenceFragment.kt
1
6844
package com.arcao.geocaching4locus.settings.fragment import android.content.SharedPreferences import androidx.preference.CheckBoxPreference import androidx.preference.ListPreference import com.arcao.geocaching4locus.R import com.arcao.geocaching4locus.authentication.util.isPremium import com.arcao.geocaching4locus.base.constants.PrefConstants.DOWNLOADING_COUNT_OF_CACHES_STEP import com.arcao.geocaching4locus.base.constants.PrefConstants.DOWNLOADING_COUNT_OF_LOGS import com.arcao.geocaching4locus.base.constants.PrefConstants.DOWNLOADING_DISABLE_DNF_NM_NA_CACHES import com.arcao.geocaching4locus.base.constants.PrefConstants.DOWNLOADING_DISABLE_DNF_NM_NA_CACHES_LOGS_COUNT import com.arcao.geocaching4locus.base.constants.PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW import com.arcao.geocaching4locus.base.constants.PrefConstants.DOWNLOADING_SIMPLE_CACHE_DATA import com.arcao.geocaching4locus.base.fragment.AbstractPreferenceFragment import com.arcao.geocaching4locus.data.account.AccountManager import com.arcao.geocaching4locus.settings.widget.SliderPreference import org.koin.android.ext.android.get class DownloadingPreferenceFragment : AbstractPreferenceFragment() { override val preferenceResource: Int get() = R.xml.preference_category_downloading override fun preparePreference() { super.preparePreference() val premiumMember: Boolean = get<AccountManager>().isPremium val simpleCacheDataPreference = preference<CheckBoxPreference>(DOWNLOADING_SIMPLE_CACHE_DATA) val fullCacheDataOnShowPreference = preference<ListPreference>(DOWNLOADING_FULL_CACHE_DATE_ON_SHOW) val downloadingCountOfLogsPreference = preference<SliderPreference>(DOWNLOADING_COUNT_OF_LOGS) val countOfCachesStepPreference = preference<ListPreference>(DOWNLOADING_COUNT_OF_CACHES_STEP) val disableDnfNmNaCachesPreference = preference<CheckBoxPreference>(DOWNLOADING_DISABLE_DNF_NM_NA_CACHES) val disableDnfNmNaCachesLogsCountPreference = preference<SliderPreference>(DOWNLOADING_DISABLE_DNF_NM_NA_CACHES_LOGS_COUNT) simpleCacheDataPreference.apply { isEnabled = premiumMember setOnPreferenceChangeListener { _, newValue -> fullCacheDataOnShowPreference.isEnabled = newValue as Boolean true } } fullCacheDataOnShowPreference.apply { isEnabled = simpleCacheDataPreference.isChecked && premiumMember summary = preparePreferenceSummary(entry, R.string.pref_download_on_show_summary) } downloadingCountOfLogsPreference.apply { isEnabled = premiumMember summary = preparePreferenceSummary(progress.toString(), R.string.pref_logs_count_summary) } countOfCachesStepPreference.apply { summary = preparePreferenceSummary(entry, R.string.pref_step_geocaching_count_summary) } disableDnfNmNaCachesPreference.isEnabled = premiumMember disableDnfNmNaCachesLogsCountPreference.apply { summary = preparePreferenceSummary(progress.toString(), 0) } if (!premiumMember) { applyPremiumTitleSign(simpleCacheDataPreference) applyPremiumTitleSign(fullCacheDataOnShowPreference) applyPremiumTitleSign(downloadingCountOfLogsPreference) applyPremiumTitleSign(disableDnfNmNaCachesPreference) applyPremiumTitleSign(disableDnfNmNaCachesLogsCountPreference) disableDnfNmNaCachesPreference.isChecked = false } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { super.onSharedPreferenceChanged(sharedPreferences, key) when (key) { DOWNLOADING_COUNT_OF_LOGS -> { val logsCountPreference = preference<SliderPreference>(key) val disableLogsCountPreference = preference<SliderPreference>(DOWNLOADING_DISABLE_DNF_NM_NA_CACHES_LOGS_COUNT) val disablePreference = preference<CheckBoxPreference>(DOWNLOADING_DISABLE_DNF_NM_NA_CACHES) val logsCount = logsCountPreference.progress logsCountPreference.summary = preparePreferenceSummary(logsCount.toString(), R.string.pref_logs_count_summary) // additional checking if enough logs will be downloaded if (disablePreference.isChecked && disableLogsCountPreference.progress > logsCount) { if (logsCount > 1) { disableLogsCountPreference.progress = logsCount } else { disablePreference.isChecked = false disableLogsCountPreference.progress = 1 } } } DOWNLOADING_COUNT_OF_CACHES_STEP -> { preference<ListPreference>(key).apply { summary = preparePreferenceSummary(entry, R.string.pref_step_geocaching_count_summary) } } DOWNLOADING_FULL_CACHE_DATE_ON_SHOW -> { preference<ListPreference>(key).apply { summary = preparePreferenceSummary(entry, R.string.pref_download_on_show_summary) } } DOWNLOADING_DISABLE_DNF_NM_NA_CACHES_LOGS_COUNT -> { val disableLogsCountPreference = preference<SliderPreference>(key) val logsCountPreference = preference<SliderPreference>(DOWNLOADING_COUNT_OF_LOGS) val disablePreference = preference<CheckBoxPreference>(DOWNLOADING_DISABLE_DNF_NM_NA_CACHES) val logsCount = disableLogsCountPreference.progress disableLogsCountPreference.summary = preparePreferenceSummary(logsCount.toString(), 0) // additional checking if enough logs will be downloaded if (disablePreference.isChecked && logsCount > logsCountPreference.progress) { logsCountPreference.progress = logsCount } } DOWNLOADING_DISABLE_DNF_NM_NA_CACHES -> { val disablePreference = preference<CheckBoxPreference>(key) val disableLogsCountPreference = preference<SliderPreference>(DOWNLOADING_DISABLE_DNF_NM_NA_CACHES_LOGS_COUNT) val logsCountPreference = preference<SliderPreference>(DOWNLOADING_COUNT_OF_LOGS) // additional checking if enough logs will be downloaded if (disablePreference.isChecked && disableLogsCountPreference.progress > logsCountPreference.progress) { logsCountPreference.progress = disableLogsCountPreference.progress } } } } }
gpl-3.0
5b261841d90a168017f8854073997b7d
47.885714
120
0.690532
5.047198
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/action/actions.kt
1
993
package cn.yiiguxing.plugin.translate.action import cn.yiiguxing.plugin.translate.util.Settings import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor interface ImportantTranslationAction val AnActionEvent.editor: Editor? get() = CommonDataKeys.EDITOR.getData(dataContext) fun hasEditorSelection(e: AnActionEvent): Boolean = e.editor?.selectionModel?.hasSelection() ?: false fun mayTranslateWithNoSelection(e: AnActionEvent): Boolean { val isContextMenu = e.place == ActionPlaces.EDITOR_POPUP val hideWithNoSelection = isContextMenu && Settings.showActionsInContextMenuOnlyWithSelection return !hideWithNoSelection } fun showReplacementActionInContextMenu(e: AnActionEvent): Boolean { val isContextMenu = e.place == ActionPlaces.EDITOR_POPUP return !isContextMenu || Settings.showReplacementActionInContextMenu }
mit
71e514a1a69c512c397dec423f6d213a
35.814815
101
0.824773
4.640187
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/util/extensions.kt
1
5835
package com.ghstudios.android.util import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.database.Cursor import android.graphics.drawable.Drawable import android.os.Bundle import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import com.google.android.material.snackbar.Snackbar import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import android.view.View import com.ghstudios.android.GenericActionBarActivity import com.ghstudios.android.mhgendatabase.R // A collection of extension functions used by the app. // Only those that could reasonably belong to a separate library should be here. // Anything with stronger coupling on non-android objects should not be here /** * Adds a bundle to a fragment and then returns the fragment. * A lambda is used to set values to the bundle */ fun <T: androidx.fragment.app.Fragment> T.applyArguments(block: Bundle.() -> Unit): T { val bundle = Bundle() bundle.block() this.arguments = bundle return this } /** * Uses the cursor, automatically closing after executing the process. * Use this instead of use {} because Cursor's are not "Closeable" pre API 16 */ inline fun <J : Cursor, R> J.useCursor(process: (J) -> R): R { try { return process(this) } catch (e: Throwable) { throw e } finally { try { close() } catch (closeException: Throwable) {} } } /** * Extension function that iterates over a cursor, doing an operation for each step * The cursor is closed at the completion of this method. */ inline fun <T, J : Cursor> J.forEach(process: (J) -> T) { this.useCursor { while (moveToNext()) { process.invoke(this) } } } /** * Extension function that converts a cursor to a list of objects using a transformation function. * The cursor is closed at the completion of this method. */ fun <T, J : Cursor> J.toList(process: (J) -> T) : List<T> { return MHUtils.cursorToList(this, object: MHUtils.CursorProcessFunction<T, J> { override fun getValue(c: J): T = process(c) }) } /** * Extension function that pulls one entry from a cursor using a transform function, * or throws a NoSuchElementException if it doesn't exist. */ fun <T, J : Cursor> J.first(process: (J) -> T): T { return this.toList(process).first() } /** * Extension function that pulls one entry from a cursor using a transform function, * or null if the cursor is empty. * The cursor is closed at the completion of this method. */ fun <T, J : Cursor> J.firstOrNull(process: (J) -> T) : T? { // todo: optimize. Use cursor.moveToFirst() and check cursor.isAfterLast return this.toList(process).firstOrNull() } /** * Extension: Retrieves a drawable associated with a resource id * via ContextCompat using the called context. */ @Suppress("NOTHING_TO_INLINE") inline fun Context.getDrawableCompat(@DrawableRes id: Int): Drawable? { return ContextCompat.getDrawable(this, id) } /** * Extension: Retrieves a color associated with a resource id * via ContextCompat using the called context. */ @Suppress("NOTHING_TO_INLINE") inline fun Context.getColorCompat(@ColorRes id: Int): Int { return ContextCompat.getColor(this, id) } /** * Creates a block where "this" is the editor of the shared preferences. * The changes are commited asynchronously. */ inline fun SharedPreferences.edit(block: SharedPreferences.Editor.() -> Unit) { val editor = this.edit() block(editor) editor.apply() } /** * Extension function that sends the activity result. If target fragment is not null, * it will call onActivityResult on the fragment. Otherwise, it will call it on the activity. * * This was created to allow a uniform interface between fragments and activities. */ fun androidx.fragment.app.DialogFragment.sendDialogResult(resultCode: Int, intent: Intent) { if (this.targetFragment != null) { targetFragment?.onActivityResult(targetRequestCode, resultCode, intent) return } val activity = activity as? GenericActionBarActivity activity ?: throw TypeCastException("sendDialogResult() only works on fragments and GenericActionBarActivity") activity.sendActivityResult(targetRequestCode, resultCode, intent) } /** * Creates a livedata from a block of code that is run in another thread. * The other thread is run in a background thread, and not on the UI thread. */ fun <T> createLiveData(block: () -> T): LiveData<T> { val result = MutableLiveData<T>() loggedThread("createLiveData") { result.postValue(block()) } return result } /** * Helper function used to create a snackbar with an undo action. * The onComplete function is called when completed, onUndo is called if undone. */ fun View.createSnackbarWithUndo(message: String, onComplete: () -> Unit, onUndo: () -> Unit) { var wasUndone = false val snackbar = Snackbar.make(this, message, Snackbar.LENGTH_SHORT) snackbar.setAction(R.string.undo) { wasUndone = true onUndo() } snackbar.addCallback(object: Snackbar.Callback() { override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { if (!wasUndone) { onComplete() } } }) snackbar.show() } /** * Helper function used to create a snackbar with an undo action. */ fun View.createSnackbarWithUndo(message: String, operation: UndoableOperation) { this.createSnackbarWithUndo(message, onComplete = operation::complete, onUndo = operation::undo) }
mit
8d86bf2ff7e2f45afb99166be63db76a
31.243094
114
0.708826
4.150071
false
false
false
false
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/util/extensions/Context.kt
1
883
package com.ruuvi.station.util.extensions import android.content.Context import android.content.pm.PackageManager import timber.log.Timber fun Context.isFirstInstall(): Boolean { try { val firstInstall = packageManager.getPackageInfo(packageName,0).firstInstallTime val lastUpdate = packageManager.getPackageInfo(packageName,0).lastUpdateTime return firstInstall == lastUpdate } catch (e: PackageManager.NameNotFoundException) { Timber.e(e) return true } } fun Context.isUpdateInstall(): Boolean { try { val firstInstall = packageManager.getPackageInfo(packageName,0).firstInstallTime val lastUpdate = packageManager.getPackageInfo(packageName,0).lastUpdateTime return firstInstall != lastUpdate } catch (e: PackageManager.NameNotFoundException) { Timber.e(e) return false } }
mit
e18329c68d01d6e83a70ff7966f56288
31.740741
88
0.724802
4.851648
false
false
false
false
tehras/ActiveTouch
activetouch/src/main/java/com/github/tehras/activetouch/touchlisteners/ActiveTouchHoverHelper.kt
1
2348
package com.github.tehras.activetouch.touchlisteners import android.graphics.Rect import android.util.Log import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import java.util.* /** * Created by tehras on 7/23/16. * * This is helper that will send back the in the callback if a view is hovered upon */ class ActiveTouchHoverHelper(val callback: ActiveTouchBehavior.OnViewHoverOverListener) { var viewMap: HashMap<View, Rect> = HashMap() fun addView(view: View) { Log.d(TAG, "view with id ${view.id} getting added") viewMap.put(view, measureRect(view)) } fun measureRect(view: View): Rect { val rect = Rect() val location = IntArray(2) view.getDrawingRect(rect) view.getLocationOnScreen(location) rect.offset(location[0], location[1]) return rect } fun onTouch(ev: MotionEvent) { for (view in viewMap.keys) { val rect = viewMap[view] if (ev.action === MotionEvent.ACTION_MOVE) { if (rect!!.contains(ev.rawX.toInt(), ev.rawY.toInt())) { callback.onHover(view, true) } else { callback.onHover(view, false) } } } } private val TAG = "ActiveTouchHoverHelper" @Suppress("unused") fun attachView(v: View?) { Log.d(TAG, "attachView $v") if (v != null && v is ViewGroup) { v.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { Log.d(TAG, "onGlobalLayout") recursiveLoopChildren(v) v.viewTreeObserver.removeOnGlobalLayoutListener(this) } }) } } private fun recursiveLoopChildren(parent: ViewGroup) { for (i in parent.childCount - 1 downTo 0) { val child = parent.getChildAt(i) if (child is ViewGroup) { addView(child) recursiveLoopChildren(child) } else { if (child != null) { addView(child) } } } } fun clearViews() { viewMap.clear() } }
apache-2.0
74135ba3d90491a01eac60ab351a5134
27.289157
107
0.569421
4.397004
false
false
false
false
pixis/TraktTV
trakt-api/src/main/java/com/pixis/trakt_api/utils/Token/TokenDatabase.kt
2
1960
package com.pixis.trakt_api.utils.Token import android.content.Context import android.content.SharedPreferences import com.pixis.trakt_api.services_trakt.models.AccessToken class TokenDatabase(val context: Context) : TokenStorage { val prefs : SharedPreferences init { prefs = context.getSharedPreferences("TRAKT_ACCESS_TOKEN", Context.MODE_PRIVATE) } companion object { private val ACCESS_TOKEN_KEY: String = "ACCESS_TOKEN_KEY" private val TOKEN_TYPE_KEY: String = "TOKEN_TYPE_KEY" private val EXPIRES_IN_KEY: String = "EXPIRES_IN_KEY" private val REFRESH_TOKEN_KEY: String = "REFRESH_TOKEN_KEY" private val CREATED_AT: String = "CREATED_AT" private val SCOPE_KEY: String = "SCOPE_KEY" } override fun isAuthenticated(): Boolean { return prefs.getBoolean("AUTHENTICATED", false) } override fun getAccessToken(): String { return prefs.getString(ACCESS_TOKEN_KEY, "") } override fun getToken(): AccessToken { return AccessToken( prefs.getString(ACCESS_TOKEN_KEY, ""), prefs.getString(TOKEN_TYPE_KEY, ""), prefs.getString(EXPIRES_IN_KEY, "0").toInt(), prefs.getString(REFRESH_TOKEN_KEY, ""), prefs.getString(CREATED_AT, ""), prefs.getString(SCOPE_KEY, "") ) } override fun saveToken(accessToken: AccessToken) { val editor = prefs.edit() editor.putString(ACCESS_TOKEN_KEY, accessToken.access_token) editor.putString(TOKEN_TYPE_KEY, accessToken.token_type) editor.putString(EXPIRES_IN_KEY, accessToken.expires_in.toString()) editor.putString(REFRESH_TOKEN_KEY, accessToken.refresh_token) editor.putString(CREATED_AT, accessToken.created_at) editor.putString(SCOPE_KEY, accessToken.scope) editor.putBoolean("AUTHENTICATED", true) editor.apply() } }
apache-2.0
ae13009c57bf4ce889cf155df4ff85b7
34.654545
88
0.652551
4.26087
false
false
false
false
Shynixn/PetBlocks
petblocks-bukkit-plugin/petblocks-bukkit-nms-112R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_12_R1/NMSPetArmorstand.kt
1
18781
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_12_R1 import com.github.shynixn.petblocks.api.PetBlocksApi import com.github.shynixn.petblocks.api.bukkit.event.PetBlocksAIPreChangeEvent import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy import com.github.shynixn.petblocks.api.business.proxy.NMSPetProxy import com.github.shynixn.petblocks.api.business.proxy.PetProxy import com.github.shynixn.petblocks.api.business.service.AIService import com.github.shynixn.petblocks.api.business.service.ConfigurationService import com.github.shynixn.petblocks.api.business.service.LoggingService import com.github.shynixn.petblocks.api.persistence.entity.* import com.github.shynixn.petblocks.core.logic.business.extension.hasChanged import com.github.shynixn.petblocks.core.logic.business.extension.relativeFront import com.github.shynixn.petblocks.core.logic.persistence.entity.PositionEntity import net.minecraft.server.v1_12_R1.* import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.craftbukkit.v1_12_R1.CraftWorld import org.bukkit.entity.ArmorStand import org.bukkit.entity.LivingEntity import org.bukkit.entity.Player import org.bukkit.event.entity.CreatureSpawnEvent import org.bukkit.util.Vector import java.lang.reflect.Field /** * 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. */ class NMSPetArmorstand(owner: Player, val petMeta: PetMeta) : EntityArmorStand((owner.location.world as CraftWorld).handle), NMSPetProxy { private var internalProxy: PetProxy? = null private var jumpingField: Field = EntityLiving::class.java.getDeclaredField("bd") private var internalHitBox: EntityInsentient? = null private val aiService = PetBlocksApi.resolve(AIService::class.java) private val flyCanHitWalls = PetBlocksApi.resolve(ConfigurationService::class.java) .findValue<Boolean>("global-configuration.fly-wall-colision") private var flyHasTakenOffGround = false private var flyIsOnGround: Boolean = false private var flyHasHitFloor: Boolean = false private var flyWallCollisionVector: Vector? = null /** * Proxy handler. */ override val proxy: PetProxy get() = internalProxy!! /** * Initializes the nms design. */ init { jumpingField.isAccessible = true val location = owner.location val mcWorld = (location.world as CraftWorld).handle val position = PositionEntity() position.x = location.x position.y = location.y position.z = location.z position.yaw = location.yaw.toDouble() position.pitch = location.pitch.toDouble() position.worldName = location.world.name position.relativeFront(3.0) this.setPositionRotation(position.x, position.y, position.z, location.yaw, location.pitch) mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM) internalProxy = Class.forName("com.github.shynixn.petblocks.bukkit.logic.business.proxy.PetProxyImpl") .getDeclaredConstructor(PetMeta::class.java, ArmorStand::class.java, Player::class.java) .newInstance(petMeta, this.bukkitEntity, owner) as PetProxy petMeta.propertyTracker.onPropertyChanged(PetMeta::aiGoals, true) applyNBTTagForArmorstand() } /** * Spawns a new hitbox */ private fun spawnHitBox() { val shouldDeleteHitBox = shouldDeleteHitBox() if (shouldDeleteHitBox && internalHitBox != null) { (internalHitBox!!.bukkitEntity as EntityPetProxy).deleteFromWorld() internalHitBox = null proxy.changeHitBox(internalHitBox) } val player = proxy.getPlayer<Player>() this.applyNBTTagForArmorstand() val hasRidingAi = petMeta.aiGoals.count { a -> a is AIGroundRiding || a is AIFlyRiding } > 0 if (hasRidingAi) { val armorstand = proxy.getHeadArmorstand<ArmorStand>() if (!armorstand.passengers.contains(player)) { armorstand.velocity = Vector(0, 1, 0) armorstand.addPassenger(player) } return } else { for (passenger in player.passengers) { if (passenger == this.bukkitEntity) { player.removePassenger(passenger) } } } val aiWearing = this.petMeta.aiGoals.firstOrNull { a -> a is AIWearing } if (aiWearing != null) { this.applyNBTTagForArmorstand() val armorstand = proxy.getHeadArmorstand<ArmorStand>() if (!player.passengers.contains(armorstand)) { player.addPassenger(armorstand) } return } val flyingAi = petMeta.aiGoals.firstOrNull { a -> a is AIFlying } if (flyingAi != null) { if (internalHitBox == null) { internalHitBox = NMSPetBat(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetBat).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) return } val hoppingAi = petMeta.aiGoals.firstOrNull { a -> a is AIHopping } if (hoppingAi != null) { if (internalHitBox == null) { internalHitBox = NMSPetRabbit(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetRabbit).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) return } if (internalHitBox == null) { internalHitBox = NMSPetVillager(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetVillager).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) } /** * Disable setting slots. */ override fun setSlot(enumitemslot: EnumItemSlot?, itemstack: ItemStack?) { } /** * Sets the slot securely. */ fun setSecureSlot(enumitemslot: EnumItemSlot?, itemstack: ItemStack?) { super.setSlot(enumitemslot, itemstack) } /** * Entity tick. */ override fun doTick() { super.doTick() try { proxy.run() if (dead) { return } if (this.internalHitBox != null) { val location = internalHitBox!!.bukkitEntity.location val aiGoal = petMeta.aiGoals.lastOrNull { p -> p is AIMovement } ?: return var y = location.y + (aiGoal as AIMovement).movementYOffSet if (this.isSmall) { y += 0.6 } if (y > -100) { this.setPositionRotation(location.x, y, location.z, location.yaw, location.pitch) this.motX = this.internalHitBox!!.motX this.motY = this.internalHitBox!!.motY this.motZ = this.internalHitBox!!.motZ } } if (proxy.teleportTarget != null) { val location = proxy.teleportTarget!! as Location if (this.internalHitBox != null) { this.internalHitBox!!.setPositionRotation( location.x, location.y, location.z, location.yaw, location.pitch ) } this.setPositionRotation(location.x, location.y, location.z, location.yaw, location.pitch) proxy.teleportTarget = null } if (PetMeta::aiGoals.hasChanged(petMeta)) { val event = PetBlocksAIPreChangeEvent(proxy.getPlayer(), proxy) Bukkit.getPluginManager().callEvent(event) if (event.isCancelled) { return } spawnHitBox() proxy.aiGoals = null } } catch (e: Exception) { PetBlocksApi.resolve(LoggingService::class.java).error("Failed to execute tick.", e) } } /** * Overrides the moving of the pet design. */ override fun move(enummovetype: EnumMoveType?, d0: Double, d1: Double, d2: Double) { super.move(enummovetype, d0, d1, d2) if (passengers == null || this.passengers.firstOrNull { p -> p is EntityHuman } == null) { return } val groundAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding } val airAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding } var offSet = when { groundAi != null -> (groundAi as AIGroundRiding).ridingYOffSet airAi != null -> (airAi as AIFlyRiding).ridingYOffSet else -> 0.0 } if (this.isSmall) { offSet += 0.6 } val axisBoundingBox = this.boundingBox this.locX = (axisBoundingBox.a + axisBoundingBox.d) / 2.0 this.locY = axisBoundingBox.b + offSet this.locZ = (axisBoundingBox.c + axisBoundingBox.f) / 2.0 } /** * Gets the bukkit entity. */ override fun getBukkitEntity(): CraftPetArmorstand { if (this.bukkitEntity == null) { this.bukkitEntity = CraftPetArmorstand(this.world.server, this) } return this.bukkitEntity as CraftPetArmorstand } /** * Riding function. */ override fun a(sidemot: Float, f2: Float, formot: Float) { val human = this.passengers.firstOrNull { p -> p is EntityHuman } if (this.passengers == null || human == null) { flyHasTakenOffGround = false return } val aiFlyRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding } if (aiFlyRiding != null) { rideInAir(human as EntityHuman, aiFlyRiding as AIFlyRiding) return } val aiGroundRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding } if (aiGroundRiding != null) { rideOnGround(human as EntityHuman, aiGroundRiding as AIGroundRiding, f2) return } } /** * Handles the riding in air. */ private fun rideInAir(human: EntityHuman, ai: AIFlyRiding) { val sideMot: Float = human.be * 0.5f val forMot: Float = human.bg this.yaw = human.yaw this.lastYaw = this.yaw this.pitch = human.pitch * 0.5f this.setYawPitch(this.yaw, this.pitch) this.aP = this.yaw this.aN = this.aP val flyingVector = Vector() val flyingLocation = Location(this.world.world, this.locX, this.locY, this.locZ) if (sideMot < 0.0f) { flyingLocation.yaw = human.yaw - 90 flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5)) } else if (sideMot > 0.0f) { flyingLocation.yaw = human.yaw + 90 flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5)) } if (forMot < 0.0f) { flyingLocation.yaw = human.yaw flyingVector.add(flyingLocation.direction.normalize().multiply(0.5)) } else if (forMot > 0.0f) { flyingLocation.yaw = human.yaw flyingVector.add(flyingLocation.direction.normalize().multiply(0.5)) } if (!flyHasTakenOffGround) { flyHasTakenOffGround = true flyingVector.setY(1f) } if (this.isPassengerJumping()) { flyingVector.setY(0.5f) this.flyIsOnGround = true this.flyHasHitFloor = false } else if (this.flyIsOnGround) { flyingVector.setY(-0.2f) } if (this.flyHasHitFloor) { flyingVector.setY(0) flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed)) this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z) } else { flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed)) this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z) } val vec3d = Vec3D(this.locX, this.locY, this.locZ) val vec3d1 = Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ) val movingObjectPosition = this.world.rayTrace(vec3d, vec3d1) if (movingObjectPosition == null) { this.flyWallCollisionVector = flyingLocation.toVector() } else if (this.flyWallCollisionVector != null && flyCanHitWalls) { this.setPosition( this.flyWallCollisionVector!!.x, this.flyWallCollisionVector!!.y, this.flyWallCollisionVector!!.z ) } } /** * Handles the riding on ground. */ private fun rideOnGround(human: EntityHuman, ai: AIGroundRiding, f2: Float) { val sideMot: Float = human.be * 0.5f var forMot: Float = human.bg this.yaw = human.yaw this.lastYaw = this.yaw this.pitch = human.pitch * 0.5f this.setYawPitch(this.yaw, this.pitch) this.aP = this.yaw this.aN = this.aP if (forMot <= 0.0f) { forMot *= 0.25f } if (this.onGround && this.isPassengerJumping()) { this.motY = 0.5 } this.P = ai.climbingHeight.toFloat() this.aR = this.cy() * 0.1f if (!this.world.isClientSide) { this.k(0.35f) super.a(sideMot * ai.ridingSpeed.toFloat(), f2, forMot * ai.ridingSpeed.toFloat()) } this.aF = this.aG val d0 = this.locX - this.lastX val d1 = this.locZ - this.lastZ var f4 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0f if (f4 > 1.0f) { f4 = 1.0f } this.aG += (f4 - this.aG) * 0.4f this.aH += this.aG } /** * Applies the entity NBT to the hitbox. */ private fun applyNBTTagToHitBox(hitBox: EntityInsentient) { val compound = NBTTagCompound() hitBox.b(compound) applyAIEntityNbt( compound, this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.hitBoxNbt }.toList() ) hitBox.a(compound) // CustomNameVisible does not working via NBT Tags. hitBox.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1 } /** * Applies the entity NBT to the armorstand. */ private fun applyNBTTagForArmorstand() { val compound = NBTTagCompound() this.b(compound) applyAIEntityNbt( compound, this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.armorStandNbt }.toList() ) this.a(compound) // CustomNameVisible does not working via NBT Tags. this.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1 } /** * Applies the raw NbtData to the given target. */ private fun applyAIEntityNbt(target: NBTTagCompound, rawNbtDatas: List<String>) { val compoundMapField = NBTTagCompound::class.java.getDeclaredField("map") compoundMapField.isAccessible = true val rootCompoundMap = compoundMapField.get(target) as MutableMap<Any?, Any?> for (rawNbtData in rawNbtDatas) { if (rawNbtData.isEmpty()) { continue } val parsedCompound = try { MojangsonParser.parse(rawNbtData) } catch (e: Exception) { throw RuntimeException("NBT Tag '$rawNbtData' cannot be parsed.", e) } val parsedCompoundMap = compoundMapField.get(parsedCompound) as Map<*, *> for (key in parsedCompoundMap.keys) { rootCompoundMap[key] = parsedCompoundMap[key] } } } /** * Should the hitbox of the armorstand be deleted. */ private fun shouldDeleteHitBox(): Boolean { val hasEmptyHitBoxAi = petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding || a is AIFlyRiding || a is AIWearing } != null if (hasEmptyHitBoxAi) { return true } if (internalHitBox != null) { if (internalHitBox is NMSPetVillager && petMeta.aiGoals.firstOrNull { a -> a is AIWalking } == null) { return true } else if (internalHitBox is NMSPetRabbit && petMeta.aiGoals.firstOrNull { a -> a is AIHopping } == null) { return true } else if (internalHitBox is NMSPetBat && petMeta.aiGoals.firstOrNull { a -> a is AIFlying } == null) { return true } } return false } /** * Gets if a passenger of the pet is jumping. */ private fun isPassengerJumping(): Boolean { return passengers != null && !this.passengers.isEmpty() && jumpingField.getBoolean(this.passengers[0]) } }
apache-2.0
5e0c5133ac4bf5f718dcccf98a56489f
34.570076
119
0.612321
4.428437
false
false
false
false
ze-pequeno/okhttp
okhttp/src/jvmMain/kotlin/okhttp3/Request.kt
2
8217
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.net.URL import kotlin.reflect.KClass import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.internal.canonicalUrl import okhttp3.internal.commonAddHeader import okhttp3.internal.commonCacheControl import okhttp3.internal.commonDelete import okhttp3.internal.commonGet import okhttp3.internal.commonHead import okhttp3.internal.commonHeader import okhttp3.internal.commonHeaders import okhttp3.internal.commonMethod import okhttp3.internal.commonPatch import okhttp3.internal.commonPost import okhttp3.internal.commonPut import okhttp3.internal.commonRemoveHeader import okhttp3.internal.commonTag import okhttp3.internal.isSensitiveHeader actual class Request internal actual constructor(builder: Builder) { @get:JvmName("url") actual val url: HttpUrl = checkNotNull(builder.url) { "url == null" } @get:JvmName("method") actual val method: String = builder.method @get:JvmName("headers") actual val headers: Headers = builder.headers.build() @get:JvmName("body") actual val body: RequestBody? = builder.body internal actual val tags: Map<KClass<*>, Any> = builder.tags.toMap() internal actual var lazyCacheControl: CacheControl? = null actual val isHttps: Boolean get() = url.isHttps /** * Constructs a new request. * * Use [Builder] for more fluent construction, including helper methods for various HTTP methods. * * @param method defaults to "GET" if [body] is null, and "POST" otherwise. */ constructor( url: HttpUrl, headers: Headers = Headers.headersOf(), method: String = "\u0000", // Sentinel value chooses based on what the body is. body: RequestBody? = null, ) : this( Builder() .url(url) .headers(headers) .method( when { method != "\u0000" -> method body != null -> "POST" else -> "GET" }, body ) ) actual fun header(name: String): String? = commonHeader(name) actual fun headers(name: String): List<String> = commonHeaders(name) @JvmName("reifiedTag") actual inline fun <reified T : Any> tag(): T? = tag(T::class) actual fun <T : Any> tag(type: KClass<T>): T? = type.java.cast(tags[type]) /** * Returns the tag attached with `Object.class` as a key, or null if no tag is attached with * that key. * * Prior to OkHttp 3.11, this method never returned null if no tag was attached. Instead it * returned either this request, or the request upon which this request was derived with * [newBuilder]. * * @suppress this method breaks Dokka! https://github.com/Kotlin/dokka/issues/2473 */ fun tag(): Any? = tag<Any>() /** * Returns the tag attached with [type] as a key, or null if no tag is attached with that * key. */ fun <T> tag(type: Class<out T>): T? = tag(type.kotlin) actual fun newBuilder(): Builder = Builder(this) @get:JvmName("cacheControl") actual val cacheControl: CacheControl get() { var result = lazyCacheControl if (result == null) { result = CacheControl.parse(headers) lazyCacheControl = result } return result } @JvmName("-deprecated_url") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "url"), level = DeprecationLevel.ERROR) fun url(): HttpUrl = url @JvmName("-deprecated_method") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "method"), level = DeprecationLevel.ERROR) fun method(): String = method @JvmName("-deprecated_headers") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "headers"), level = DeprecationLevel.ERROR) fun headers(): Headers = headers @JvmName("-deprecated_body") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "body"), level = DeprecationLevel.ERROR) fun body(): RequestBody? = body @JvmName("-deprecated_cacheControl") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "cacheControl"), level = DeprecationLevel.ERROR) fun cacheControl(): CacheControl = cacheControl override fun toString(): String = buildString { append("Request{method=") append(method) append(", url=") append(url) if (headers.size != 0) { append(", headers=[") headers.forEachIndexed { index, (name, value) -> if (index > 0) { append(", ") } append(name) append(':') append(if (isSensitiveHeader(name)) "██" else value) } append(']') } if (tags.isNotEmpty()) { append(", tags=") append(tags) } append('}') } actual open class Builder { internal actual var url: HttpUrl? = null internal actual var method: String internal actual var headers: Headers.Builder internal actual var body: RequestBody? = null internal actual var tags = mapOf<KClass<*>, Any>() actual constructor() { this.method = "GET" this.headers = Headers.Builder() } internal actual constructor(request: Request) { this.url = request.url this.method = request.method this.body = request.body this.tags = when { request.tags.isEmpty() -> mapOf() else -> request.tags.toMutableMap() } this.headers = request.headers.newBuilder() } open fun url(url: HttpUrl): Builder = apply { this.url = url } actual open fun url(url: String): Builder { return url(canonicalUrl(url).toHttpUrl()) } /** * Sets the URL target of this request. * * @throws IllegalArgumentException if the scheme of [url] is not `http` or `https`. */ open fun url(url: URL) = url(url.toString().toHttpUrl()) actual open fun header(name: String, value: String) = commonHeader(name, value) actual open fun addHeader(name: String, value: String) = commonAddHeader(name, value) actual open fun removeHeader(name: String) = commonRemoveHeader(name) actual open fun headers(headers: Headers) = commonHeaders(headers) actual open fun cacheControl(cacheControl: CacheControl): Builder = commonCacheControl(cacheControl) actual open fun get(): Builder = commonGet() actual open fun head(): Builder = commonHead() actual open fun post(body: RequestBody): Builder = commonPost(body) @JvmOverloads actual open fun delete(body: RequestBody?): Builder = commonDelete(body) actual open fun put(body: RequestBody): Builder = commonPut(body) actual open fun patch(body: RequestBody): Builder = commonPatch(body) actual open fun method(method: String, body: RequestBody?): Builder = commonMethod(method, body) @JvmName("reifiedTag") actual inline fun <reified T : Any> tag(tag: T?): Builder = tag(T::class, tag) actual fun <T : Any> tag(type: KClass<T>, tag: T?): Builder = commonTag(type, tag) /** Attaches [tag] to the request using `Object.class` as a key. */ open fun tag(tag: Any?): Builder = commonTag(Any::class, tag) /** * Attaches [tag] to the request using [type] as a key. Tags can be read from a * request using [Request.tag]. Use null to remove any existing tag assigned for [type]. * * Use this API to attach timing, debugging, or other application data to a request so that * you may read it in interceptors, event listeners, or callbacks. */ open fun <T> tag(type: Class<in T>, tag: T?) = commonTag(type.kotlin, tag) actual open fun build() = Request(this) } }
apache-2.0
fcf2d896fe93084d435c446456c17c67
30.228137
104
0.666748
4.120923
false
false
false
false
konachan700/Mew
software/MeWSync/app/src/androidTest/java/com/mewhpm/mewsync/CryptoInstrumentedTest.kt
1
1183
package com.mewhpm.mewsync import androidx.test.runner.AndroidJUnit4 import com.mewhpm.mewsync.utils.CryptoUtils import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith import java.nio.charset.StandardCharsets @RunWith(AndroidJUnit4::class) class CryptoInstrumentedTest { @Test fun rsa4k_test() { val testString = "Test 12345 Test 12345 Test 12345 Test 12345 Test 12345 Test 12345 Test 12345 Test 12345" val encrypted = CryptoUtils.encryptRSA(testString.toByteArray()) val decrypted = CryptoUtils.decryptRSA(encrypted) assertEquals(testString, decrypted.toString(StandardCharsets.UTF_8)) } @Test fun sha256_test() { val originalHash = "9822b4afe3b5e3e15aa3b2145926f937dedb26c849414982b7d7b17a920bc2ac" val hash = CryptoUtils.sha256("83741623874782548235453284567354715635223457354234534") assertEquals(originalHash, hash) } @Test fun getUniqueSalt_test() { val salt1 = CryptoUtils.getUniqueSalt() val salt2 = CryptoUtils.getUniqueSalt() assertNotNull(salt1) assertTrue(salt1.isNotBlank()) assertEquals(salt1, salt2) } }
gpl-3.0
eb4fb1e18bda481885a9da2f57e22bd6
30.131579
114
0.727811
3.731861
false
true
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/logging/PerfEventStore.kt
1
1878
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.litho.kotlin.logging import com.facebook.litho.PerfEvent /** * The Litho logging system is designed to be stateless and have batches of data sent to the server * for processing, to avoid overhead on the device. This sample implementation is to illustrate the * data you can work with, not on how to actually implement logging on the client. */ object PerfEventStore { private val events: MutableMap<PerfEvent, EventData> = hashMapOf() fun obtain(eventId: Int, instanceKey: Int): PerfEvent { val event = SamplePerfEvent(eventId, instanceKey) events[event] = EventData(System.nanoTime()) return event } fun markerAnnotate(event: SamplePerfEvent, annotationKey: String, annotationValue: Any?) { // We can be pretty lose with lookup here as we control event creation. // Also, if we misuse the APIs in the framework, we don't want that to silently fail. events[event]!!.addAnnotation(annotationKey, annotationValue) } fun markerPoint(event: SamplePerfEvent, eventName: String) { events[event]!!.addMarker(System.nanoTime(), eventName) } fun release(event: PerfEvent): EventData { val data = events.remove(event)!! data.endTimeNs = System.nanoTime() return data } }
apache-2.0
72f91d25d3803b2641dd81c980a1757d
36.56
99
0.735889
4.191964
false
false
false
false
jksiezni/xpra-client
xpra-client-android/src/main/java/com/github/jksiezni/xpra/gl/GLDrawTarget.kt
1
2322
/* * Copyright (C) 2020 Jakub Ksiezniak * * 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 com.github.jksiezni.xpra.gl import android.opengl.GLES20 import com.android.grafika.gles.EglSurfaceBase import com.android.grafika.gles.GlUtil import com.android.grafika.gles.WindowSurface import timber.log.Timber /** * */ internal class GLDrawTarget( private var eglSurface: EglSurfaceBase, val texture: Int ) { private var textureWidth: Int = 0 private var textureHeight: Int = 0 fun validateTextureSize(width: Int, height: Int) { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture) if (width > textureWidth || height > textureHeight) { Timber.d("create texture ${width}x${height}") GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGB, width, height, 0, GLES20.GL_RGB, GLES20.GL_UNSIGNED_BYTE, null) GlUtil.checkGlError("glTexImage2D") textureWidth = width textureHeight = height } } fun makeCurrent() { eglSurface.makeCurrent() if (eglSurface is WindowSurface) { GLES20.glViewport(0, 0, eglSurface.width, eglSurface.height) } } fun swapBuffers() { eglSurface.swapBuffers() GlUtil.checkGlError("sswapBuffers") } fun setTarget(eglSurface: EglSurfaceBase) { if (this.eglSurface is WindowSurface) { this.eglSurface.releaseEglSurface() } this.eglSurface = eglSurface } fun isEglSurface(surface: EglSurfaceBase) : Boolean = eglSurface == surface }
gpl-3.0
65d3e59674d84771f6d2bf5e42586bfa
31.704225
135
0.670112
3.976027
false
false
false
false
Kotlin/dokka
plugins/base/src/main/kotlin/renderers/html/HtmlRenderer.kt
1
37478
package org.jetbrains.dokka.base.renderers.html import kotlinx.html.* import kotlinx.html.stream.createHTML import org.jetbrains.dokka.DokkaSourceSetID import org.jetbrains.dokka.Platform import org.jetbrains.dokka.base.DokkaBase import org.jetbrains.dokka.base.renderers.* import org.jetbrains.dokka.base.renderers.html.command.consumers.ImmediateResolutionTagConsumer import org.jetbrains.dokka.base.renderers.html.innerTemplating.DefaultTemplateModelFactory import org.jetbrains.dokka.base.renderers.html.innerTemplating.DefaultTemplateModelMerger import org.jetbrains.dokka.base.renderers.html.innerTemplating.DokkaTemplateTypes import org.jetbrains.dokka.base.renderers.html.innerTemplating.HtmlTemplater import org.jetbrains.dokka.base.resolvers.anchors.SymbolAnchorHint import org.jetbrains.dokka.base.resolvers.local.DokkaBaseLocationProvider import org.jetbrains.dokka.base.templating.* import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.* import org.jetbrains.dokka.model.properties.PropertyContainer import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.pages.HtmlContent import org.jetbrains.dokka.plugability.* import org.jetbrains.dokka.utilities.htmlEscape import org.jetbrains.kotlin.utils.addIfNotNull internal const val TEMPLATE_REPLACEMENT: String = "###" open class HtmlRenderer( context: DokkaContext ) : DefaultRenderer<FlowContent>(context) { private val sourceSetDependencyMap: Map<DokkaSourceSetID, List<DokkaSourceSetID>> = context.configuration.sourceSets.associate { sourceSet -> sourceSet.sourceSetID to context.configuration.sourceSets .map { it.sourceSetID } .filter { it in sourceSet.dependentSourceSets } } private val templateModelFactories = listOf(DefaultTemplateModelFactory(context)) // TODO: Make extension point private val templateModelMerger = DefaultTemplateModelMerger() private val templater = HtmlTemplater(context).apply { setupSharedModel(templateModelMerger.invoke(templateModelFactories) { buildSharedModel() }) } private var shouldRenderSourceSetBubbles: Boolean = false override val preprocessors = context.plugin<DokkaBase>().query { htmlPreprocessors } private val tabSortingStrategy = context.plugin<DokkaBase>().querySingle { tabSortingStrategy } private fun <R> TagConsumer<R>.prepareForTemplates() = if (context.configuration.delayTemplateSubstitution || this is ImmediateResolutionTagConsumer) this else ImmediateResolutionTagConsumer(this, context) private fun <T : ContentNode> sortTabs(strategy: TabSortingStrategy, tabs: Collection<T>): List<T> { val sorted = strategy.sort(tabs) if (sorted.size != tabs.size) context.logger.warn("Tab sorting strategy has changed number of tabs from ${tabs.size} to ${sorted.size}") return sorted } override fun FlowContent.wrapGroup( node: ContentGroup, pageContext: ContentPage, childrenCallback: FlowContent.() -> Unit ) { val additionalClasses = node.style.joinToString(" ") { it.toString().toLowerCase() } return when { node.hasStyle(ContentStyle.TabbedContent) -> div(additionalClasses) { val secondLevel = node.children.filterIsInstance<ContentComposite>().flatMap { it.children } .filterIsInstance<ContentHeader>().flatMap { it.children }.filterIsInstance<ContentText>() val firstLevel = node.children.filterIsInstance<ContentHeader>().flatMap { it.children } .filterIsInstance<ContentText>() val renderable = sortTabs(tabSortingStrategy, firstLevel.union(secondLevel)) div(classes = "tabs-section") { attributes["tabs-section"] = "tabs-section" renderable.forEachIndexed { index, node -> button(classes = "section-tab") { if (index == 0) attributes["data-active"] = "" attributes["data-togglable"] = node.text text(node.text) } } } div(classes = "tabs-section-body") { childrenCallback() } } node.hasStyle(ContentStyle.WithExtraAttributes) -> div { node.extra.extraHtmlAttributes().forEach { attributes[it.extraKey] = it.extraValue } childrenCallback() } node.dci.kind in setOf(ContentKind.Symbol) -> div("symbol $additionalClasses") { childrenCallback() } node.hasStyle(ContentStyle.KDocTag) -> span("kdoc-tag") { childrenCallback() } node.hasStyle(ContentStyle.Footnote) -> div("footnote") { childrenCallback() } node.hasStyle(TextStyle.BreakableAfter) -> { span { childrenCallback() } wbr { } } node.hasStyle(TextStyle.Breakable) -> { span("breakable-word") { childrenCallback() } } node.hasStyle(TextStyle.Span) -> span { childrenCallback() } node.dci.kind == ContentKind.Symbol -> div("symbol $additionalClasses") { childrenCallback() } node.dci.kind == SymbolContentKind.Parameters -> { span("parameters $additionalClasses") { childrenCallback() } } node.dci.kind == SymbolContentKind.Parameter -> { span("parameter $additionalClasses") { childrenCallback() } } node.hasStyle(TextStyle.InlineComment) -> div("inline-comment") { childrenCallback() } node.dci.kind == ContentKind.BriefComment -> div("brief $additionalClasses") { childrenCallback() } node.dci.kind == ContentKind.Cover -> div("cover $additionalClasses") { //TODO this can be removed childrenCallback() } node.dci.kind == ContentKind.Deprecation -> div("deprecation-content") { childrenCallback() } node.hasStyle(TextStyle.Paragraph) -> p(additionalClasses) { childrenCallback() } node.hasStyle(TextStyle.Block) -> div(additionalClasses) { childrenCallback() } node.hasStyle(TextStyle.Quotation) -> blockQuote(additionalClasses) { childrenCallback() } node.hasStyle(TextStyle.FloatingRight) -> span("clearfix") { span("floating-right") { childrenCallback() } } node.hasStyle(TextStyle.Strikethrough) -> strike { childrenCallback() } node.isAnchorable -> buildAnchor( node.anchor!!, node.anchorLabel!!, node.sourceSetsFilters ) { childrenCallback() } node.extra[InsertTemplateExtra] != null -> node.extra[InsertTemplateExtra]?.let { templateCommand(it.command) } ?: Unit node.hasStyle(ListStyle.DescriptionTerm) -> DT(emptyMap(), consumer).visit { [email protected]() } node.hasStyle(ListStyle.DescriptionDetails) -> DD(emptyMap(), consumer).visit { [email protected]() } else -> childrenCallback() } } private fun FlowContent.filterButtons(page: PageNode) { if (shouldRenderSourceSetBubbles && page is ContentPage) { div(classes = "filter-section") { id = "filter-section" page.content.withDescendants().flatMap { it.sourceSets }.distinct() .sortedBy { it.comparableKey }.forEach { button(classes = "platform-tag platform-selector") { attributes["data-active"] = "" attributes["data-filter"] = it.sourceSetIDs.merged.toString() when (it.platform.key) { "common" -> classes = classes + "common-like" "native" -> classes = classes + "native-like" "jvm" -> classes = classes + "jvm-like" "js" -> classes = classes + "js-like" } text(it.name) } } } } } private fun FlowContent.copyButton() = span(classes = "top-right-position") { span("copy-icon") copiedPopup("Content copied to clipboard", "popup-to-left") } private fun FlowContent.copiedPopup(notificationContent: String, additionalClasses: String = "") = div("copy-popup-wrapper $additionalClasses") { span("copy-popup-icon") span { text(notificationContent) } } override fun FlowContent.buildPlatformDependent( content: PlatformHintedContent, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) = buildPlatformDependent( content.sourceSets.filter { sourceSetRestriction == null || it in sourceSetRestriction }.associateWith { setOf(content.inner) }, pageContext, content.extra, content.style ) private fun FlowContent.buildPlatformDependent( nodes: Map<DisplaySourceSet, Collection<ContentNode>>, pageContext: ContentPage, extra: PropertyContainer<ContentNode> = PropertyContainer.empty(), styles: Set<Style> = emptySet(), shouldHaveTabs: Boolean = shouldRenderSourceSetBubbles ) { val contents = contentsForSourceSetDependent(nodes, pageContext) val isOnlyCommonContent = contents.singleOrNull()?.let { (sourceSet, _) -> sourceSet.platform == Platform.common && sourceSet.name.equals("common", ignoreCase = true) && sourceSet.sourceSetIDs.all.all { sourceSetDependencyMap[it]?.isEmpty() == true } } ?: false // little point in rendering a single "common" tab - it can be // assumed that code without any tabs is common by default val renderTabs = shouldHaveTabs && !isOnlyCommonContent val divStyles = "platform-hinted ${styles.joinToString()}" + if (renderTabs) " with-platform-tabs" else "" div(divStyles) { attributes["data-platform-hinted"] = "data-platform-hinted" extra.extraHtmlAttributes().forEach { attributes[it.extraKey] = it.extraValue } if (renderTabs) { div("platform-bookmarks-row") { attributes["data-toggle-list"] = "data-toggle-list" contents.forEachIndexed { index, pair -> button(classes = "platform-bookmark") { attributes["data-filterable-current"] = pair.first.sourceSetIDs.merged.toString() attributes["data-filterable-set"] = pair.first.sourceSetIDs.merged.toString() if (index == 0) attributes["data-active"] = "" attributes["data-toggle"] = pair.first.sourceSetIDs.merged.toString() text(pair.first.name) } } } } contents.forEach { consumer.onTagContentUnsafe { +it.second } } } } private fun contentsForSourceSetDependent( nodes: Map<DisplaySourceSet, Collection<ContentNode>>, pageContext: ContentPage, ): List<Pair<DisplaySourceSet, String>> { var counter = 0 return nodes.toList().map { (sourceSet, elements) -> val htmlContent = createHTML(prettyPrint = false).prepareForTemplates().div { elements.forEach { buildContentNode(it, pageContext, sourceSet.toSet()) } }.stripDiv() sourceSet to createHTML(prettyPrint = false).prepareForTemplates() .div(classes = "content sourceset-dependent-content") { if (counter++ == 0) attributes["data-active"] = "" attributes["data-togglable"] = sourceSet.sourceSetIDs.merged.toString() unsafe { +htmlContent } } }.sortedBy { it.first.comparableKey } } override fun FlowContent.buildDivergent(node: ContentDivergentGroup, pageContext: ContentPage) { if (node.implicitlySourceSetHinted) { val groupedInstancesBySourceSet = node.children.flatMap { instance -> instance.sourceSets.map { sourceSet -> instance to sourceSet } }.groupBy( Pair<ContentDivergentInstance, DisplaySourceSet>::second, Pair<ContentDivergentInstance, DisplaySourceSet>::first ) val nodes = groupedInstancesBySourceSet.mapValues { val distinct = groupDivergentInstancesWithSourceSet(it.value, it.key, pageContext, beforeTransformer = { instance, _, sourceSet -> createHTML(prettyPrint = false).prepareForTemplates().div { instance.before?.let { before -> buildContentNode(before, pageContext, sourceSet) } }.stripDiv() }, afterTransformer = { instance, _, sourceSet -> createHTML(prettyPrint = false).prepareForTemplates().div { instance.after?.let { after -> buildContentNode(after, pageContext, sourceSet) } }.stripDiv() }) val isPageWithOverloadedMembers = pageContext is MemberPage && pageContext.documentables().size > 1 val contentOfSourceSet = mutableListOf<ContentNode>() distinct.onEachIndexed{ index, (_, distinctInstances) -> contentOfSourceSet.addIfNotNull(distinctInstances.firstOrNull()?.before) contentOfSourceSet.addAll(distinctInstances.map { it.divergent }) contentOfSourceSet.addIfNotNull( distinctInstances.firstOrNull()?.after ?: if (index != distinct.size - 1) ContentBreakLine(it.key) else null ) // content kind main is important for declarations list to avoid double line breaks if (node.dci.kind == ContentKind.Main && index != distinct.size - 1) { if (isPageWithOverloadedMembers) { // add some spacing and distinction between function/property overloads. // not ideal, but there's no other place to modify overloads page atm contentOfSourceSet.add(ContentBreakLine(it.key, style = setOf(HorizontalBreakLineStyle))) } else { contentOfSourceSet.add(ContentBreakLine(it.key)) } } } contentOfSourceSet } buildPlatformDependent(nodes, pageContext) } else { node.children.forEach { buildContentNode(it.divergent, pageContext, it.sourceSets) } } } private fun groupDivergentInstancesWithSourceSet( instances: List<ContentDivergentInstance>, sourceSet: DisplaySourceSet, pageContext: ContentPage, beforeTransformer: (ContentDivergentInstance, ContentPage, DisplaySourceSet) -> String, afterTransformer: (ContentDivergentInstance, ContentPage, DisplaySourceSet) -> String ): Map<SerializedBeforeAndAfter, List<ContentDivergentInstance>> = instances.map { instance -> instance to Pair( beforeTransformer(instance, pageContext, sourceSet), afterTransformer(instance, pageContext, sourceSet) ) }.groupBy( Pair<ContentDivergentInstance, SerializedBeforeAndAfter>::second, Pair<ContentDivergentInstance, SerializedBeforeAndAfter>::first ) private fun ContentPage.documentables(): List<Documentable> { return (this as? WithDocumentables)?.documentables ?: emptyList() } override fun FlowContent.buildList( node: ContentList, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) = when { node.ordered -> { ol { buildListItems(node.children, pageContext, sourceSetRestriction) } } node.hasStyle(ListStyle.DescriptionList) -> { dl { node.children.forEach { it.build(this, pageContext, sourceSetRestriction) } } } else -> { ul { buildListItems(node.children, pageContext, sourceSetRestriction) } } } open fun OL.buildListItems( items: List<ContentNode>, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? = null ) { items.forEach { if (it is ContentList) buildList(it, pageContext) else li { it.build(this, pageContext, sourceSetRestriction) } } } open fun UL.buildListItems( items: List<ContentNode>, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? = null ) { items.forEach { if (it is ContentList) buildList(it, pageContext) else li { it.build(this, pageContext) } } } override fun FlowContent.buildResource( node: ContentEmbeddedResource, pageContext: ContentPage ) = // TODO: extension point there if (node.isImage()) { img(src = node.address, alt = node.altText) } else { println("Unrecognized resource type: $node") } private fun FlowContent.buildRow( node: ContentGroup, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) { node.children .filter { sourceSetRestriction == null || it.sourceSets.any { s -> s in sourceSetRestriction } } .takeIf { it.isNotEmpty() } ?.let { when (pageContext) { is MultimoduleRootPage -> buildRowForMultiModule(node, it, pageContext, sourceSetRestriction) is ModulePage -> buildRowForModule(node, it, pageContext, sourceSetRestriction) else -> buildRowForContent(node, it, pageContext, sourceSetRestriction) } } } private fun FlowContent.buildRowForMultiModule( contextNode: ContentGroup, toRender: List<ContentNode>, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) { buildAnchor(contextNode) div(classes = "table-row") { div("main-subrow " + contextNode.style.joinToString(separator = " ")) { buildRowHeaderLink(toRender, pageContext, sourceSetRestriction, contextNode.anchor, "w-100") div { buildRowBriefSectionForDocs(toRender, pageContext, sourceSetRestriction) } } } } private fun FlowContent.buildRowForModule( contextNode: ContentGroup, toRender: List<ContentNode>, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) { buildAnchor(contextNode) div(classes = "table-row") { addSourceSetFilteringAttributes(contextNode) div { div("main-subrow " + contextNode.style.joinToString(separator = " ")) { buildRowHeaderLink(toRender, pageContext, sourceSetRestriction, contextNode.anchor) div("pull-right") { if (ContentKind.shouldBePlatformTagged(contextNode.dci.kind)) { createPlatformTags(contextNode, cssClasses = "no-gutters") } } } div { buildRowBriefSectionForDocs(toRender, pageContext, sourceSetRestriction) } } } } private fun FlowContent.buildRowForContent( contextNode: ContentGroup, toRender: List<ContentNode>, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) { buildAnchor(contextNode) div(classes = "table-row") { addSourceSetFilteringAttributes(contextNode) div("main-subrow keyValue " + contextNode.style.joinToString(separator = " ")) { buildRowHeaderLink(toRender, pageContext, sourceSetRestriction, contextNode.anchor) div { toRender.filter { it !is ContentLink && !it.hasStyle(ContentStyle.RowTitle) } .takeIf { it.isNotEmpty() }?.let { div("title") { it.forEach { it.build(this, pageContext, sourceSetRestriction) } } } } } } } private fun FlowContent.buildRowHeaderLink( toRender: List<ContentNode>, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>?, anchorDestination: String?, classes: String = "" ) { toRender.filter { it is ContentLink || it.hasStyle(ContentStyle.RowTitle) }.takeIf { it.isNotEmpty() }?.let { div(classes) { it.filter { sourceSetRestriction == null || it.sourceSets.any { s -> s in sourceSetRestriction } } .forEach { span("inline-flex") { div { it.build(this, pageContext, sourceSetRestriction) } if (it is ContentLink && !anchorDestination.isNullOrBlank()) { buildAnchorCopyButton(anchorDestination) } } } } } } private fun FlowContent.addSourceSetFilteringAttributes( contextNode: ContentGroup, ) { attributes["data-filterable-current"] = contextNode.sourceSets.joinToString(" ") { it.sourceSetIDs.merged.toString() } attributes["data-filterable-set"] = contextNode.sourceSets.joinToString(" ") { it.sourceSetIDs.merged.toString() } } private fun FlowContent.buildRowBriefSectionForDocs( toRender: List<ContentNode>, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>?, ) { toRender.filter { it !is ContentLink }.takeIf { it.isNotEmpty() }?.let { it.forEach { span(classes = if (it.dci.kind == ContentKind.Comment) "brief-comment" else "") { it.build(this, pageContext, sourceSetRestriction) } } } } private fun FlowContent.createPlatformTagBubbles(sourceSets: List<DisplaySourceSet>, cssClasses: String = "") { if (shouldRenderSourceSetBubbles) { div("platform-tags $cssClasses") { sourceSets.sortedBy { it.name }.forEach { div("platform-tag") { when (it.platform.key) { "common" -> classes = classes + "common-like" "native" -> classes = classes + "native-like" "jvm" -> classes = classes + "jvm-like" "js" -> classes = classes + "js-like" } text(it.name) } } } } } private fun FlowContent.createPlatformTags( node: ContentNode, sourceSetRestriction: Set<DisplaySourceSet>? = null, cssClasses: String = "" ) { node.takeIf { sourceSetRestriction == null || it.sourceSets.any { s -> s in sourceSetRestriction } }?.let { createPlatformTagBubbles(node.sourceSets.filter { sourceSetRestriction == null || it in sourceSetRestriction }.sortedBy { it.name }, cssClasses) } } override fun FlowContent.buildTable( node: ContentTable, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) { when { node.style.contains(CommentTable) -> buildDefaultTable(node, pageContext, sourceSetRestriction) else -> div(classes = "table") { node.extra.extraHtmlAttributes().forEach { attributes[it.extraKey] = it.extraValue } node.children.forEach { buildRow(it, pageContext, sourceSetRestriction) } } } } fun FlowContent.buildDefaultTable( node: ContentTable, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) { table { thead { node.header.forEach { tr { it.children.forEach { th { it.build(this@table, pageContext, sourceSetRestriction) } } } } } tbody { node.children.forEach { tr { it.children.forEach { td { it.build(this, pageContext, sourceSetRestriction) } } } } } } } override fun FlowContent.buildHeader(level: Int, node: ContentHeader, content: FlowContent.() -> Unit) { val classes = node.style.joinToString { it.toString() }.toLowerCase() when (level) { 1 -> h1(classes = classes, content) 2 -> h2(classes = classes, content) 3 -> h3(classes = classes, content) 4 -> h4(classes = classes, content) 5 -> h5(classes = classes, content) else -> h6(classes = classes, content) } } private fun FlowContent.buildAnchor( anchor: String, anchorLabel: String, sourceSets: String, content: FlowContent.() -> Unit ) { a { attributes["data-name"] = anchor attributes["anchor-label"] = anchorLabel attributes["id"] = anchor attributes["data-filterable-set"] = sourceSets } content() } private fun FlowContent.buildAnchor(anchor: String, anchorLabel: String, sourceSets: String) = buildAnchor(anchor, anchorLabel, sourceSets) {} private fun FlowContent.buildAnchor(node: ContentNode) { node.anchorLabel?.let { label -> buildAnchor(node.anchor!!, label, node.sourceSetsFilters) } } override fun FlowContent.buildNavigation(page: PageNode) = div(classes = "breadcrumbs") { val path = locationProvider.ancestors(page).filterNot { it is RendererSpecificPage }.asReversed() if (path.size > 1) { buildNavigationElement(path.first(), page) path.drop(1).forEach { node -> span(classes = "delimiter") { text("/") } buildNavigationElement(node, page) } } } private fun FlowContent.buildNavigationElement(node: PageNode, page: PageNode) = if (node.isNavigable) { val isCurrentPage = (node == page) if (isCurrentPage) { span(classes = "current") { text(node.name) } } else { buildLink(node, page) } } else { text(node.name) } private fun FlowContent.buildLink(to: PageNode, from: PageNode) = locationProvider.resolve(to, from)?.let { path -> buildLink(path) { text(to.name) } } ?: span { attributes["data-unresolved-link"] = to.name.htmlEscape() text(to.name) } fun FlowContent.buildAnchorCopyButton(pointingTo: String) { span(classes = "anchor-wrapper") { span(classes = "anchor-icon") { attributes["pointing-to"] = pointingTo } copiedPopup("Link copied to clipboard") } } fun FlowContent.buildLink( to: DRI, platforms: List<DisplaySourceSet>, from: PageNode? = null, block: FlowContent.() -> Unit ) = locationProvider.resolve(to, platforms.toSet(), from)?.let { buildLink(it, block) } ?: run { context.logger.error("Cannot resolve path for `$to` from `$from`"); block() } override fun buildError(node: ContentNode) = context.logger.error("Unknown ContentNode type: $node") override fun FlowContent.buildLineBreak() = br() override fun FlowContent.buildLineBreak(node: ContentBreakLine, pageContext: ContentPage) { if (node.style.contains(HorizontalBreakLineStyle)) { hr() } else { buildLineBreak() } } override fun FlowContent.buildLink(address: String, content: FlowContent.() -> Unit) = a(href = address, block = content) override fun FlowContent.buildDRILink( node: ContentDRILink, pageContext: ContentPage, sourceSetRestriction: Set<DisplaySourceSet>? ) = locationProvider.resolve(node.address, node.sourceSets, pageContext)?.let { address -> buildLink(address) { buildText(node.children, pageContext, sourceSetRestriction) } } ?: if (isPartial) { templateCommand(ResolveLinkCommand(node.address)) { buildText(node.children, pageContext, sourceSetRestriction) } } else { span { attributes["data-unresolved-link"] = node.address.toString().htmlEscape() buildText(node.children, pageContext, sourceSetRestriction) } } override fun FlowContent.buildCodeBlock( code: ContentCodeBlock, pageContext: ContentPage ) { div("sample-container") { val codeLang = "lang-" + code.language.ifEmpty { "kotlin" } val stylesWithBlock = code.style + TextStyle.Block + codeLang pre { code(stylesWithBlock.joinToString(" ") { it.toString().toLowerCase() }) { attributes["theme"] = "idea" code.children.forEach { buildContentNode(it, pageContext) } } } /* Disable copy button on samples as: - it is useless - it overflows with playground's run button */ if (!code.style.contains(ContentStyle.RunnableSample)) copyButton() } } override fun FlowContent.buildCodeInline( code: ContentCodeInline, pageContext: ContentPage ) { val codeLang = "lang-" + code.language.ifEmpty { "kotlin" } val stylesWithBlock = code.style + codeLang code(stylesWithBlock.joinToString(" ") { it.toString().toLowerCase() }) { code.children.forEach { buildContentNode(it, pageContext) } } } override fun FlowContent.buildText(textNode: ContentText) = buildText(textNode, textNode.style) private fun FlowContent.buildText(textNode: ContentText, unappliedStyles: Set<Style>) { when { textNode.extra[HtmlContent] != null -> { consumer.onTagContentUnsafe { raw(textNode.text) } } unappliedStyles.contains(TextStyle.Indented) -> { consumer.onTagContentEntity(Entities.nbsp) buildText(textNode, unappliedStyles - TextStyle.Indented) } unappliedStyles.isNotEmpty() -> { val styleToApply = unappliedStyles.first() applyStyle(styleToApply) { buildText(textNode, unappliedStyles - styleToApply) } } textNode.hasStyle(ContentStyle.RowTitle) || textNode.hasStyle(TextStyle.Cover) -> buildBreakableText(textNode.text) else -> text(textNode.text) } } private inline fun FlowContent.applyStyle(styleToApply: Style, crossinline body: FlowContent.() -> Unit) { when (styleToApply) { TextStyle.Bold -> b { body() } TextStyle.Italic -> i { body() } TextStyle.Strikethrough -> strike { body() } TextStyle.Strong -> strong { body() } TextStyle.Var -> htmlVar { body() } TextStyle.Underlined -> underline { body() } is TokenStyle -> span("token ${styleToApply.prismJsClass()}") { body() } else -> body() } } private fun TokenStyle.prismJsClass(): String = when(this) { // Prism.js parser adds Builtin token instead of Annotation // for some reason, so we also add it for consistency and correct coloring TokenStyle.Annotation -> "annotation builtin" else -> this.toString().toLowerCase() } override fun render(root: RootPageNode) { shouldRenderSourceSetBubbles = shouldRenderSourceSetBubbles(root) super.render(root) } override fun buildPage(page: ContentPage, content: (FlowContent, ContentPage) -> Unit): String = buildHtml(page, page.embeddedResources) { content(this, page) } open fun buildHtml(page: PageNode, resources: List<String>, content: FlowContent.() -> Unit): String = templater.renderFromTemplate(DokkaTemplateTypes.BASE) { val generatedContent = createHTML().div("main-content") { id = "content" (page as? ContentPage)?.let { attributes["pageIds"] = "${context.configuration.moduleName}::${page.pageId}" } content() } templateModelMerger.invoke(templateModelFactories) { buildModel( page, resources, locationProvider, shouldRenderSourceSetBubbles, generatedContent ) } } /** * This is deliberately left open for plugins that have some other pages above ours and would like to link to them * instead of ours when clicking the logo */ open fun FlowContent.clickableLogo(page: PageNode, pathToRoot: String) { if (context.configuration.delayTemplateSubstitution && page is ContentPage) { templateCommand(PathToRootSubstitutionCommand(pattern = "###", default = pathToRoot)) { a { href = "###index.html" templateCommand( ProjectNameSubstitutionCommand( pattern = "@@@", default = context.configuration.moduleName ) ) { span { text("@@@") } } } } } else { a { href = pathToRoot + "index.html" text(context.configuration.moduleName) } } } private val ContentNode.isAnchorable: Boolean get() = anchorLabel != null private val ContentNode.anchorLabel: String? get() = extra[SymbolAnchorHint]?.anchorName private val ContentNode.anchor: String? get() = extra[SymbolAnchorHint]?.contentKind?.let { contentKind -> (locationProvider as DokkaBaseLocationProvider).anchorForDCI(DCI(dci.dri, contentKind), sourceSets) } private val isPartial = context.configuration.delayTemplateSubstitution } fun List<SimpleAttr>.joinAttr() = joinToString(" ") { it.extraKey + "=" + it.extraValue } private fun String.stripDiv() = drop(5).dropLast(6) // TODO: Find a way to do it without arbitrary trims private val PageNode.isNavigable: Boolean get() = this !is RendererSpecificPage || strategy != RenderingStrategy.DoNothing private fun PropertyContainer<ContentNode>.extraHtmlAttributes() = allOfType<SimpleAttr>() private val ContentNode.sourceSetsFilters: String get() = sourceSets.sourceSetIDs.joinToString(" ") { it.toString() } private val DisplaySourceSet.comparableKey get() = sourceSetIDs.merged.let { it.scopeId + it.sourceSetName }
apache-2.0
a80d145e555f4aa438d2fe5e46749d21
41.062851
123
0.567826
5.118547
false
false
false
false
Kotlin/dokka
integration-tests/gradle/projects/it-basic/src/main/kotlin/it/basic/PublicClass.kt
1
1554
@file:Suppress("unused") package it.basic import RootPackageClass /** * This class, unlike [RootPackageClass] is located in a sub-package * * §PUBLIC§ (marker for asserts) */ class PublicClass { /** * This function is public and documented */ fun publicDocumentedFunction(): String = "" fun publicUndocumentedFunction(): String = "" /** * This function is internal and documented */ internal fun internalDocumentedFunction(): String = "" internal fun internalUndocumentedFunction(): String = "" /** * This function is protected and documented */ protected fun protectedDocumentedFunction(): String = "" protected fun protectedUndocumentedFunction(): String = "" /** * This function is private and documented */ private fun privateDocumentedFunction(): String = "" private fun privateUndocumentedFunction(): String = "" /** * This property is public and documented */ val publicDocumentedProperty: Int = 0 val publicUndocumentedProperty: Int = 0 /** * This property internal and documented */ val internalDocumentedProperty: Int = 0 val internalUndocumentedProperty: Int = 0 /** * This property is protected and documented */ val protectedDocumentedProperty: Int = 0 val protectedUndocumentedProperty: Int = 0 /** * This property private and documented */ private val privateDocumentedProperty: Int = 0 private val privateUndocumentedProperty: Int = 0 }
apache-2.0
2e548044526d06ec5186490af68c5178
21.492754
68
0.664304
5.038961
false
false
false
false
approov/shipfast-api-protection
app/android/kotlin/ShipFast/app/src/main/java/com/criticalblue/shipfast/LoginActivity.kt
1
6020
/* Copyright (C) 2020 CriticalBlue Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.criticalblue.shipfast import android.app.Dialog import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.ProgressBar import android.widget.Toast import com.auth0.android.Auth0 import com.auth0.android.authentication.AuthenticationException import com.auth0.android.provider.AuthCallback import com.auth0.android.provider.WebAuthProvider import com.auth0.android.result.Credentials import com.criticalblue.shipfast.config.API_BASE_URL import com.criticalblue.shipfast.config.HOME_SCREEN_TITLE import com.criticalblue.shipfast.config.JniEnv import com.criticalblue.shipfast.user.saveUserCredentials /** * The Login activity class. * * TODO: use Auth0 CredentialsManager * TODO: use Android Lock rather than web Lock */ class LoginActivity : BaseActivity() { /** The progress bar */ private lateinit var loginProgressBar: ProgressBar /** The user login button */ private lateinit var loginButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) supportActionBar?.title = HOME_SCREEN_TITLE supportActionBar?.subtitle = "URL: $API_BASE_URL" // Add an 'on-click' listener to the user login button loginButton = findViewById(R.id.loginButton) loginButton.setOnClickListener { _ -> performLogin()} loginProgressBar = findViewById(R.id.loginProgressBar) } /** * Get the value for the given key from the `AndroidManifest.xml` file. * * @param key The key name to retrieve the value for. * * @return the value for the given key. */ private fun getManifestValueFor(key: String): String { var value: String? = null try { val app = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) value = app.metaData.getString(key) } catch (e: PackageManager.NameNotFoundException) { Log.e(TAG, "${key} NameNotFound: " + e.message) } catch (e: NullPointerException) { Log.e(TAG, "${key}, NullPointer: " + e.message) } if (value == null) { throw RuntimeException("Android Manifest is missing value for key: ${key}") } return value } /** * Perform user login using Auth0. */ private fun performLogin() { startProgress() val jniEnv = JniEnv() // The Auth0 domain is not retrieve from the `JninEnv`, because the Auth0 package requires // it to be present in the `build.gradle` files as a manifest placeholder. val auth0Domain = this.getManifestValueFor("com.criticalblue.shipfast.auth0Domain") val auth0 = Auth0(jniEnv.getAuth0ClientId(), auth0Domain) // Always prompt the user, otherwise if we have multiple Gmail accounts // we will not know wich one was used by the ShipFast App in order to // login with the same one in ShipRaider. val parameters: HashMap<String, Any> = HashMap() parameters.put("prompt", "select_account") auth0.isOIDCConformant = true WebAuthProvider.init(auth0) .withScheme(this.getManifestValueFor("com.criticalblue.shipfast.auth0Scheme")) .withAudience(String.format("https://%s/userinfo", auth0Domain)) .withParameters(parameters) .start(this@LoginActivity, object : AuthCallback { override fun onFailure(dialog: Dialog) { stopProgress() runOnUiThread { dialog.show() } } override fun onFailure(exception: AuthenticationException) { stopProgress() runOnUiThread { Toast.makeText(this@LoginActivity, "Login Failed (${exception.localizedMessage})", Toast.LENGTH_LONG).show() } } override fun onSuccess(credentials: Credentials) { stopProgress() saveUserCredentials(this@LoginActivity, credentials) val intent = Intent(this@LoginActivity, ShipmentActivity::class.java) startActivity(intent) } }) } /** * Start showing progress. */ private fun startProgress() { runOnUiThread { loginProgressBar.visibility = View.VISIBLE } } /** * Stop showing progress. */ private fun stopProgress() { runOnUiThread { loginProgressBar.visibility = View.INVISIBLE } } }
mit
b8ca9a64625b6db2b4e3d024c87616be
35.047904
110
0.651661
4.808307
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/entity/ability/Cost.kt
1
3966
/* * The MIT License * * Copyright 2015 Nathan Templon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.entity.ability import com.badlogic.ashley.core.Entity import com.jupiter.europa.entity.Families import com.jupiter.europa.entity.Mappers import com.jupiter.europa.entity.component.ResourceComponent import java.util.Collections import java.util.EnumMap /** * Created by nathan on 5/20/15. */ public abstract class Cost(public val description: String) { // Abstract Methods public abstract fun getSpecificCosts(entity: Entity): Map<ResourceComponent.Resources, Int> public open fun canPay(entity: Entity): Boolean { if (!Families.resourced.matches(entity)) { return false } val costs = this.getSpecificCosts(entity) val component = Mappers.resources.get(entity) return costs.entrySet() .map { entry -> component.getCurrent(entry.getKey()) >= entry.getValue() } // If the specific cost can be payed .fold(true, { first, second -> first && second }) // If all costs can be payed } public open fun exact(entity: Entity) { if (!Families.resourced.matches(entity)) { return } val costs = this.getSpecificCosts(entity) val component = Mappers.resources.get(entity) costs.entrySet() .forEach { entry -> component.setCurrent(entry.getKey(), Math.max(0, entry.getValue() - (costs[entry.getKey()] ?: 0))) } } public fun and(other: Cost): Cost { return CompositeCost(this, other) } companion object { // Constants public val NONE: Cost = object : Cost("No Cost") { private val costs = EnumMap<ResourceComponent.Resources, Int>(javaClass<ResourceComponent.Resources>()) init { for (resource in ResourceComponent.Resources.values()) { costs.put(resource, 0) } } private val costsView = Collections.unmodifiableMap(this.costs) override fun getSpecificCosts(entity: Entity): Map<ResourceComponent.Resources, Int> { return this.costsView } override fun canPay(entity: Entity): Boolean { return true } override fun exact(entity: Entity) { } } // Static Methods public fun constant(resource: ResourceComponent.Resources, cost: Int): Cost { return ConstantCost(resource, cost) } public fun scaling(resource: ResourceComponent.Resources, levelsPerEpoch: Int, costPerEpoch: Int): Cost { return ScalingCost(resource, levelsPerEpoch, costPerEpoch) } public fun all(vararg costs: Cost): Cost { return CompositeCost(*costs) } } }// Public Methods
mit
a3dcdc3c962e8664d224af019328076a
33.789474
127
0.652799
4.606272
false
false
false
false
sangcomz/FishBun
FishBun/src/main/java/com/sangcomz/fishbun/ui/album/adapter/AlbumListAdapter.kt
1
3060
package com.sangcomz.fishbun.ui.album.adapter import android.net.Uri import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import com.sangcomz.fishbun.R import com.sangcomz.fishbun.adapter.image.ImageAdapter import com.sangcomz.fishbun.ui.album.model.Album import com.sangcomz.fishbun.ui.album.model.AlbumMetaData import com.sangcomz.fishbun.ui.album.listener.AlbumClickListener import com.sangcomz.fishbun.util.SquareImageView class AlbumListAdapter( private val albumClickListener: AlbumClickListener, private val thumbnailSize: Int, private val imageAdapter: ImageAdapter? ) : RecyclerView.Adapter<AlbumListAdapter.ViewHolder>() { private var albumList = emptyList<Album>() init { setHasStableIds(true) } override fun getItemId(position: Int): Long { return albumList[position].id } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = return ViewHolder( parent, thumbnailSize, imageAdapter ).apply { itemView.setOnClickListener { albumClickListener.onAlbumClick(adapterPosition, albumList[adapterPosition]) } } } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.setData(albumList[position]) } fun setAlbumList(albumList: List<Album>) { this.albumList = albumList notifyDataSetChanged() } fun updateAlbumMeta(position: Int, addedCount: Int, thumbnailPath: String) { val oldAlbum = albumList[position] val updateAlbum = oldAlbum.copy( metaData = AlbumMetaData( oldAlbum.metaData.count + addedCount, thumbnailPath ) ) albumList = albumList.toMutableList().apply { set(position, updateAlbum) } notifyItemChanged(position) } override fun getItemCount(): Int = albumList.size class ViewHolder( parent: ViewGroup, albumSize: Int, private val imageAdapter: ImageAdapter? ) : RecyclerView.ViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.album_item, parent, false) ) { private val imgAlbumThumb: SquareImageView = itemView.findViewById(R.id.img_album_thumb) private val txtAlbumName: TextView = itemView.findViewById(R.id.txt_album_name) private val txtAlbumCount: TextView = itemView.findViewById(R.id.txt_album_count) init { imgAlbumThumb.layoutParams = LinearLayout.LayoutParams(albumSize, albumSize) } fun setData(album: Album) { val uri: Uri = Uri.parse(album.metaData.thumbnailPath) imageAdapter?.loadImage(imgAlbumThumb, uri) itemView.tag = album txtAlbumName.text = album.displayName txtAlbumCount.text = album.metaData.count.toString() } } }
apache-2.0
ea6bad25d78aa6e13010ff253cdc5dcd
31.56383
96
0.680392
4.580838
false
false
false
false
MADWI/AppZUT
app/src/main/java/pl/edu/zut/mad/appzut/MainActivity.kt
1
2402
package pl.edu.zut.mad.appzut import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.format.DateFormat import android.view.Menu import android.view.MenuItem import org.joda.time.LocalDate import pl.edu.zut.mad.schedule.DateListener import pl.edu.zut.mad.schedule.ScheduleFragment import pl.edu.zut.mad.schedule.search.SearchActivity class MainActivity : AppCompatActivity(), DateListener { companion object { private val DATE_FORMAT = "LLLL" } private val scheduleFragment = ScheduleFragment() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) init(savedInstanceState) } private fun init(savedInstanceState: Bundle?) { initBar() startScheduleFragment(savedInstanceState) scheduleFragment.dateListener = this } private fun initBar() { supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setIcon(R.drawable.ic_logo_zut) } private fun startScheduleFragment(savedInstanceState: Bundle?) { if (savedInstanceState != null) { return } supportFragmentManager.beginTransaction() .replace(R.id.main_container, scheduleFragment) .commit() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_activity_menu, menu) return true } override fun onDateChanged(date: LocalDate) { supportActionBar?.title = DateFormat.format(DATE_FORMAT, date.toDate()).toString() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_today -> scheduleFragment.moveToToday() R.id.action_authors -> showAboutUs() R.id.action_refresh -> scheduleFragment.refreshSchedule() R.id.action_search -> startActivity(Intent(this, SearchActivity::class.java)) R.id.action_logout -> scheduleFragment.logout() else -> return super.onOptionsItemSelected(item) } return true } private fun showAboutUs() { supportFragmentManager.beginTransaction() .add(R.id.main_container, AboutUsFragment()) .addToBackStack(null) .commit() } }
apache-2.0
edb296ad8d56254922916b78e35b730e
31.026667
90
0.678601
4.575238
false
false
false
false
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/speakercall/EditSpeakerFragment.kt
1
20771
package org.fossasia.openevent.general.speakercall import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Bundle import android.provider.MediaStore import android.util.Base64 import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.toBitmap import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.navArgs import com.google.android.material.textfield.TextInputLayout import com.squareup.picasso.MemoryPolicy import com.squareup.picasso.Picasso import java.io.ByteArrayOutputStream import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import kotlinx.android.synthetic.main.dialog_edit_profile_image.view.editImage import kotlinx.android.synthetic.main.dialog_edit_profile_image.view.removeImage import kotlinx.android.synthetic.main.dialog_edit_profile_image.view.replaceImage import kotlinx.android.synthetic.main.dialog_edit_profile_image.view.takeImage import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerCountry import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerCountryLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerEmail import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerEmailLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerFacebook import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerGithub import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerGithubLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerHeardFrom import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerHeardFromLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerImage import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerLinkedIn import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerLinkedInLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerLongBio import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerLongBioLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerMobile import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerMobileLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerName import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerNameLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerOrgLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerOrganization import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerPosition import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerPositionLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerShortBio import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerShortBioLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerSpeakingExp import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerSpeakingExpLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerTwitter import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerTwitterLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerWebsite import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.speakerWebsiteLayout import kotlinx.android.synthetic.main.fragment_proposal_speaker.view.submitButton import org.fossasia.openevent.general.CircleTransform import org.fossasia.openevent.general.ComplexBackPressFragment import org.fossasia.openevent.general.R import org.fossasia.openevent.general.RotateBitmap import org.fossasia.openevent.general.attendees.forms.CustomForm import org.fossasia.openevent.general.auth.User import org.fossasia.openevent.general.auth.UserId import org.fossasia.openevent.general.event.EventId import org.fossasia.openevent.general.speakercall.form.SpeakerIdentifier import org.fossasia.openevent.general.speakers.Speaker import org.fossasia.openevent.general.utils.Utils.hideSoftKeyboard import org.fossasia.openevent.general.utils.Utils.progressDialog import org.fossasia.openevent.general.utils.Utils.requireDrawable import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.Utils.show import org.fossasia.openevent.general.utils.checkEmpty import org.fossasia.openevent.general.utils.emptyToNull import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.nullToEmpty import org.fossasia.openevent.general.utils.setRequired import org.jetbrains.anko.design.snackbar import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber class EditSpeakerFragment : Fragment(), ComplexBackPressFragment { private lateinit var rootView: View private val editSpeakerViewModel by viewModel<EditSpeakerViewModel>() private val safeArgs: EditSpeakerFragmentArgs by navArgs() private var isCreatingNewSpeaker = true private var storagePermissionGranted = false private val PICK_IMAGE_REQUEST = 100 private val READ_STORAGE = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) private val READ_STORAGE_REQUEST_CODE = 1 private var cameraPermissionGranted = false private val TAKE_IMAGE_REQUEST = 101 private val CAMERA_REQUEST = arrayOf(Manifest.permission.CAMERA) private val CAMERA_REQUEST_CODE = 2 private lateinit var speakerAvatar: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) isCreatingNewSpeaker = (safeArgs.speakerId == -1L) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(R.layout.fragment_proposal_speaker, container, false) setToolbar(activity, getString(R.string.proposal_speaker)) setHasOptionsMenu(true) storagePermissionGranted = (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) cameraPermissionGranted = (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) editSpeakerViewModel.user .nonNull() .observe(viewLifecycleOwner, Observer { autoFillByUserInformation(it) }) val currentSpeaker = editSpeakerViewModel.speaker.value if (currentSpeaker == null) { if (isCreatingNewSpeaker) { editSpeakerViewModel.user.value?.let { autoFillByUserInformation(it) } ?: editSpeakerViewModel.loadUser(editSpeakerViewModel.getId()) } else { editSpeakerViewModel.loadSpeaker(safeArgs.speakerId) } } else loadSpeakerUI(currentSpeaker) editSpeakerViewModel.speaker .nonNull() .observe(viewLifecycleOwner, Observer { loadSpeakerUI(it) }) val progressDialog = progressDialog(context) editSpeakerViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressDialog.show(it) }) editSpeakerViewModel.message .nonNull() .observe(viewLifecycleOwner, Observer { rootView.snackbar(it) }) editSpeakerViewModel.submitSuccess .nonNull() .observe(viewLifecycleOwner, Observer { if (it) findNavController(rootView).popBackStack() }) setupCustomForms() rootView.speakerNameLayout.setRequired() rootView.speakerEmailLayout.setRequired() rootView.submitButton.text = getString(if (isCreatingNewSpeaker) R.string.add_speaker else R.string.edit_speaker) return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) editSpeakerViewModel.getUpdatedTempFile() .nonNull() .observe(viewLifecycleOwner, Observer { file -> Picasso.get() .load(file) .placeholder(requireDrawable(requireContext(), R.drawable.ic_person_black)) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) .transform(CircleTransform()) .into(rootView.speakerImage) }) rootView.speakerImage.setOnClickListener { showEditPhotoDialog() } rootView.submitButton.setOnClickListener { if (!checkSpeakerSuccess()) return@setOnClickListener val speaker = Speaker( id = editSpeakerViewModel.speaker.value?.id ?: editSpeakerViewModel.getId(), name = rootView.speakerName.text.toString(), email = rootView.speakerEmail.text.toString(), organisation = rootView.speakerOrganization.text.toString(), position = rootView.speakerPosition.text.toString(), shortBiography = rootView.speakerShortBio.text.toString(), longBiography = rootView.speakerLongBio.text.toString(), country = rootView.speakerCountry.text.toString(), mobile = rootView.speakerMobile.text.toString(), speakingExperience = rootView.speakerSpeakingExp.text.toString(), heardFrom = rootView.speakerHeardFrom.text.toString(), facebook = rootView.speakerFacebook.text.toString().emptyToNull(), github = rootView.speakerGithub.text.toString().emptyToNull(), linkedin = rootView.speakerLinkedIn.text.toString().emptyToNull(), website = rootView.speakerWebsite.text.toString().emptyToNull(), twitter = rootView.speakerTwitter.text.toString().emptyToNull(), event = EventId(safeArgs.eventId), user = UserId(editSpeakerViewModel.getId()) ) if (isCreatingNewSpeaker) editSpeakerViewModel.submitSpeaker(speaker) else editSpeakerViewModel.editSpeaker(speaker) } } override fun handleBackPress() { hideSoftKeyboard(context, rootView) AlertDialog.Builder(requireContext()) .setMessage(getString(R.string.changes_not_saved)) .setNegativeButton(R.string.discard) { _, _ -> findNavController(rootView).popBackStack() } .setPositiveButton(getString(R.string.continue_string)) { _, _ -> /*Do Nothing*/ } .create() .show() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } override fun onActivityResult(requestCode: Int, resultCode: Int, intentData: Intent?) { super.onActivityResult(requestCode, resultCode, intentData) if (resultCode != Activity.RESULT_OK) return if (requestCode == PICK_IMAGE_REQUEST && intentData?.data != null) { val imageUri = intentData.data ?: return try { val selectedImage = RotateBitmap().handleSamplingAndRotationBitmap(requireContext(), imageUri) editSpeakerViewModel.encodedImage = selectedImage?.let { encodeImage(it) } } catch (e: FileNotFoundException) { Timber.d(e, "File Not Found Exception") } } else if (requestCode == TAKE_IMAGE_REQUEST) { val imageBitmap = intentData?.extras?.get("data") if (imageBitmap is Bitmap) { editSpeakerViewModel.encodedImage = imageBitmap.let { encodeImage(it) } } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == READ_STORAGE_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { storagePermissionGranted = true rootView.snackbar(getString(R.string.permission_granted_message, getString(R.string.external_storage))) showFileChooser() } else { rootView.snackbar(getString(R.string.permission_denied_message, getString(R.string.external_storage))) } } else if (requestCode == CAMERA_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { cameraPermissionGranted = true rootView.snackbar(getString(R.string.permission_granted_message, getString(R.string.camera))) takeImage() } else { rootView.snackbar(getString(R.string.permission_denied_message, getString(R.string.camera))) } } } private fun showFileChooser() { val intent = Intent() intent.type = "image/*" intent.action = Intent.ACTION_GET_CONTENT startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)), PICK_IMAGE_REQUEST) } private fun autoFillByUserInformation(user: User) { rootView.speakerName.setText("${user.firstName.nullToEmpty()} ${user.lastName.nullToEmpty()}") rootView.speakerEmail.setText(user.email) rootView.speakerShortBio.setText(user.details) Picasso.get() .load(user.avatarUrl) .placeholder(R.drawable.ic_account_circle_grey) .transform(CircleTransform()) .into(rootView.speakerImage) speakerAvatar = user.avatarUrl ?: "" } private fun showEditPhotoDialog() { val editImageView = layoutInflater.inflate(R.layout.dialog_edit_profile_image, null) editImageView.removeImage.isVisible = this::speakerAvatar.isInitialized && speakerAvatar.isNotEmpty() editImageView.editImage.isVisible = false val dialog = AlertDialog.Builder(requireContext()) .setView(editImageView) .create() editImageView.editImage.isVisible = false editImageView.removeImage.setOnClickListener { dialog.cancel() clearAvatar() } editImageView.takeImage.setOnClickListener { dialog.cancel() if (cameraPermissionGranted) { takeImage() } else { requestPermissions(CAMERA_REQUEST, CAMERA_REQUEST_CODE) } } editImageView.replaceImage.setOnClickListener { dialog.cancel() if (storagePermissionGranted) { showFileChooser() } else { requestPermissions(READ_STORAGE, READ_STORAGE_REQUEST_CODE) } } dialog.show() } private fun clearAvatar() { val drawable = requireDrawable(requireContext(), R.drawable.ic_account_circle_grey) Picasso.get() .load(R.drawable.ic_account_circle_grey) .placeholder(drawable) .transform(CircleTransform()) .into(rootView.speakerImage) val newSpeakerImage = encodeImage(drawable.toBitmap(120, 120)) editSpeakerViewModel.encodedImage = newSpeakerImage } private fun takeImage() { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) startActivityForResult(intent, TAKE_IMAGE_REQUEST) } private fun encodeImage(bitmap: Bitmap): String { val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) val bytes = baos.toByteArray() // create temp file try { val tempAvatar = File(context?.cacheDir, "tempAvatar") if (tempAvatar.exists()) { tempAvatar.delete() } val fos = FileOutputStream(tempAvatar) fos.write(bytes) fos.flush() fos.close() editSpeakerViewModel.setUpdatedTempFile(tempAvatar) } catch (e: IOException) { e.printStackTrace() } return "data:image/jpeg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT) } private fun checkSpeakerSuccess(): Boolean { var valid = rootView.speakerEmail.checkEmpty(rootView.speakerEmailLayout) valid = rootView.speakerName.checkEmpty(rootView.speakerNameLayout) && valid return valid } private fun loadSpeakerUI(speaker: Speaker) { Picasso.get() .load(speaker.photoUrl) .placeholder(R.drawable.ic_account_circle_grey) .transform(CircleTransform()) .into(rootView.speakerImage) speakerAvatar = speaker.photoUrl ?: "" rootView.speakerName.setText(speaker.name) rootView.speakerEmail.setText(speaker.email) rootView.speakerOrganization.setText(speaker.organisation) rootView.speakerPosition.setText(speaker.position) rootView.speakerShortBio.setText(speaker.shortBiography) rootView.speakerWebsite.setText(speaker.website) rootView.speakerTwitter.setText(speaker.twitter) rootView.speakerHeardFrom.setText(speaker.heardFrom) rootView.speakerSpeakingExp.setText(speaker.speakingExperience) } private fun setupCustomForms() { editSpeakerViewModel.forms .nonNull() .observe(viewLifecycleOwner, Observer { it.forEach { form -> setupFormWithSpeakerFields(form) } }) val currentForms = editSpeakerViewModel.forms.value if (currentForms != null) currentForms.forEach { setupFormWithSpeakerFields(it) } else editSpeakerViewModel.getFormsForSpeaker(safeArgs.eventId) } private fun setupFormWithSpeakerFields(form: CustomForm) { when (form.fieldIdentifier) { SpeakerIdentifier.NAME -> setupField(rootView.speakerNameLayout, form.isRequired) SpeakerIdentifier.EMAIL -> setupField(rootView.speakerEmailLayout, form.isRequired) SpeakerIdentifier.PHOTO -> rootView.speakerImage.isVisible = true SpeakerIdentifier.ORGANIZATION -> setupField(rootView.speakerOrgLayout, form.isRequired) SpeakerIdentifier.POSITION -> setupField(rootView.speakerPositionLayout, form.isRequired) SpeakerIdentifier.SHORT_BIO -> setupField(rootView.speakerShortBioLayout, form.isRequired) SpeakerIdentifier.LONG_BIO -> setupField(rootView.speakerLongBioLayout, form.isRequired) SpeakerIdentifier.COUNTRY -> setupField(rootView.speakerCountryLayout, form.isRequired) SpeakerIdentifier.MOBILE -> setupField(rootView.speakerMobileLayout, form.isRequired) SpeakerIdentifier.WEBSITE -> setupField(rootView.speakerWebsiteLayout, form.isRequired) SpeakerIdentifier.FACEBOOK -> setupField(rootView.speakerWebsiteLayout, form.isRequired) SpeakerIdentifier.GITHUB -> setupField(rootView.speakerGithubLayout, form.isRequired) SpeakerIdentifier.TWITTER -> setupField(rootView.speakerTwitterLayout, form.isRequired) SpeakerIdentifier.LINKEDIN -> setupField(rootView.speakerLinkedInLayout, form.isRequired) SpeakerIdentifier.HEARD_FROM -> setupField(rootView.speakerHeardFromLayout, form.isRequired) SpeakerIdentifier.SPEAKING_EXPERIENCE -> setupField(rootView.speakerSpeakingExpLayout, form.isRequired) else -> return } } private fun setupField(layout: TextInputLayout, isRequired: Boolean) { layout.isVisible = true if (isRequired) { layout.setRequired() } } }
apache-2.0
ee61dbddc836843392fd7f8df84f8faa
44.450766
119
0.698378
4.843983
false
false
false
false
deianvn/misc
vfu/course_3/android/CurrencyConverter/app/src/main/java/bg/vfu/rizov/currencyconverter/main/selection/SelectionAdapter.kt
1
1417
package bg.vfu.rizov.currencyconverter.main.selection import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import bg.vfu.rizov.currencyconverter.R import bg.vfu.rizov.currencyconverter.model.Currency import kotlinx.android.synthetic.main.view_currency_item.view.* typealias SelectionCallback = (item: Currency) -> Unit class SelectionAdapter( currencies: Map<String, Currency>, val callback: SelectionCallback ) : RecyclerView.Adapter<SelectionAdapter.ViewHolder>() { private val currencies = currencies.entries.map { it.value } .toList() .sortedBy { it.name.trim() } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val currency: TextView = view.currency val currencyName: TextView = view.currencyName } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.view_currency_item, parent, false) as View return ViewHolder(view) } override fun getItemCount() = currencies.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.currency.text = currencies[position].code holder.currencyName.text = currencies[position].name holder.itemView.setOnClickListener { callback(currencies[position]) } } }
apache-2.0
c1578dcddc9470a530d055215e552aa2
31.204545
81
0.762879
4.217262
false
false
false
false
V2Ray-Android/Actinium
app/src/main/kotlin/com/v2ray/actinium/ui/PerAppProxyActivity.kt
1
6216
package com.v2ray.actinium.ui import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.app.ProgressDialog import android.os.Bundle import android.support.v7.widget.RecyclerView import android.view.Menu import android.view.MenuItem import android.view.View import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import com.dinuscxj.itemdecoration.LinearDividerItemDecoration import com.v2ray.actinium.R import com.v2ray.actinium.defaultDPreference import com.v2ray.actinium.util.AppInfo import com.v2ray.actinium.util.AppManagerUtil import kotlinx.android.synthetic.main.activity_bypass_list.* import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.text.Collator import java.util.* class PerAppProxyActivity : BaseActivity() { companion object { const val PREF_PER_APP_PROXY_SET = "pref_per_app_proxy_set" const val PREF_BYPASS_APPS = "pref_bypass_apps" } private var adapter: PerAppProxyAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_bypass_list) supportActionBar?.setDisplayHomeAsUpEnabled(true) val dividerItemDecoration = LinearDividerItemDecoration( this, LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL) recycler_view.addItemDecoration(dividerItemDecoration) val dialog = ProgressDialog(this) dialog.isIndeterminate = true dialog.setCancelable(false) dialog.setMessage(getString(R.string.msg_dialog_progress)) dialog.show() AppManagerUtil.rxLoadNetworkAppList(this) .subscribeOn(Schedulers.io()) .map { val comparator = object : Comparator<AppInfo> { val collator = Collator.getInstance() override fun compare(o1: AppInfo, o2: AppInfo) = collator.compare(o1.appName, o2.appName) } it.sortedWith(comparator) } .observeOn(AndroidSchedulers.mainThread()) .subscribe { val blacklist = defaultDPreference.getPrefStringSet(PREF_PER_APP_PROXY_SET, null) adapter = PerAppProxyAdapter(it, blacklist) recycler_view.adapter = adapter dialog.dismiss() } recycler_view.addOnScrollListener(object : RecyclerView.OnScrollListener() { var dst = 0 val threshold = resources.getDimensionPixelSize(R.dimen.bypass_list_header_height) * 2 override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { dst += dy if (dst > threshold) { header_view.hide() dst = 0 } else if (dst < -20) { header_view.show() dst = 0 } } var hiding = false fun View.hide() { val target = -height.toFloat() if (hiding || translationY == target) return animate() .translationY(target) .setInterpolator(AccelerateInterpolator(2F)) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { hiding = false } }) hiding = true } var showing = false fun View.show() { val target = 0f if (showing || translationY == target) return animate() .translationY(target) .setInterpolator(DecelerateInterpolator(2F)) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { showing = false } }) showing = true } }) switch_per_app_proxy.setOnCheckedChangeListener { buttonView, isChecked -> defaultDPreference.setPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, isChecked) } switch_per_app_proxy.isChecked = defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, false) switch_bypass_apps.setOnCheckedChangeListener { buttonView, isChecked -> defaultDPreference.setPrefBoolean(PREF_BYPASS_APPS, isChecked) tv_bypass_apps.setText(if (isChecked) R.string.switch_bypass_apps_on else R.string.switch_bypass_apps_off) } switch_bypass_apps.isChecked = defaultDPreference.getPrefBoolean(PREF_BYPASS_APPS, false) tv_bypass_apps.setText(if (switch_bypass_apps.isChecked) R.string.switch_bypass_apps_on else R.string.switch_bypass_apps_off) container_per_app_proxy.setOnClickListener { switch_bypass_apps.performClick() } container_bypass_apps.setOnClickListener { switch_bypass_apps.performClick() } } override fun onPause() { super.onPause() adapter?.let { defaultDPreference.setPrefStringSet(PREF_PER_APP_PROXY_SET, it.blacklist) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_bypass_list, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.select_all -> adapter?.let { val pkgNames = it.apps.map { it.packageName } if (it.blacklist.containsAll(pkgNames)) it.blacklist.clear() else it.blacklist.addAll(pkgNames) it.notifyDataSetChanged() true } ?: false else -> super.onOptionsItemSelected(item) } }
gpl-3.0
5f2820e8ab6cc71c97c135a16d8f4115
37.614907
118
0.594434
5.13719
false
false
false
false
kassisdion/workshpKotlin
app/src/main/java/com/eldorne/workshop/helper/WindowsHelper.kt
1
2003
package com.eldorne.workshop.helper import android.content.Context import android.os.Build import android.view.View import android.view.Window import android.view.WindowManager object WindowsHelper { /* ************************************************************************************************ ** Public fun ************************************************************************************************ */ fun setStatusBarTranslucent(window: Window, topView: View, makeTranslucent: Boolean) { if (isKitkatOrOver()) { if (makeTranslucent) { //Make status bar translucent window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) //Set padding to the root val context = topView.getContext() val statusBarHeight = getStatusBarHeight(context) // Set the padding to match the Status Bar height topView.setPadding(0, statusBarHeight, 0, 0) } else { //Remove status bar translucent window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) //Unset the padding topView.setPadding(0, 0, 0, 0) } } } /* ************************************************************************************************ ** Private fun ************************************************************************************************ */ private fun getStatusBarHeight(context: Context): Int { val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android") var result = 0 if (resourceId > 0) { result = context.resources.getDimensionPixelSize(resourceId) } return result } private fun isKitkatOrOver(): Boolean { return Build.VERSION.SDK_INT >= 19 } }
mit
1e582ef7e1ff68cc72c4c3dcdfaf2c2e
33.551724
100
0.462806
5.96131
false
false
false
false
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/entitymapper/UserListMapper.kt
1
2539
package net.simonvt.cathode.entitymapper import android.database.Cursor import android.text.TextUtils import net.simonvt.cathode.api.enumeration.Privacy import net.simonvt.cathode.api.enumeration.SortBy import net.simonvt.cathode.api.enumeration.SortOrientation import net.simonvt.cathode.common.data.MappedCursorLiveData import net.simonvt.cathode.common.database.getBoolean import net.simonvt.cathode.common.database.getInt import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.common.database.getString import net.simonvt.cathode.common.database.getStringOrNull import net.simonvt.cathode.entity.UserList import net.simonvt.cathode.provider.DatabaseContract.ListsColumns object UserListMapper : MappedCursorLiveData.CursorMapper<UserList> { override fun map(cursor: Cursor): UserList? { return if (cursor.moveToFirst()) mapList(cursor) else null } fun mapList(cursor: Cursor): UserList { val id = cursor.getLong(ListsColumns.ID) val name = cursor.getString(ListsColumns.NAME) val description = cursor.getStringOrNull(ListsColumns.DESCRIPTION) val privacyString = cursor.getStringOrNull(ListsColumns.PRIVACY) val privacy = if (!TextUtils.isEmpty(privacyString)) { Privacy.fromValue(privacyString!!) } else { Privacy.PRIVATE } val displayNumbers = cursor.getBoolean(ListsColumns.DISPLAY_NUMBERS) val allowComments = cursor.getBoolean(ListsColumns.ALLOW_COMMENTS) val sortByString = cursor.getStringOrNull(ListsColumns.SORT_BY) val sortBy = SortBy.fromValue(sortByString) val sortOrientationString = cursor.getStringOrNull(ListsColumns.SORT_ORIENTATION) val sortOrientation = SortOrientation.fromValue(sortOrientationString) val updatedAt = cursor.getLong(ListsColumns.UPDATED_AT) val likes = cursor.getInt(ListsColumns.LIKES) val slug = cursor.getStringOrNull(ListsColumns.SLUG) val traktId = cursor.getLong(ListsColumns.TRAKT_ID) return UserList( id, name, description, privacy, displayNumbers, allowComments, sortBy, sortOrientation, updatedAt, likes, slug, traktId ) } val projection = arrayOf( ListsColumns.ID, ListsColumns.NAME, ListsColumns.DESCRIPTION, ListsColumns.PRIVACY, ListsColumns.DISPLAY_NUMBERS, ListsColumns.ALLOW_COMMENTS, ListsColumns.SORT_BY, ListsColumns.SORT_ORIENTATION, ListsColumns.UPDATED_AT, ListsColumns.LIKES, ListsColumns.SLUG, ListsColumns.TRAKT_ID ) }
apache-2.0
8288754ea11cf4f11a17f592b7756ef8
33.310811
85
0.761323
4.296108
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/playback/LocalPlayback.kt
1
6458
package com.simplecity.amp_library.playback import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.media.AudioManager import android.support.annotation.CallSuper import android.util.Log import com.simplecity.amp_library.playback.Playback.Callbacks import com.simplecity.amp_library.playback.constants.MediaButtonCommand import com.simplecity.amp_library.playback.constants.ServiceCommand /** * A base class for local playback engines, which manages requesting/cancelling audio focus, and pausing, resuming or ducking * the audio in response to incoming calls/notifications etc. */ abstract class LocalPlayback(context: Context) : Playback { object Volume { /** * The volume we set the media player to when we lose audio focus, but are * allowed to reduce the volume instead of stopping playback. */ const val DUCK = 0.2f /** The volume we set the media player when we have audio focus. */ const val NORMAL = 1.0f } object AudioFocus { /** We don't have audio focus, and can't duck */ const val NO_FOCUS_NO_DUCK = "no_focus_no_duck" /** We don't have focus, but can duck */ const val NO_FOCUS_CAN_DUCK = "no_focus_can_duck" /** We have full audio focus */ const val FOCUSED = "focused" } internal var context: Context = context.applicationContext private val audioManager: AudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager private var playOnFocusGain: Boolean = false private var audioNoisyReceiverRegistered: Boolean = false private var currentAudioFocusState = AudioFocus.NO_FOCUS_NO_DUCK private val audioNoisyIntentFilter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY) override var callbacks: Callbacks? = null private val audioNoisyReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (AudioManager.ACTION_AUDIO_BECOMING_NOISY == intent.action) { Log.d(TAG, "Headphones disconnected.") if (isPlaying) { val intent = Intent(context, MusicService::class.java) intent.action = ServiceCommand.COMMAND intent.putExtra(MediaButtonCommand.CMD_NAME, ServiceCommand.PAUSE) context.startService(intent) } } } } private val onAudioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange -> Log.d(TAG, String.format("onAudioFocusChange. focusChange: %s", focusChange)) when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> currentAudioFocusState = AudioFocus.FOCUSED AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> // Audio focus was lost, but it's possible to duck (i.e.: play quietly) currentAudioFocusState = AudioFocus.NO_FOCUS_CAN_DUCK AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> { // Lost audio focus, but will gain it back (shortly), so note whether // playback should resume currentAudioFocusState = AudioFocus.NO_FOCUS_NO_DUCK playOnFocusGain = isPlaying } AudioManager.AUDIOFOCUS_LOSS -> // Lost audio focus, probably "permanently" currentAudioFocusState = AudioFocus.NO_FOCUS_NO_DUCK } // Update the player state based on the change configurePlayerState() } override fun willResumePlayback(): Boolean { // Fixme: This returns true even after manually pausing playback. This should not be the case. return playOnFocusGain } @CallSuper override fun pause(fade: Boolean) { unregisterAudioNoisyReceiver() } @CallSuper override fun stop() { playOnFocusGain = false giveUpAudioFocus() unregisterAudioNoisyReceiver() } @CallSuper override fun start() { playOnFocusGain = true tryToGetAudioFocus() registerAudioNoisyReceiver() } private fun tryToGetAudioFocus() { Log.d(TAG, "tryToGetAudioFocus") val result = audioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { currentAudioFocusState = AudioFocus.FOCUSED } else { currentAudioFocusState = AudioFocus.NO_FOCUS_NO_DUCK } } private fun giveUpAudioFocus() { Log.d(TAG, "giveUpAudioFocus") if (audioManager.abandonAudioFocus(onAudioFocusChangeListener) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { currentAudioFocusState = AudioFocus.NO_FOCUS_NO_DUCK } } private fun registerAudioNoisyReceiver() { if (!audioNoisyReceiverRegistered) { context.registerReceiver(audioNoisyReceiver, audioNoisyIntentFilter) audioNoisyReceiverRegistered = true } } private fun unregisterAudioNoisyReceiver() { if (audioNoisyReceiverRegistered) { context.unregisterReceiver(audioNoisyReceiver) audioNoisyReceiverRegistered = false } } private fun configurePlayerState() { Log.d(TAG, String.format("configurePlayerState() called. currentAudioFocusState: %s", currentAudioFocusState)) if (currentAudioFocusState == AudioFocus.NO_FOCUS_NO_DUCK) { // We don't have audio focus and can't duck, so we have to pause pause(false) } else { registerAudioNoisyReceiver() if (currentAudioFocusState == AudioFocus.NO_FOCUS_CAN_DUCK) { // We're permitted to play, but only if we 'duck', ie: play softly Log.d(TAG, "Adjusting volume: DUCK") setVolume(Volume.DUCK) } else { Log.d(TAG, "Adjusting volume: Normal") setVolume(Volume.NORMAL) } // If we were playing when we lost focus, we need to resume playing. if (playOnFocusGain) { start() playOnFocusGain = false } } } companion object { const val TAG = "LocalPlayback" } }
gpl-3.0
4dfb1a264b4a48fb606483b78532ee45
35.908571
136
0.647879
4.851991
false
false
false
false
cedardevs/onestop
buildSrc/src/main/kotlin/PackageJSON.kt
1
3545
import com.google.gson.Gson import com.google.gson.JsonObject import org.gradle.api.DefaultTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.TaskAction import java.io.File import java.io.FileWriter data class PackageJSON( val name: String, val version: String, val description: String, val author: String, val license: String, val homepage: String, val repositoryUrl: String, val repositoryDirectory: String, val bugsUrl: String ) open class PackageJSONTask : DefaultTask() { @Input var updates: PackageJSON? = null // utilities to help keep values in package.json files up-to-date with gradle values private fun updatePackageJSON(filePath: String, packageJSON: PackageJSON?): Boolean { // nothing given to update if(packageJSON == null) { return false } // create Gson instance for deserializing/serializing val gson = Gson() try { // read the JSON file as a string val jsonString: String = File(filePath).readText(Charsets.UTF_8) // deserialize JSON file into JsonObject val jsonObject = gson.fromJson(jsonString, JsonObject::class.java) // update root-level keys jsonObject.addProperty("name", packageJSON.name) // Node package version must be formatted as strict semantic version, // so if it's not valid, we fall back the package.json version to '0.0.0'. // This shouldn't be the case for a valid tag/release; however, we don't // publish to a public NPM registry during builds, anyway. val semVerPattern: Regex = "[1-9]\\d*\\.\\d+\\.\\d+(?:-[a-zA-Z0-9]+)?".toRegex() val isSemVer: Boolean = semVerPattern.matches(packageJSON.version) val semVer: String = if(isSemVer) packageJSON.version else "0.0.0" jsonObject.addProperty("version", semVer) jsonObject.addProperty("description", packageJSON.description) jsonObject.addProperty("author", packageJSON.author) jsonObject.addProperty("license", packageJSON.license) jsonObject.addProperty("homepage", packageJSON.homepage) // update keys under 'repository' section val repository: JsonObject = jsonObject.getAsJsonObject("repository") repository.addProperty("url", packageJSON.repositoryUrl) repository.addProperty("directory", packageJSON.repositoryDirectory) // update keys under 'bugs' section jsonObject.getAsJsonObject("bugs").addProperty("url", packageJSON.bugsUrl) // re-serialize updated JSON and write back to original file with pretty formatting FileWriter(filePath, Charsets.UTF_8).use { writer -> gson.newBuilder().setPrettyPrinting().create().toJson(jsonObject, writer) } } catch(e: Exception) { // if anything goes wrong in the process, return false return false } return true } @TaskAction fun update() { logger.lifecycle("Running 'updatePackageJSON' task on ${project.name}") val packageJsonPath = project.projectDir.absolutePath + "/package.json" logger.warn("packageJsonPath = $packageJsonPath") if(!updatePackageJSON(packageJsonPath, updates)) { logger.warn("'WARNING: package.json' was NOT updated in '${project.name}'") } } }
gpl-2.0
ffad7ee290b374d04536154dc9ad5bb4
37.967033
95
0.63921
4.764785
false
false
false
false
pavelaizen/SoundZones
app/src/main/java/com/gm/soundzones/excel/DataProvider.kt
1
5478
package com.gm.soundzones.excel import android.content.Context import android.os.Environment import com.gm.soundzones.model.SoundRun import com.gm.soundzones.model.SoundSet import com.gm.soundzones.model.SoundTrack import com.gm.soundzones.model.User import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.sync.Mutex import kotlinx.coroutines.experimental.sync.withLock import org.apache.poi.hssf.usermodel.HSSFDateUtil import org.apache.poi.ss.usermodel.* import org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING import org.apache.poi.xssf.usermodel.XSSFWorkbook import java.io.File import java.text.SimpleDateFormat import java.util.* object DataProvider { private const val NOISE_SUFFIX = "_noise" private const val EXCEL_NAME = "tablet_input.xlsx" private lateinit var sheet: Sheet private lateinit var formulaEvaluator: FormulaEvaluator private val TOTAL_RUNS = 5 private val SETS_IN_RUN = 9 private val SOUND_SET_ROWS = 5 private val CELLS_IN_RUN = SOUND_SET_ROWS * SETS_IN_RUN + 1 // +1 for run# column private var workbook: Workbook? = null val excelFile = File(Environment.getExternalStorageDirectory(), "output.xlsx") private val defaultVolumeLevels = HashMap<String, Int>() fun setDefaultVolume(dirName: String, hasNoise: Boolean, volume: Int) = defaultVolumeLevels.put(if (hasNoise) dirName.plus(NOISE_SUFFIX) else dirName, volume) fun getDefaultVolume(dirName: String, hasNoise: Boolean): Int? = defaultVolumeLevels[if (hasNoise) dirName.plus(NOISE_SUFFIX) else dirName] fun setup(context: Context) { (excelFile.takeIf { excelFile.exists() }?.inputStream() ?: context.assets.open(EXCEL_NAME)).also { stream -> workbook = XSSFWorkbook(stream).also { sheet = it.getSheetAt(0) formulaEvaluator = it.creationHelper.createFormulaEvaluator() } stream.close() } // workbook?.getSheetAt(0)?.getRow(0)?.getCell(15)?.setCellValue("123") } fun getUser(id: Int): User = sheet.getRow(id).let { User(getCellAsString(it, 1, formulaEvaluator).toDouble().toInt(), Array<SoundRun>(TOTAL_RUNS) { index -> val position = index * CELLS_IN_RUN + 2 collectSoundRun(it, formulaEvaluator, position) }) } fun applyVolumeAccept(id: Int, runId: String, setIndex: Int, volume: Int) { sheet.getRow(id)?.let { row -> row.find { it.cellType == CELL_TYPE_STRING && it.stringCellValue == runId }?.columnIndex?.let { val volumeCellIndex = it + ((setIndex + 1) * SOUND_SET_ROWS) - 1 row.getCell(volumeCellIndex)?.setCellValue(volume.toString()).also { saveToFile() } } } } fun applyVolumeGreat(id: Int, runId: String, setIndex: Int, volume: Int) { sheet.getRow(id)?.let { row -> row.find { it.cellType == CELL_TYPE_STRING && it.stringCellValue == runId }?.columnIndex?.let { val volumeCellIndex = it + ((setIndex + 1) * SOUND_SET_ROWS) row.getCell(volumeCellIndex)?.setCellValue(volume.toString()).also { saveToFile() } } } } private val lock = Mutex() private fun saveToFile() { launch(CommonPool) { lock.withLock { excelFile.takeUnless { it.exists() }?.createNewFile() val os = excelFile.outputStream() workbook?.write(os) os.close() } } } private fun collectSoundRun(row: Row, formulaEvaluator: FormulaEvaluator, cellNumber: Int): SoundRun { val soundSets = Array<SoundSet>(SETS_IN_RUN) { val position = cellNumber.inc() + (it * SOUND_SET_ROWS) collectSoundSet(row, formulaEvaluator, position) } val runId = getCellAsString(row, cellNumber, formulaEvaluator) return SoundRun(runId, soundSets) } private fun collectSoundSet(row: Row, formulaEvaluator: FormulaEvaluator, startingCell: Int): SoundSet { val pair = getCellAsString(row, startingCell, formulaEvaluator) val primary = getCellAsString(row, startingCell + 1, formulaEvaluator) val secondary = getCellAsString(row, startingCell + 2, formulaEvaluator) return SoundSet(pair, SoundTrack(primary), SoundTrack(secondary)) } private fun getCellAsString(row: Row, c: Int, formulaEvaluator: FormulaEvaluator) = row.getCell(c).let { cell -> formulaEvaluator.evaluate(cell)?.let { cellValue -> when (cellValue.cellType) { Cell.CELL_TYPE_BOOLEAN -> cellValue.booleanValue.toString() Cell.CELL_TYPE_NUMERIC -> SimpleDateFormat("dd/MM/yy", Locale.US) .takeIf { HSSFDateUtil.isCellDateFormatted(cell) }?.format(HSSFDateUtil.getJavaDate(cellValue.numberValue)) ?: cellValue.numberValue.toString() Cell.CELL_TYPE_STRING -> cellValue.stringValue else -> cellValue.stringValue } } ?: "" } }
apache-2.0
18146d9225606683515110a75b060270
41.146154
143
0.616831
4.26968
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/backup/TasksJsonExporter.kt
1
7095
package org.tasks.backup import android.app.Activity import android.app.ProgressDialog import android.app.backup.BackupManager import android.content.Context import android.net.Uri import android.os.Handler import com.google.common.io.Files import com.google.gson.Gson import com.google.gson.GsonBuilder import com.todoroo.andlib.utility.DialogUtilities import com.todoroo.astrid.data.Task import org.tasks.BuildConfig import org.tasks.R import org.tasks.backup.BackupContainer.TaskBackup import org.tasks.caldav.VtodoCache import org.tasks.data.* import org.tasks.date.DateTimeUtils.newDateTime import org.tasks.extensions.Context.toast import org.tasks.files.FileHelper import org.tasks.jobs.WorkManager import org.tasks.preferences.Preferences import timber.log.Timber import java.io.File import java.io.IOException import java.io.OutputStream import java.io.OutputStreamWriter import java.nio.charset.Charset import javax.inject.Inject class TasksJsonExporter @Inject constructor( private val tagDataDao: TagDataDao, private val taskDao: TaskDao, private val userActivityDao: UserActivityDao, private val preferences: Preferences, private val alarmDao: AlarmDao, private val locationDao: LocationDao, private val tagDao: TagDao, private val googleTaskDao: GoogleTaskDao, private val filterDao: FilterDao, private val googleTaskListDao: GoogleTaskListDao, private val taskAttachmentDao: TaskAttachmentDao, private val caldavDao: CaldavDao, private val workManager: WorkManager, private val taskListMetadataDao: TaskListMetadataDao, private val vtodoCache: VtodoCache, ) { private var context: Context? = null private var exportCount = 0 private var progressDialog: ProgressDialog? = null private var handler: Handler? = null private fun post(runnable: () -> Unit) = handler?.post(runnable) private fun setProgress(taskNumber: Int, total: Int) = post { progressDialog?.max = total progressDialog?.progress = taskNumber } suspend fun exportTasks(context: Context?, exportType: ExportType, progressDialog: ProgressDialog?) { this.context = context exportCount = 0 this.progressDialog = progressDialog if (exportType == ExportType.EXPORT_TYPE_MANUAL) { handler = Handler() } runBackup(exportType) } private suspend fun runBackup(exportType: ExportType) { try { val filename = getFileName(exportType) val tasks = taskDao.getAll() val file = File(String.format("%s/%s", context!!.filesDir, BackupConstants.INTERNAL_BACKUP)) file.delete() file.createNewFile() val internalStorageBackup = Uri.fromFile(file) val os = context!!.contentResolver.openOutputStream(internalStorageBackup) doTasksExport(os, tasks) os!!.close() val externalStorageBackup = FileHelper.newFile( context!!, preferences.backupDirectory!!, MIME, Files.getNameWithoutExtension(filename), EXTENSION) FileHelper.copyStream(context!!, internalStorageBackup, externalStorageBackup) workManager.scheduleDriveUpload(externalStorageBackup, exportType == ExportType.EXPORT_TYPE_SERVICE) BackupManager(context).dataChanged() if (exportType == ExportType.EXPORT_TYPE_MANUAL) { onFinishExport(filename) } } catch (e: IOException) { Timber.e(e) } finally { post { if (progressDialog != null && progressDialog!!.isShowing && context is Activity) { DialogUtilities.dismissDialog(context as Activity?, progressDialog) } } } } @Throws(IOException::class) private suspend fun doTasksExport(os: OutputStream?, tasks: List<Task>) { val taskBackups: MutableList<TaskBackup> = ArrayList() for (task in tasks) { setProgress(taskBackups.size, tasks.size) val taskId = task.id val caldavTasks = caldavDao.getTasks(taskId) taskBackups.add( TaskBackup( task, alarmDao.getAlarms(taskId), locationDao.getGeofencesForTask(taskId), tagDao.getTagsForTask(taskId), googleTaskDao.getAllByTaskId(taskId), userActivityDao.getComments(taskId), taskAttachmentDao.getAttachmentsForTask(taskId), caldavTasks, vtodoCache.getVtodo( caldavTasks.firstOrNull { !it.isDeleted() }) )) } val data: MutableMap<String, Any> = HashMap() data["version"] = BuildConfig.VERSION_CODE data["timestamp"] = System.currentTimeMillis() data["data"] = BackupContainer( taskBackups, locationDao.getPlaces(), tagDataDao.getAll(), filterDao.getFilters(), googleTaskListDao.getAccounts(), googleTaskListDao.getAllLists(), caldavDao.getAccounts(), caldavDao.getCalendars(), taskListMetadataDao.getAll(), taskAttachmentDao.getAttachments(), preferences.getPrefs(Integer::class.java), preferences.getPrefs(java.lang.Long::class.java), preferences.getPrefs(String::class.java), preferences.getPrefs(java.lang.Boolean::class.java), preferences.getPrefs(java.util.Set::class.java), ) val out = OutputStreamWriter(os, UTF_8) val gson = if (BuildConfig.DEBUG) GsonBuilder().setPrettyPrinting().create() else Gson() out.write(gson.toJson(data)) out.close() exportCount = taskBackups.size } private fun onFinishExport(outputFile: String) = post { context?.toast( R.string.export_toast, context!! .resources .getQuantityString(R.plurals.Ntasks, exportCount, exportCount), outputFile ) } private fun getFileName(type: ExportType): String = when (type) { ExportType.EXPORT_TYPE_SERVICE -> String.format(BackupConstants.BACKUP_FILE_NAME, dateForExport) ExportType.EXPORT_TYPE_MANUAL -> String.format(BackupConstants.EXPORT_FILE_NAME, dateForExport) } enum class ExportType { EXPORT_TYPE_SERVICE, EXPORT_TYPE_MANUAL } companion object { val UTF_8: Charset = Charset.forName("UTF-8") private const val MIME = "application/json" private const val EXTENSION = ".json" private val dateForExport: String get() = newDateTime().toString("yyMMdd-HHmm") } }
gpl-3.0
1bac47d679f8fdcb841ced9c3b45d72e
37.989011
112
0.627625
4.903248
false
false
false
false
arturbosch/detekt
detekt-rules-complexity/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/LongParameterList.kt
1
5655
package io.gitlab.arturbosch.detekt.rules.complexity import io.gitlab.arturbosch.detekt.api.AnnotationExcluder import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Metric import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell import io.gitlab.arturbosch.detekt.api.UnstableApi import io.gitlab.arturbosch.detekt.api.config import io.gitlab.arturbosch.detekt.api.configWithFallback import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault import io.gitlab.arturbosch.detekt.api.internal.Configuration import io.gitlab.arturbosch.detekt.rules.isOverride import org.jetbrains.kotlin.psi.KtAnnotated import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtParameterList import org.jetbrains.kotlin.psi.KtPrimaryConstructor import org.jetbrains.kotlin.psi.KtSecondaryConstructor /** * Reports functions and constructors which have more parameters than a certain threshold. */ @ActiveByDefault(since = "1.0.0") class LongParameterList(config: Config = Config.empty) : Rule(config) { override val issue = Issue( "LongParameterList", Severity.Maintainability, "The more parameters a function has the more complex it is. Long parameter lists are often " + "used to control complex algorithms and violate the Single Responsibility Principle. " + "Prefer functions with short parameter lists.", Debt.TWENTY_MINS ) @Deprecated("Use `functionThreshold` and `constructorThreshold` instead") @Configuration("number of parameters required to trigger the rule") private val threshold: Int by config(DEFAULT_FUNCTION_THRESHOLD) @Suppress("DEPRECATION") @OptIn(UnstableApi::class) @Configuration("number of function parameters required to trigger the rule") private val functionThreshold: Int by configWithFallback(::threshold, DEFAULT_FUNCTION_THRESHOLD) @Suppress("DEPRECATION") @OptIn(UnstableApi::class) @Configuration("number of constructor parameters required to trigger the rule") private val constructorThreshold: Int by configWithFallback(::threshold, DEFAULT_CONSTRUCTOR_THRESHOLD) @Configuration("ignore parameters that have a default value") private val ignoreDefaultParameters: Boolean by config(false) @Configuration("ignore long constructor parameters list for data classes") private val ignoreDataClasses: Boolean by config(true) @Configuration( "ignore the annotated parameters for the count (e.g. `fun foo(@Value bar: Int)` would not be counted" ) private val ignoreAnnotatedParameter: List<String> by config(emptyList<String>()) { list -> list.map { it.removePrefix("*").removeSuffix("*") } } private lateinit var annotationExcluder: AnnotationExcluder override fun visitKtFile(file: KtFile) { annotationExcluder = AnnotationExcluder(file, ignoreAnnotatedParameter) super.visitKtFile(file) } override fun visitNamedFunction(function: KtNamedFunction) { checkLongParameterList(function, functionThreshold, "function ${function.nameAsSafeName}") } override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) { validateConstructor(constructor) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { validateConstructor(constructor) } private fun KtAnnotated.isIgnored(): Boolean { return annotationExcluder.shouldExclude(annotationEntries) } private fun validateConstructor(constructor: KtConstructor<*>) { val owner = constructor.getContainingClassOrObject() if (owner is KtClass && owner.isDataClassOrIgnored()) { return } checkLongParameterList(constructor, constructorThreshold, "constructor") } private fun KtClass.isDataClassOrIgnored() = ignoreDataClasses && isData() private fun checkLongParameterList(function: KtFunction, threshold: Int, identifier: String) { if (function.isOverride()) return val parameterList = function.valueParameterList ?: return val parameterNumber = parameterList.parameterCount() if (parameterNumber >= threshold) { val parameterPrint = function.valueParameters.joinToString(separator = ", ") { it.nameAsSafeName.identifier + ": " + it.typeReference?.text } report( ThresholdedCodeSmell( issue, Entity.from(parameterList), Metric("SIZE", parameterNumber, threshold), "The $identifier($parameterPrint) has too many parameters. " + "The current threshold is set to $threshold." ) ) } } private fun KtParameterList.parameterCount(): Int { val preFilteredParameters = parameters.filter { !it.isIgnored() } return if (ignoreDefaultParameters) { preFilteredParameters.count { !it.hasDefaultValue() } } else { preFilteredParameters.size } } companion object { private const val DEFAULT_FUNCTION_THRESHOLD = 6 private const val DEFAULT_CONSTRUCTOR_THRESHOLD = 7 } }
apache-2.0
17417ec0f44829b14912478faf815e81
40.277372
109
0.721662
4.982379
false
true
false
false
nemerosa/ontrack
ontrack-extension-auto-versioning/src/test/java/net/nemerosa/ontrack/extension/av/validation/AutoVersioningValidationServiceIT.kt
1
14699
package net.nemerosa.ontrack.extension.av.validation import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.extension.av.AbstractAutoVersioningTestSupport import net.nemerosa.ontrack.extension.general.autoValidationStampProperty import net.nemerosa.ontrack.extension.scm.service.TestSCMExtension import net.nemerosa.ontrack.model.structure.Build import org.junit.jupiter.api.Test import org.junit.jupiter.api.fail import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue internal class AutoVersioningValidationServiceIT : AbstractAutoVersioningTestSupport() { @Autowired private lateinit var autoVersioningValidationService: AutoVersioningValidationService @Autowired private lateinit var testSCMExtension: TestSCMExtension @Test fun `Check and validate for no configuration at all`() { project { branch { val build = build() val data = autoVersioningValidationService.checkAndValidate(build) assertTrue(data.isEmpty(), "No data returned") } } } @Test fun `Check and validate for no configuration`() { project { branch { setAutoVersioning { // No configuration } val build = build() val data = autoVersioningValidationService.checkAndValidate(build) assertTrue(data.isEmpty(), "No data returned") } } } @Test fun `Check and validate for no validation stamp`() { project { branch { setAutoVersioning { autoVersioningConfig { project = "source" branch = "main" promotion = "GOLD" validationStamp = null } } val build = build() val data = autoVersioningValidationService.checkAndValidate(build) assertTrue(data.isEmpty(), "No data returned") } } } @Test fun `Check and validate for outdated dependency read from the linked build with auto validation`() { val (linkedBuild430, _) = project<Pair<Build, Build>> { branch<Pair<Build, Build>>("main") { val gold = promotionLevel("GOLD") val b430 = build("4.3.0") b430.promote(gold) val b431 = build("4.3.1") b431.promote(gold) b430 to b431 } } project { branch { autoValidationStampProperty(project, autoCreateIfNotPredefined = true) setAutoVersioning { autoVersioningConfig { project = linkedBuild430.project.name branch = linkedBuild430.branch.name promotion = "GOLD" validationStamp = "auto" } } val build = build() build.linkTo(linkedBuild430) val data = autoVersioningValidationService.checkAndValidate(build) assertNotNull(data.firstOrNull(), "One validation") { validationData -> assertEquals(linkedBuild430.project.name, validationData.project) assertEquals("4.3.0", validationData.version) assertEquals("4.3.1", validationData.latestVersion) assertEquals("gradle.properties", validationData.path) assertTrue(validationData.time > 0) } val vs = structureService.findValidationStampByName( build.project.name, build.branch.name, "auto-versioning-${linkedBuild430.project.name}" ).getOrNull() ?: fail("Getting the auto versioning validation stamp") val run = structureService.getValidationRunsForBuildAndValidationStamp(build.id, vs.id, 0, 1).firstOrNull() assertNotNull(run, "Validation has been created") { assertEquals("FAILED", it.lastStatusId, "Validation failed") } } } } @Test fun `Check and validate for outdated dependency read from the linked build with existing validation stamp`() { val (linkedBuild430, _) = project<Pair<Build, Build>> { branch<Pair<Build, Build>>("main") { val gold = promotionLevel("GOLD") val b430 = build("4.3.0") b430.promote(gold) val b431 = build("4.3.1") b431.promote(gold) b430 to b431 } } project { branch { val vs = validationStamp() autoValidationStampProperty(project, autoCreateIfNotPredefined = true) setAutoVersioning { autoVersioningConfig { project = linkedBuild430.project.name branch = linkedBuild430.branch.name promotion = "GOLD" validationStamp = vs.name } } val build = build() build.linkTo(linkedBuild430) run(""" mutation { checkAutoVersioning(input: { project: "${build.project.name}", branch: "${build.branch.name}", build: "${build.name}", }) { errors { message } } } """) { data -> checkGraphQLUserErrors(data, "checkAutoVersioning") } val run = structureService.getValidationRunsForBuildAndValidationStamp(build.id, vs.id, 0, 1).firstOrNull() assertNotNull(run, "Validation has been created") { assertEquals("FAILED", it.lastStatusId, "Validation failed") } } } } @Test fun `Check and validate for up-to-date dependency read from the linked build with existing validation stamp`() { val (linkedBuild430, linkedBuild431) = project<Pair<Build, Build>> { branch<Pair<Build, Build>>("main") { val gold = promotionLevel("GOLD") val b430 = build("4.3.0") b430.promote(gold) val b431 = build("4.3.1") b431.promote(gold) b430 to b431 } } project { branch { val vs = validationStamp() autoValidationStampProperty(project, autoCreateIfNotPredefined = true) setAutoVersioning { autoVersioningConfig { project = linkedBuild430.project.name branch = linkedBuild430.branch.name promotion = "GOLD" validationStamp = vs.name } } val build = build() build.linkTo(linkedBuild431) val data = autoVersioningValidationService.checkAndValidate(build) assertNotNull(data.firstOrNull(), "One validation") { validationData -> assertEquals(linkedBuild430.project.name, validationData.project) assertEquals("4.3.1", validationData.version) assertEquals("4.3.1", validationData.latestVersion) assertEquals("gradle.properties", validationData.path) assertTrue(validationData.time > 0) } val run = structureService.getValidationRunsForBuildAndValidationStamp(build.id, vs.id, 0, 1).firstOrNull() assertNotNull(run, "Validation has been created") { assertEquals("PASSED", it.lastStatusId, "Validation passed") } } } } @Test fun `Check and validate using GraphQL for up-to-date dependency read from the linked build with existing validation stamp`() { val (linkedBuild430, linkedBuild431) = project<Pair<Build, Build>> { branch<Pair<Build, Build>>("main") { val gold = promotionLevel("GOLD") val b430 = build("4.3.0") b430.promote(gold) val b431 = build("4.3.1") b431.promote(gold) b430 to b431 } } project { branch { val vs = validationStamp() autoValidationStampProperty(project, autoCreateIfNotPredefined = true) setAutoVersioning { autoVersioningConfig { project = linkedBuild430.project.name branch = linkedBuild430.branch.name promotion = "GOLD" validationStamp = vs.name } } val build = build() build.linkTo(linkedBuild431) val data = autoVersioningValidationService.checkAndValidate(build) assertNotNull(data.firstOrNull(), "One validation") { validationData -> assertEquals(linkedBuild430.project.name, validationData.project) assertEquals("4.3.1", validationData.version) assertEquals("4.3.1", validationData.latestVersion) assertEquals("gradle.properties", validationData.path) assertTrue(validationData.time > 0) } val run = structureService.getValidationRunsForBuildAndValidationStamp(build.id, vs.id, 0, 1).firstOrNull() assertNotNull(run, "Validation has been created") { assertEquals("PASSED", it.lastStatusId, "Validation passed") } } } } @Test fun `Check and validate using GraphQL for up-to-date dependency read from the linked build with non existing validation stamp`() { val (linkedBuild430, linkedBuild431) = project<Pair<Build, Build>> { branch<Pair<Build, Build>>("main") { val gold = promotionLevel("GOLD") val b430 = build("4.3.0") b430.promote(gold) val b431 = build("4.3.1") b431.promote(gold) b430 to b431 } } project { branch { val vs = validationStamp() // autoValidationStampProperty(project, autoCreateIfNotPredefined = true) setAutoVersioning { autoVersioningConfig { project = linkedBuild430.project.name branch = linkedBuild430.branch.name promotion = "GOLD" validationStamp = vs.name } } val build = build() build.linkTo(linkedBuild431) val data = autoVersioningValidationService.checkAndValidate(build) assertNotNull(data.firstOrNull(), "One validation") { validationData -> assertEquals(linkedBuild430.project.name, validationData.project) assertEquals("4.3.1", validationData.version) assertEquals("4.3.1", validationData.latestVersion) assertEquals("gradle.properties", validationData.path) assertTrue(validationData.time > 0) } val run = structureService.getValidationRunsForBuildAndValidationStamp(build.id, vs.id, 0, 1).firstOrNull() assertNotNull(run, "Validation has been created") { assertEquals("PASSED", it.lastStatusId, "Validation passed") } } } } @Test fun `Check and validate for up-to-date dependency read from the SCM with existing validation stamp`() { val (linkedBuild430, linkedBuild431) = project<Pair<Build, Build>> { branch<Pair<Build, Build>>("main") { val gold = promotionLevel("GOLD") val b430 = build("4.3.0") b430.promote(gold) val b431 = build("4.3.1") b431.promote(gold) b430 to b431 } } project { branch { testSCMExtension.registerProjectForTestSCM(project) { withFile("gradle.properties", branch = name) { "version = 4.3.1" } } val vs = validationStamp() autoValidationStampProperty(project, autoCreateIfNotPredefined = true) setAutoVersioning { autoVersioningConfig { project = linkedBuild430.project.name branch = linkedBuild430.branch.name promotion = "GOLD" validationStamp = vs.name } } val build = build() val data = autoVersioningValidationService.checkAndValidate(build) assertNotNull(data.firstOrNull(), "One validation") { validationData -> assertEquals(linkedBuild430.project.name, validationData.project) assertEquals("4.3.1", validationData.version) assertEquals("4.3.1", validationData.latestVersion) assertEquals("gradle.properties", validationData.path) assertTrue(validationData.time > 0) } val run = structureService.getValidationRunsForBuildAndValidationStamp(build.id, vs.id, 0, 1).firstOrNull() assertNotNull(run, "Validation has been created") { assertEquals("PASSED", it.lastStatusId, "Validation passed") } // Checks that the build link has been created structureService.isLinkedTo(build, linkedBuild431.project.name, linkedBuild431.name) } } } }
mit
649cb5fc5bc50644543e67cf6e02466c
39.273973
134
0.523165
5.532179
false
true
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/typing/RsEnterInLineCommentHandler.kt
1
4668
package org.rust.ide.typing import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate.Result import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.util.Ref import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.TokenType.WHITE_SPACE import com.intellij.util.text.CharArrayUtil import org.rust.lang.core.parser.RustParserDefinition.Companion.EOL_COMMENT import org.rust.lang.core.parser.RustParserDefinition.Companion.INNER_EOL_DOC_COMMENT import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.ext.elementType import org.rust.lang.doc.psi.RsDocKind class RsEnterInLineCommentHandler : EnterHandlerDelegateAdapter() { override fun preprocessEnter( file: PsiFile, editor: Editor, caretOffsetRef: Ref<Int>, caretAdvanceRef: Ref<Int>, dataContext: DataContext, originalHandler: EditorActionHandler? ): Result { // return if this is not a Rust file if (file !is RsFile) { return Result.Continue } // get current document and commit any changes, so we'll get latest PSI val document = editor.document PsiDocumentManager.getInstance(file.project).commitDocument(document) val caretOffset = caretOffsetRef.get() val text = document.charsSequence // skip following spaces and tabs val offset = CharArrayUtil.shiftForward(text, caretOffset, " \t") // figure out if the caret is at the end of the line val isEOL = offset < text.length && text[offset] == '\n' // find the PsiElement at the caret var elementAtCaret = file.findElementAt(offset) ?: return Result.Continue if (isEOL && elementAtCaret.isEolWhitespace(offset)) { // ... or the previous one if this is end-of-line whitespace elementAtCaret = elementAtCaret.prevSibling ?: return Result.Continue } // check if the element at the caret is a line comment // and extract the comment token (//, /// or //!) from the comment text val prefix = when (elementAtCaret.elementType) { OUTER_EOL_DOC_COMMENT -> RsDocKind.OuterEol.prefix INNER_EOL_DOC_COMMENT -> RsDocKind.InnerEol.prefix EOL_COMMENT -> { // return if caret is at end of line for a non-documentation comment if (isEOL) { return Result.Continue } "//" } else -> return Result.Continue } // If caret is currently inside some prefix, do nothing. if (offset < elementAtCaret.textOffset + prefix.length) { return Result.Continue } if (text.startsWith(prefix, offset)) { // If caret is currently at the beginning of some sequence which // starts the same as our prefix, we are at one of these situations: // a) // comment // <caret>// comment // b) // comment <caret>//comment // Here, we don't want to insert any prefixes, as there is already one // in code. We only have to insert space after prefix if it's missing // and update caret position. val afterPrefix = offset + prefix.length if (afterPrefix < document.textLength && text[afterPrefix] != ' ') { document.insertString(afterPrefix, " ") } caretOffsetRef.set(offset) } else { // Otherwise; add one space, if caret isn't at one // currently, and insert prefix just before it. val prefixToAdd = if (text[caretOffset] != ' ') prefix + ' ' else prefix document.insertString(caretOffset, prefixToAdd) caretAdvanceRef.set(prefixToAdd.length) } return Result.Default } // Returns true for // ``` // fooo <caret> // // // ``` // // Returns false for // ``` // fooo // // <caret> // ``` private fun PsiElement.isEolWhitespace(caretOffset: Int): Boolean { if (node?.elementType != WHITE_SPACE) return false val pos = node.text.indexOf('\n') return pos == -1 || caretOffset <= pos + textRange.startOffset } }
mit
e1c2f3c9790a6554e15265116214ff41
38.226891
85
0.634533
4.644776
false
false
false
false
FranPregernik/radarsimulator
designer/src/main/kotlin/hr/franp/rsim/Main.kt
1
1289
package hr.franp.rsim import javafx.stage.Stage import org.controlsfx.glyphfont.FontAwesome import org.controlsfx.glyphfont.GlyphFont import org.controlsfx.glyphfont.GlyphFontRegistry import org.slf4j.bridge.SLF4JBridgeHandler import tornadofx.* class Main : App(DesignerView::class, Styles::class) { val radarScreenView = find(RadarScreenView::class) val simController = find(SimulatorController::class) init { // Optionally remove existing handlers attached to j.u.l root logger SLF4JBridgeHandler.removeHandlersForRootLogger() // (since SLF4J 1.6.5) // add SLF4JBridgeHandler to j.u.l's root logger, should be done once during // the initialization phase of your application SLF4JBridgeHandler.install() reloadStylesheetsOnFocus() val faStream = Main::class.java.getResourceAsStream("/fontawesome-webfont.ttf") val fa: GlyphFont = FontAwesome(faStream) GlyphFontRegistry.register(fa) } override fun start(stage: Stage) { super.start(stage.apply { minWidth = 1240.0 minHeight = 768.0 isFullScreen = true }) } override fun stop() { radarScreenView.onUndock() simController.close() super.stop() } }
apache-2.0
246b1b50b363cd0be300ad1f5311948b
28.976744
87
0.683476
4.13141
false
false
false
false
ptrgags/holo-pyramid
app/src/main/java/io/github/ptrgags/holopyramid/ModelSelectActivity.kt
1
1726
package io.github.ptrgags.holopyramid import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ListView class ModelSelectActivity : AppCompatActivity() { /** Display names for each model */ private val modelNames = listOf( "Utah Teapot", "Icosahedron", "Spider", "Steam Train") /** Corresponding resource IDs */ private val modelIds = listOf( R.raw.utah_teapot_obj, R.raw.icosahedron_obj, R.raw.spider_obj, R.raw.steam_train_obj) /** reference to the list view */ lateinit var listView: ListView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_model_select) // Set a custom title for the activity. setTitle(R.string.model_select_label) // Save a reference to the list view listView = findViewById(R.id.model_select_list) as ListView // Make a list item for each model listView.adapter = ArrayAdapter( this, android.R.layout.simple_list_item_1, modelNames) // When a model name is tapped, go to the hologram activity // and pass in the model ID. val context: Context = this listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, i, _ -> val modelId = modelIds[i] val intent = Intent(context, HoloPyramidActivity::class.java) intent.putExtra("model_id", modelId) startActivity(intent) } } }
gpl-3.0
fea33556a0424ae5185b2e904c736f44
33.52
73
0.654693
4.261728
false
false
false
false
is00hcw/anko
dsl/src/org/jetbrains/android/anko/utils/SignatureParser.kt
2
5296
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.utils import org.objectweb.asm.Opcodes import org.objectweb.asm.signature.SignatureReader import org.objectweb.asm.signature.SignatureVisitor import java.util.* interface Classifier data class BaseType(val descriptor: Char) : Classifier interface NamedClass : Classifier data class TopLevelClass(val internalName: String) : NamedClass data class InnerClass(val outer: GenericType, val name: String) : NamedClass data class TypeVariable(val name: String) : Classifier object ArrayC : Classifier enum class Wildcard { SUPER, // ? super X EXTENDS // ? extends X } interface TypeArgument data class BoundedWildcard(val wildcard: Wildcard, val bound: GenericType) : TypeArgument object UnboundedWildcard : TypeArgument data class NoWildcard(val genericType: GenericType) : TypeArgument interface GenericType { val classifier: Classifier val arguments: List<TypeArgument> } class GenericTypeImpl : GenericType { var classifierVar: Classifier? = null override val arguments: MutableList<TypeArgument> = ArrayList() override val classifier: Classifier get() = classifierVar!! override fun toString(): String = "$classifier<${arguments.joinToString(separator = ", ")}>" } class TypeParameter(val name: String, val upperBounds: List<GenericType>) class ValueParameter(val index: Int, val genericType: GenericType) class GenericMethodSignature( val typeParameters: List<TypeParameter>, val returnType: GenericType, val valueParameters: List<ValueParameter> ) fun parseGenericMethodSignature(signature: String): GenericMethodSignature { val typeParameters = ArrayList<TypeParameter>() val returnType = GenericTypeImpl() val valueParameters = ArrayList<ValueParameter>() SignatureReader(signature).accept( object : SignatureVisitor(Opcodes.ASM4) { var bounds = ArrayList<GenericType>() public override fun visitFormalTypeParameter(name: String) { bounds = ArrayList<GenericType>() var param = TypeParameter(name, bounds) typeParameters.add(param) } public override fun visitClassBound(): SignatureVisitor { val bound = GenericTypeImpl() bounds.add(bound) return GenericTypeParser(bound) } public override fun visitInterfaceBound(): SignatureVisitor { val bound = GenericTypeImpl() bounds.add(bound) return GenericTypeParser(bound) } public override fun visitParameterType(): SignatureVisitor { val parameterType = GenericTypeImpl() val param = ValueParameter(valueParameters.size(), parameterType) valueParameters.add(param) return GenericTypeParser(parameterType) } public override fun visitReturnType(): SignatureVisitor { return GenericTypeParser(returnType) } } ) return GenericMethodSignature(typeParameters, returnType, valueParameters) } private class GenericTypeParser(val result: GenericTypeImpl) : SignatureVisitor(Opcodes.ASM4) { override fun visitBaseType(descriptor: Char) { result.classifierVar = BaseType(descriptor) } override fun visitTypeVariable(name: String) { result.classifierVar = TypeVariable(name) } override fun visitArrayType(): SignatureVisitor { result.classifierVar = ArrayC val argument = GenericTypeImpl() result.arguments.add(NoWildcard(argument)) return GenericTypeParser(argument) } override fun visitClassType(name: String) { result.classifierVar = TopLevelClass(name) } override fun visitInnerClassType(name: String) { val outer = GenericTypeImpl() outer.classifierVar = result.classifier outer.arguments.addAll(result.arguments) result.classifierVar = InnerClass(outer, name) result.arguments.clear() } override fun visitTypeArgument() { result.arguments.add(UnboundedWildcard) } override fun visitTypeArgument(wildcard: Char): SignatureVisitor { val argument = GenericTypeImpl() result.arguments.add(when (wildcard) { SignatureVisitor.EXTENDS -> BoundedWildcard(Wildcard.EXTENDS, argument) SignatureVisitor.SUPER -> BoundedWildcard(Wildcard.SUPER, argument) SignatureVisitor.INSTANCEOF -> NoWildcard(argument) else -> throw IllegalArgumentException("Unknown wildcard: $wildcard") }) return GenericTypeParser(argument) } }
apache-2.0
702c51d6425b0c725e963afbda468388
33.614379
96
0.695619
5.02944
false
false
false
false
sksamuel/akka-patterns
rxhive-parquet/src/test/kotlin/com/sksamuel/rxhive/parquet/ParquetWriterTest.kt
1
2387
package com.sksamuel.rxhive.parquet import com.sksamuel.rxhive.BooleanType import com.sksamuel.rxhive.Int32Type import com.sksamuel.rxhive.StringType import com.sksamuel.rxhive.Struct import com.sksamuel.rxhive.StructField import com.sksamuel.rxhive.StructType import io.kotlintest.shouldBe import io.kotlintest.specs.FunSpec import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.FileSystem import org.apache.hadoop.fs.Path import org.apache.parquet.hadoop.ParquetFileReader import org.apache.parquet.hadoop.util.HadoopInputFile import org.apache.parquet.schema.OriginalType import org.apache.parquet.schema.PrimitiveType import org.apache.parquet.schema.Type import org.apache.parquet.schema.Types class ParquetWriterTest : FunSpec() { init { val conf = Configuration() val fs = FileSystem.getLocal(conf) test("StructParquetWriter should write a single struct") { val path = Path("test.pq") if (fs.exists(path)) fs.delete(path, false) val schema = StructType(StructField("a", StringType), StructField("b", Int32Type), StructField("c", BooleanType)) val struct = Struct(schema, "a", 1, true) val messageType = ToParquetSchema.toMessageType(schema, "element") val writer = parquetWriter(path, conf, messageType) writer.write(struct) writer.close() val input = HadoopInputFile.fromPath(path, conf) ParquetFileReader.open(input).fileMetaData.schema shouldBe Types.buildMessage() .addField(Types.primitive(PrimitiveType.PrimitiveTypeName.BINARY, Type.Repetition.OPTIONAL).`as`(OriginalType.UTF8).named("a")) .addField(Types.primitive(PrimitiveType.PrimitiveTypeName.INT32, Type.Repetition.OPTIONAL).named("b")) .addField(Types.primitive(PrimitiveType.PrimitiveTypeName.BOOLEAN, Type.Repetition.OPTIONAL).named("c")) .named("element") } test("should support overwrite") { val schema = StructType(StructField("a", StringType), StructField("b", Int32Type), StructField("c", BooleanType)) val struct = Struct(schema, "a", 1, true) val messageType = ToParquetSchema.toMessageType(schema, "element") val path = Path("test.pq") fs.exists(path) shouldBe true val writer = parquetWriter(path, conf, messageType, true) writer.write(struct) writer.close() } } }
apache-2.0
45f35952a9e0db69068aa0d5ecb0d025
35.738462
141
0.725597
4.129758
false
true
false
false
Ztiany/Repository
Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/generic/Generic3.kt
2
4581
package me.ztiany.generic import java.util.* import kotlin.reflect.KClass /** 泛型:变型和子类型化*/ /*添加out,使其可以型变*/ private class Producer<out T> private fun testProducer() { val intProducer = Producer<Int>() val numProducer: Producer<Number> //因为具有了协变性,可以进行赋值 numProducer = intProducer } private fun testList() { val listInt = listOf(1, 2, 3) val listNumber: List<Number> //Kotlin中的只读列表List是协变的:List<out E> listNumber = listInt } private open class Animal { fun feed() {} } private class Cat : Animal() private class Herd1<out T : Animal>(vararg animals: T) private class Herd2<out T : Animal>(val leadAnimal: T, vararg animals: T) /*此时 T 不能被声明为 out,因为var默认生成了get/set, 即可变属性leadAnimal在out和in位置上都是用了T,而T只被声明为out*/ private class Herd3<T : Animal>(var leadAnimal: T, vararg animals: T) /*此时 T 又能被声明为 out,因为位置规则只覆盖了类外部可见的API,即public/protected/internal的,私有方法的参数既不在in位置,也不在out位置, * 变型规则只会防止外部使用者对类的误用,但不会对类自己起作用*/ private class Herd4<out T : Animal>(private var leadAnimal: T, vararg animals: T) /*逆变性:Comparator这个接口只是为了消费T类型,这说明T只在in位置使用,因此它的声明之前添加了in关键字,现在Comparator可以用于比较任何类型*/ private val anyComparator = Comparator<Any> { e1: Any, e2: Any -> e1.hashCode() - e2.hashCode() } private fun testAnyComparator() { val strings = listOf("A", "D", "B") strings.sortedWith(anyComparator) } private fun <T> copyData1(source: MutableList<T>, destination: MutableList<T>) { for (item in source) { destination.add(item) } } private fun <T : R, R> copyData2(source: MutableList<T>, destination: MutableList<R>) { for (item in source) { destination.add(item) } } private fun <T> copyData3(source: MutableList<out T>, destination: MutableList<T>) { for (item in source) { destination.add(item) } } private fun <T> copyData4(source: MutableList<T>, destination: MutableList<in T>) { for (item in source) { destination.add(item) } } private fun testCopyData() { val ints: MutableList<Int> = mutableListOf(1, 2, 3) val anyItems: MutableList<Any> = mutableListOf<Any>() val numberItems: MutableList<Number> = mutableListOf<Number>() //copyData2(ints, anyItems) copyData3(ints, anyItems) copyData3(ints, numberItems) copyData4(ints, anyItems) copyData4(ints, numberItems) } private fun printFirst(list: List<*>) { if (list.isNotEmpty()) { println(list.first()) } } private interface FieldValidator<in T> { fun validate(input: T): Boolean } private object DefaultStringValidator : FieldValidator<String> { override fun validate(input: String) = input.isNotEmpty() } private object DefaultIntValidator : FieldValidator<Int> { override fun validate(input: Int) = input >= 0 } private object Validators { private val validators = mutableMapOf<KClass<*>, FieldValidator<*>>() fun <T : Any> registerValidator(kClass: KClass<T>, fieldValidator: FieldValidator<T>) { validators[kClass] = fieldValidator } @Suppress("UNCHECKED_CAST") operator fun <T : Any> get(kClass: KClass<T>): FieldValidator<T> = validators[kClass] as? FieldValidator<T> ?: throw IllegalArgumentException("No validator for ${kClass.simpleName}") } private interface Function<in T, out U> { fun invoke(t: T): U } private fun map1(function: Function<*, String>) { } private fun map2(function: Function<Int, *>) { } private fun map3(function: Function<*, *>) { } private fun testStar(args: Array<String>) { Validators.registerValidator(String::class, DefaultStringValidator) Validators.registerValidator(Int::class, DefaultIntValidator) println(Validators[String::class].validate("Kotlin")) println(Validators[Int::class].validate(42)) map1(object : Function<Nothing, String> { override fun invoke(t: Nothing): String { return "" } }) map2(object : Function<Int, Date> { override fun invoke(t: Int): Date { return Date() } }) map3(object : Function<Nothing, Number> { override fun invoke(t: Nothing): Number { return 3 } }) }
apache-2.0
ecdd5d89aea5a28483964ffae59a92ed
24.807453
94
0.676053
3.326661
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/topread/TopReadFragment.kt
1
5748
package org.wikipedia.feed.topread import android.app.ActivityOptions import android.os.Bundle import android.util.Pair import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import org.wikipedia.Constants import org.wikipedia.Constants.InvokeSource import org.wikipedia.R import org.wikipedia.databinding.FragmentMostReadBinding import org.wikipedia.feed.model.Card import org.wikipedia.feed.view.ListCardItemView import org.wikipedia.history.HistoryEntry import org.wikipedia.page.ExclusiveBottomSheetPresenter import org.wikipedia.page.PageActivity import org.wikipedia.readinglist.AddToReadingListDialog import org.wikipedia.readinglist.MoveToReadingListDialog import org.wikipedia.readinglist.ReadingListBehaviorsUtil import org.wikipedia.util.DimenUtil import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.L10nUtil import org.wikipedia.util.TabUtil import org.wikipedia.views.DefaultRecyclerAdapter import org.wikipedia.views.DefaultViewHolder import org.wikipedia.views.DrawableItemDecoration class TopReadFragment : Fragment() { private var _binding: FragmentMostReadBinding? = null private val binding get() = _binding!! private val bottomSheetPresenter = ExclusiveBottomSheetPresenter() private val viewModel: TopReadViewModel by viewModels { TopReadViewModel.Factory(requireActivity().intent.extras!!) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) _binding = FragmentMostReadBinding.inflate(inflater, container, false) val card = viewModel.card appCompatActivity.setSupportActionBar(binding.toolbar) appCompatActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true) appCompatActivity.supportActionBar?.title = "" binding.toolbarTitle.text = getString(R.string.top_read_activity_title, card.subtitle()) L10nUtil.setConditionalLayoutDirection(binding.root, card.wikiSite().languageCode) binding.mostReadRecyclerView.layoutManager = LinearLayoutManager(context) binding.mostReadRecyclerView.addItemDecoration(DrawableItemDecoration(requireContext(), R.attr.list_separator_drawable)) binding.mostReadRecyclerView.isNestedScrollingEnabled = false binding.mostReadRecyclerView.adapter = RecyclerAdapter(card.items(), Callback()) return binding.root } override fun onDestroyView() { _binding = null super.onDestroyView() } private val appCompatActivity get() = requireActivity() as AppCompatActivity private class RecyclerAdapter constructor(items: List<TopReadItemCard>, private val callback: Callback) : DefaultRecyclerAdapter<TopReadItemCard, ListCardItemView>(items) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder<ListCardItemView> { return DefaultViewHolder(ListCardItemView(parent.context)) } override fun onBindViewHolder(holder: DefaultViewHolder<ListCardItemView>, position: Int) { val card = item(position) holder.view.setCard(card).setHistoryEntry(HistoryEntry(card.pageTitle, HistoryEntry.SOURCE_FEED_MOST_READ_ACTIVITY)).setCallback(callback) } } private inner class Callback : ListCardItemView.Callback { override fun onSelectPage(card: Card, entry: HistoryEntry, openInNewBackgroundTab: Boolean) { if (openInNewBackgroundTab) { TabUtil.openInNewBackgroundTab(entry) FeedbackUtil.showMessage(requireActivity(), R.string.article_opened_in_background_tab) } else { startActivity(PageActivity.newIntentForNewTab(requireContext(), entry, entry.title)) } } override fun onSelectPage(card: Card, entry: HistoryEntry, sharedElements: Array<Pair<View, String>>) { val options = ActivityOptions.makeSceneTransitionAnimation(requireActivity(), *sharedElements) val intent = PageActivity.newIntentForNewTab(requireContext(), entry, entry.title) if (sharedElements.isNotEmpty()) { intent.putExtra(Constants.INTENT_EXTRA_HAS_TRANSITION_ANIM, true) } startActivity(intent, if (DimenUtil.isLandscape(requireContext()) || sharedElements.isEmpty()) null else options.toBundle()) } override fun onAddPageToList(entry: HistoryEntry, addToDefault: Boolean) { if (addToDefault) { ReadingListBehaviorsUtil.addToDefaultList(requireActivity(), entry.title, InvokeSource.MOST_READ_ACTIVITY) { readingListId -> onMovePageToList(readingListId, entry) } } else { bottomSheetPresenter.show(childFragmentManager, AddToReadingListDialog.newInstance(entry.title, InvokeSource.MOST_READ_ACTIVITY)) } } override fun onMovePageToList(sourceReadingListId: Long, entry: HistoryEntry) { bottomSheetPresenter.show(childFragmentManager, MoveToReadingListDialog.newInstance(sourceReadingListId, entry.title, InvokeSource.MOST_READ_ACTIVITY)) } } companion object { fun newInstance(card: TopReadListCard): TopReadFragment { return TopReadFragment().apply { arguments = bundleOf(TopReadArticlesActivity.TOP_READ_CARD to card) } } } }
apache-2.0
91e3bad6249a508fc1700b374873f415
44.984
136
0.7373
5.192412
false
false
false
false
stripe/stripe-android
paymentsheet/src/test/java/com/stripe/android/paymentsheet/PaymentSheetListFragmentTest.kt
1
13638
package com.stripe.android.paymentsheet import android.content.Context import android.os.Looper.getMainLooper import androidx.core.os.bundleOf import androidx.fragment.app.activityViewModels import androidx.fragment.app.testing.FragmentScenario import androidx.fragment.app.testing.launchFragmentInContainer import androidx.lifecycle.Lifecycle import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.ApplicationProvider import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import com.stripe.android.ApiKeyFixtures import com.stripe.android.PaymentConfiguration import com.stripe.android.core.injection.InjectorKey import com.stripe.android.core.injection.WeakMapInjectorRegistry import com.stripe.android.model.PaymentIntentFixtures import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodFixtures import com.stripe.android.model.SetupIntentFixtures import com.stripe.android.paymentsheet.model.FragmentConfig import com.stripe.android.paymentsheet.model.FragmentConfigFixtures import com.stripe.android.paymentsheet.model.PaymentSelection import com.stripe.android.paymentsheet.model.SavedSelection import com.stripe.android.ui.core.address.AddressRepository import com.stripe.android.ui.core.forms.resources.LpmRepository import com.stripe.android.utils.TestUtils.idleLooper import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.verify import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) internal class PaymentSheetListFragmentTest : PaymentSheetViewModelTestInjection() { @InjectorKey private val injectorKey: String = "PaymentSheetListFragmentTest" @After override fun after() { super.after() } @Before fun setup() { PaymentConfiguration.init( ApplicationProvider.getApplicationContext(), ApiKeyFixtures.FAKE_PUBLISHABLE_KEY ) } @Test fun `recovers payment method selection when shown`() { val paymentMethod = PaymentMethodFixtures.CARD_PAYMENT_METHOD val paymentSelection = PaymentSelection.Saved(paymentMethod) val scenario = createScenario( fragmentConfig = FRAGMENT_CONFIG.copy( isGooglePayReady = true, savedSelection = SavedSelection.PaymentMethod(paymentMethod.id.orEmpty()) ), initialState = Lifecycle.State.INITIALIZED ).moveToState(Lifecycle.State.CREATED).onFragment { fragment -> fragment.initializePaymentOptions(paymentMethods = listOf(paymentMethod)) }.moveToState(Lifecycle.State.STARTED).onFragment { assertThat(activityViewModel(it).selection.value) .isEqualTo(paymentSelection) } scenario.recreate() scenario.onFragment { assertThat(activityViewModel(it).selection.value) .isEqualTo(paymentSelection) } } @Test fun `recovers edit state when shown`() { val paymentMethod = PaymentMethodFixtures.CARD_PAYMENT_METHOD createScenario( fragmentConfig = FRAGMENT_CONFIG.copy( isGooglePayReady = true, savedSelection = SavedSelection.PaymentMethod(paymentMethod.id.orEmpty()) ), initialState = Lifecycle.State.INITIALIZED ).moveToState(Lifecycle.State.CREATED).onFragment { fragment -> fragment.initializePaymentOptions(paymentMethods = listOf(paymentMethod)) }.moveToState(Lifecycle.State.STARTED).onFragment { fragment -> assertThat(fragment.isEditing).isFalse() fragment.isEditing = true }.recreate().onFragment { assertThat(it.isEditing).isTrue() } } @Test fun `When last item is deleted then edit menu item is hidden`() { val paymentMethod = PaymentMethodFixtures.CARD_PAYMENT_METHOD createScenario( fragmentConfig = FRAGMENT_CONFIG.copy( savedSelection = SavedSelection.PaymentMethod(paymentMethod.id.orEmpty()) ) ).onFragment { fragment -> fragment.isEditing = true fragment.adapter.items = fragment.adapter.items.dropLast(1) fragment.deletePaymentMethod(PaymentOptionsItem.SavedPaymentMethod(paymentMethod)) assertThat(fragment.isEditing).isFalse() } } @Test fun `sets up adapter`() { createScenario( initialState = Lifecycle.State.INITIALIZED ).moveToState(Lifecycle.State.CREATED).onFragment { fragment -> fragment.initializePaymentOptions( isGooglePayReady = false, isLinkEnabled = false, ) }.moveToState(Lifecycle.State.RESUMED).onFragment { idleLooper() val adapter = recyclerView(it).adapter as PaymentOptionsAdapter assertThat(adapter.itemCount) .isEqualTo(3) } } @Test @Config(qualifiers = "w320dp") fun `when screen is 320dp wide, adapter should show 2 and a half items with 114dp width`() { createScenario( initialState = Lifecycle.State.INITIALIZED ).moveToState(Lifecycle.State.CREATED).onFragment { fragment -> fragment.initializePaymentOptions() }.moveToState(Lifecycle.State.RESUMED).onFragment { val item = recyclerView(it).layoutManager!!.findViewByPosition(0) assertThat(item!!.measuredWidth).isEqualTo(114) } } @Test @Config(qualifiers = "w481dp") fun `when screen is 481dp wide, adapter should show 3 and a half items with 128dp width`() { createScenario( initialState = Lifecycle.State.INITIALIZED ).moveToState(Lifecycle.State.CREATED).onFragment { fragment -> fragment.initializePaymentOptions() }.moveToState(Lifecycle.State.RESUMED).onFragment { val item = recyclerView(it).layoutManager!!.findViewByPosition(0) assertThat(item!!.measuredWidth).isEqualTo(128) } } @Test @Config(qualifiers = "w482dp") fun `when screen is 482dp wide, adapter should show 4 items with 112dp width`() { createScenario( initialState = Lifecycle.State.INITIALIZED ).moveToState(Lifecycle.State.CREATED).onFragment { fragment -> fragment.initializePaymentOptions() }.moveToState(Lifecycle.State.RESUMED).onFragment { val item = recyclerView(it).layoutManager!!.findViewByPosition(0) assertThat(item!!.measuredWidth).isEqualTo(112) } } @Test fun `updates selection on click`() { val savedPaymentMethod = PaymentMethodFixtures.CARD_PAYMENT_METHOD val selectedItem = PaymentOptionsItem.SavedPaymentMethod(savedPaymentMethod) createScenario().onFragment { val activityViewModel = activityViewModel(it) idleLooper() val adapter = recyclerView(it).adapter as PaymentOptionsAdapter adapter.paymentOptionSelected(selectedItem) idleLooper() assertThat(activityViewModel.selection.value) .isEqualTo(PaymentSelection.Saved(savedPaymentMethod)) } } @Test fun `posts transition when add card clicked`() { createScenario().onFragment { val activityViewModel = activityViewModel(it) assertThat(activityViewModel.transition.value?.peekContent()).isNull() idleLooper() val adapter = recyclerView(it).adapter as PaymentOptionsAdapter adapter.addCardClickListener() idleLooper() assertThat(activityViewModel.transition.value?.peekContent()) .isEqualTo( PaymentSheetViewModel.TransitionTarget.AddPaymentMethodFull( FragmentConfigFixtures.DEFAULT ) ) } } @Test fun `started fragment should report onShowExistingPaymentOptions() event`() { createScenario().onFragment { verify(eventReporter).onShowExistingPaymentOptions(any(), any()) } } @Test fun `fragment created without FragmentConfig should emit fatal`() { createScenario( fragmentConfig = null, initialState = Lifecycle.State.CREATED ).onFragment { fragment -> assertThat((fragment.sheetViewModel.paymentSheetResult.value as PaymentSheetResult.Failed).error.message) .isEqualTo("Failed to start existing payment options fragment.") } } @Test fun `total amount label correctly displays amount`() { createScenario().onFragment { fragment -> shadowOf(getMainLooper()).idle() fragment.sheetViewModel.setStripeIntent( PaymentIntentFixtures.PI_OFF_SESSION.copy( amount = 399 ) ) assertThat(fragment.sheetViewModel.isProcessingPaymentIntent).isTrue() } } @Test fun `total amount label is hidden for SetupIntent`() { createScenario( FRAGMENT_CONFIG.copy(stripeIntent = SetupIntentFixtures.SI_REQUIRES_PAYMENT_METHOD), PaymentSheetFixtures.ARGS_CUSTOMER_WITH_GOOGLEPAY_SETUP ).onFragment { fragment -> shadowOf(getMainLooper()).idle() assertThat(fragment.sheetViewModel.isProcessingPaymentIntent).isFalse() } } @Test fun `when config has saved payment methods then show options menu`() { createScenario( initialState = Lifecycle.State.INITIALIZED, paymentMethods = PAYMENT_METHODS ).moveToState(Lifecycle.State.STARTED).onFragment { fragment -> assertThat(fragment.hasOptionsMenu()).isTrue() } } @Test fun `when config does not have saved payment methods then show no options menu`() { createScenario( initialState = Lifecycle.State.INITIALIZED, paymentMethods = emptyList() ).moveToState(Lifecycle.State.STARTED).onFragment { fragment -> fragment.initializePaymentOptions() idleLooper() assertThat(fragment.hasOptionsMenu()).isFalse() } } private fun recyclerView(it: PaymentSheetListFragment) = it.requireView().findViewById<RecyclerView>(R.id.recycler) private fun activityViewModel( fragment: PaymentSheetListFragment ): PaymentSheetViewModel { return fragment.activityViewModels<PaymentSheetViewModel> { PaymentSheetViewModel.Factory { PaymentSheetFixtures.ARGS_CUSTOMER_WITH_GOOGLEPAY } }.value } private fun createScenario( fragmentConfig: FragmentConfig? = FRAGMENT_CONFIG, starterArgs: PaymentSheetContract.Args = PaymentSheetFixtures.ARGS_CUSTOMER_WITH_GOOGLEPAY.copy( injectorKey = injectorKey ), initialState: Lifecycle.State = Lifecycle.State.RESUMED, paymentMethods: List<PaymentMethod> = listOf(PaymentMethodFixtures.CARD_PAYMENT_METHOD) ): FragmentScenario<PaymentSheetListFragment> { assertThat(WeakMapInjectorRegistry.retrieve(injectorKey)).isNull() fragmentConfig?.let { createViewModel( fragmentConfig.stripeIntent, customerRepositoryPMs = paymentMethods, injectorKey = starterArgs.injectorKey, args = starterArgs ).apply { updatePaymentMethods(fragmentConfig.stripeIntent) setStripeIntent(fragmentConfig.stripeIntent) idleLooper() registerViewModel(starterArgs.injectorKey, this, lpmRepository, addressRepository) } } return launchFragmentInContainer( bundleOf( PaymentSheetActivity.EXTRA_FRAGMENT_CONFIG to fragmentConfig, PaymentSheetActivity.EXTRA_STARTER_ARGS to starterArgs ), R.style.StripePaymentSheetDefaultTheme, initialState = initialState ) } private fun PaymentSheetListFragment.initializePaymentOptions( paymentMethods: List<PaymentMethod> = PAYMENT_METHODS, isGooglePayReady: Boolean = false, isLinkEnabled: Boolean = false, savedSelection: SavedSelection = SavedSelection.None, ) { sheetViewModel._paymentMethods.value = paymentMethods sheetViewModel._isGooglePayReady.value = isGooglePayReady sheetViewModel._isLinkEnabled.value = isLinkEnabled sheetViewModel.savedStateHandle["saved_selection"] = savedSelection } private companion object { private val PAYMENT_METHODS = listOf( PaymentMethodFixtures.CARD_PAYMENT_METHOD, PaymentMethodFixtures.CARD_PAYMENT_METHOD ) private val FRAGMENT_CONFIG = FragmentConfigFixtures.DEFAULT val addressRepository = AddressRepository(ApplicationProvider.getApplicationContext<Context>().resources) val lpmRepository = LpmRepository( LpmRepository.LpmRepositoryArguments( InstrumentationRegistry.getInstrumentation().targetContext.resources ) ).apply { this.updateFromDisk() } } }
mit
954405f9277a0ac24f6a7a0d6f0a5c16
37.634561
117
0.669673
5.523694
false
true
false
false
thanksmister/androidthings-mqtt-alarm-panel
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/ui/views/AlarmPendingView.kt
1
3382
/* * <!-- * ~ Copyright (c) 2017. ThanksMister 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.thanksmister.iot.mqtt.alarmpanel.ui.views import android.content.Context import android.os.CountDownTimer import android.util.AttributeSet import android.view.animation.RotateAnimation import android.widget.LinearLayout import kotlinx.android.synthetic.main.dialog_alarm_disable.view.* import timber.log.Timber class AlarmPendingView : LinearLayout { var alarmListener: ViewListener? = null /** * Method to return number of display seconds remaining on countdown. * @return Integer for seconds remaining. */ var countDownTimeRemaining: Int = 0 private var countDownTimer: CountDownTimer? = null constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} override fun onFinishInflate() { super.onFinishInflate() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() stopCountDown() } fun setListener(listener: ViewListener) { this.alarmListener = listener } /** * Countdown timer time * @param pendingTime seconds */ fun startCountDown(pendingTime: Int) { if (pendingTime <= 0) { stopCountDown() if (alarmListener != null) { alarmListener!!.onTimeOut() countDownTimeRemaining = 0 } return } if (countDownTimer != null) { countDownTimer!!.cancel() countDownTimer = null countDownTimeRemaining = 0 } Timber.d("startCountDown: " + pendingTime * 1300) val divideBy = 360 / pendingTime countDownTimer = object : CountDownTimer((pendingTime * 1000).toLong(), 1000) { override fun onTick(millisUntilFinished: Long) { countDownTimeRemaining = (millisUntilFinished / 1000).toInt() val an = RotateAnimation(0.0f, 90.0f, 250f, 273f) an.fillAfter = true countDownProgressWheel.setText(countDownTimeRemaining.toString()) countDownProgressWheel.setProgress(countDownTimeRemaining * divideBy) } override fun onFinish() { Timber.d("Timed up...") if (alarmListener != null) { alarmListener!!.onTimeOut() countDownTimeRemaining = 0 } } }.start() } fun stopCountDown() { if (countDownTimer != null) { countDownTimer!!.cancel() countDownTimer = null } countDownTimeRemaining = 0 } interface ViewListener { fun onTimeOut() } }
apache-2.0
ea20e270d2585ad1fe23704153a8778d
29.754545
87
0.615612
4.677732
false
false
false
false
AndroidX/androidx
room/room-common/src/main/java/androidx/room/Entity.kt
3
4507
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room /** * Marks a class as an entity. This class will have a mapping SQLite table in the database. * * Each entity must have at least 1 field annotated with [PrimaryKey]. * You can also use [primaryKeys] attribute to define the primary key. * * Each entity must either have a no-arg constructor or a constructor whose parameters match * fields (based on type and name). Constructor does not have to receive all fields as parameters * but if a field is not passed into the constructor, it should either be public or have a public * setter. If a matching constructor is available, Room will always use it. If you don't want it * to use a constructor, you can annotate it with [Ignore]. * * When a class is marked as an [Entity], all of its fields are persisted. If you would like to * exclude some of its fields, you can mark them with [Ignore]. * * If a field is `transient`, it is automatically ignored **unless** it is annotated with * `ColumnInfo`, `Embedded` or `Relation`. * * Example: * ``` * @Entity * data class Song ( * @PrimaryKey * val id: Long, * val name: String, * @ColumnInfo(name = "release_year") * val releaseYear: Int * ) * ``` * * @see Dao * @see Database * @see PrimaryKey * @see ColumnInfo * @see Index */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.BINARY) public annotation class Entity( /** * The table name in the SQLite database. If not set, defaults to the class name. * * @return The SQLite tableName of the Entity. */ val tableName: String = "", /** * List of indices on the table. * * @return The list of indices on the table. */ val indices: Array<Index> = [], /** * If set to `true`, any Index defined in parent classes of this class will be carried * over to the current `Entity`. Note that if you set this to `true`, even if the * `Entity` has a parent which sets this value to `false`, the `Entity` will * still inherit indices from it and its parents. * * When the `Entity` inherits an index from the parent, it is **always** renamed with * the default naming schema since SQLite **does not** allow using the same index name in * multiple tables. See [Index] for the details of the default name. * * By default, indices defined in parent classes are dropped to avoid unexpected indices. * When this happens, you will receive a [RoomWarnings.INDEX_FROM_PARENT_FIELD_IS_DROPPED] * or [RoomWarnings.INDEX_FROM_PARENT_IS_DROPPED] warning during compilation. * * @return True if indices from parent classes should be automatically inherited by this Entity, * false otherwise. Defaults to false. */ val inheritSuperIndices: Boolean = false, /** * The list of Primary Key column names. * * If you would like to define an auto generated primary key, you can use [PrimaryKey] * annotation on the field with [PrimaryKey.autoGenerate] set to `true`. * * @return The primary key of this Entity. Can be empty if the class has a field annotated * with [PrimaryKey]. */ val primaryKeys: Array<String> = [], /** * List of [ForeignKey] constraints on this entity. * * @return The list of [ForeignKey] constraints on this entity. */ val foreignKeys: Array<ForeignKey> = [], /** * The list of column names that should be ignored by Room. * * Normally, you can use [Ignore], but this is useful for ignoring fields inherited from * parents. * * Columns that are part of an [Embedded] field can not be individually ignored. To ignore * columns from an inherited [Embedded] field, use the name of the field. * * @return The list of field names. */ val ignoredColumns: Array<String> = [] )
apache-2.0
834072c17a19dbda2579d45645a7ce0f
36.247934
100
0.676281
4.21215
false
false
false
false
AndroidX/androidx
wear/watchface/watchface-complications-data-source/src/main/java/androidx/wear/watchface/complications/datasource/ComplicationDataSourceUpdateRequester.kt
3
6331
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface.complications.datasource import android.app.PendingIntent import android.content.ComponentName import android.content.Context import android.content.Intent import androidx.annotation.RestrictTo import androidx.wear.watchface.complications.ComplicationDataSourceUpdateRequesterConstants /** * Allows complication complication data source to request update calls from the system. This * effectively allows complication data source to push updates to the system outside of the update * request cycle. */ public interface ComplicationDataSourceUpdateRequester { /** * Requests that the system call * [onComplicationUpdate][ComplicationDataSourceService.onComplicationRequest] on the specified * complication data source, for all active complications using that complication data source. * * This will do nothing if no active complications are configured to use the specified * complication data source. * * This will also only work if called from the same package as the omplication data source. */ public fun requestUpdateAll() /** * Requests that the system call * [onComplicationUpdate][ComplicationDataSourceService.onComplicationRequest] on the specified * complication data source, for the given complication ids. Inactive complications are ignored, * as are complications configured to use a different complication data source. * * @param complicationInstanceIds The system's IDs for the complications to be updated as * provided to [ComplicationDataSourceService.onComplicationActivated] and * [ComplicationDataSourceService.onComplicationRequest]. */ public fun requestUpdate(vararg complicationInstanceIds: Int) public companion object { /** * The package of the service that accepts complication data source requests. * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public const val UPDATE_REQUEST_RECEIVER_PACKAGE = "com.google.android.wearable.app" /** * Creates a [ComplicationDataSourceUpdateRequester]. * * @param context The [ComplicationDataSourceService]'s [Context] * @param complicationDataSourceComponent The [ComponentName] of the * [ComplicationDataSourceService] to reload. * @return The constructed [ComplicationDataSourceUpdateRequester]. */ @JvmStatic public fun create( context: Context, complicationDataSourceComponent: ComponentName ): ComplicationDataSourceUpdateRequester = ComplicationDataSourceUpdateRequesterImpl(context, complicationDataSourceComponent) /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public const val ACTION_REQUEST_UPDATE: String = "android.support.wearable.complications.ACTION_REQUEST_UPDATE" /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public const val ACTION_REQUEST_UPDATE_ALL: String = "android.support.wearable.complications.ACTION_REQUEST_UPDATE_ALL" /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public const val EXTRA_PROVIDER_COMPONENT: String = "android.support.wearable.complications.EXTRA_PROVIDER_COMPONENT" /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public const val EXTRA_COMPLICATION_IDS: String = "android.support.wearable.complications.EXTRA_COMPLICATION_IDS" } } /** * @param context The [ComplicationDataSourceService]'s [Context] * @param complicationDataSourceComponent The [ComponentName] of the ComplicationDataSourceService] * to reload. */ private class ComplicationDataSourceUpdateRequesterImpl( private val context: Context, private val complicationDataSourceComponent: ComponentName ) : ComplicationDataSourceUpdateRequester { override fun requestUpdateAll() { val intent = Intent(ComplicationDataSourceUpdateRequester.ACTION_REQUEST_UPDATE_ALL) intent.setPackage(ComplicationDataSourceUpdateRequester.UPDATE_REQUEST_RECEIVER_PACKAGE) intent.putExtra( ComplicationDataSourceUpdateRequester.EXTRA_PROVIDER_COMPONENT, complicationDataSourceComponent ) // Add a placeholder PendingIntent to allow the UID to be checked. intent.putExtra( ComplicationDataSourceUpdateRequesterConstants.EXTRA_PENDING_INTENT, PendingIntent.getActivity( context, 0, Intent(""), PendingIntent.FLAG_IMMUTABLE ) ) context.sendBroadcast(intent) } override fun requestUpdate(vararg complicationInstanceIds: Int) { val intent = Intent(ComplicationDataSourceUpdateRequester.ACTION_REQUEST_UPDATE) intent.setPackage(ComplicationDataSourceUpdateRequester.UPDATE_REQUEST_RECEIVER_PACKAGE) intent.putExtra( ComplicationDataSourceUpdateRequester.EXTRA_PROVIDER_COMPONENT, complicationDataSourceComponent ) intent.putExtra( ComplicationDataSourceUpdateRequester.EXTRA_COMPLICATION_IDS, complicationInstanceIds ) // Add a placeholder PendingIntent to allow the UID to be checked. intent.putExtra( ComplicationDataSourceUpdateRequesterConstants.EXTRA_PENDING_INTENT, PendingIntent.getActivity( context, 0, Intent(""), PendingIntent.FLAG_IMMUTABLE ) ) context.sendBroadcast(intent) } }
apache-2.0
b024ced4aee233e2ed78ce1c668b5898
40.379085
100
0.706208
5.40649
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/utils/import/ImportCandidatesCollector.kt
2
20174
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.utils.import import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.util.containers.MultiMap import com.intellij.util.containers.map2Array import org.rust.cargo.project.workspace.PackageOrigin import org.rust.cargo.util.AutoInjectedCrates import org.rust.lang.core.crate.Crate import org.rust.lang.core.crate.CrateGraphService import org.rust.lang.core.crate.CratePersistentId import org.rust.lang.core.crate.crateGraph import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsFile.Attributes import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.Namespace import org.rust.lang.core.resolve.TraitImplSource import org.rust.lang.core.resolve.ref.MethodResolveVariant import org.rust.lang.core.resolve.ref.deepResolve import org.rust.lang.core.resolve2.* import org.rust.stdext.mapNotNullToSet import org.rust.stdext.mapToSet /** * ## High-level description * Consider we have code like: * ```rust * fn main() { * func(); * } * ``` * And want to find import for `func`. * Import will have path like `mod1::mod2::mod3::modn::func`. * - `mod1` is always crate root - either current crate or one of its dependencies. * See [getInitialDefMapsToSearch]. * - Given candidates for `mod{n}` we can find candidates for `mod{n+1}` among [ModData.visibleItems] for `mod{n}`. * See [getAllModPaths]. * - Finally when we have path `mod1::mod2::mod3::modn`, * we filter items by name in [ModData.visibleItems] for `modn`, * and receive result path `mod1::mod2::mod3::modn::func`. * See [getAllItemPathsInMod]. * * ### Filtration (when we find multiple paths for single item) * - If we can use path to crate where item is declared, then we ignore reexports in all other crates - see [filterForSingleCrate]. * - If there are multiple paths in single crate, then we choose the shortest one - see [filterShortestPath]. * - Private reexports are not used - see [checkVisibility]. * * ### Sorting * We sort items in following order: * - Std * - Workspace * - Dependencies * See [ImportCandidate.compareTo]. */ object ImportCandidatesCollector { fun getImportCandidates(context: ImportContext, targetName: String): List<ImportCandidate> { val itemsPaths = context.getAllModPaths() .flatMap { context.getAllItemPathsInMod(it, targetName) } return context.convertToCandidates(itemsPaths) } fun getCompletionCandidates( context: ImportContext, prefixMatcher: PrefixMatcher, processedElements: MultiMap<String, RsElement> ): List<ImportCandidate> { val modPaths = context.getAllModPaths() val allNames = modPaths.flatMapTo(hashSetOf()) { it.mod.visibleItems.keys } val nameToPriority = prefixMatcher.sortMatching(allNames) .withIndex().associate { (index, value) -> value to index } val itemsPaths = modPaths .flatMap { context.getAllItemPathsInMod(it, nameToPriority::containsKey) } return context.convertToCandidates(itemsPaths) /** we need this filter in addition to [hasVisibleItemInRootScope] because there can be local imports */ .filter { it.item !in processedElements[it.itemName] } .sortedBy { nameToPriority[it.itemName] } } /** * Returns a sequence of import trait candidates for given [resolvedMethods]. * After importing any of which it becomes possible to resolve the corresponding method call correctly. * * Returns null if there aren't traits to import at all. It can mean: * * given [resolvedMethods] don't refer to any trait * * if at least one trait related to [resolvedMethods] is already in scope */ fun getImportCandidates(scope: RsElement, resolvedMethods: List<MethodResolveVariant>): List<ImportCandidate>? = getTraitImportCandidates(scope, resolvedMethods.map { it.source }) fun getTraitImportCandidates(scope: RsElement, sources: List<TraitImplSource>): List<ImportCandidate>? { val traits = collectTraitsToImport(scope, sources) ?: return null val traitsPaths = traits.mapNotNullToSet { it.asModPath() } val context = ImportContext.from(scope, ImportContext.Type.AUTO_IMPORT) ?: return emptyList() val modPaths = context.getAllModPaths() val itemsPaths = modPaths.flatMap { context.getTraitsPathsInMod(it, traitsPaths) } return context.convertToCandidates(itemsPaths) } private fun collectTraitsToImport(scope: RsElement, sources: List<TraitImplSource>): List<RsTraitItem>? { val traits = sources.mapNotNull { source -> if (source.isInherent) return null source.requiredTraitInScope } return if (traits.filterInScope(scope).isNotEmpty()) null else traits } private fun getImportCandidates(context: ImportContext, target: RsQualifiedNamedElement): List<ImportCandidate> { val name = if (target is RsFile) { target.modName } else { target.name } ?: return emptyList() return getImportCandidates(context, name) .filter { it.item == target } } fun findImportCandidate(context: ImportContext, target: RsQualifiedNamedElement): ImportCandidate? = getImportCandidates(context, target).firstOrNull() } private fun ImportContext.convertToCandidates(itemsPaths: List<ItemUsePath>): List<ImportCandidate> = itemsPaths .filterForSingleRootItem(this) .groupBy { it.toItemWithNamespace() } .mapValues { (item, paths) -> filterForSingleItem(paths, item) } .flatMap { (item, paths) -> val itemsPsi = item .toPsi(rootInfo) .filterIsInstance<RsQualifiedNamedElement>() .filterByNamespace(this) // cartesian product of `itemsPsi` and `paths` itemsPsi.flatMap { itemPsi -> paths.map { path -> val importInfo = createImportInfo(path) val isRootPathResolved = isRootPathResolved(importInfo.usePath) ImportCandidate(itemPsi, path.path, path.crate, importInfo, isRootPathResolved) } } } .filter { it.item !is RsTraitItem || isUsefulTraitImport(it.info.usePath) } // for items which belongs to multiple namespaces (e.g. unit structs) .distinctBy { it.item to it.info.usePath } .sorted() @Suppress("ArrayInDataClass") private data class ModUsePath( val path: Array<String>, /** corresponds to `path.first()` */ val crate: Crate, /** corresponds to `path.last()` */ val mod: ModData, val needExternCrate: Boolean, ) { override fun toString(): String = path.joinToString("::") } private fun ImportContext.getAllModPaths(): List<ModUsePath> { val defMaps = rootDefMap.getInitialDefMapsToSearch(project.crateGraph) val explicitCrates = defMaps.explicit.mapToSet { (_, defMap) -> defMap.crate } val result = mutableListOf<ModUsePath>() for ((crateName, defMap) in defMaps.all) { val filterCrate = { crate: CratePersistentId -> crate == defMap.crate || crate !in explicitCrates } val crate = project.crateGraph.findCrateById(defMap.crate) ?: continue val rootPath = ModUsePath(arrayOf(crateName), crate, defMap.root, needExternCrate = defMap.crate !in explicitCrates) visitVisibleModules(rootPath, filterCrate, result::add) } return result } /** bfs using [ModData.visibleItems] as edges */ private fun ImportContext.visitVisibleModules( rootPath: ModUsePath, filterCrate: (CratePersistentId) -> Boolean, processor: (ModUsePath) -> Unit ) { val visited = hashSetOf(rootPath.mod) var pathsCurrent = listOf(rootPath) var pathsNext = mutableListOf<ModUsePath>() while (pathsCurrent.isNotEmpty()) { for (pathCurrent in pathsCurrent) { processor(pathCurrent) for (pathNext in findPathsToModulesInScope(pathCurrent)) { if (filterCrate(pathNext.mod.crate) && pathNext.mod !in visited) { pathsNext += pathNext } } } visited += pathsNext.map { it.mod } pathsCurrent = pathsNext pathsNext = mutableListOf() } } private fun ImportContext.findPathsToModulesInScope(path: ModUsePath): List<ModUsePath> = path.mod.visibleItems.mapNotNull { (name, perNs) -> val childMod = perNs.types.singleOrNull { it.isModOrEnum && checkVisibility(it, path.mod) } ?: return@mapNotNull null val childModData = rootDefMap.tryCastToModData(childMod) ?: return@mapNotNull null path.copy(path = path.path + name, mod = childModData) } private data class InitialDefMaps( /** * Crates which are available as-is (without inserting addition `extern crate`). * Note that though technically `core` is available as-is, * it is not included in this list since `std` should be used instead. */ val explicit: List<Pair<String, CrateDefMap>>, /** All crates which we can import from */ val all: List<Pair<String, CrateDefMap>>, ) /** * Other stdlib crates such as `proc_macro`, `test`, `unwind` * are available only when there is explicit `extern crate ...;` */ private val ADDITIONAL_STDLIB_DEPENDENCIES: Set<String> = setOf("core", "alloc") private fun CrateDefMap.getInitialDefMapsToSearch(crateGraph: CrateGraphService): InitialDefMaps { val externPreludeAdjusted = if (AutoInjectedCrates.STD in externPrelude) { externPrelude.filterKeys { it != AutoInjectedCrates.CORE } } else { externPrelude } val dependencies = externPreludeAdjusted .entries.groupBy({ it.value }, { it.key }) .mapValues { (defMap, names) -> // if crate is imported using `extern crate` with alias, we should use alias // if there are multiply aliases, we choose any of them names.singleOrNull() ?: names.first { it != defMap.metaData.name } } .map { (defMap, name) -> name to defMap } val additionalStdlibDependencies = ADDITIONAL_STDLIB_DEPENDENCIES .mapNotNull { name -> val defMap = directDependenciesDefMaps[name] ?: return@mapNotNull null name to defMap } .filter { (name, defMap) -> name !in externPreludeAdjusted && crateGraph.findCrateById(defMap.crate)?.origin == PackageOrigin.STDLIB && stdlibAttributes.canUseCrate(name) } val explicitDefMaps = listOf("crate" to this) + dependencies val allDefMaps = explicitDefMaps + additionalStdlibDependencies return InitialDefMaps(explicitDefMaps, allDefMaps) } private fun Attributes.canUseCrate(crate: String): Boolean = when (this) { Attributes.NONE -> true Attributes.NO_STD -> crate != AutoInjectedCrates.STD Attributes.NO_CORE -> crate != AutoInjectedCrates.STD && crate != AutoInjectedCrates.CORE } /** * Checks that import is visible, and it is not private reexport. * We shouldn't use private reexports in order to not generate code like `use crate::HashSet;`. */ private fun ImportContext.checkVisibility(visItem: VisItem, modData: ModData): Boolean { val visibility = visItem.visibility if (!visibility.isVisibleFromMod(rootModData)) return false if (visibility is Visibility.Restricted) { val isPrivate = visibility.inMod == modData val isExplicitlyDeclared = !visItem.isCrateRoot && visItem.containingMod == modData.path if (isPrivate && !isExplicitlyDeclared) { Testmarks.IgnorePrivateImportInParentMod.hit() return false } } return true } @Suppress("ArrayInDataClass") private data class ItemUsePath( val path: Array<String>, /** corresponds to `path.first()` */ val crate: Crate, /** corresponds to `path.last()` */ val item: VisItem, val namespace: Namespace, val needExternCrate: Boolean, ) { fun toItemWithNamespace(): ItemWithNamespace = ItemWithNamespace(item.path, item.isModOrEnum, namespace) override fun toString(): String = "${path.joinToString("::")} for ${item.path}" } private fun ImportContext.getAllItemPathsInMod(modPath: ModUsePath, itemNameFilter: (String) -> Boolean): Sequence<ItemUsePath> = modPath.mod.visibleItems .asSequence().filter { itemNameFilter(it.key) } .flatMap { (name, perNs) -> getPerNsPaths(modPath, perNs, name) } private fun ImportContext.getAllItemPathsInMod(modPath: ModUsePath, itemName: String): List<ItemUsePath> { val perNs = modPath.mod.visibleItems[itemName] ?: return emptyList() return getPerNsPaths(modPath, perNs, itemName) } private fun ImportContext.getPerNsPaths(modPath: ModUsePath, perNs: PerNs, name: String): List<ItemUsePath> = perNs.getVisItemsByNamespace().flatMap { (visItems, namespace) -> visItems .filter { checkVisibility(it, modPath.mod) && (type == ImportContext.Type.OTHER || !hasVisibleItemInRootScope(name, namespace)) } .map { ItemUsePath(modPath.path + name, modPath.crate, it, namespace, modPath.needExternCrate) } } private fun ImportContext.hasVisibleItemInRootScope(name: String, namespace: Namespace): Boolean { val perNs = rootDefMap.resolveNameInModule(rootModData, name, withLegacyMacros = true) return perNs.getVisItems(namespace).isNotEmpty() } /** Returns paths to [traits] in scope of [modPath] */ private fun ImportContext.getTraitsPathsInMod(modPath: ModUsePath, traits: Set<ModPath>): List<ItemUsePath> = modPath.mod.visibleItems .flatMap { (name, perNs) -> perNs.types .filter { checkVisibility(it, modPath.mod) && it.path in traits } .map { ItemUsePath(modPath.path + name, modPath.crate, it, Namespace.Types, modPath.needExternCrate) } } private data class ItemWithNamespace(val path: ModPath, val isModOrEnum: Boolean, val namespace: Namespace) { override fun toString(): String = "$path ($namespace)" } private fun ItemWithNamespace.toPsi(info: RsModInfo): List<RsNamedElement> = VisItem(path, Visibility.Public, isModOrEnum).toPsi(info, namespace) private fun filterForSingleItem(paths: List<ItemUsePath>, item: ItemWithNamespace): List<ItemUsePath> = filterForSingleCrate(paths, item.path.crate) .groupBy { it.crate } .mapValues { filterShortestPath(it.value) } .flatMap { it.value } /** * If we can access crate of item ⇒ ignore paths through other crates. * Exception: when item is declared in `core` and reexported in `std`, we should use `std` path. */ private fun filterForSingleCrate(paths: List<ItemUsePath>, itemCrate: CratePersistentId): List<ItemUsePath> { return paths.filter { it.crate.normName == AutoInjectedCrates.STD } .ifEmpty { paths.filter { it.crate.id == itemCrate } } .ifEmpty { paths } } /** In each crate choose the shortest path(s) */ private fun filterShortestPath(paths: List<ItemUsePath>): List<ItemUsePath> { val minPathSize = paths.minOf { it.path.size } return paths.filter { it.path.size == minPathSize } } /** * error::Error * ~~~~~ this = [std::error, core::error] * ~~~~~~~~~~~~ root path - same item for both, so keep only `std::error` */ private fun List<ItemUsePath>.filterForSingleRootItem(context: ImportContext): List<ItemUsePath> { if (size <= 1 || !all { it.item.isModOrEnum }) return this if (context.type == ImportContext.Type.COMPLETION) return this val segments = context.pathInfo?.nextSegments ?: return this return groupBy { resolveRootPath(context.rootDefMap, it, segments) ?: return this } .mapValues { (perNs, paths) -> val crate = perNs.singleCrate() ?: return this filterForSingleCrate(paths, crate) } .flatMap { it.value } } private fun PerNs.singleCrate(): CratePersistentId? = (types + values + macros) .mapTo(hashSetOf()) { it.crate } .singleOrNull() /** * mod1::mod2::Item * ~~~~~~~~~~ segments * ~~~~ path */ private fun resolveRootPath(defMap: CrateDefMap, path: ItemUsePath, segments: List<String>): PerNs? { var perNs = PerNs.types(path.item) for (segment in segments) { val visItem = perNs.types.singleOrNull { !it.visibility.isInvisible } ?: return null val modData = defMap.tryCastToModData(visItem) ?: return null perNs = modData.getVisibleItem(segment) } return perNs } private fun List<RsQualifiedNamedElement>.filterByNamespace(context: ImportContext): List<RsQualifiedNamedElement> { val pathInfo = context.pathInfo ?: return this return filter { pathInfo.namespaceFilter(it) && checkProcMacroType(it, pathInfo.parentIsMetaItem) } } fun checkProcMacroType(element: RsQualifiedNamedElement, parentIsMetaItem: Boolean): Boolean { if (parentIsMetaItem) return true /** attr and derives are checked in [RsPath.namespaceFilter] */ return if (element is RsFunction && element.isProcMacroDef) element.isBangProcMacroDef else true } private fun ImportContext.isUsefulTraitImport(usePath: String): Boolean { if (pathInfo?.rootPathText == null) return true val path = createPathWithImportAdded(usePath) ?: return false val element = path.reference?.deepResolve() as? RsQualifiedNamedElement ?: return false // Looks like it's useless to access trait associated types directly (i.e. `Trait::Type`), // but methods can be used in UFCS and associated functions or constants can be accessed // it they have `Self` type in a signature return element !is RsAbstractable || element.owner !is RsAbstractableOwner.Trait || element.canBeAccessedByTraitName } private fun ImportContext.isRootPathResolved(usePath: String): Boolean { if (type == ImportContext.Type.COMPLETION) return true val path = createPathWithImportAdded(usePath) ?: return false return path.reference?.resolve() != null } private fun ImportContext.createPathWithImportAdded(usePath: String): RsPath? { val rootPathText = pathInfo?.rootPathText ?: return null val rootPathParsingMode = pathInfo.rootPathParsingMode ?: return null val rootPathAllowedNamespaces = pathInfo.rootPathAllowedNamespaces ?: return null return RsCodeFragmentFactory(project) .createPathInTmpMod(rootPathText, rootMod, rootPathParsingMode, rootPathAllowedNamespaces, usePath, null) } private fun ImportContext.createImportInfo(path: ItemUsePath): ImportInfo { val crateName = path.path.first() val segments = path.path.map2Array(String::escapeIdentifierIfNeeded) return if (crateName == "crate") { val usePath = segments.joinToString("::").let { if (rootDefMap.isAtLeastEdition2018) it else it.removePrefix("crate::") } ImportInfo.LocalImportInfo(usePath) } else { val needInsertExternCrateItem = path.needExternCrate || !rootDefMap.isAtLeastEdition2018 && !rootDefMap.hasExternCrateInCrateRoot(crateName) val crateRelativePath = segments.copyOfRange(1, segments.size).joinToString("::") ImportInfo.ExternCrateImportInfo( crate = path.crate, externCrateName = crateName, needInsertExternCrateItem = needInsertExternCrateItem, crateRelativePath = crateRelativePath, hasModWithSameNameAsExternCrate = crateName in rootModData.childModules ) } } private fun CrateDefMap.hasExternCrateInCrateRoot(externCrateName: String): Boolean { val externDefMap = externPrelude[externCrateName] ?: return false return externCratesInRoot[externCrateName] == externDefMap } private fun RsNamedElement.asModPath(): ModPath? { val name = name ?: return null val modInfo = getModInfo(containingMod) ?: return null return modInfo.modData.path.append(name) }
mit
e4b8b0dc51a185fdfeb9f445e6cdf7f8
41.828025
131
0.688975
4.213033
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/annotator/fixes/AddMissingSupertraitImplFixTest.kt
2
9603
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator.fixes import org.rust.ide.annotator.ExplicitPreview import org.rust.ide.annotator.RsAnnotatorTestBase import org.rust.ide.annotator.RsErrorAnnotator class AddMissingSupertraitImplFixTest : RsAnnotatorTestBase(RsErrorAnnotator::class) { fun `test empty supertrait`() = checkFixByText("Implement missing supertrait(s)", """ trait A {} trait B: A {} struct S; <error>impl <error>B/*caret*/</error> for S</error> {} """, """ trait A {} trait B: A {} struct S; impl A for S {} impl B/*caret*/ for S {} """) fun `test supertrait with items`() = checkFixByText("Implement missing supertrait(s)", """ trait A { type FOO; const BAR: u32; fn foo(&self); } trait B: A {} struct S; <error>impl <error>B/*caret*/</error> for S</error> {} """, """ trait A { type FOO; const BAR: u32; fn foo(&self); } trait B: A {} struct S; impl A for S { type FOO = (); const BAR: u32 = 0; fn foo(&self) { todo!() } } impl B/*caret*/ for S {} """) fun `test multiple supertraits`() = checkFixByText("Implement missing supertrait(s)", """ trait A {} trait B {} trait C: A + B {} struct S; <error>impl <error>C/*caret*/</error> for S</error> {} """, """ trait A {} trait B {} trait C: A + B {} struct S; impl A for S {} impl B for S {} impl C/*caret*/ for S {} """) fun `test grandparent supertrait`() = checkFixByText("Implement missing supertrait(s)", """ trait A {} trait B: A {} trait C: B {} struct S; <error>impl <error>C/*caret*/</error> for S</error> {} """, """ trait A {} trait B: A {} trait C: B {} struct S; impl B for S {} impl A for S {} impl C/*caret*/ for S {} """) fun `test do not implement supertrait multiple times`() = checkFixByText("Implement missing supertrait(s)", """ trait A {} trait B: A {} trait C: B + A {} struct S; <error>impl <error>C/*caret*/</error> for S</error> {} """, """ trait A {} trait B: A {} trait C: B + A {} struct S; impl B for S {} impl A for S {} impl C/*caret*/ for S {} """) fun `test implement supertrait multiple times with different generic arguments`() = checkFixByText("Implement missing supertrait(s)", """ trait A<T> {} trait B: A<u32> {} trait C: B + A<bool> {} struct S; <error>impl <error>C/*caret*/</error> for S</error> {} """, """ trait A<T> {} trait B: A<u32> {} trait C: B + A<bool> {} struct S; impl B for S {} impl A<u32> for S {} impl A<bool> for S {} impl C/*caret*/ for S {} """) fun `test already implemented trait`() = checkFixByText("Implement missing supertrait(s)", """ trait A {} trait B {} trait C: A + B {} struct S; impl B for S {} <error>impl <error>C/*caret*/</error> for S</error> {} """, """ trait A {} trait B {} trait C: A + B {} struct S; impl B for S {} impl A for S {} impl C/*caret*/ for S {} """) fun `test implemented trait for specific generic argument`() = checkFixByText("Implement missing supertrait(s)", """ trait A<T> { fn foo(&self) -> T; } trait C<T>: A<T> {} struct S; <error>impl <error>C<u32>/*caret*/</error> for S</error> {} """, """ trait A<T> { fn foo(&self) -> T; } trait C<T>: A<T> {} struct S; impl A<u32> for S { fn foo(&self) -> u32 { todo!() } } impl C<u32>/*caret*/ for S {} """) fun `test trait partially implemented for specific type`() = checkFixByText("Implement missing supertrait(s)", """ trait A<T> {} trait C<T>: A<T> {} struct S; impl A<u32> for S {} <error>impl <R> <error>C<R>/*caret*/</error> for S</error> {} """, """ trait A<T> {} trait C<T>: A<T> {} struct S; impl A<u32> for S {} impl<R> A<R> for S {} impl <R> C<R>/*caret*/ for S {} """) fun `test generic type generic type argument`() = checkFixByText("Implement missing supertrait(s)", """ trait A<T> {} trait B<T>: A<T> {} struct S<T>(T); <error>impl <R> <error>B<u32>/*caret*/</error> for S<R></error> {} """, """ trait A<T> {} trait B<T>: A<T> {} struct S<T>(T); impl<R> A<u32> for S<R> {} impl <R> B<u32> for S<R> {} """) fun `test generic type specific type argument`() = checkFixByText("Implement missing supertrait(s)", """ trait A<T> {} trait B<T>: A<T> {} struct S<T>(T); <error>impl <error>B<u32>/*caret*/</error> for S<bool></error> {} """, """ trait A<T> {} trait B<T>: A<T> {} struct S<T>(T); impl A<u32> for S<bool> {} impl B<u32> for S<bool> {} """) // TODO: psiSubst merging? fun `test recursive generics`() = checkFixByText("Implement missing supertrait(s)", """ trait T1<A> {} trait T2<B>: T1<B> {} trait T3<D>: T2<D> {} trait T4<R>: T3<R> {} trait T5<C>: T4<C> {} trait T6<D>: T5<D> {} trait T7<E>: T6<E> {} struct S<T>(T); <error>impl <R> <error>T7<R>/*caret*/</error> for S<R></error> {} """, """ trait T1<A> {} trait T2<B>: T1<B> {} trait T3<D>: T2<D> {} trait T4<R>: T3<R> {} trait T5<C>: T4<C> {} trait T6<D>: T5<D> {} trait T7<E>: T6<E> {} struct S<T>(T); impl<R> T6<R> for S<R> {} impl<R> T5<R> for S<R> {} impl<R> T4<R> for S<R> {} impl<R> T3<R> for S<R> {} impl<R> T2<R> for S<R> {} impl<R> T1<R> for S<R> {} impl <R> T7<R> for S<R> {} """) fun `test filter unused type parameters`() = checkFixByText("Implement missing supertrait(s)", """ trait A {} trait B<T>: A {} struct S<T>(T); <error>impl <R> <error>B<R>/*caret*/</error> for S<u32></error> {} """, """ trait A {} trait B<T>: A {} struct S<T>(T); impl A for S<u32> {} impl <R> B<R> for S<u32> {} """) fun `test filter unused where clause`() = checkFixByText("Implement missing supertrait(s)", """ trait A {} trait B<T>: A {} struct S<T>(T); <error>impl <R> <error>B<R>/*caret*/</error> for S<u32></error> where R: A {} """, """ trait A {} trait B<T>: A {} struct S<T>(T); impl A for S<u32> {} impl <R> B<R> for S<u32> where R: A {} """) fun `test import trait`() = checkFixByText("Implement missing supertrait(s)", """ mod foo { pub trait A {} pub trait B: A {} } struct S; <error>impl <error>foo::B/*caret*/</error> for S</error> {} """, """ use crate::foo::A; mod foo { pub trait A {} pub trait B: A {} } struct S; impl A for S {} impl foo::B/*caret*/ for S {} """, preview = ExplicitPreview(""" mod foo { pub trait A {} pub trait B: A {} } struct S; impl A for S {} impl foo::B for S {} """)) fun `test empty supertrait with an impl for normalizable associated type`() = checkFixByText("Implement missing supertrait(s)", """ struct Struct; trait Trait { type Item; } impl Trait for Struct { type Item = S; } trait A {} trait B: A {} struct S; <error>impl <error>B/*caret*/</error> for <Struct as Trait>::Item</error> {} """, """ struct Struct; trait Trait { type Item; } impl Trait for Struct { type Item = S; } trait A {} trait B: A {} struct S; impl A for <Struct as Trait>::Item {} impl B/*caret*/ for <Struct as Trait>::Item {} """) fun `test grandparent supertrait with an impl for normalizable associated type`() = checkFixByText("Implement missing supertrait(s)", """ struct Struct; trait Trait { type Item; } impl Trait for Struct { type Item = S; } trait A {} trait B: A {} trait C: B {} struct S; impl A for S {} <error>impl <error>C/*caret*/</error> for <Struct as Trait>::Item</error> {} """, """ struct Struct; trait Trait { type Item; } impl Trait for Struct { type Item = S; } trait A {} trait B: A {} trait C: B {} struct S; impl A for S {} impl B for <Struct as Trait>::Item {} impl C/*caret*/ for <Struct as Trait>::Item {} """) } // TODO: all kinds of bounds and generics
mit
9fa7a7811c7f74cdb6114329277cdf35
21.280742
141
0.462564
3.641638
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/electronico/ejecutar/Electronica.kt
1
12796
package com.quijotelui.electronico.ejecutar import com.quijotelui.electronico.correo.EnviarCorreo import com.quijotelui.electronico.util.TipoComprobante import com.quijotelui.electronico.xml.GeneraFactura import com.quijotelui.electronico.xml.GeneraGuia import com.quijotelui.electronico.xml.GeneraNotaCredito import com.quijotelui.electronico.xml.GeneraRetencion import com.quijotelui.model.Electronico import com.quijotelui.service.* import com.quijotelui.ws.definicion.AutorizacionEstado import ec.gob.sri.comprobantes.ws.RespuestaSolicitud import ec.gob.sri.comprobantes.ws.Comprobante import java.text.SimpleDateFormat import java.time.LocalDateTime import java.util.* class Electronica(val codigo : String, val numero : String, val parametroService : IParametroService, val key : String) { var claveAcceso : String? = null private var facturaService : IFacturaService? = null private var retencionService : IRetencionService? = null private var notaCreditoService : INotaCreditoService? = null private var guiaService : IGuiaService? = null private var electronicoService : IElectronicoService? = null constructor(facturaService : IFacturaService, codigo : String, numero : String, parametroService : IParametroService, key: String, electronicoService : IElectronicoService) : this(codigo, numero, parametroService, key) { this.facturaService = facturaService this.electronicoService = electronicoService } constructor(retencionService : IRetencionService, codigo : String, numero : String, parametroService : IParametroService, key: String, electronicoService : IElectronicoService) : this(codigo, numero, parametroService, key) { this.retencionService = retencionService this.electronicoService = electronicoService } constructor(guiaService: IGuiaService, codigo : String, numero : String, parametroService : IParametroService, key: String, electronicoService : IElectronicoService) : this(codigo, numero, parametroService, key) { this.guiaService = guiaService this.electronicoService = electronicoService } constructor(notaCreditoService: INotaCreditoService, codigo : String, numero : String, parametroService : IParametroService, key: String, electronicoService : IElectronicoService) : this(codigo, numero, parametroService, key) { this.notaCreditoService = notaCreditoService this.electronicoService = electronicoService } fun enviar(tipo : TipoComprobante) : String { if (tipo == TipoComprobante.FACTURA) { val genera = GeneraFactura(this.facturaService!!, this.codigo, this.numero) this.claveAcceso = genera.xml() } else if (tipo == TipoComprobante.RETENCION) { val genera = GeneraRetencion(this.retencionService!!, this.codigo, this.numero) this.claveAcceso = genera.xml() } else if (tipo == TipoComprobante.NOTA_CREDITO) { val genera = GeneraNotaCredito(this.notaCreditoService!!, this.codigo, this.numero) this.claveAcceso = genera.xml() } else if (tipo == TipoComprobante.GUIA) { val genera = GeneraGuia(this.guiaService!!, this.codigo, this.numero) this.claveAcceso = genera.xml() } if (this.claveAcceso == ""){ println("Error al generar la Clave de Acceso") return "" } val procesar = ProcesarElectronica(parametroService, key) var respuestaEstado = "" if (procesar.firmar(this.claveAcceso!!)) { val respuesta = procesar.enviar(this.claveAcceso!!) respuesta?.let { respuestaEstado = grabarRespuestaEnvio(it) } procesar.imprimirPDF(this.claveAcceso!!, "", "", tipo) } return respuestaEstado } fun comprobar(informacionService : IInformacionService, tipo: TipoComprobante) { this.claveAcceso = generaClaveAcceso(tipo) val procesar = ProcesarElectronica(parametroService, key) val autorizacionEstado = procesar.comprobar(this.claveAcceso!!) grabarAutorizacion(autorizacionEstado) procesar.imprimirPDF(this.claveAcceso!!, autorizacionEstado.autorizacion.numeroAutorizacion, autorizacionEstado.autorizacion.fechaAutorizacion?.toString(), tipo) println("Estado de ${codigo} ${numero} para envío al correo: ${autorizacionEstado.autorizacion.estado}") if (autorizacionEstado.autorizacion.estado == "AUTORIZADO"){ if (tipo == TipoComprobante.FACTURA) { val correo = EnviarCorreo(codigo, numero, parametroService, key, informacionService, facturaService!!) correo.enviar(tipo) } else if (tipo == TipoComprobante.RETENCION) { val correo = EnviarCorreo(codigo, numero, parametroService, key, informacionService, retencionService!!) correo.enviar(tipo) } else if (tipo == TipoComprobante.NOTA_CREDITO) { val correo = EnviarCorreo(codigo, numero, parametroService, key, informacionService, notaCreditoService!!) correo.enviar(tipo) } } } fun generaClaveAcceso(tipo : TipoComprobante) :String { if (tipo == TipoComprobante.FACTURA) { val genera = GeneraFactura(this.facturaService!!, this.codigo, this.numero) return genera.claveAcceso.toString() } else if (tipo == TipoComprobante.RETENCION) { val genera = GeneraRetencion(this.retencionService!!, this.codigo, this.numero) return genera.claveAcceso.toString() } else if (tipo == TipoComprobante.NOTA_CREDITO) { val genera = GeneraNotaCredito(this.notaCreditoService!!, this.codigo, this.numero) return genera.claveAcceso.toString() } else if (tipo == TipoComprobante.GUIA) { val genera = GeneraGuia(this.guiaService!!, this.codigo, this.numero) return genera.claveAcceso.toString() } return "" } private fun grabarRespuestaEnvio(respuesta : RespuestaSolicitud) : String { var comprobante: Comprobante var electronico = Electronico() val fecha = LocalDateTime.now() var mensaje = "$fecha |" if (respuesta.comprobantes == null) { return "RESPUESTA NULA" } if (respuesta.comprobantes.comprobante.size > 0) { for (i in respuesta.comprobantes.comprobante.indices) { comprobante = respuesta.comprobantes.comprobante[i] as ec.gob.sri.comprobantes.ws.Comprobante // mensaje = mensaje + " " + comprobante.claveAcceso + ": " for (m in comprobante.mensajes.mensaje.indices) { val mensajeRespuesta = comprobante.mensajes.mensaje[m] if (mensajeRespuesta.mensaje != null) { mensaje = mensaje + " " + mensajeRespuesta.mensaje + " " + mensajeRespuesta.informacionAdicional } } mensaje += " " } } if (mensaje.equals("RECIBIDA")){ mensaje = "$mensaje Conexión exitosa" } // Si no existe en la base de datos se inserta if (this.electronicoService!!.findByComprobante(this.codigo, this.numero).isEmpty()) { electronico.codigo = this.codigo electronico.numero = this.numero electronico.observacion = mensaje electronico.estado = respuesta.estado this.electronicoService?.saveElectronico(electronico) } // Si existe en la base de datos se actualiza else{ var electronicoUpdate = this.electronicoService!!.findByComprobante(this.codigo, this.numero) for (e in electronicoUpdate.indices) { electronico = electronicoUpdate[e] } electronico.observacion = mensaje + " | " + electronico.observacion electronico.estado = respuesta.estado this.electronicoService!!.updateElectronico(electronico) } return respuesta.estado } private fun grabarAutorizacion(autorizacionEstado : AutorizacionEstado) { var electronico = Electronico() var fecha : String? = null var mensaje = "" // Mejorar // print("Estado autorización: " + autorizacionEstado.estadoAutorizacion.descripcion) if (autorizacionEstado.autorizacion.mensajes != null) { for (m in autorizacionEstado.autorizacion.mensajes.mensaje.indices) { val mensajeRespuesta = autorizacionEstado.autorizacion.mensajes.mensaje[m] if (mensajeRespuesta.mensaje != null) { mensaje = mensaje + " " + mensajeRespuesta.mensaje + " " + mensajeRespuesta.informacionAdicional } } } // Si no existe en la base de datos se inserta if (this.electronicoService!!.findByComprobante(this.codigo, this.numero).isEmpty()) { electronico.codigo = this.codigo electronico.numero = this.numero electronico.observacion = " | ${autorizacionEstado.autorizacion.numeroAutorizacion} " + "${autorizacionEstado.autorizacion.fechaAutorizacion} " electronico.numeroAutorizacion = autorizacionEstado.autorizacion.numeroAutorizacion electronico.estado = autorizacionEstado.autorizacion.estado fecha = autorizacionEstado.autorizacion.fechaAutorizacion.year.toString() + "-" + autorizacionEstado.autorizacion.fechaAutorizacion.month.toString() + "-" + autorizacionEstado.autorizacion.fechaAutorizacion.day.toString() + " " + autorizacionEstado.autorizacion.fechaAutorizacion.hour.toString() + ":" + autorizacionEstado.autorizacion.fechaAutorizacion.minute.toString() val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm") val fechaInDateType : Date fechaInDateType = simpleDateFormat.parse(fecha) println("Fecha autorización: $fechaInDateType") electronico.fechaAutorizacion = fechaInDateType this.electronicoService!!.saveElectronico(electronico) println("Guardado ${electronico.codigo} ${electronico.numero}") } // Si existe en la base de datos se actualiza else { var electronicoUpdate = this.electronicoService!!.findByComprobante(this.codigo, this.numero) for (e in electronicoUpdate.indices) { electronico = electronicoUpdate[e] } electronico.observacion = mensaje + electronico.observacion if (autorizacionEstado.autorizacion.fechaAutorizacion!=null) { electronico.observacion = " | ${autorizacionEstado.autorizacion.numeroAutorizacion} " + "${autorizacionEstado.autorizacion.fechaAutorizacion} " + electronico.observacion electronico.numeroAutorizacion = autorizacionEstado.autorizacion.numeroAutorizacion fecha = autorizacionEstado.autorizacion.fechaAutorizacion.year.toString() + "-" + autorizacionEstado.autorizacion.fechaAutorizacion.month.toString() + "-" + autorizacionEstado.autorizacion.fechaAutorizacion.day.toString() + " " + autorizacionEstado.autorizacion.fechaAutorizacion.hour.toString() + ":" + autorizacionEstado.autorizacion.fechaAutorizacion.minute.toString() electronico.estado = autorizacionEstado.autorizacion.estado val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm") val fechaInDateType: Date fechaInDateType = simpleDateFormat.parse(fecha) println("Fecha autorización: $fechaInDateType - Fecha Cruda : ${autorizacionEstado.autorizacion.fechaAutorizacion}") electronico.fechaAutorizacion = fechaInDateType } this.electronicoService!!.updateElectronico(electronico) println("Guardado ${electronico.codigo} ${electronico.numero}") } } }
gpl-3.0
c129575a4ef325db113431e17fe1c529
41.357616
132
0.634352
4.083972
false
false
false
false
charleskorn/batect
app/src/unitTest/kotlin/batect/ui/ConsoleSpec.kt
1
17040
/* Copyright 2017-2020 Charles Korn. 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 batect.ui import batect.os.Dimensions import batect.testutils.createForEachTest import batect.testutils.given import batect.testutils.on import batect.testutils.withMessage import batect.testutils.withPlatformSpecificLineSeparator import batect.ui.text.Text import batect.ui.text.TextRun import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.throws import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.io.ByteArrayOutputStream import java.io.PrintStream object ConsoleSpec : Spek({ val ESC = "\u001B" val whiteText = "$ESC[37m" val redText = "$ESC[31m" val boldText = "$ESC[1m" val reset = "$ESC[0m" describe("a console") { describe("when complex output is enabled") { val output by createForEachTest { ByteArrayOutputStream() } val console by createForEachTest { Console(PrintStream(output), enableComplexOutput = true, consoleDimensions = mock()) } on("printing text") { beforeEachTest { console.print("This is some text") } it("writes the text directly to the output") { assertThat(output.toString(), equalTo("This is some text")) } } on("printing a line of text") { beforeEachTest { console.println("This is some text") } it("writes the text directly to the output") { assertThat(output.toString(), equalTo("This is some text\n".withPlatformSpecificLineSeparator())) } } on("printing a blank line of text") { beforeEachTest { console.println() } it("writes a blank line directly to the output") { assertThat(output.toString(), equalTo("\n".withPlatformSpecificLineSeparator())) } } on("printing unformatted text") { beforeEachTest { console.print(Text("Hello")) } it("writes that text directly to the output") { assertThat(output.toString(), equalTo("Hello")) } } on("printing unformatted text, ending with a new line") { beforeEachTest { console.println(Text("Hello")) } it("writes that text directly to the output") { assertThat(output.toString(), equalTo("Hello\n".withPlatformSpecificLineSeparator())) } } on("printing some coloured text") { beforeEachTest { console.print(Text.white("the white text")) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${whiteText}the white text$reset")) } } on("printing some coloured text, ending with a new line") { beforeEachTest { console.println(Text.white("the white text")) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${whiteText}the white text$reset\n".withPlatformSpecificLineSeparator())) } } on("printing some bold text") { beforeEachTest { console.print(Text.bold("the bold text")) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${boldText}the bold text$reset")) } } on("printing some bold text, ending with a new line") { beforeEachTest { console.println(Text.bold("the bold text")) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${boldText}the bold text$reset\n".withPlatformSpecificLineSeparator())) } } on("printing bold and coloured text") { beforeEachTest { console.print(Text("bold and red", ConsoleColor.Red, true)) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${redText}${boldText}bold and red$reset")) } } on("printing bold and coloured text, ending with a new line") { beforeEachTest { console.println(Text("bold and red", ConsoleColor.Red, true)) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${redText}${boldText}bold and red$reset\n".withPlatformSpecificLineSeparator())) } } on("printing a series of unformatted text elements") { beforeEachTest { console.print(Text("Hello") + Text(" World")) } it("writes that text directly to the output") { assertThat(output.toString(), equalTo("Hello World")) } } on("printing a series of unformatted text elements, ending with a new line") { beforeEachTest { console.println(Text("Hello") + Text(" World")) } it("writes that text directly to the output") { assertThat(output.toString(), equalTo("Hello World\n".withPlatformSpecificLineSeparator())) } } on("printing a series of coloured text elements") { beforeEachTest { console.print(Text.red("red") + Text.white("white")) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${redText}red${reset}${whiteText}white$reset")) } } on("printing a series of coloured text elements, ending with a new line") { beforeEachTest { console.println(Text.red("red") + Text.white("white")) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${redText}red${reset}${whiteText}white$reset\n".withPlatformSpecificLineSeparator())) } } on("printing a series of bold and non-bold text elements") { beforeEachTest { console.print(Text.bold("bold") + Text("not")) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${boldText}bold${reset}not")) } } on("printing a series of bold and non-bold text elements, ending with a new line") { beforeEachTest { console.println(Text.bold("bold") + Text("not")) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${boldText}bold${reset}not\n".withPlatformSpecificLineSeparator())) } } on("printing some bold and coloured text elements") { beforeEachTest { console.print(Text.bold(Text.red("red") + Text.white("white"))) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${redText}${boldText}red${reset}${whiteText}${boldText}white$reset")) } } on("printing some bold and coloured text elements, ending with a new line") { beforeEachTest { console.println(Text.bold(Text.red("red") + Text.white("white"))) } it("writes the text to the output with the appropriate escape codes") { assertThat(output.toString(), equalTo("${redText}${boldText}red${reset}${whiteText}${boldText}white$reset\n".withPlatformSpecificLineSeparator())) } } describe("moving the cursor up") { on("moving the cursor up one line") { beforeEachTest { console.moveCursorUp() } it("writes the appropriate escape code to the output") { assertThat(output.toString(), equalTo("$ESC[1A")) } } on("moving the cursor up multiple lines") { beforeEachTest { console.moveCursorUp(23) } it("writes the appropriate escape code to the output") { assertThat(output.toString(), equalTo("$ESC[23A")) } } on("attempting to move the cursor up zero lines") { it("throws an appropriate exception") { assertThat({ console.moveCursorUp(0) }, throws<IllegalArgumentException>(withMessage("Number of lines must be positive."))) } } on("attempting to move the cursor up a negative number of lines") { it("throws an appropriate exception") { assertThat({ console.moveCursorUp(-1) }, throws<IllegalArgumentException>(withMessage("Number of lines must be positive."))) } } } describe("moving the cursor down") { on("moving the cursor down one line") { beforeEachTest { console.moveCursorDown() } it("writes the appropriate escape code to the output") { assertThat(output.toString(), equalTo("$ESC[1B")) } } on("moving the cursor down multiple lines") { beforeEachTest { console.moveCursorDown(23) } it("writes the appropriate escape code to the output") { assertThat(output.toString(), equalTo("$ESC[23B")) } } on("attempting to move the cursor down zero lines") { it("throws an appropriate exception") { assertThat({ console.moveCursorDown(0) }, throws<IllegalArgumentException>(withMessage("Number of lines must be positive."))) } } on("attempting to move the cursor down a negative number of lines") { it("throws an appropriate exception") { assertThat({ console.moveCursorDown(-1) }, throws<IllegalArgumentException>(withMessage("Number of lines must be positive."))) } } } on("clearing the current line") { beforeEachTest { console.clearCurrentLine() } it("writes the appropriate escape code sequence to the output") { assertThat(output.toString(), equalTo("\r$ESC[K")) } } on("moving to the start of the current line") { beforeEachTest { console.moveCursorToStartOfLine() } it("writes the appropriate escape code to the output") { assertThat(output.toString(), equalTo("\r")) } } } describe("when complex output is disabled") { val output by createForEachTest { ByteArrayOutputStream() } val console by createForEachTest { Console(PrintStream(output), enableComplexOutput = false, consoleDimensions = mock()) } on("printing text") { beforeEachTest { console.print("This is some text") } it("writes the text directly to the output") { assertThat(output.toString(), equalTo("This is some text")) } } on("printing a line of text") { beforeEachTest { console.println("This is some text") } it("writes the text directly to the output") { assertThat(output.toString(), equalTo("This is some text\n".withPlatformSpecificLineSeparator())) } } on("printing a blank line of text") { beforeEachTest { console.println() } it("writes a blank line directly to the output") { assertThat(output.toString(), equalTo("\n".withPlatformSpecificLineSeparator())) } } on("printing coloured text") { beforeEachTest { console.print(Text.white("the white text")) } it("writes the text to the output without any escape codes") { assertThat(output.toString(), equalTo("the white text")) } } on("printing bold text") { beforeEachTest { console.print(Text.bold("the bold text")) } it("writes the text to the output without any escape codes") { assertThat(output.toString(), equalTo("the bold text")) } } on("moving the cursor up") { it("throws an appropriate exception") { assertThat({ console.moveCursorUp(1) }, throws<UnsupportedOperationException>(withMessage("Cannot move the cursor when complex output is disabled."))) } } on("moving the cursor down") { it("throws an appropriate exception") { assertThat({ console.moveCursorDown(1) }, throws<UnsupportedOperationException>(withMessage("Cannot move the cursor when complex output is disabled."))) } } on("clearing the current line") { it("throws an appropriate exception") { assertThat({ console.clearCurrentLine() }, throws<UnsupportedOperationException>(withMessage("Cannot clear the current line when complex output is disabled."))) } } on("moving to the start of the current line") { it("throws an appropriate exception") { assertThat({ console.moveCursorToStartOfLine() }, throws<UnsupportedOperationException>(withMessage("Cannot move the cursor when complex output is disabled."))) } } } describe("printing text restricted to the width of the console") { given("the console dimensions are not available") { val consoleDimensions by createForEachTest { mock<ConsoleDimensions> { on { current } doReturn null as Dimensions? } } val output by createForEachTest { ByteArrayOutputStream() } val console by createForEachTest { Console(PrintStream(output), true, consoleDimensions) } on("printing text") { beforeEachTest { console.printLineLimitedToConsoleWidth(TextRun("This is some text")) } it("prints all text") { assertThat(output.toString(), equalTo("This is some text\n".withPlatformSpecificLineSeparator())) } } } given("the console dimensions are available") { val consoleDimensions by createForEachTest { mock<ConsoleDimensions> { on { current } doReturn Dimensions(40, 10) } } val output by createForEachTest { ByteArrayOutputStream() } val console by createForEachTest { Console(PrintStream(output), true, consoleDimensions) } on("printing text") { val text = mock<TextRun> { on { limitToLength(10) } doReturn TextRun("This is some shortened text") } beforeEachTest { console.printLineLimitedToConsoleWidth(text) } it("prints the shortened text") { assertThat(output.toString(), equalTo("This is some shortened text\n".withPlatformSpecificLineSeparator())) } } } } } })
apache-2.0
3f6c99b2d8c721ec3fedc7fb2cc6dcc4
42.580563
180
0.558509
5.444089
false
true
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/model/Contribuyente.kt
1
842
package com.quijotelui.model import org.hibernate.annotations.Immutable import java.io.Serializable import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table @Entity @Immutable @Table(name = "v_ele_contribuyentes") class Contribuyente : Serializable{ @Id @Column(name = "id") var id : Long? = null @Column(name = "razon_social") var razonSocial : String? = null @Column(name = "nombre_comercial") var nombreComercial : String? = null @Column(name = "ruc") var ruc : String? = null @Column(name = "direccion") var direccion : String? = null @Column(name = "obligado_contabilidad") var obligadoContabilidad : String? = null @Column(name = "contribuyente_especial") var contribuyenteEspecial : String? = null }
gpl-3.0
fc78f0c9a9cd28cf7e0fdb50287bd7fe
21.783784
46
0.699525
3.368
false
false
false
false
SimpleMobileTools/Simple-Notes
app/src/main/kotlin/com/simplemobiletools/notes/pro/helpers/NotesImporter.kt
1
3593
package com.simplemobiletools.notes.pro.helpers import android.content.Context import com.google.gson.Gson import com.google.gson.JsonSyntaxException import com.google.gson.reflect.TypeToken import com.simplemobiletools.commons.extensions.showErrorToast import com.simplemobiletools.commons.helpers.PROTECTION_NONE import com.simplemobiletools.commons.helpers.ensureBackgroundThread import com.simplemobiletools.notes.pro.extensions.notesDB import com.simplemobiletools.notes.pro.models.Note import java.io.File class NotesImporter(private val context: Context) { enum class ImportResult { IMPORT_FAIL, IMPORT_OK, IMPORT_PARTIAL, IMPORT_NOTHING_NEW } private val gson = Gson() private var notesImported = 0 private var notesFailed = 0 fun importNotes(path: String, filename: String, callback: (result: ImportResult) -> Unit) { ensureBackgroundThread { try { val inputStream = if (path.contains("/")) { File(path).inputStream() } else { context.assets.open(path) } inputStream.bufferedReader().use { reader -> val json = reader.readText() val type = object : TypeToken<List<Note>>() {}.type val notes = gson.fromJson<List<Note>>(json, type) val totalNotes = notes.size if (totalNotes <= 0) { callback.invoke(ImportResult.IMPORT_NOTHING_NEW) return@ensureBackgroundThread } for (note in notes) { val exists = context.notesDB.getNoteIdWithTitle(note.title) != null if (!exists) { context.notesDB.insertOrUpdate(note) notesImported++ } } } } catch (e: JsonSyntaxException) { // Import notes expects a json with note name, content etc, but lets be more flexible and accept the basic files with note content only too val inputStream = if (path.contains("/")) { File(path).inputStream() } else { context.assets.open(path) } inputStream.bufferedReader().use { reader -> val text = reader.readText() val note = Note(null, filename, text, NoteType.TYPE_TEXT.value, "", PROTECTION_NONE, "") var i = 1 if (context.notesDB.getNoteIdWithTitle(note.title) != null) { while (true) { val tryTitle = "$filename ($i)" if (context.notesDB.getNoteIdWithTitle(tryTitle) == null) { break } i++ } note.title = "$filename ($i)" } context.notesDB.insertOrUpdate(note) notesImported++ } } catch (e: Exception) { context.showErrorToast(e) notesFailed++ } callback.invoke( when { notesImported == 0 -> ImportResult.IMPORT_FAIL notesFailed > 0 -> ImportResult.IMPORT_PARTIAL else -> ImportResult.IMPORT_OK } ) } } }
gpl-3.0
85a51feb8b53f12afc3c0b3ecc578c60
38.054348
155
0.507097
5.485496
false
false
false
false
taigua/exercism
kotlin/binary-search/src/main/kotlin/BinarySearch.kt
1
556
/** * Created by Corwin on 2017/2/1. */ object BinarySearch { fun <T: Comparable<T>>search(list: List<T>, target: T) : Int { if (list.sorted() != list) throw IllegalArgumentException() var hi = list.size - 1 var lo = 0 while (hi >= lo) { val guess = lo + (hi - lo) / 2 if (list[guess] > target) hi = guess - 1 else if (list[guess] < target) lo = guess + 1 else return guess } return -1 } }
mit
7d3cf415bd91da531bb5f97c4c0c3571
24.318182
66
0.442446
3.915493
false
false
false
false
Soya93/Extract-Refactoring
plugins/settings-repository/src/keychain/FileCredentialsStore.kt
4
2779
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.keychain import com.intellij.openapi.util.PasswordUtil import com.intellij.util.delete import com.intellij.util.exists import com.intellij.util.inputStream import com.intellij.util.io.IOUtil import com.intellij.util.outputStream import java.io.DataInputStream import java.io.DataOutputStream import java.io.IOException import java.nio.file.Path class FileCredentialsStore(private val storeFile: Path) : CredentialsStore { // we store only one for any URL, don't want to add complexity, OS keychain should be used private var credentials: Credentials? = null private var dataLoaded = !storeFile.exists() private fun ensureLoaded() { if (dataLoaded) { return } dataLoaded = true if (storeFile.exists()) { try { var hasErrors = true val `in` = DataInputStream(storeFile.inputStream().buffered()) try { credentials = Credentials(PasswordUtil.decodePassword(IOUtil.readString(`in`)), PasswordUtil.decodePassword(IOUtil.readString(`in`))) hasErrors = false } finally { if (hasErrors) { //noinspection ResultOfMethodCallIgnored storeFile.delete() } `in`.close() } } catch (e: IOException) { LOG.error(e) } } } override fun get(host: String?, sshKeyFile: String?): Credentials? { ensureLoaded() return credentials } override fun reset(host: String) { if (credentials != null) { dataLoaded = true storeFile.delete() credentials = Credentials(credentials!!.id, null) } } override fun save(host: String?, credentials: Credentials, sshKeyFile: String?) { if (credentials.equals(this.credentials)) { return } this.credentials = credentials try { val out = DataOutputStream(storeFile.outputStream().buffered()) try { IOUtil.writeString(PasswordUtil.encodePassword(credentials.id), out) IOUtil.writeString(PasswordUtil.encodePassword(credentials.token), out) } finally { out.close() } } catch (e: IOException) { LOG.error(e) } } }
apache-2.0
201c6c567aab5c9c450de779b2c8211b
27.367347
143
0.672544
4.281972
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/project/ElmModuleType.kt
1
1416
package org.elm.ide.project import com.intellij.ide.util.projectWizard.EmptyModuleBuilder import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.openapi.module.ModuleType import com.intellij.openapi.module.ModuleTypeManager import org.elm.ide.icons.ElmIcons import javax.swing.Icon /* DEPRECATED! We used to define a custom module as part of IntelliJ IDEA's new project wizard in order to provide a `ModuleBuilder`. But that doesn't work on WebStorm, and it was needlessly complicated by a bunch of Java junk. I am now standardizing on a "web project" technique that is simpler and works for both WebStorm and IDEA. The `moduleType` extension point is no longer strictly necessary, HOWEVER, if we were to remove it entirely, users who created an IntelliJ project using our *old* "new project" wizard, would see an "unknown module type" error when they open their project. */ class ElmModuleType : ModuleType<ModuleBuilder>(ID) { override fun createModuleBuilder() = EmptyModuleBuilder() override fun getName(): String = "Elm" override fun getDescription(): String = "Elm module" override fun getNodeIcon(isOpened: Boolean): Icon = ElmIcons.FILE companion object { val ID = "ELM_MODULE" val INSTANCE: ElmModuleType by lazy { ModuleTypeManager.getInstance().findByID(ID) as ElmModuleType } } }
mit
913ffa18df199a962000c74ebf1d9d8c
35.333333
94
0.741525
4.425
false
false
false
false
inorichi/tachiyomi-extensions
src/ru/nudemoon/src/eu/kanade/tachiyomi/extension/ru/nudemoon/Nudemoon.kt
1
11230
package eu.kanade.tachiyomi.extension.ru.nudemoon import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.net.URLEncoder import java.text.SimpleDateFormat import java.util.Locale @Nsfw class Nudemoon : ParsedHttpSource() { override val name = "Nude-Moon" override val baseUrl = "https://nude-moon.net" override val lang = "ru" override val supportsLatest = true private val cookiesHeader by lazy { val cookies = mutableMapOf<String, String>() cookies["NMfYa"] = "1" buildCookies(cookies) } private fun buildCookies(cookies: Map<String, String>) = cookies.entries.joinToString(separator = "; ", postfix = ";") { "${URLEncoder.encode(it.key, "UTF-8")}=${URLEncoder.encode(it.value, "UTF-8")}" } override val client = network.client.newBuilder() .addNetworkInterceptor { chain -> val newReq = chain .request() .newBuilder() .addHeader("Cookie", cookiesHeader) .addHeader("Referer", baseUrl) .build() chain.proceed(newReq) }.build()!! override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/all_manga?views&rowstart=${30 * (page - 1)}", headers) override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/all_manga?date&rowstart=${30 * (page - 1)}", headers) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { // Search by query on this site works really badly, i don't even sure of the need to implement it val url = if (query.isNotEmpty()) { "$baseUrl/search?stext=${URLEncoder.encode(query, "CP1251")}&rowstart=${30 * (page - 1)}" } else { var genres = "" var order = "" for (filter in if (filters.isEmpty()) getFilterList() else filters) { when (filter) { is GenreList -> { filter.state.forEach { f -> if (f.state) { genres += f.id + '+' } } } } } if (genres.isNotEmpty()) { for (filter in filters) { when (filter) { is OrderBy -> { // The site has no ascending order order = arrayOf("&date", "&views", "&like")[filter.state!!.index] } } } "$baseUrl/tags/${genres.dropLast(1)}$order&rowstart=${30 * (page - 1)}" } else { for (filter in filters) { when (filter) { is OrderBy -> { // The site has no ascending order order = arrayOf("all_manga?date", "all_manga?views", "all_manga?like")[filter.state!!.index] } } } "$baseUrl/$order&rowstart=${30 * (page - 1)}" } } return GET(url, headers) } override fun popularMangaSelector() = "tr[valign=top]" override fun latestUpdatesSelector() = popularMangaSelector() override fun searchMangaSelector() = popularMangaSelector() override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select("img[class^=news]").attr("abs:src") element.select("a:has(h2)").let { manga.title = it.text() manga.setUrlWithoutDomain(it.attr("href")) } return manga } override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun popularMangaNextPageSelector() = "a.small:contains(Следующая)" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() override fun mangaDetailsParse(document: Document): SManga { val manga = SManga.create() manga.author = document.select("div.tbl1 a[href^=mangaka]").text() manga.genre = document.select("div.tbl2 span.tag-links a").joinToString { it.text() } manga.description = document.select(".description").text() manga.thumbnail_url = document.select("tr[valign=top] img[class^=news]").attr("abs:src") return manga } override fun chapterListRequest(manga: SManga): Request { val chapterUrl = if (manga.title.contains("\\s#\\d+".toRegex())) "/vse_glavy/" + manga.title.split("\\s#\\d+".toRegex())[0].replace("\\W".toRegex(), "_") else manga.url return GET(baseUrl + chapterUrl, headers) } override fun chapterListSelector() = popularMangaSelector() override fun chapterListParse(response: Response): List<SChapter> { val responseUrl = response.request.url.toString() val document = response.asJsoup() if (!responseUrl.contains("/vse_glavy/")) { return listOf(chapterFromElement(document)) } // Order chapters by its number 'cause on the site they are in random order return document.select(chapterListSelector()).sortedByDescending { val regex = "#(\\d+)".toRegex() val chapterName = it.select("img[class^=news]").first().parent().attr("title") regex.find(chapterName)?.groupValues?.get(1)?.toInt() ?: 0 }.map { chapterFromElement(it) } } override fun chapterFromElement(element: Element): SChapter { val chapter = SChapter.create() val infoElem = element.select("tr[valign=top]").first().parent() val chapterName = infoElem.select("h1, h2").text() var chapterUrl = infoElem.select("a[title]:has(img)").attr("href") if (!chapterUrl.contains("-online")) { chapterUrl = chapterUrl.replace("/\\d+".toRegex(), "$0-online") } else { chapter.chapter_number = 1F } chapter.setUrlWithoutDomain(if (!chapterUrl.startsWith("/")) "/$chapterUrl" else chapterUrl) chapter.name = chapterName chapter.date_upload = infoElem.text().substringAfter("Дата:").substringBefore("Просмотров").trim().let { try { SimpleDateFormat("dd MMMM yyyy", Locale("ru")).parse(it)?.time ?: 0L } catch (e: Exception) { 0 } } return chapter } override fun pageListParse(response: Response): List<Page> { val imgScript = response.asJsoup().select("script:containsData(var images)").first().data() return Regex("""images\[(\d+)].src\s=\s'(http.*)'""").findAll(imgScript).map { Page(it.groupValues[1].toInt(), imageUrl = it.groupValues[2]) }.toList() } override fun imageUrlParse(document: Document) = throw Exception("Not Used") override fun pageListParse(document: Document): List<Page> = throw Exception("Not Used") private class Genre(name: String, val id: String = name.replace(' ', '_')) : Filter.CheckBox(name.capitalize()) private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Тэги", genres) private class OrderBy : Filter.Sort( "Сортировка", arrayOf("Дата", "Просмотры", "Лайки"), Selection(1, false) ) override fun getFilterList() = FilterList( OrderBy(), GenreList(getGenreList()) ) private fun getGenreList() = listOf( Genre("анал"), Genre("без цензуры"), Genre("беременные"), Genre("близняшки"), Genre("большие груди"), Genre("в бассейне"), Genre("в больнице"), Genre("в ванной"), Genre("в общественном месте"), Genre("в первый раз"), Genre("в транспорте"), Genre("в туалете"), Genre("гарем"), Genre("гипноз"), Genre("горничные"), Genre("горячий источник"), Genre("групповой секс"), Genre("драма"), Genre("запредельное"), Genre("золотой дождь"), Genre("зрелые женщины"), Genre("идолы"), Genre("извращение"), Genre("измена"), Genre("имеют парня"), Genre("клизма"), Genre("колготки"), Genre("комиксы"), Genre("комиксы 3D"), Genre("косплей"), Genre("мастурбация"), Genre("мерзкий мужик"), Genre("много спермы"), Genre("молоко"), Genre("монстры"), Genre("на камеру"), Genre("на природе"), Genre("обычный секс"), Genre("огромный член"), Genre("пляж"), Genre("подглядывание"), Genre("принуждение"), Genre("продажность"), Genre("пьяные"), Genre("рабыни"), Genre("романтика"), Genre("с ушками"), Genre("секс игрушки"), Genre("спящие"), Genre("страпон"), Genre("студенты"), Genre("суккуб"), Genre("тентакли"), Genre("толстушки"), Genre("трапы"), Genre("ужасы"), Genre("униформа"), Genre("учитель и ученик"), Genre("фемдом"), Genre("фетиш"), Genre("фурри"), Genre("футанари"), Genre("футфетиш"), Genre("фэнтези"), Genre("цветная"), Genre("чикан"), Genre("чулки"), Genre("шимейл"), Genre("эксгибиционизм"), Genre("юмор"), Genre("юри"), Genre("ahegao"), Genre("BDSM"), Genre("ganguro"), Genre("gender bender"), Genre("megane"), Genre("mind break"), Genre("monstergirl"), Genre("netorare"), Genre("nipple penetration"), Genre("titsfuck"), Genre("x-ray") ) }
apache-2.0
180054ecc81cecff7d91c20b2e5d51d1
33.568627
120
0.565797
4.143361
false
false
false
false
felipebz/sonar-plsql
its/ruling/src/test/kotlin/org/sonar/plsqlopen/it/OracleDocsExtractor.kt
1
2948
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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.sonar.plsqlopen.it import org.jsoup.Jsoup import java.io.File import java.util.zip.ZipFile fun main() { OracleDocsExtractor().extract() } class OracleDocsExtractor { fun extract() { val zipFile = ZipFile(System.getProperty("oracleDocs")) // example: https://docs.oracle.com/en/database/oracle/oracle-database/19/zip/oracle-database_19.zip val outputDir = File("../sources/oracle-database_19") if (outputDir.exists()) { outputDir.deleteRecursively() } outputDir.mkdirs() val entries = zipFile.entries() while (entries.hasMoreElements()) { val entry = entries.nextElement() if (!entry.isDirectory && File(entry.name).parent.endsWith("sqlrf")) { zipFile.getInputStream(entry).use { stream -> Jsoup.parse(stream, Charsets.UTF_8.name(), "").run { select("pre.oac_no_warn").forEachIndexed { index, element -> var text = element.text() val lines = text.lines() val line = lines.indexOfFirst { it.contains("---") } try { if (line != -1) { text = text.lines().take(line - 2).joinToString(separator = "\n") } if (text.isNotEmpty()) { val name = "${File(entry.name).nameWithoutExtension}-$index.sql" val path = entry.name.substring(entry.name.indexOf("sqlrf")) text = "-- https://docs.oracle.com/en/database/oracle/oracle-database/19/$path\n$text" File(outputDir.absolutePath, name).writeText(text, Charsets.UTF_8) } } catch (e: Exception) { } } } } } } } }
lgpl-3.0
919439e1be46a7d4d5683db1c7615609
39.383562
164
0.548847
4.770227
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lang/documentation/XQueryDocumentationProvider.kt
1
7667
/* * Copyright (C) 2019-2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.lang.documentation import com.intellij.lang.documentation.AbstractDocumentationProvider import com.intellij.navigation.NavigationItem import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.navigation.ItemPresentationEx import uk.co.reecedunn.intellij.plugin.core.psi.resourcePath import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation import uk.co.reecedunn.intellij.plugin.xdm.module.path.XdmModuleType import uk.co.reecedunn.intellij.plugin.xdm.types.XdmElementNode import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xdm.types.element import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathInlineFunctionExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathNCName import uk.co.reecedunn.intellij.plugin.xpm.context.expand import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionDeclaration import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionReference import uk.co.reecedunn.intellij.plugin.xpm.optree.function.impl.XpmFunctionReferenceImpl import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceDeclaration import uk.co.reecedunn.intellij.plugin.xqdoc.documentation.XQDocDocumentation import uk.co.reecedunn.intellij.plugin.xqdoc.documentation.XQDocDocumentationSourceProvider import uk.co.reecedunn.intellij.plugin.xqdoc.documentation.sections import uk.co.reecedunn.intellij.plugin.xqdoc.resources.XQDocTemplates import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.* import uk.co.reecedunn.intellij.plugin.xquery.resources.XQueryBundle class XQueryDocumentationProvider : AbstractDocumentationProvider() { companion object { private fun getElementPresentationText(decl: XpmNamespaceDeclaration, element: PsiElement): String? { val prefix = decl.namespacePrefix?.data val uri = decl.namespaceUri?.data ?: return null val path = decl.namespaceUri?.element?.containingFile?.resourcePath() return if (element is XQueryModuleDecl) prefix?.let { "module namespace $it = \"$uri\"\nat \"$path\"" } ?: "module namespace \"$uri\"\nat \"$path\"" else prefix?.let { "namespace $it = \"$uri\"" } ?: "namespace \"{$uri}\"" } fun getElementPresentationText(element: PsiElement?): String? = when (val parent = element?.parent) { is XQueryFunctionDecl -> { val sig = when (val presentation = (parent as NavigationItem).presentation) { is ItemPresentationEx -> presentation.getPresentableText(ItemPresentationEx.Type.StructureView) else -> null } "declare function $sig" } is XPathInlineFunctionExpr -> (parent as XpmFunctionDeclaration).let { val params = it.paramListPresentableText val returnType = it.returnType if (returnType == null) "function $params" else "function $params as ${returnType.typeName}" } is XQueryVarDecl -> { val sig = (parent as NavigationItem).presentation?.presentableText "declare variable \$$sig" } is XPathNCName -> (parent.parent as? XpmNamespaceDeclaration)?.let { decl -> getElementPresentationText(decl, parent.parent) } is XdmElementNode -> { val dynamic = XQueryBundle.message("element.dynamic") "element ${parent.nodeName?.let { qname_presentation(it) } ?: dynamic} {...}" } else -> (element as? XQueryModule)?.let { when (val module = it.mainOrLibraryModule) { is XQueryLibraryModule -> { val moduleDecl = module.firstChild getElementPresentationText(moduleDecl as XpmNamespaceDeclaration, moduleDecl) } else -> null } } } } override fun getQuickNavigateInfo(element: PsiElement?, originalElement: PsiElement?): String? { return getElementPresentationText(element) } // Generate the main documentation for the documentation pane. override fun generateDoc(element: PsiElement?, originalElement: PsiElement?): String? = originalElement?.let { val text = lookup(it).firstOrNull()?.sections ?: return@let null return XQDocTemplates.QuickDocumentation.replace("[CONTENTS]", text) } // Generate the summary documentation for the documentation hover tooltip. override fun generateHoverDoc(element: PsiElement, originalElement: PsiElement?): String? = originalElement?.let { val text = lookup(it).firstOrNull()?.sections ?: return@let null return XQDocTemplates.QuickDocumentation.replace("[CONTENTS]", text) } // Generate the external documentation links displayed below the main/summary documentation. override fun getUrlFor(element: PsiElement?, originalElement: PsiElement?): List<String> { return originalElement?.let { lookup(it).mapNotNull { ref -> ref.href }.toList() } ?: emptyList() } private fun lookup(element: PsiElement): Sequence<XQDocDocumentation> { val parent = element.parent return when { (parent as? XsQNameValue)?.prefix?.element === element -> lookupPrefix(parent as XsQNameValue) (parent as? XsQNameValue)?.localName?.element === element -> lookupLocalName(parent as XsQNameValue) else -> emptySequence() } } private fun lookupPrefix(qname: XsQNameValue): Sequence<XQDocDocumentation> { val decl = qname.expand().firstOrNull()?.namespace?.element?.parent as? XpmNamespaceDeclaration return decl?.let { XQDocDocumentationSourceProvider.lookup(it) } ?: emptySequence() } private fun lookupLocalName(qname: XsQNameValue): Sequence<XQDocDocumentation> { return when (val ref = qname.element?.parent) { is XpmFunctionReference -> lookupFunction(ref.functionName, ref.positionalArity, ref.keywordArity) is XpmFunctionDeclaration -> lookupFunction(ref.functionName, ref.declaredArity, 0) is XpmNamespaceDeclaration -> XQDocDocumentationSourceProvider.lookup(ref) else -> emptySequence() } } private fun lookupFunction( functionName: XsQNameValue?, positionalArity: Int, keywordArity: Int ): Sequence<XQDocDocumentation> { // NOTE: NCName may bind to the current module (MarkLogic behaviour) and the default function namespace. return functionName?.expand()?.flatMap { XQDocDocumentationSourceProvider.lookup(XpmFunctionReferenceImpl(it, positionalArity, keywordArity)) }?.filter { it.moduleTypes.contains(XdmModuleType.XQuery) } ?: emptySequence() } }
apache-2.0
79b81af318cad4f0ba95512604d91794
50.113333
118
0.685014
4.880331
false
false
false
false
grueni75/GeoDiscoverer
Source/Platform/Target/Android/wear/src/main/java/com/untouchableapps/android/geodiscoverer/theme/Theme.kt
1
1767
//============================================================================ // Name : Theme // Author : Matthias Gruenewald // Copyright : Copyright 2010-2022 Matthias Gruenewald // // This file is part of GeoDiscoverer. // // GeoDiscoverer 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. // // GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>. // //============================================================================ package com.untouchableapps.android.geodiscoverer.theme import androidx.compose.runtime.Composable import androidx.compose.ui.res.colorResource import androidx.wear.compose.material.Colors import androidx.wear.compose.material.MaterialTheme import com.untouchableapps.android.geodiscoverer.core.R @Composable fun WearAppTheme( content: @Composable () -> Unit ) { val wearColorPalette = Colors( primary = colorResource(id = R.color.gd_orange), surface = colorResource(id = R.color.gd_surface), ) MaterialTheme( colors = wearColorPalette, typography = Typography, // For shapes, we generally recommend using the default Material Wear shapes which are // optimized for round and non-round devices. content = content ) }
gpl-3.0
7018b3db757423de94e28e11f4b5f0f1
38.266667
94
0.666101
4.428571
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-w3/main/uk/co/reecedunn/intellij/plugin/w3/documentation/FunctionsAndOperatorsDocumentation.kt
1
3410
/* * Copyright (C) 2019-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.w3.documentation import com.intellij.openapi.util.Key import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.TextNode import uk.co.reecedunn.intellij.plugin.core.util.UserDataHolderBase import uk.co.reecedunn.intellij.plugin.xpath.lang.FunctionsAndOperatorsSpec import uk.co.reecedunn.intellij.plugin.xpm.lang.documentation.XpmDocumentationSource import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionReference import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceDeclaration import uk.co.reecedunn.intellij.plugin.xqdoc.documentation.* import java.util.* object FunctionsAndOperatorsDocumentation : UserDataHolderBase(), XQDocDocumentationSourceProvider, XQDocDocumentationIndex { // region Namespaces private val NAMESPACES_31 = mapOf( "http://www.w3.org/2005/xpath-functions/array" to "array", "http://www.w3.org/2005/xpath-functions" to "fn", "http://www.w3.org/2005/xpath-functions/map" to "map", "http://www.w3.org/2005/xpath-functions/math" to "math" ) // endregion // region XQDocDocumentationIndex private val DOCUMENT = Key.create<Optional<Document>>("DOCUMENT") private val active = FunctionsAndOperatorsSpec.REC_3_1_20170321 as XpmDocumentationSource private val doc: Document? get() = computeUserDataIfAbsent(DOCUMENT) { val file = XQDocDocumentationDownloader.getInstance().load(active, download = true) @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") // charsetName can be null Optional.ofNullable(file?.let { Jsoup.parse(it.inputStream, null as String?, "") }) }.orElse(null) override fun invalidate(source: XpmDocumentationSource) { if (source === active) { clearUserData(DOCUMENT) } } override fun lookup(ref: XpmFunctionReference): XQDocFunctionDocumentation? { val prefix = NAMESPACES_31[ref.functionName?.namespace?.data] ?: return null val localName = ref.functionName?.localName?.data ?: return null val lookupName = "$prefix:$localName" val match = doc?.select("h3 > a, h4 > a")?.firstOrNull { val parts = (it.nextSibling() as? TextNode)?.text()?.split(" ") ?: return@firstOrNull false val name = parts.asReversed().find { part -> part.isNotEmpty() } name == lookupName } return match?.let { W3CFunctionReference(it.parent()?.parent()!!, active.href) } } override fun lookup(decl: XpmNamespaceDeclaration): XQDocDocumentation? = null override val sources: List<XpmDocumentationSource> by lazy { FunctionsAndOperatorsSpec.versions.filterIsInstance<XpmDocumentationSource>() } // endregion }
apache-2.0
2bd72645f6886c91a95294bcc903d5c4
41.625
103
0.715836
4.209877
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/latex/model/block/MetaBlock.kt
2
310
package org.stepik.android.domain.latex.model.block class MetaBlock( baseUrl: String ) : ContentBlock { override val header: String = """ <meta name="viewport" content="width=device-width, user-scalable=no, target-densitydpi=medium-dpi" /> <base href="$baseUrl"> """.trimIndent() }
apache-2.0
b93b2d2e820de15d4ab93e6b599ef2a1
30.1
109
0.674194
3.780488
false
false
false
false
jiaminglu/kotlin-native
Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Utils.kt
1
12296
/* * 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 kotlinx.cinterop interface NativePlacement { fun alloc(size: Long, align: Int): NativePointed fun alloc(size: Int, align: Int) = alloc(size.toLong(), align) } interface NativeFreeablePlacement : NativePlacement { fun free(mem: NativePtr) } fun NativeFreeablePlacement.free(pointer: CPointer<*>) = this.free(pointer.rawValue) fun NativeFreeablePlacement.free(pointed: NativePointed) = this.free(pointed.rawPtr) object nativeHeap : NativeFreeablePlacement { override fun alloc(size: Long, align: Int) = nativeMemUtils.alloc(size, align) override fun free(mem: NativePtr) = nativeMemUtils.free(mem) } // TODO: implement optimally class Arena(private val parent: NativeFreeablePlacement = nativeHeap) : NativePlacement { private val allocatedChunks = ArrayList<NativePointed>() override fun alloc(size: Long, align: Int): NativePointed { val res = parent.alloc(size, align) try { allocatedChunks.add(res) return res } catch (e: Throwable) { parent.free(res) throw e } } fun clear() { allocatedChunks.forEach { parent.free(it) } allocatedChunks.clear() } } /** * Allocates variable of given type. * * @param T must not be abstract */ inline fun <reified T : CVariable> NativePlacement.alloc(): T = alloc(sizeOf<T>(), alignOf<T>()).reinterpret() /** * Allocates C array of given elements type and length. * * @param T must not be abstract */ inline fun <reified T : CVariable> NativePlacement.allocArray(length: Long): CArrayPointer<T> = alloc(sizeOf<T>() * length, alignOf<T>()).reinterpret<T>().ptr /** * Allocates C array of given elements type and length. * * @param T must not be abstract */ inline fun <reified T : CVariable> NativePlacement.allocArray(length: Int): CArrayPointer<T> = allocArray(length.toLong()) /** * Allocates C array of given elements type and length, and initializes its elements applying given block. * * @param T must not be abstract */ inline fun <reified T : CVariable> NativePlacement.allocArray(length: Long, initializer: T.(index: Long)->Unit): CArrayPointer<T> { val res = allocArray<T>(length) (0 .. length - 1).forEach { index -> res[index].initializer(index) } return res } /** * Allocates C array of given elements type and length, and initializes its elements applying given block. * * @param T must not be abstract */ inline fun <reified T : CVariable> NativePlacement.allocArray(length: Int, initializer: T.(index: Int)->Unit): CArrayPointer<T> = allocArray(length.toLong()) { index -> this.initializer(index.toInt()) } /** * Allocates C array of pointers to given elements. */ fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(elements: List<T?>): CArrayPointer<CPointerVar<T>> { val res = allocArray<CPointerVar<T>>(elements.size) elements.forEachIndexed { index, value -> res[index] = value?.ptr } return res } /** * Allocates C array of pointers to given elements. */ fun <T : CPointed> NativePlacement.allocArrayOfPointersTo(vararg elements: T?) = allocArrayOfPointersTo(listOf(*elements)) /** * Allocates C array of given values. */ inline fun <reified T : CPointer<*>> NativePlacement.allocArrayOf(vararg elements: T?): CArrayPointer<CPointerVarOf<T>> { return allocArrayOf(listOf(*elements)) } /** * Allocates C array of given values. */ inline fun <reified T : CPointer<*>> NativePlacement.allocArrayOf(elements: List<T?>): CArrayPointer<CPointerVarOf<T>> { val res = allocArray<CPointerVarOf<T>>(elements.size) var index = 0 while (index < elements.size) { res[index] = elements[index] ++index } return res } fun NativePlacement.allocArrayOf(elements: ByteArray): CArrayPointer<ByteVar> { val result = allocArray<ByteVar>(elements.size) nativeMemUtils.putByteArray(elements, result.pointed, elements.size) return result } fun NativePlacement.allocArrayOf(vararg elements: Float): CArrayPointer<FloatVar> { val res = allocArray<FloatVar>(elements.size) var index = 0 while (index < elements.size) { res[index] = elements[index] ++index } return res } fun <T : CPointed> NativePlacement.allocPointerTo() = alloc<CPointerVar<T>>() fun <T : CVariable> zeroValue(size: Int, align: Int): CValue<T> = object : CValue<T>() { override fun getPointer(placement: NativePlacement): CPointer<T> { val result = placement.alloc(size, align) nativeMemUtils.zeroMemory(result, size) return interpretCPointer(result.rawPtr)!! } override val size get() = size } inline fun <reified T : CVariable> zeroValue(): CValue<T> = zeroValue<T>(sizeOf<T>().toInt(), alignOf<T>()) private fun <T : CPointed> NativePlacement.placeBytes(bytes: ByteArray, align: Int): CPointer<T> { val result = this.alloc(size = bytes.size, align = align) nativeMemUtils.putByteArray(bytes, result, bytes.size) return interpretCPointer(result.rawPtr)!! } fun <T : CVariable> CPointed.readValues(size: Int, align: Int): CValues<T> { val bytes = ByteArray(size) nativeMemUtils.getByteArray(this, bytes, size) return object : CValues<T>() { override fun getPointer(placement: NativePlacement): CPointer<T> = placement.placeBytes(bytes, align) override val size get() = bytes.size } } inline fun <reified T : CVariable> T.readValues(count: Int): CValues<T> = this.readValues<T>(size = count * sizeOf<T>().toInt(), align = alignOf<T>()) fun <T : CVariable> CPointed.readValue(size: Long, align: Int): CValue<T> { val bytes = ByteArray(size.toInt()) nativeMemUtils.getByteArray(this, bytes, size.toInt()) return object : CValue<T>() { override fun getPointer(placement: NativePlacement): CPointer<T> = placement.placeBytes(bytes, align) override val size get() = bytes.size } } // Note: can't be declared as property due to possible clash with a struct field. // TODO: find better name. inline fun <reified T : CStructVar> T.readValue(): CValue<T> = this.readValue(sizeOf<T>(), alignOf<T>()) fun CValue<*>.write(location: NativePtr) { // TODO: probably CValue must be redesigned. val fakePlacement = object : NativePlacement { var used = false override fun alloc(size: Long, align: Int): NativePointed { assert(!used) used = true return interpretPointed<ByteVar>(location) } } this.getPointer(fakePlacement) assert(fakePlacement.used) } // TODO: optimize fun <T : CVariable> CValues<T>.getBytes(): ByteArray = memScoped { val result = ByteArray(size) nativeMemUtils.getByteArray( source = [email protected](memScope).reinterpret<ByteVar>().pointed, dest = result, length = result.size ) result } /** * Calls the [block] with temporary copy if this value as receiver. */ inline fun <reified T : CStructVar, R> CValue<T>.useContents(block: T.() -> R): R = memScoped { [email protected](memScope).pointed.block() } inline fun <reified T : CStructVar> CValue<T>.copy(modify: T.() -> Unit): CValue<T> = useContents { this.modify() this.readValue() } inline fun <reified T : CStructVar> cValue(initialize: T.() -> Unit): CValue<T> = zeroValue<T>().copy(modify = initialize) inline fun <reified T : CVariable> createValues(count: Int, initializer: T.(index: Int) -> Unit) = memScoped { val array = allocArray<T>(count, initializer) array[0].readValues(count) } fun cValuesOf(vararg elements: Byte): CValues<ByteVar> = object : CValues<ByteVar>() { override fun getPointer(placement: NativePlacement) = placement.allocArrayOf(elements) override val size get() = 1 * elements.size } // TODO: optimize other [cValuesOf] methods: fun cValuesOf(vararg elements: Short): CValues<ShortVar> = createValues(elements.size) { index -> this.value = elements[index] } fun cValuesOf(vararg elements: Int): CValues<IntVar> = createValues(elements.size) { index -> this.value = elements[index] } fun cValuesOf(vararg elements: Long): CValues<LongVar> = createValues(elements.size) { index -> this.value = elements[index] } fun cValuesOf(vararg elements: Float): CValues<FloatVar> = object : CValues<FloatVar>() { override fun getPointer(placement: NativePlacement) = placement.allocArrayOf(*elements) override val size get() = 4 * elements.size } fun cValuesOf(vararg elements: Double): CValues<DoubleVar> = createValues(elements.size) { index -> this.value = elements[index] } fun <T : CPointed> cValuesOf(vararg elements: CPointer<T>?): CValues<CPointerVar<T>> = createValues(elements.size) { index -> this.value = elements[index] } fun ByteArray.toCValues() = cValuesOf(*this) fun ShortArray.toCValues() = cValuesOf(*this) fun IntArray.toCValues() = cValuesOf(*this) fun LongArray.toCValues() = cValuesOf(*this) fun FloatArray.toCValues() = cValuesOf(*this) fun DoubleArray.toCValues() = cValuesOf(*this) fun <T : CPointed> Array<CPointer<T>?>.toCValues() = cValuesOf(*this) fun <T : CPointed> List<CPointer<T>?>.toCValues() = this.toTypedArray().toCValues() /** * @return the value of zero-terminated UTF-8-encoded C string constructed from given [kotlin.String]. */ val String.cstr: CValues<ByteVar> get() { val bytes = encodeToUtf8(this) return object : CValues<ByteVar>() { override val size get() = bytes.size + 1 override fun getPointer(placement: NativePlacement): CPointer<ByteVar> { val result = placement.allocArray<ByteVar>(bytes.size + 1) nativeMemUtils.putByteArray(bytes, result.pointed, bytes.size) result[bytes.size] = 0.toByte() return result } } } val String.wcstr: CValues<ShortVar> get() { val chars = CharArray(this.length, { i -> this.get(i)}) return object : CValues<ShortVar>() { override val size get() = 2 * (chars.size + 1) override fun getPointer(placement: NativePlacement): CPointer<ShortVar> { val result = placement.allocArray<ShortVar>(chars.size + 1) nativeMemUtils.putCharArray(chars, result.pointed, chars.size) result[chars.size] = 0.toShort() return result } } } /** * TODO: should the name of the function reflect the encoding? * * @return the [kotlin.String] decoded from given zero-terminated UTF-8-encoded C string. */ fun CPointer<ByteVar>.toKString(): String { val nativeBytes = this var length = 0 while (nativeBytes[length] != 0.toByte()) { ++length } val bytes = ByteArray(length) nativeMemUtils.getByteArray(nativeBytes.pointed, bytes, length) return decodeFromUtf8(bytes) } class MemScope : NativePlacement { private val arena = Arena() override fun alloc(size: Long, align: Int) = arena.alloc(size, align) fun clear() = arena.clear() val memScope: NativePlacement get() = this } /** * Runs given [block] providing allocation of memory * which will be automatically disposed at the end of this scope. */ inline fun <R> memScoped(block: MemScope.()->R): R { val memScope = MemScope() try { return memScope.block() } finally { memScope.clear() } }
apache-2.0
c5b439efc5a2aa71abb001e550b9aab2
31.272966
117
0.663061
4.126174
false
false
false
false
jiaminglu/kotlin-native
samples/html5Canvas/src/jsinterop/kotlin/jsinterop.kt
1
1978
package kotlinx.wasm.jsinterop import konan.internal.ExportForCppRuntime import kotlinx.cinterop.* typealias Arena = Int typealias Object = Int typealias Pointer = Int @SymbolName("Konan_js_allocateArena") external public fun allocateArena(): Arena @SymbolName("Konan_js_freeArena") external public fun freeArena(arena: Arena) @SymbolName("Kotlin_String_utf16pointer") external public fun stringPointer(message: String): Pointer @SymbolName("Kotlin_String_utf16length") external public fun stringLengthBytes(message: String): Int typealias KtFunction = (ArrayList<JsValue>)->Unit fun wrapFunction(func: KtFunction): Int { val ptr: Long = StableObjPtr.create(func).value.toLong() return ptr.toInt() // TODO: LP64 unsafe. } @ExportForCppRuntime("Konan_js_runLambda") fun runLambda(userData: Int, arena: Arena, arenaSize: Int) { val arguments = arrayListOf<JsValue>() for (i in 0..arenaSize-1) { arguments.add(JsValue(arena, i)); } // TODO: LP64 unsafe: wasm32 passes Int, not Long. val func = StableObjPtr.fromValue(userData.toLong().toCPointer()!!).get() as KtFunction func(arguments); } open class JsValue(val arena: Arena, val index: Object) { fun getInt(property: String): Int { return getInt(arena, index, stringPointer(property), stringLengthBytes(property)) } } @SymbolName("Konan_js_getInt") external public fun getInt(arena: Arena, obj: Object, propertyPtr: Pointer, propertyLen: Int): Int; @SymbolName("Konan_js_setFunction") external public fun setFunction(arena: Arena, obj: Object, propertyName: Pointer, propertyLength: Int , function: Int) fun setter(obj: JsValue, property: String, lambda: (arguments: ArrayList<JsValue>) -> Unit) { val index = wrapFunction(lambda); setFunction(obj.arena, obj.index, stringPointer(property), stringLengthBytes(property), index) } fun JsValue.setter(property: String, lambda: (ArrayList<JsValue>) -> Unit) { setter(this, property, lambda) }
apache-2.0
70f76a11f58f707e8a955ea7968b77cc
31.42623
118
0.735592
3.782027
false
false
false
false
Commit451/GitLabAndroid
app/src/main/java/com/commit451/gitlab/activity/AddNewLabelActivity.kt
2
4323
package com.commit451.gitlab.activity import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.View import androidx.annotation.ColorInt import androidx.appcompat.widget.Toolbar import com.afollestad.materialdialogs.color.ColorChooserDialog import com.commit451.addendum.design.snackbar import com.commit451.gitlab.App import com.commit451.gitlab.R import com.commit451.gitlab.extension.checkValid import com.commit451.gitlab.extension.text import com.commit451.gitlab.extension.with import com.commit451.gitlab.util.ColorUtil import kotlinx.android.synthetic.main.activity_add_new_label.* import kotlinx.android.synthetic.main.progress_fullscreen.* import retrofit2.HttpException import timber.log.Timber /** * Create a brand new label */ class AddNewLabelActivity : BaseActivity(), ColorChooserDialog.ColorCallback { companion object { private const val KEY_PROJECT_ID = "project_id" const val KEY_NEW_LABEL = "new_label" fun newIntent(context: Context, projectId: Long): Intent { val intent = Intent(context, AddNewLabelActivity::class.java) intent.putExtra(KEY_PROJECT_ID, projectId) return intent } } var chosenColor = -1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_new_label) rootColor.setOnClickListener { // Pass AppCompatActivity which implements ColorCallback, along with the textTitle of the dialog ColorChooserDialog.Builder(this, R.string.add_new_label_choose_color) .preselect(chosenColor) .show(this) } toolbar.setNavigationIcon(R.drawable.ic_back_24dp) toolbar.setNavigationOnClickListener { onBackPressed() } toolbar.inflateMenu(R.menu.create) toolbar.setOnMenuItemClickListener(Toolbar.OnMenuItemClickListener { item -> when (item.itemId) { R.id.action_create -> { createLabel() return@OnMenuItemClickListener true } } false }) } override fun onColorSelection(dialog: ColorChooserDialog, @ColorInt selectedColor: Int) { chosenColor = selectedColor imageColor.setImageDrawable(ColorDrawable(selectedColor)) } override fun onColorChooserDismissed(dialog: ColorChooserDialog) { } private val projectId: Long get() = intent.getLongExtra(KEY_PROJECT_ID, -1) private fun createLabel() { val valid = textInputLayoutTitle.checkValid() if (valid) { if (chosenColor == -1) { root.snackbar(R.string.add_new_label_color_is_required) return } val title = textInputLayoutTitle.text() var description: String? = null if (!textDescription.text.isNullOrEmpty()) { description = textDescription.text.toString() } var color: String? = null if (chosenColor != -1) { color = ColorUtil.convertColorIntToString(chosenColor) Timber.d("Setting color to %s", color) } fullscreenProgress.visibility = View.VISIBLE fullscreenProgress.alpha = 0.0f fullscreenProgress.animate().alpha(1.0f) App.get().gitLab.createLabel(projectId, title, color, description) .with(this) .subscribe({ val data = Intent() data.putExtra(KEY_NEW_LABEL, it.body()) setResult(Activity.RESULT_OK, data) finish() }, { Timber.e(it) fullscreenProgress.visibility = View.GONE if (it is HttpException && it.response()?.code() == 409) { root.snackbar(R.string.label_already_exists) } else { root.snackbar(R.string.failed_to_create_label) } }) } } }
apache-2.0
eb6bec6b3e777a58d12adf497c30385d
35.327731
108
0.612769
4.879233
false
false
false
false