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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
testpress/android | app/src/test/java/in/testpress/testpress/util/RegisterRepositoryTest.kt | 1 | 1633 | package `in`.testpress.testpress.util
import `in`.testpress.enums.Status
import `in`.testpress.testpress.util.fakes.FakeRepository
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class RegisterRepositoryTest {
private val repository = FakeRepository()
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Test
fun successNetworkCallShouldReturnSuccessResponse() {
runBlocking {
repository.apiStatus = Status.SUCCESS
repository.register(userDetails = hashMapOf())
assertEquals(repository.result.status, Status.SUCCESS)
}
}
@Test
fun networkFailureShouldReturnException() {
runBlocking {
repository.apiStatus = Status.ERROR
repository.register(hashMapOf())
assertEquals(repository.result.status, Status.ERROR)
}
}
@Test
fun initializeNetworkCallShouldReturnSuccess() {
runBlocking {
repository.apiStatus = Status.SUCCESS
repository.initialize()
assertEquals(repository.initializeResponse.status, Status.SUCCESS)
}
}
@Test
fun initializeNetworkFailureShouldReturnException() {
runBlocking {
repository.apiStatus = Status.ERROR
repository.register(hashMapOf())
assertEquals(repository.result.status, Status.ERROR)
}
}
}
| mit | 4c3b53be0ee5296f4480fdb857e562b2 | 28.160714 | 78 | 0.690753 | 4.993884 | false | true | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_gpu_shader_int64.kt | 4 | 7048 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val ARB_gpu_shader_int64 = "ARBGPUShaderInt64".nativeClassGL("ARB_gpu_shader_int64") {
documentation =
"""
Native bindings to the $registryLink extension.
The extension introduces the following features for all shader types:
${ul(
"""
support for 64-bit scalar and vector integer data types, including uniform API, uniform buffer object, transform feedback, and shader input and
output support;
""",
"new built-in functions to pack and unpack 64-bit integer types into a two-component 32-bit integer vector;",
"new built-in functions to convert double-precision floating-point values to or from their 64-bit integer bit encodings;",
"vector relational functions supporting comparisons of vectors of 64-bit integer types; and",
"common functions abs, sign, min, max, clamp, and mix supporting arguments of 64-bit integer types."
)}
Requires ${GL40.link} and GLSL 4.00.
"""
IntConstant(
"Returned by the {@code type} parameter of GetActiveAttrib, GetActiveUniform, and GetTransformFeedbackVarying.",
"INT64_ARB"..0x140E,
"UNSIGNED_INT64_ARB"..0x140F,
"INT64_VEC2_ARB"..0x8FE9,
"INT64_VEC3_ARB"..0x8FEA,
"INT64_VEC4_ARB"..0x8FEB,
"UNSIGNED_INT64_VEC2_ARB"..0x8FF5,
"UNSIGNED_INT64_VEC3_ARB"..0x8FF6,
"UNSIGNED_INT64_VEC4_ARB"..0x8FF7
)
val args = arrayOf(
GLuint("program", "the program object"),
GLint("location", "the location of the uniform variable to be modified"),
GLint64("x", "the uniform x value"),
GLint64("y", "the uniform y value"),
GLint64("z", "the uniform z value"),
GLint64("w", "the uniform w value")
)
val autoSizes = arrayOf(
AutoSize(1, "value"),
AutoSize(2, "value"),
AutoSize(3, "value"),
AutoSize(4, "value")
)
val autoSizeDoc = "the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array."
for (i in 1..4) {
val glslType = if (i == 1) "int64_t" else "i64vec$i"
val valueDoc = "a pointer to an array of {@code count} values that will be used to update the specified $glslType variable"
// Uniform{1,2,3,4}i64ARB
void(
"Uniform${i}i64ARB",
"Specifies the value of an $glslType uniform variable for the current program object.",
*args.copyOfRange(1, 2 + i)
)
// Uniform{1,2,3,4}i64vARB
void(
"Uniform${i}i64vARB",
"Specifies the value of a single $glslType uniform variable or a $glslType uniform variable array for the current program object.",
args[1],
autoSizes[i - 1]..GLsizei("count", autoSizeDoc),
GLint64.p("value", valueDoc)
)
// ProgramUniform{1,2,3,4}i64ARB
void(
"ProgramUniform${i}i64ARB",
"Specifies the value of an $glslType uniform variable for the specified program object.",
*args.copyOfRange(0, 2 + i)
)
// ProgramUniform{1,2,3,4}i64vARB
void(
"ProgramUniform${i}i64vARB",
"Specifies the value of a single $glslType uniform variable or a $glslType uniform variable array for the specified program object.",
args[0],
args[1],
autoSizes[i - 1]..GLsizei("count", autoSizeDoc),
GLint64.p("value", valueDoc)
)
}
args[2] = GLuint64("x", "the uniform x value")
args[3] = GLuint64("y", "the uniform y value")
args[4] = GLuint64("z", "the uniform z value")
args[5] = GLuint64("w", "the uniform w value")
for (i in 1..4) {
val glslType = if (i == 1) "uint64_t" else "u64vec$i"
val valueDoc = "a pointer to an array of {@code count} values that will be used to update the specified $glslType variable"
// Uniform{1,2,3,4}ui64ARB
void(
"Uniform${i}ui64ARB",
"Specifies the value of an $glslType uniform variable for the current program object.",
*args.copyOfRange(1, 2 + i)
)
// Uniform{1,2,3,4}ui64vARB
void(
"Uniform${i}ui64vARB",
"Specifies the value of a single $glslType uniform variable or a $glslType uniform variable array for the current program object.",
args[1],
autoSizes[i - 1]..GLsizei("count", autoSizeDoc),
GLuint64.const.p("value", valueDoc)
)
// ProgramUniform{1,2,3,4}ui64ARB
void(
"ProgramUniform${i}ui64ARB",
"Specifies the value of an $glslType uniform variable for the current program object.",
*args.copyOfRange(0, 2 + i)
)
// ProgramUniform{1,2,3,4}ui64vARB
void(
"ProgramUniform${i}ui64vARB",
"Specifies the value of a single $glslType uniform variable or a $glslType uniform variable array for the specified program object.",
args[0],
args[1],
autoSizes[i - 1]..GLsizei("count", autoSizeDoc),
GLuint64.const.p("value", valueDoc)
)
}
void(
"GetUniformi64vARB",
"Returns the int64_t value(s) of a uniform variable.",
GLuint("program", "the program object to be queried"),
GLint("location", "the location of the uniform variable to be queried"),
ReturnParam..Check(1)..GLint64.p("params", "the value of the specified uniform variable")
)
void(
"GetUniformui64vARB",
"Returns the uint64_t value(s) of a uniform variable.",
GLuint("program", "the program object to be queried"),
GLint("location", "the location of the uniform variable to be queried"),
ReturnParam..Check(1)..GLuint64.p("params", "the value of the specified uniform variable")
)
void(
"GetnUniformi64vARB",
"Robust version of #GetUniformi64vARB().",
GLuint("program", "the program object to be queried"),
GLint("location", "the location of the uniform variable to be queried"),
AutoSize("params")..GLsizei("bufSize", "the maximum number of values to write in {@code params}"),
ReturnParam..GLint64.p("params", "the value of the specified uniform variable")
)
void(
"GetnUniformui64vARB",
"Robust version of #GetUniformui64vARB().",
GLuint("program", "the program object to be queried"),
GLint("location", "the location of the uniform variable to be queried"),
AutoSize("params")..GLsizei("bufSize", "the maximum number of values to write in {@code params}"),
ReturnParam..GLuint64.p("params", "the value of the specified uniform variable")
)
} | bsd-3-clause | 32528ae43cfa19a0c0993dfb6985a29a | 37.730769 | 171 | 0.606555 | 4.018244 | false | false | false | false |
google/android-fhir | engine/src/test/java/com/google/android/fhir/search/NumberSearchParameterizedTest.kt | 1 | 10487 | /*
* Copyright 2021 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.fhir.search
import android.os.Build
import ca.uhn.fhir.rest.param.ParamPrefixEnum
import com.google.common.truth.Truth.assertThat
import java.lang.IllegalArgumentException
import java.math.BigDecimal
import org.hl7.fhir.r4.model.ResourceType
import org.hl7.fhir.r4.model.RiskAssessment
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.ParameterizedRobolectricTestRunner
import org.robolectric.annotation.Config
/** Unit tests for when [NumberParamFilterCriterion] used in [MoreSearch]. */
@RunWith(ParameterizedRobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.P])
class NumberSearchParameterizedTest(
private val num: BigDecimal,
private val lowerBound: BigDecimal,
private val upperBound: BigDecimal
) {
companion object {
@JvmStatic
@ParameterizedRobolectricTestRunner.Parameters
fun params(): Collection<Array<BigDecimal>> {
return listOf(
arrayOf(BigDecimal("100.00"), BigDecimal("99.995"), BigDecimal("100.005")),
arrayOf(BigDecimal("100.0"), BigDecimal("99.95"), BigDecimal("100.05")),
arrayOf(BigDecimal("1e-1"), BigDecimal("0.5e-1"), BigDecimal("1.5e-1")),
)
}
}
private val baseQuery: String =
"""
SELECT a.serializedResource
FROM ResourceEntity a
WHERE a.resourceType = ?
AND a.resourceUuid IN (
SELECT resourceUuid FROM NumberIndexEntity
""".trimIndent()
@Test
fun `should search equal values`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.EQUAL
value = num
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND (index_value >= ? AND index_value < ?)
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
lowerBound.toDouble(),
upperBound.toDouble()
)
)
}
@Test
fun `should search unequal values`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.NOT_EQUAL
value = num
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND (index_value < ? OR index_value >= ?)
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
lowerBound.toDouble(),
upperBound.toDouble()
)
)
}
@Test
fun `should search values greater than a number`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.GREATERTHAN
value = num
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND index_value > ?
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
num.toDouble()
)
)
}
@Test
fun `should search values greater than or equal to a number`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.GREATERTHAN_OR_EQUALS
value = num
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND index_value >= ?
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
num.toDouble()
)
)
}
@Test
fun `should search values less than a number`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.LESSTHAN
value = num
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND index_value < ?
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
num.toDouble()
)
)
}
@Test
fun `should search values less than or equal to a number`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.LESSTHAN_OR_EQUALS
value = num
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND index_value <= ?
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
num.toDouble()
)
)
}
@Test
fun `should throw error when ENDS_BEFORE prefix given with integer value`() {
val illegalArgumentException =
Assert.assertThrows(IllegalArgumentException::class.java) {
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.ENDS_BEFORE
value = BigDecimal("100")
}
)
}
.getQuery()
}
assertThat(illegalArgumentException.message)
.isEqualTo("Prefix ENDS_BEFORE not allowed for Integer type")
}
@Test
fun `should search value when ENDS_BEFORE prefix given with decimal value`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.ENDS_BEFORE
value = num
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND index_value < ?
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
num.toDouble()
)
)
}
@Test
fun `should throw error when STARTS_AFTER prefix given with integer value`() {
val illegalArgumentException =
Assert.assertThrows(IllegalArgumentException::class.java) {
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.STARTS_AFTER
value = BigDecimal(100)
}
)
}
.getQuery()
}
assertThat(illegalArgumentException.message)
.isEqualTo("Prefix STARTS_AFTER not allowed for Integer type")
}
@Test
fun `should search value when STARTS_AFTER prefix given with decimal value`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.STARTS_AFTER
value = num
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND index_value > ?
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
num.toDouble()
)
)
}
@Test
fun `should search approximate values`() {
val search =
Search(ResourceType.RiskAssessment)
.apply {
filter(
RiskAssessment.PROBABILITY,
{
prefix = ParamPrefixEnum.APPROXIMATE
value = BigDecimal("1e-1")
}
)
}
.getQuery()
assertThat(search.query)
.isEqualTo(
"""
|$baseQuery
|WHERE resourceType = ? AND index_name = ? AND (index_value >= ? AND index_value <= ?)
|)""".trimMargin()
)
assertThat(search.args)
.isEqualTo(
listOf(
ResourceType.RiskAssessment.name,
ResourceType.RiskAssessment.name,
RiskAssessment.PROBABILITY.paramName,
0.09,
0.11
)
)
}
}
| apache-2.0 | 35014412366f4ade23cfd1c572d81bc7 | 25.283208 | 94 | 0.567751 | 4.745249 | false | false | false | false |
bozaro/git-lfs-java | gitlfs-server/src/main/kotlin/ru/bozaro/gitlfs/server/LocksServlet.kt | 1 | 4247 | package ru.bozaro.gitlfs.server
import jakarta.servlet.ServletException
import jakarta.servlet.http.HttpServlet
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import ru.bozaro.gitlfs.common.JsonHelper
import ru.bozaro.gitlfs.common.LockConflictException
import ru.bozaro.gitlfs.common.data.*
import ru.bozaro.gitlfs.server.LockManager.LockRead
import ru.bozaro.gitlfs.server.LockManager.LockWrite
import ru.bozaro.gitlfs.server.internal.ObjectResponse
import ru.bozaro.gitlfs.server.internal.ResponseWriter
import java.io.IOException
class LocksServlet(private val lockManager: LockManager) : HttpServlet() {
@Throws(ServletException::class, IOException::class)
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
try {
val lockRead = lockManager.checkDownloadAccess(req)
if (req.pathInfo == null) {
listLocks(req, lockRead).write(resp)
return
}
} catch (e: ServerError) {
PointerServlet.sendError(resp, e)
return
}
super.doGet(req, resp)
}
@Throws(ServletException::class, IOException::class)
override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
try {
PointerServlet.checkMimeTypes(req)
val lockWrite = lockManager.checkUploadAccess(req)
when {
req.pathInfo == null -> {
createLock(req, lockWrite).write(resp)
return
}
"/verify" == req.pathInfo -> {
verifyLocks(req, lockWrite).write(resp)
return
}
req.pathInfo.endsWith("/unlock") -> {
deleteLock(req, lockWrite, req.pathInfo.substring(1, req.pathInfo.length - 7)).write(resp)
return
}
}
} catch (e: ServerError) {
PointerServlet.sendError(resp, e)
return
}
super.doPost(req, resp)
}
@Throws(IOException::class)
private fun createLock(req: HttpServletRequest, lockWrite: LockWrite): ResponseWriter {
val createLockReq = JsonHelper.mapper.readValue(req.inputStream, CreateLockReq::class.java)
return try {
val lock = lockWrite.lock(createLockReq.path, createLockReq.ref)
ObjectResponse(HttpServletResponse.SC_CREATED, CreateLockRes(lock))
} catch (e: LockConflictException) {
ObjectResponse(HttpServletResponse.SC_CONFLICT, LockConflictRes(e.message!!, e.lock))
}
}
@Throws(IOException::class)
private fun verifyLocks(req: HttpServletRequest, lockWrite: LockWrite): ResponseWriter {
val verifyLocksReq = JsonHelper.mapper.readValue(req.inputStream, VerifyLocksReq::class.java)
val result = lockWrite.verifyLocks(verifyLocksReq.ref)
return ObjectResponse(HttpServletResponse.SC_OK, VerifyLocksRes(result.ourLocks, result.theirLocks, null))
}
@Throws(IOException::class, ServerError::class)
private fun deleteLock(
req: HttpServletRequest,
lockWrite: LockWrite,
lockId: String
): ResponseWriter {
val deleteLockReq = JsonHelper.mapper.readValue(req.inputStream, DeleteLockReq::class.java)
return try {
val lock = lockWrite.unlock(lockId, deleteLockReq.isForce(), deleteLockReq.ref)
?: throw ServerError(HttpServletResponse.SC_NOT_FOUND, String.format("Lock %s not found", lockId))
ObjectResponse(HttpServletResponse.SC_OK, CreateLockRes(lock))
} catch (e: LockConflictException) {
ObjectResponse(HttpServletResponse.SC_FORBIDDEN, CreateLockRes(e.lock))
}
}
@Throws(IOException::class)
private fun listLocks(req: HttpServletRequest, lockRead: LockRead): ResponseWriter {
val refName = req.getParameter("refspec")
val path = req.getParameter("path")
val lockId = req.getParameter("id")
val locks = lockRead.getLocks(path, lockId, Ref.create(refName))
return ObjectResponse(HttpServletResponse.SC_OK, LocksRes(locks, null))
}
}
| lgpl-3.0 | 938e95ebf2a2b12a784eaabdd1a35be8 | 41.47 | 118 | 0.654344 | 4.484688 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/openal/src/templates/kotlin/openal/ALCBinding.kt | 4 | 5909 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package openal
import org.lwjgl.generator.*
import java.io.*
fun NativeClass.capName(core: String) =
if (templateName.startsWith(prefixTemplate)) {
if (prefix == core)
"Open$core${templateName.substring(core.length)}"
else
templateName
} else {
"${prefixTemplate}_$templateName"
}
private val NativeClass.isCore: Boolean get() = templateName.startsWith("ALC")
private const val ALC_CAP_CLASS = "ALCCapabilities"
val ALCBinding = Generator.register(object : APIBinding(
Module.OPENAL,
ALC_CAP_CLASS,
APICapabilities.JAVA_CAPABILITIES
) {
private val classes by lazy { super.getClasses("ALC") }
private val functions by lazy {
classes.getFunctionPointers {
it.hasNativeFunctions && it.prefix == "ALC"
}
}
private val functionOrdinals by lazy {
LinkedHashMap<String, Int>().also { functionOrdinals ->
classes.asSequence()
.filter { it.hasNativeFunctions && it.prefix == "ALC" }
.forEach {
it.functions.asSequence()
.forEach { cmd ->
if (!cmd.has<Macro>() && !functionOrdinals.contains(cmd.name)) {
functionOrdinals[cmd.name] = functionOrdinals.size
}
}
}
}
}
override fun shouldCheckFunctionAddress(function: Func): Boolean = function.nativeClass.templateName != "ALC10"
override fun generateFunctionAddress(writer: PrintWriter, function: Func) {
writer.println("\t\tlong $FUNCTION_ADDRESS = ALC.getICD().${function.name};")
}
private fun PrintWriter.printCheckFunctions(
nativeClass: NativeClass,
filter: (Func) -> Boolean
) {
print("checkFunctions(provider, device, caps, new int[] {")
nativeClass.printPointers(this, { func -> functionOrdinals[func.name].toString() }, filter)
print("},")
nativeClass.printPointers(this, { "\"${it.name}\"" }, filter)
print(")")
}
private fun PrintWriter.checkExtensionFunctions(nativeClass: NativeClass) {
val capName = nativeClass.capName("ALC")
print(
"""
private static boolean check_${nativeClass.templateName}(FunctionProviderLocal provider, long device, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("$capName")) {
return false;
}"""
)
print("\n\n$t${t}return ")
printCheckFunctions(nativeClass) { !it.has(IgnoreMissing) }
println(" || reportMissing(\"ALC\", \"$capName\");")
println("$t}")
}
init {
javaImport(
"org.lwjgl.*",
"java.util.function.IntFunction",
"static org.lwjgl.system.Checks.*"
)
documentation = "Defines the capabilities of the OpenAL Context API."
}
override fun PrintWriter.generateJava() {
generateJavaPreamble()
println("public final class $ALC_CAP_CLASS {")
val functionSet = LinkedHashSet<String>()
classes.asSequence()
.filter { it.hasNativeFunctions && it.prefix == "ALC" }
.forEach {
val functions = it.functions.asSequence()
.filter { cmd ->
if (!cmd.has<Macro>()) {
if (functionSet.add(cmd.name)) {
return@filter true
}
}
false
}
.joinToString(",\n$t$t") { cmd -> cmd.name }
if (functions.isNotEmpty()) {
println("\n$t// ${it.templateName}")
println("${t}public final long")
println("$t$t$functions;")
}
}
println()
classes.forEach {
println(it.getCapabilityJavadoc())
println("${t}public final boolean ${it.capName("ALC")};")
}
print(
"""
/** Device handle. */
final long device;
/** Off-heap array of the above function addresses. */
final PointerBuffer addresses;
$ALC_CAP_CLASS(FunctionProviderLocal provider, long device, Set<String> ext, IntFunction<PointerBuffer> bufferFactory) {
this.device = device;
PointerBuffer caps = bufferFactory.apply(${functions.size});
"""
)
for (extension in classes) {
val capName = extension.capName("ALC")
print(
if (extension.hasNativeFunctions && extension.prefix == "ALC")
"\n$t$t$capName = check_${extension.templateName}(provider, device, caps, ext);"
else
"\n$t$t$capName = ext.contains(\"$capName\");"
)
}
println()
functionOrdinals.forEach { (it, index) ->
print("\n$t$t$it = caps.get($index);")
}
print(
"""
addresses = ThreadLocalUtil.setupAddressBuffer(caps);
}
/** Returns the buffer of OpenAL function pointers. */
public PointerBuffer getAddressBuffer() {
return addresses;
}
"""
)
for (extension in classes) {
if (extension.hasNativeFunctions && extension.prefix == "ALC") {
checkExtensionFunctions(extension)
}
}
println("\n}")
}
})
// DSL Extensions
fun String.nativeClassALC(templateName: String, prefix: String = "ALC", postfix: String = "", init: (NativeClass.() -> Unit)? = null) =
nativeClass(Module.OPENAL, templateName, prefix = prefix, prefixTemplate = "ALC", postfix = postfix, binding = ALCBinding, init = init) | bsd-3-clause | 5e6c6e0d476e6d01062387cd8abae357 | 30.604278 | 144 | 0.548147 | 4.765323 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/persistence/local/room/entity/SubmissionMutationEntity.kt | 1 | 2675 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.persistence.local.room.entity
import androidx.room.*
import com.google.android.ground.model.mutation.SubmissionMutation
import com.google.android.ground.persistence.local.room.models.MutationEntitySyncStatus
import com.google.android.ground.persistence.local.room.models.MutationEntityType
import java.util.*
/** Representation of a [SubmissionMutation] in local data store. */
@Entity(
tableName = "submission_mutation",
foreignKeys =
[
ForeignKey(
entity = LocationOfInterestEntity::class,
parentColumns = ["id"],
childColumns = ["location_of_interest_id"],
onDelete = ForeignKey.CASCADE
),
ForeignKey(
entity = SubmissionEntity::class,
parentColumns = ["id"],
childColumns = ["submission_id"],
onDelete = ForeignKey.CASCADE
)
],
indices = [Index("location_of_interest_id"), Index("submission_id")]
)
data class SubmissionMutationEntity(
@ColumnInfo(name = "id") @PrimaryKey(autoGenerate = true) val id: Long? = 0,
@ColumnInfo(name = "survey_id") val surveyId: String,
@ColumnInfo(name = "type") val type: MutationEntityType,
@ColumnInfo(name = "state") val syncStatus: MutationEntitySyncStatus,
@ColumnInfo(name = "retry_count") val retryCount: Long,
@ColumnInfo(name = "last_error") val lastError: String,
@ColumnInfo(name = "user_id") val userId: String,
@ColumnInfo(name = "client_timestamp") val clientTimestamp: Long,
@ColumnInfo(name = "location_of_interest_id") val locationOfInterestId: String,
@ColumnInfo(name = "job_id") val jobId: String,
@ColumnInfo(name = "submission_id") val submissionId: String,
/**
* For mutations of type [MutationEntityType.CREATE] and [MutationEntityType.UPDATE], returns a
* [JSONObject] with the new values of modified task responses, with `null` values representing
* responses that were removed/cleared.
*
* This method returns `null` for mutation type [MutationEntityType.DELETE].
*/
@ColumnInfo(name = "response_deltas") val responseDeltas: String?
)
| apache-2.0 | 504255fad888a23398e875465483f2ef | 40.796875 | 97 | 0.719626 | 4.153727 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/chat/ChatComponentKeybind.kt | 1 | 1947 | /*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.chat
/**
* ## ChatComponentKeybind (聊天组件按键)
*
* @see [ChatComponent]
* @see [ChatComponentAbstract]
* @author lgou2w
* @since 2.0
* @constructor ChatComponentKeybind
* @param keybind Keybind
* @param keybind 按键
*/
open class ChatComponentKeybind(
/**
* * Gets or sets the keybind object for this chat component keybind.
* * 获取或设置此聊天组件按键的按键对象.
*/
var keybind: String
) : ChatComponentAbstract() {
/**
* @see [ChatComponentKeybind.keybind]
*/
fun setKeybind(keybind: String): ChatComponentKeybind
{ this.keybind = keybind; return this; }
override fun equals(other: Any?): Boolean {
if(other === this)
return true
if(other is ChatComponentKeybind)
return super.equals(other) && keybind == other.keybind
return false
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + keybind.hashCode()
return result
}
override fun toString(): String {
return "ChatComponentKeybind(keybind='$keybind', style=$style, extras=$extras)"
}
}
| gpl-3.0 | eee4b623663a6ef6c40f4e2557ad9de9 | 29.111111 | 87 | 0.664207 | 3.960334 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/completion/stringTemplates/InsertStringTemplateBracesLookupElementDecorator.kt | 7 | 2104 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.completion.stringTemplates
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.psiUtil.startOffset
fun wrapLookupElementForStringTemplateAfterDotCompletion(originLookupElement: LookupElement): LookupElement {
return LookupElementDecorator.withDelegateInsertHandler(originLookupElement) { insertionContext: InsertionContext, lookupElement: LookupElement ->
insertStringTemplateBraces(insertionContext, lookupElement)
}
}
private fun insertStringTemplateBraces(insertionContext: InsertionContext, lookupElement: LookupElement) {
val document = insertionContext.document
val startOffset = insertionContext.startOffset
val psiDocumentManager = PsiDocumentManager.getInstance(insertionContext.project)
psiDocumentManager.commitAllDocuments()
val token = getToken(insertionContext.file, document.charsSequence, startOffset)
val nameRef = token.parent as KtNameReferenceExpression
document.insertString(nameRef.startOffset, "{")
val tailOffset = insertionContext.tailOffset
document.insertString(tailOffset, "}")
insertionContext.tailOffset = tailOffset
lookupElement.handleInsert(insertionContext)
}
private fun getToken(file: PsiFile, charsSequence: CharSequence, startOffset: Int): PsiElement {
assert(startOffset > 1 && charsSequence[startOffset - 1] == '.')
val token = file.findElementAt(startOffset - 2)!!
return if (token.node.elementType == KtTokens.IDENTIFIER || token.node.elementType == KtTokens.THIS_KEYWORD)
token
else
getToken(file, charsSequence, token.startOffset + 1)
}
| apache-2.0 | 001a95d0f76a2c4e2d0eb5e4d92a2618 | 43.765957 | 150 | 0.803707 | 5.057692 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/strategy/StrategyUtils.kt | 10 | 5806 | // 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.
@file:Suppress("DEPRECATION")
package com.intellij.grazie.grammar.strategy
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy.TextDomain
import com.intellij.grazie.ide.language.LanguageGrammarChecking
import com.intellij.grazie.utils.LinkedSet
import com.intellij.grazie.utils.Text
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.lang.LanguageParserDefinitions
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.elementType
object StrategyUtils {
private val EMPTY_LINKED_SET = LinkedSet<Nothing>()
@Suppress("UNCHECKED_CAST")
fun <T> emptyLinkedSet(): LinkedSet<T> = EMPTY_LINKED_SET as LinkedSet<T>
/**
* Get extension point of [strategy]
*
* @return extension point
*/
internal fun getStrategyExtensionPoint(strategy: GrammarCheckingStrategy): LanguageExtensionPoint<GrammarCheckingStrategy> {
return LanguageGrammarChecking.getExtensionPointByStrategy(strategy) ?: error("Strategy is not registered")
}
fun getTextDomainOrDefault(strategy: GrammarCheckingStrategy, root: PsiElement, default: TextDomain): TextDomain {
val extension = getStrategyExtensionPoint(strategy)
if (extension.language != root.language.id) return default
val parser = LanguageParserDefinitions.INSTANCE.forLanguage(root.language) ?: return default
return when {
parser.stringLiteralElements.contains(root.elementType) -> TextDomain.LITERALS
parser.commentTokens.contains(root.elementType) -> TextDomain.COMMENTS
else -> default
}
}
/**
* Finds indent indexes for each line (indent of specific [chars])
* NOTE: If you use this method in [GrammarCheckingStrategy.getStealthyRanges],
* make sure that [GrammarCheckingStrategy.getReplaceCharRules] doesn't contain a [ReplaceNewLines] rule!
*
* @param str source text
* @param chars characters, which considered as indentation
* @return list of IntRanges for such indents
*/
fun indentIndexes(str: CharSequence, chars: Set<Char>): LinkedSet<IntRange> {
val result = LinkedSet<IntRange>()
var from = -1
for ((index, char) in str.withIndex()) {
if ((Text.isNewline(char) || (index == 0 && char in chars)) && from == -1) {
// for first line without \n
from = index + if (Text.isNewline(char)) 1 else 0
}
else {
if (from != -1) {
if (char !in chars) {
if (index > from) result.add(IntRange(from, index - 1))
from = if (Text.isNewline(char)) index + 1 else -1
}
}
}
}
if (from != -1) result.add(IntRange(from, str.length - 1))
return result
}
/**
* Get all siblings of [element] of specific [types]
* which are no further than one line
*
* @param element element whose siblings are to be found
* @param types possible types of siblings
* @return sequence of siblings with whitespace tokens
*/
@Deprecated("Use com.intellij.grazie.utils.getNotSoDistantSimilarSiblings")
fun getNotSoDistantSiblingsOfTypes(strategy: GrammarCheckingStrategy, element: PsiElement, types: Set<IElementType>) =
getNotSoDistantSiblingsOfTypes(strategy, element) { type -> type in types }
/**
* Get all siblings of [element] of type accepted by [checkType]
* which are no further than one line
*
* @param element element whose siblings are to be found
* @param checkType predicate to check if type is accepted
* @return sequence of siblings with whitespace tokens
*/
@Deprecated("Use com.intellij.grazie.utils.getNotSoDistantSimilarSiblings")
fun getNotSoDistantSiblingsOfTypes(strategy: GrammarCheckingStrategy, element: PsiElement, checkType: (IElementType?) -> Boolean) =
getNotSoDistantSimilarSiblings(strategy, element) { sibling -> checkType(sibling.elementType) }
/**
* Get all siblings of [element] that are accepted by [checkSibling]
* which are no further than one line
*
* @param element element whose siblings are to be found
* @param checkSibling predicate to check if sibling is accepted
* @return sequence of siblings with whitespace tokens
*/
@Deprecated("Use com.intellij.grazie.utils.getNotSoDistantSimilarSiblings")
fun getNotSoDistantSimilarSiblings(strategy: GrammarCheckingStrategy, element: PsiElement, checkSibling: (PsiElement?) -> Boolean) =
sequence {
fun PsiElement.process(checkSibling: (PsiElement?) -> Boolean, next: Boolean) = sequence<PsiElement> {
val whitespaceTokens = strategy.getWhiteSpaceTokens()
var newLinesBetweenSiblingsCount = 0
var sibling: PsiElement? = this@process
while (sibling != null) {
val candidate = if (next) sibling.nextSibling else sibling.prevSibling
val type = candidate.elementType
sibling = when {
checkSibling(candidate) -> {
newLinesBetweenSiblingsCount = 0
candidate
}
type in whitespaceTokens -> {
newLinesBetweenSiblingsCount += candidate.text.count { char -> char == '\n' }
if (newLinesBetweenSiblingsCount > 1) null else candidate
}
else -> null
}
if (sibling != null) yield(sibling)
}
}
yieldAll(element.process(checkSibling, false).toList().asReversed())
yield(element)
yieldAll(element.process(checkSibling, true))
}
internal fun quotesOffset(str: CharSequence): Int {
var index = 0
while (index < str.length / 2) {
if (str[index] != str[str.length - index - 1] || !Text.isQuote(str[index])) {
return index
}
index++
}
return index
}
}
| apache-2.0 | 6c7737e6197481716fa0918333fad4e8 | 37.450331 | 140 | 0.699966 | 4.310319 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/references/FindReferences.kt | 1 | 11177 | package org.javacs.kt.references
import org.eclipse.lsp4j.Location
import org.eclipse.lsp4j.Range
import org.javacs.kt.LOG
import org.javacs.kt.SourcePath
import org.javacs.kt.position.location
import org.javacs.kt.position.toURIString
import org.javacs.kt.util.emptyResult
import org.javacs.kt.util.findParent
import org.javacs.kt.util.preOrderTraversal
import org.javacs.kt.util.toPath
import org.javacs.kt.CompiledFile
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.util.OperatorNameConventions
import java.nio.file.Path
fun findReferences(file: Path, cursor: Int, sp: SourcePath): List<Location> {
return doFindReferences(file, cursor, sp)
.map { location(it) }
.filterNotNull()
.toList()
.sortedWith(compareBy({ it.getUri() }, { it.getRange().getStart().getLine() }))
}
fun findReferences(declaration: KtNamedDeclaration, sp: SourcePath): List<Location> {
return doFindReferences(declaration, sp)
.map { location(it) }
.filterNotNull()
.toList()
.sortedWith(compareBy({ it.getUri() }, { it.getRange().getStart().getLine() }))
}
private fun doFindReferences(file: Path, cursor: Int, sp: SourcePath): Collection<KtElement> {
val recover = sp.currentVersion(file.toUri())
val element = recover.elementAtPoint(cursor)?.findParent<KtNamedDeclaration>() ?: return emptyResult("No declaration at ${recover.describePosition(cursor)}")
return doFindReferences(element, sp)
}
private fun doFindReferences(element: KtNamedDeclaration, sp: SourcePath): Collection<KtElement> {
val recover = sp.currentVersion(element.containingFile.toPath().toUri())
val declaration = recover.compile[BindingContext.DECLARATION_TO_DESCRIPTOR, element] ?: return emptyResult("Declaration ${element.fqName} has no descriptor")
val maybes = possibleReferences(declaration, sp).map { it.toPath() }
LOG.debug("Scanning {} files for references to {}", maybes.size, element.fqName)
val recompile = sp.compileFiles(maybes.map(Path::toUri))
return when {
isComponent(declaration) -> findComponentReferences(element, recompile) + findNameReferences(element, recompile)
isIterator(declaration) -> findIteratorReferences(element, recompile) + findNameReferences(element, recompile)
isPropertyDelegate(declaration) -> findDelegateReferences(element, recompile) + findNameReferences(element, recompile)
else -> findNameReferences(element, recompile)
}
}
/**
* Finds references to the named declaration in the given file. The declaration may or may not reside in another file.
*
* @returns ranges of references in the file. Empty list if none are found
*/
fun findReferencesToDeclarationInFile(declaration: KtNamedDeclaration, file: CompiledFile): List<Range> {
val descriptor = file.compile[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] ?: return emptyResult("Declaration ${declaration.fqName} has no descriptor")
val bindingContext = file.compile
val references = when {
isComponent(descriptor) -> findComponentReferences(declaration, bindingContext) + findNameReferences(declaration, bindingContext)
isIterator(descriptor) -> findIteratorReferences(declaration, bindingContext) + findNameReferences(declaration, bindingContext)
isPropertyDelegate(descriptor) -> findDelegateReferences(declaration, bindingContext) + findNameReferences(declaration, bindingContext)
else -> findNameReferences(declaration, bindingContext)
}
return references.map {
location(it)?.range
}.filterNotNull()
.sortedWith(compareBy({ it.start.line }))
}
private fun findNameReferences(element: KtNamedDeclaration, recompile: BindingContext): List<KtReferenceExpression> {
val references = recompile.getSliceContents(BindingContext.REFERENCE_TARGET)
return references.filter { matchesReference(it.value, element) }.map { it.key }
}
private fun findDelegateReferences(element: KtNamedDeclaration, recompile: BindingContext): List<KtElement> {
val references = recompile.getSliceContents(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL)
return references
.filter { matchesReference(it.value.candidateDescriptor, element) }
.map { it.value.call.callElement }
}
private fun findIteratorReferences(element: KtNamedDeclaration, recompile: BindingContext): List<KtElement> {
val references = recompile.getSliceContents(BindingContext.LOOP_RANGE_ITERATOR_RESOLVED_CALL)
return references
.filter { matchesReference( it.value.candidateDescriptor, element) }
.map { it.value.call.callElement }
}
private fun findComponentReferences(element: KtNamedDeclaration, recompile: BindingContext): List<KtElement> {
val references = recompile.getSliceContents(BindingContext.COMPONENT_RESOLVED_CALL)
return references
.filter { matchesReference(it.value.candidateDescriptor, element) }
.map { it.value.call.callElement }
}
// TODO use imports to limit search
private fun possibleReferences(declaration: DeclarationDescriptor, sp: SourcePath): Set<KtFile> {
if (declaration is ClassConstructorDescriptor) {
return possibleNameReferences(declaration.constructedClass.name, sp)
}
if (isComponent(declaration)) {
return possibleComponentReferences(sp) + possibleNameReferences(declaration.name, sp)
}
if (isPropertyDelegate(declaration)) {
return hasPropertyDelegates(sp) + possibleNameReferences(declaration.name, sp)
}
if (isGetSet(declaration)) {
return possibleGetSets(sp) + possibleNameReferences(declaration.name, sp)
}
if (isIterator(declaration)) {
return hasForLoops(sp) + possibleNameReferences(declaration.name, sp)
}
if (declaration is FunctionDescriptor && declaration.isOperator && declaration.name == OperatorNameConventions.INVOKE) {
return possibleInvokeReferences(declaration, sp) + possibleNameReferences(declaration.name, sp)
}
if (declaration is FunctionDescriptor) {
val operators = operatorNames(declaration.name)
return possibleTokenReferences(operators, sp) + possibleNameReferences(declaration.name, sp)
}
return possibleNameReferences(declaration.name, sp)
}
private fun isPropertyDelegate(declaration: DeclarationDescriptor) =
declaration is FunctionDescriptor &&
declaration.isOperator &&
(declaration.name == OperatorNameConventions.GET_VALUE || declaration.name == OperatorNameConventions.SET_VALUE)
private fun hasPropertyDelegates(sp: SourcePath): Set<KtFile> =
sp.all().filter(::hasPropertyDelegate).toSet()
fun hasPropertyDelegate(source: KtFile): Boolean =
source.preOrderTraversal().filterIsInstance<KtPropertyDelegate>().any()
private fun isIterator(declaration: DeclarationDescriptor) =
declaration is FunctionDescriptor &&
declaration.isOperator &&
declaration.name == OperatorNameConventions.ITERATOR
private fun hasForLoops(sp: SourcePath): Set<KtFile> =
sp.all().filter(::hasForLoop).toSet()
private fun hasForLoop(source: KtFile): Boolean =
source.preOrderTraversal().filterIsInstance<KtForExpression>().any()
private fun isGetSet(declaration: DeclarationDescriptor) =
declaration is FunctionDescriptor &&
declaration.isOperator &&
(declaration.name == OperatorNameConventions.GET || declaration.name == OperatorNameConventions.SET)
private fun possibleGetSets(sp: SourcePath): Set<KtFile> =
sp.all().filter(::possibleGetSet).toSet()
private fun possibleGetSet(source: KtFile) =
source.preOrderTraversal().filterIsInstance<KtArrayAccessExpression>().any()
private fun possibleInvokeReferences(declaration: FunctionDescriptor, sp: SourcePath) =
sp.all().filter { possibleInvokeReference(declaration, it) }.toSet()
// TODO this is not very selective
private fun possibleInvokeReference(@Suppress("UNUSED_PARAMETER") declaration: FunctionDescriptor, source: KtFile): Boolean =
source.preOrderTraversal().filterIsInstance<KtCallExpression>().any()
private fun isComponent(declaration: DeclarationDescriptor): Boolean =
declaration is FunctionDescriptor &&
declaration.isOperator &&
OperatorNameConventions.COMPONENT_REGEX.matches(declaration.name.identifier)
private fun possibleComponentReferences(sp: SourcePath): Set<KtFile> =
sp.all().filter { possibleComponentReference(it) }.toSet()
private fun possibleComponentReference(source: KtFile): Boolean =
source.preOrderTraversal()
.filterIsInstance<KtDestructuringDeclarationEntry>()
.any()
private fun possibleTokenReferences(find: List<KtSingleValueToken>, sp: SourcePath): Set<KtFile> =
sp.all().filter { possibleTokenReference(find, it) }.toSet()
private fun possibleTokenReference(find: List<KtSingleValueToken>, source: KtFile): Boolean =
source.preOrderTraversal()
.filterIsInstance<KtOperationReferenceExpression>()
.any { it.operationSignTokenType in find }
private fun possibleNameReferences(declaration: Name, sp: SourcePath): Set<KtFile> =
sp.all().filter { possibleNameReference(declaration, it) }.toSet()
private fun possibleNameReference(declaration: Name, source: KtFile): Boolean =
source.preOrderTraversal()
.filterIsInstance<KtSimpleNameExpression>()
.any { it.getReferencedNameAsName() == declaration }
private fun matchesReference(found: DeclarationDescriptor, search: KtNamedDeclaration): Boolean {
if (found is ConstructorDescriptor && found.isPrimary)
return search is KtClass && found.constructedClass.fqNameSafe == search.fqName
else
return found.findPsi() == search
}
private fun operatorNames(name: Name): List<KtSingleValueToken> =
when (name) {
OperatorNameConventions.EQUALS -> listOf(KtTokens.EQEQ)
OperatorNameConventions.COMPARE_TO -> listOf(KtTokens.GT, KtTokens.LT, KtTokens.LTEQ, KtTokens.GTEQ)
else -> {
val token = OperatorConventions.UNARY_OPERATION_NAMES.inverse()[name] ?:
OperatorConventions.BINARY_OPERATION_NAMES.inverse()[name] ?:
OperatorConventions.ASSIGNMENT_OPERATIONS.inverse()[name] ?:
OperatorConventions.BOOLEAN_OPERATIONS.inverse()[name]
listOfNotNull(token)
}
}
| mit | fe5de2a56cb79c4373f3491828f10bc8 | 46.969957 | 165 | 0.739912 | 4.870153 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemFilter.kt | 3 | 3865 | // 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.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.Problem
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel.renderSeverity
import com.intellij.util.ui.tree.TreeUtil.promiseExpandAll
import org.jetbrains.annotations.Nls
internal class ProblemFilter(val state: ProblemsViewState) : (Problem) -> Boolean {
override fun invoke(problem: Problem): Boolean {
val highlighting = problem as? HighlightingProblem ?: return true
return !(state.hideBySeverity.contains(highlighting.severity))
}
}
internal class SeverityFiltersActionGroup : DumbAware, ActionGroup() {
override fun getChildren(event: AnActionEvent?): Array<AnAction> {
val project = event?.project ?: return AnAction.EMPTY_ARRAY
if (project.isDisposed) return AnAction.EMPTY_ARRAY
val panel = ProblemsView.getSelectedPanel(project) as? HighlightingPanel ?: return AnAction.EMPTY_ARRAY
val severities = SeverityRegistrar.getSeverityRegistrar(project).allSeverities.reversed()
.filter { it != HighlightSeverity.INFO && it > HighlightSeverity.INFORMATION && it < HighlightSeverity.ERROR }
val (mainSeverities, otherSeverities) = severities.partition { it >= HighlightSeverity.GENERIC_SERVER_ERROR_OR_WARNING }
val actions = mainSeverities.mapTo(ArrayList<AnAction>()) {
SeverityFilterAction(renderSeverity(it), it.myVal, panel)
}
actions.add(OtherSeveritiesFilterAction(otherSeverities.map { it.myVal }, panel))
return actions.toTypedArray()
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
}
private abstract class SeverityFilterActionBase(name: @Nls String, protected val panel: HighlightingPanel): DumbAwareToggleAction(name) {
abstract fun updateState(selected: Boolean): Boolean
override fun setSelected(event: AnActionEvent, selected: Boolean) {
val changed = updateState(selected)
if (changed) {
val wasEmpty = panel.tree.isEmpty
panel.state.intIncrementModificationCount()
panel.treeModel.structureChanged(null)
panel.powerSaveStateChanged()
// workaround to expand a root without handle
if (wasEmpty) {
promiseExpandAll(panel.tree)
}
}
}
}
private class OtherSeveritiesFilterAction(
private val severities: Collection<Int>,
panel: HighlightingPanel
): SeverityFilterActionBase(ProblemsViewBundle.message("problems.view.highlighting.other.problems.show"), panel) {
override fun isSelected(event: AnActionEvent): Boolean {
val state = panel.state.hideBySeverity
return !severities.all { state.contains(it) }
}
override fun updateState(selected: Boolean): Boolean {
val state = panel.state.hideBySeverity
return when {
selected -> state.removeAll(severities)
else -> state.addAll(severities)
}
}
}
private class SeverityFilterAction(@Nls name: String, val severity: Int, panel: HighlightingPanel): SeverityFilterActionBase(name, panel) {
override fun isSelected(event: AnActionEvent) = !panel.state.hideBySeverity.contains(severity)
override fun updateState(selected: Boolean): Boolean {
val state = panel.state.hideBySeverity
return when {
selected -> state.remove(severity)
else -> state.add(severity)
}
}
}
| apache-2.0 | dcda5948aa0e8f686690d1758bf90725 | 41.944444 | 139 | 0.769987 | 4.568558 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/metric/Metric.kt | 1 | 1675 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.metric
import com.google.common.hash.Hasher
import java.lang.IllegalStateException
interface Metric {
val timestamp: Long
fun valid(): Boolean
fun hash(hasher: Hasher)
companion object {
@JvmField val comparator: Comparator<Metric> = Comparator.comparingLong(Metric::timestamp)
@JvmField val invalid = object: Metric {
override val timestamp: Long
get() = throw IllegalStateException("invalid does not have a timestamp")
override fun valid(): Boolean = false
override fun hash(hasher: Hasher) {
}
}
@Deprecated("Use property instead of function")
fun invalid() = invalid
@Deprecated("Use property instead of function")
fun comparator() = comparator
}
} | apache-2.0 | 465b3072a4c9195b3010b1b67157c8d5 | 30.622642 | 98 | 0.693731 | 4.627072 | false | false | false | false |
github/codeql | java/ql/test/kotlin/library-tests/classes/local_anonymous.kt | 1 | 832 | package LocalAnonymous
class Class1 {
fun fn1(): Any {
return object {
fun fn() {}
}
}
fun fn2() {
fun fnLocal() {}
fnLocal()
}
fun fn3() {
val lambda1 = { a: Int, b: Int -> a + b }
val lambda2 = fun(a: Int, b: Int) = a + b
}
fun fn4() {
val fnRef = Class1::fn3
}
fun fn5() {
class LocalClass {}
LocalClass()
}
fun nullableAnonymous() = object {
var x = 1
fun member() {
val maybeThis = if (x == 1) this else null // Expression with nullable anonymous type
}
}
}
interface Interface2 {}
class Class2 {
var i = object: Interface2 {
init {
var answer: String = "42" // Local variable in anonymous class initializer
}
}
}
| mit | 6feb2301eab0652c46f58815a629962b | 17.488889 | 97 | 0.478365 | 3.869767 | false | false | false | false |
JimSeker/sensors | input2_tk/app/src/main/java/edu/cs4730/input2_tk/MainActivity.kt | 1 | 5993 | package edu.cs4730.input2_tk
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.widget.Toast
import android.view.GestureDetector.OnGestureListener
import android.view.GestureDetector.OnDoubleTapListener
import androidx.core.view.GestureDetectorCompat
/**
* This is example is copied from the input2 java version.
* It sets a gesture detector on the "screen". There is no real layout.
* needs testing with say a edittext field and button to see what if anything breaks.
* <p>
* we are overriding the default ontouchlistener (onTouchEvent) to call the gesture detector.
* <p>
* Also overriding the default onKeyDown() for the activity, this maybe not be good idea
* if there are widgets that also need the key events such as a EditText.
* <p>
* Overriding the backbuttonpressed as well. it just calls finish().
*/
class MainActivity : AppCompatActivity(), OnGestureListener, OnDoubleTapListener {
val TAG = "Gestures"
var mDetector: GestureDetectorCompat? = null
val chars = charArrayOf(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '0'
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Instantiate the gesture detector with the application context and an implementation of GestureDetector.OnGestureListener
mDetector = GestureDetectorCompat(this, this)
// Also Set the gesture detector as the double tap listener. See the overrides below for which events comes from which.
mDetector!!.setOnDoubleTapListener(this)
}
/**
* Keyevent that comes from the activity.
*/
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
val key = event.getMatch(chars)
if (key != '\u0000') {
Log.d(TAG, "onKeyDown: $key")
Toast.makeText(applicationContext, "onKeyDown: $key", Toast.LENGTH_SHORT).show()
return true
}
//allow the system to deal with the events we do not, like all the rest of the buttons.
return super.onKeyDown(keyCode, event)
}
/**
* This is really not recommended by well anyone. You are change the default function of the device.
* users really hate when you do that.
*/
override fun onBackPressed() {
// do something on back.
Log.d(TAG, "onBackPressed: it was pushed.")
Toast.makeText(applicationContext, "onBackPressed: it was pushed.", Toast.LENGTH_SHORT)
.show()
finish() //we have to manually end the program, since we captured the backup button.
}
/**
* touch event that comes from he activity.
*/
override fun onTouchEvent(event: MotionEvent): Boolean {
mDetector!!.onTouchEvent(event)
//log it, but no toast here.
Log.d(TAG, "onTouchEvent: $event")
// Be sure to call the superclass implementation, since we are not handling anything here.
return super.onTouchEvent(event)
}
/**
* overridden from the OnGuestureListener.
*/
override fun onDown(event: MotionEvent): Boolean {
Log.d(TAG, "onDown: $event")
Toast.makeText(applicationContext, "onDown: $event", Toast.LENGTH_SHORT).show()
return true
}
/**
* overridden from the OnGuestureListener.
*/
override fun onFling(
event1: MotionEvent, event2: MotionEvent,
velocityX: Float, velocityY: Float
): Boolean {
val msg = "onFling: $event1$event2"
Log.d(TAG, msg)
Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()
return true
}
/**
* overridden from the OnGuestureListener.
*/
override fun onLongPress(event: MotionEvent) {
Toast.makeText(applicationContext, "onLongPress: $event", Toast.LENGTH_SHORT).show()
Log.d(TAG, "onLongPress: $event")
}
/**
* overridden from the OnGuestureListener.
*/
override fun onScroll(
e1: MotionEvent, e2: MotionEvent, distanceX: Float,
distanceY: Float
): Boolean {
val msg = "onScroll: $e1$e2"
Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()
Log.d(TAG, msg)
return true
}
/**
* overridden from the OnGuestureListener.
*/
override fun onShowPress(event: MotionEvent) {
Toast.makeText(applicationContext, "onShowPress: $event", Toast.LENGTH_SHORT).show()
Log.d(TAG, "onShowPress: $event")
}
/**
* overridden from the OnGuestureListener.
*/
override fun onSingleTapUp(event: MotionEvent): Boolean {
Toast.makeText(applicationContext, "onSingleTapUp: $event", Toast.LENGTH_SHORT).show()
Log.d(TAG, "onSingleTapUp: $event")
return true
}
/**
* overridden from the OnDoubleTapListener
*/
override fun onDoubleTap(event: MotionEvent): Boolean {
Toast.makeText(applicationContext, "onDoubleTap: $event", Toast.LENGTH_SHORT).show()
Log.d(TAG, "onDoubleTap: $event")
return true
}
/**
* overridden from the OnDoubleTapListener
*/
override fun onDoubleTapEvent(event: MotionEvent): Boolean {
Toast.makeText(applicationContext, "onDoubleTapEvent: $event", Toast.LENGTH_SHORT).show()
Log.d(TAG, "onDoubleTapEvent: $event")
return true
}
/**
* overridden from the OnDoubleTapListener
*/
override fun onSingleTapConfirmed(event: MotionEvent): Boolean {
Toast.makeText(applicationContext, "onSingleTapConfirmed: $event", Toast.LENGTH_SHORT)
.show()
Log.d(TAG, "onSingleTapConfirmed: $event")
return true
}
} | apache-2.0 | 7b6619e9c25197b0b50d368b4e41b420 | 33.448276 | 131 | 0.645753 | 4.193842 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/content/interactor/ContentInteractorImp.kt | 1 | 3139 | package org.secfirst.umbrella.feature.content.interactor
import org.secfirst.umbrella.data.database.checklist.Checklist
import org.secfirst.umbrella.data.database.content.ContentData
import org.secfirst.umbrella.data.database.content.ContentRepo
import org.secfirst.umbrella.data.database.difficulty.Difficulty
import org.secfirst.umbrella.data.database.form.Form
import org.secfirst.umbrella.data.database.lesson.Module
import org.secfirst.umbrella.data.database.lesson.Subject
import org.secfirst.umbrella.data.database.reader.FeedSource
import org.secfirst.umbrella.data.database.reader.RSS
import org.secfirst.umbrella.data.database.segment.Markdown
import org.secfirst.umbrella.data.disk.TentLoader
import org.secfirst.umbrella.data.disk.TentRepo
import org.secfirst.umbrella.data.network.ApiHelper
import org.secfirst.umbrella.data.preferences.AppPreferenceHelper
import org.secfirst.umbrella.feature.base.interactor.BaseInteractorImp
import javax.inject.Inject
class ContentInteractorImp @Inject constructor(apiHelper: ApiHelper,
preferenceHelper: AppPreferenceHelper,
contentRepo: ContentRepo,
private val tentRepo: TentRepo,
private val tentLoader: TentLoader)
: BaseInteractorImp(apiHelper, preferenceHelper, contentRepo), ContentBaseInteractor {
override suspend fun resetDatabase() = contentRepo.resetContent()
override suspend fun persistRSS(rssList: List<RSS>) = contentRepo.insertDefaultRSS(rssList)
override suspend fun getSubject(subjectId: String) = contentRepo.getSubject(subjectId)
override suspend fun getDifficulty(difficultyId: String) = contentRepo.getDifficulty(difficultyId)
override suspend fun getModule(moduleId: String) = contentRepo.getModule(moduleId)
override suspend fun getMarkdown(markdownId: String) = contentRepo.getMarkdown(markdownId)
override suspend fun getChecklist(checklistId: String) = contentRepo.getChecklist(checklistId)
override suspend fun getForm(formId: String) = contentRepo.getForm(formId)
override suspend fun saveAllChecklists(checklists: List<Checklist>) = contentRepo.saveAllChecklists(checklists)
override suspend fun saveAllMarkdowns(markdowns: List<Markdown>) = contentRepo.saveAllMarkdowns(markdowns)
override suspend fun saveAllModule(modules: List<Module>) = contentRepo.saveAllModule(modules)
override suspend fun saveAllDifficulties(difficulties: List<Difficulty>) = contentRepo.saveAllDifficulties(difficulties)
override suspend fun saveAllForms(forms: List<Form>) = contentRepo.saveAllForms(forms)
override suspend fun saveAllSubjects(subjects: List<Subject>) = contentRepo.saveAllSubjects(subjects)
override suspend fun persistFeedSource(feedSources: List<FeedSource>) = contentRepo.insertFeedSource(feedSources)
override suspend fun fetchData(url: String) = tentRepo.fetchRepository(url)
override suspend fun persist(contentData: ContentData) = contentRepo.insertAllLessons(contentData)
} | gpl-3.0 | e49e9acc55b8427c63bd0b2987abd7d5 | 50.47541 | 124 | 0.776362 | 4.814417 | false | false | false | false |
FireZenk/Kartographer | sample/src/main/java/org/firezenk/kartographer/pages/page4/Page4Activity.kt | 1 | 1531 | package org.firezenk.kartographer.pages.page4
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_page4.*
import org.firezenk.kartographer.ExternalRoute
import org.firezenk.kartographer.R
import org.firezenk.kartographer.SampleApplication
import org.firezenk.kartographer.annotations.RoutableActivity
import org.firezenk.kartographer.library.Kartographer
import org.firezenk.kartographer.library.dsl.routeExternal
import org.firezenk.kartographer.pages.page3.Page3
import java.util.*
import javax.inject.Inject
@RoutableActivity(path = "PAGE4", flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
class Page4Activity : AppCompatActivity() {
@Inject lateinit var router: Kartographer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_page4)
SampleApplication.component.injectTo(this)
val param = router.bundle<Bundle>()?.getInt("TESTINT")
button.setOnClickListener {
router next routeExternal {
target = ExternalRoute()
params = mapOf<String, Any>("test" to "HEY!")
}
}
}
override fun onBackPressed() {
router.backOnPath({ super.onBackPressed() })
}
override fun finish() {
router.sendResult(Page3.REQUEST_CODE, "Result from activity " + Random().nextInt())
super.finish()
}
} | mit | fd8a22159a305ea1b191f0ede088b204 | 32.304348 | 107 | 0.726976 | 4.361823 | false | false | false | false |
MGaetan89/ShowsRage | app/src/main/kotlin/com/mgaetan89/showsrage/helper/GenericCallback.kt | 1 | 847 | package com.mgaetan89.showsrage.helper
import android.support.v4.app.FragmentActivity
import android.widget.Toast
import com.mgaetan89.showsrage.model.GenericResponse
import retrofit.Callback
import retrofit.RetrofitError
import retrofit.client.Response
import java.lang.ref.WeakReference
open class GenericCallback(activity: FragmentActivity?) : Callback<GenericResponse> {
private val activityReference = WeakReference(activity)
override fun failure(error: RetrofitError?) {
error?.printStackTrace()
}
override fun success(genericResponse: GenericResponse?, response: Response?) {
if (genericResponse?.message?.isNotBlank() == true) {
val activity = this.getActivity() ?: return
Toast.makeText(activity, genericResponse.message, Toast.LENGTH_SHORT).show()
}
}
protected fun getActivity() = this.activityReference.get()
}
| apache-2.0 | 97df13fe5a256059a961d52e477229c4 | 30.37037 | 85 | 0.793388 | 4.277778 | false | false | false | false |
orauyeu/SimYukkuri | subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/statistic/statistics/GrowthImpl.kt | 1 | 420 | package simyukkuri.gameobject.yukkuri.statistic.statistics
/** [Growth]の標準的ゆっくりへの実装 */
class GrowthImpl(override val growthStage: Growth.GrowthStage) : Growth {
override val isBaby: Boolean = growthStage == Growth.GrowthStage.BABY
override val isChild: Boolean = growthStage == Growth.GrowthStage.CHILD
override val isAdult: Boolean = growthStage == Growth.GrowthStage.ADULT
} | apache-2.0 | 7af0b40d9adb1e00ea7353227392595f | 47.75 | 75 | 0.765152 | 3.6 | false | false | false | false |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/utils/Dim.kt | 1 | 4453 | // Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// PdfLayoutMgr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.utils
import org.apache.pdfbox.pdmodel.common.PDRectangle
import java.lang.AssertionError
import java.lang.Math.abs
/**
Immutable 2D dimension in terms of non-negative width and height.
Do not confuse a dimension (measurement) with a Coord(inate) which represents an offset from
(0, 0) at the bottom of the page.
Remember: a Dimensions on a Portrait orientation may have the width and height *reversed*.
*/
data class Dim(val width: Double, val height: Double) {
init {
if (width < 0.0 || height < 0.0) {
throw IllegalArgumentException("Dimensions must be positive: width=$width height=$height")
}
}
/**
* Returns an Dim with the width and height taken from the same-named fields on the given
* rectangle.
*/
constructor(rect: PDRectangle) : this(rect.width.toDouble(), rect.height.toDouble())
fun withWidth(newX: Double) = Dim(newX, height)
fun withHeight(newY: Double) = Dim(width, newY)
/**
* If true, returns this, if false, returns a new Dim with width and height values swapped.
* PDFs think the long dimension is always the height of the page, regardless of portrait vs.
* landscape, so we need to conditionally adjust what we call width and height.
*/
// This is suspicious because we're swapping width and height and the compiler thinks
// we might be doing so by accident.
fun swapWh() = Dim(height, width)
/** Returns a PDRectangle with the given width and height (but no/0 offset) */
fun toRect() = PDRectangle(width.toFloat(), height.toFloat())
// /** Returns a PDRectangle with the given width and height (but no/0 offset) */
// public PDRectangle toRect(Coord off) {
// return new PDRectangle(off.x(), off.y(), width, height);
// }
/** Subtracts the given Dim from this one (remember, these can't be negative). */
operator fun minus(that: Dim) = Dim(this.width - that.width, this.height - that.height)
/** Adds the given Dim from this one */
operator fun plus(that: Dim) = Dim(this.width + that.width, this.height + that.height)
// public XyPair plusXMinusY(XyPair that) { return of(this.width + that.width(), this.height - that.height()); }
// public Dim maxXandY(Dim that) {
// if ((this.width >= that.width()) && (this.height >= that.height())) { return this; }
// if ((this.width <= that.width()) && (this.height <= that.height())) { return that; }
// return of((this.width > that.width()) ? this.width : that.width(),
// (this.height > that.height()) ? this.height : that.height());
// }
/** Compares dim and returns true if that dimension doesn't extend beyond this one. */
fun lte(that: Dim): Boolean = this.width <= that.width &&
this.height <= that.height
override fun toString() = "Dim($width, $height)"
companion object {
/** Zero-dimension (zero width, zero height) */
@JvmField
val ZERO = Dim(0.0, 0.0)
fun sum(xys:Iterable<Dim>) = xys.fold(ZERO, { acc, xy -> acc.plus(xy)})
fun assertEquals(xya: Dim, xyb: Dim, latitude: Double) {
if ((abs(xya.height - xyb.height) > latitude) ||
(abs(xya.width - xyb.width) > latitude)) {
throw AssertionError("\n" +
"Expected: $xya\n" +
"Actual: $xyb")
}
}
}
}
| agpl-3.0 | a3451112ec3d28dd00e8e16ccbea4606 | 41.817308 | 119 | 0.637099 | 3.944198 | false | false | false | false |
vladmm/intellij-community | platform/script-debugger/debugger-ui/src/util.kt | 1 | 1531 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.xdebugger.util
import com.intellij.xdebugger.XDebugSession
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.debugger.SuspendContext
import org.jetbrains.debugger.Vm
import org.jetbrains.rpc.LOG
// have to use package "com.intellij.xdebugger.util" to avoid package clash
fun XDebugSession.rejectedErrorReporter(description: String? = null): (Throwable) -> Unit = {
Promise.logError(LOG, it)
if (it != AsyncPromise.OBSOLETE_ERROR) {
reportError("${if (description == null) "" else description + ": "}${it.getMessage()}")
}
}
inline fun <T> contextDependentResultConsumer(context: SuspendContext, crossinline done: (result: T, vm: Vm) -> Unit) : (T) -> Unit {
return {
val vm = context.valueManager.vm
if (vm.attachStateManager.isAttached() && !vm.suspendContextManager.isContextObsolete(context)) {
done(it, vm)
}
}
} | apache-2.0 | 1daa1fad238f5117b72f1fc10eba6735 | 37.3 | 133 | 0.740039 | 3.997389 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/exception/SetupException.kt | 1 | 1175 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.exception
import javax.swing.JComponent
sealed class SetupException(val j: JComponent) : Exception() {
abstract val error: String
}
class EmptyFieldSetupException(j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>Please fill in all required fields</html>"
}
class BadListSetupException(j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>Please enter as a comma separated list</html>"
}
class EmptyInputSetupException(j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>Please fill in all required fields</html>"
}
class InvalidMainClassNameException(j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>Main Class Name must be a valid Java identifier and cannot be the default package</html>"
}
class OtherSetupException(private val msg: String, j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>$msg</html>"
}
| mit | 1bf3cc606972bdb4bc15709c17aaa773 | 26.325581 | 112 | 0.700426 | 3.916667 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mixin/action/GenerateShadowAction.kt | 1 | 8470 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.demonwav.mcdev.platform.mixin.util.findFields
import com.demonwav.mcdev.platform.mixin.util.findMethods
import com.demonwav.mcdev.util.findContainingClass
import com.demonwav.mcdev.util.findFirstMember
import com.demonwav.mcdev.util.findLastChild
import com.demonwav.mcdev.util.findNextMember
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.toTypedArray
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.generation.GenerationInfo
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.generation.OverrideImplementsAnnotationsHandler
import com.intellij.codeInsight.generation.PsiElementClassMember
import com.intellij.codeInsight.generation.PsiFieldMember
import com.intellij.codeInsight.generation.PsiGenerationInfo
import com.intellij.codeInsight.generation.PsiMethodMember
import com.intellij.codeInsight.hint.HintManager
import com.intellij.ide.util.MemberChooser
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiModifierList
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.PsiSubstitutor
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import java.util.stream.Stream
import kotlin.streams.toList
class GenerateShadowAction : MixinCodeInsightAction() {
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val offset = editor.caretModel.offset
val psiClass = file.findElementAt(offset)?.findContainingClass() ?: return
val fields = findFields(psiClass)?.map(::PsiFieldMember) ?: emptySequence()
val methods = findMethods(psiClass)?.map(::PsiMethodMember) ?: emptySequence()
val members = (fields + methods).toTypedArray()
if (members.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No members to shadow have been found")
return
}
val chooser = MemberChooser<PsiElementClassMember<*>>(members, false, true, project)
chooser.title = "Select members to Shadow"
chooser.setCopyJavadocVisible(false)
chooser.show()
val elements = (chooser.selectedElements ?: return).ifEmpty { return }
disableAnnotationWrapping(project) {
runWriteAction {
GenerateMembersUtil.insertMembersAtOffset(
file,
offset,
createShadowMembers(
project,
psiClass,
elements.stream().map(PsiElementClassMember<*>::getElement)
)
// Select first element in editor
).firstOrNull()?.positionCaret(editor, false)
}
}
}
}
fun insertShadows(project: Project, psiClass: PsiClass, members: Stream<PsiMember>) {
insertShadows(psiClass, createShadowMembers(project, psiClass, members))
}
fun insertShadows(psiClass: PsiClass, shadows: List<GenerationInfo>) {
// Find first element after shadow
val lastShadow = psiClass.findLastChild {
(it as? PsiModifierListOwner)?.modifierList?.findAnnotation(MixinConstants.Annotations.SHADOW) != null
}
val anchor = lastShadow?.findNextMember() ?: psiClass.findFirstMember()
// Insert new shadows after last shadow (or at the top of the class)
GenerateMembersUtil.insertMembersBeforeAnchor(psiClass, anchor, shadows)
}
fun createShadowMembers(
project: Project,
psiClass: PsiClass,
members: Stream<PsiMember>
): List<PsiGenerationInfo<PsiMember>> {
var methodAdded = false
val result = members.map { m ->
val shadowMember: PsiMember = when (m) {
is PsiMethod -> {
methodAdded = true
shadowMethod(psiClass, m)
}
is PsiField -> shadowField(project, m)
else -> throw UnsupportedOperationException("Unsupported member type: ${m::class.java.name}")
}
// Add @Shadow annotation
shadowMember.modifierList!!.addAnnotation(MixinConstants.Annotations.SHADOW)
PsiGenerationInfo(shadowMember)
}.toList()
// Make the class abstract (if not already)
if (methodAdded && !psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
psiClass.modifierList!!.setModifierProperty(PsiModifier.ABSTRACT, true)
}
return result
}
private fun shadowMethod(psiClass: PsiClass, method: PsiMethod): PsiMethod {
val newMethod = GenerateMembersUtil.substituteGenericMethod(method, PsiSubstitutor.EMPTY, psiClass)
// Remove Javadocs
OverrideImplementUtil.deleteDocComment(newMethod)
val newModifiers = newMethod.modifierList
// Relevant modifiers are copied by GenerateMembersUtil.substituteGenericMethod
// Copy annotations
copyAnnotations(psiClass.containingFile, method.modifierList, newModifiers)
// If the method was original private, make it protected now
if (newModifiers.hasModifierProperty(PsiModifier.PRIVATE)) {
newModifiers.setModifierProperty(PsiModifier.PROTECTED, true)
}
// Make method abstract
newModifiers.setModifierProperty(PsiModifier.ABSTRACT, true)
// Remove code block
newMethod.body?.delete()
return newMethod
}
private fun shadowField(project: Project, field: PsiField): PsiField {
val newField = JavaPsiFacade.getElementFactory(project).createField(field.name, field.type)
val newModifiers = newField.modifierList!!
val modifiers = field.modifierList!!
// Copy modifiers
copyModifiers(modifiers, newModifiers)
// Copy annotations
copyAnnotations(field.containingFile, modifiers, newModifiers)
if (newModifiers.hasModifierProperty(PsiModifier.FINAL)) {
// If original field was final, add the @Final annotation instead
newModifiers.setModifierProperty(PsiModifier.FINAL, false)
newModifiers.addAnnotation(MixinConstants.Annotations.FINAL)
}
return newField
}
private fun copyModifiers(modifiers: PsiModifierList, newModifiers: PsiModifierList) {
for (modifier in PsiModifier.MODIFIERS) {
if (modifiers.hasExplicitModifier(modifier)) {
newModifiers.setModifierProperty(modifier, true)
}
}
}
private fun copyAnnotations(file: PsiFile, modifiers: PsiModifierList, newModifiers: PsiModifierList) {
// Copy annotations registered by extensions (e.g. @Nullable), based on OverrideImplementUtil.annotateOnOverrideImplement
for (ext in OverrideImplementsAnnotationsHandler.EP_NAME.extensionList) {
for (annotation in ext.getAnnotations(file)) {
copyAnnotation(modifiers, newModifiers, annotation)
}
}
// Copy @Deprecated annotation
copyAnnotation(modifiers, newModifiers, CommonClassNames.JAVA_LANG_DEPRECATED)
}
private fun copyAnnotation(modifiers: PsiModifierList, newModifiers: PsiModifierList, annotation: String) {
// Check if annotation exists
val psiAnnotation = modifiers.findAnnotation(annotation) ?: return
// Have we already added this annotation? If not, copy it
newModifiers.findAnnotation(annotation) ?: newModifiers.addAfter(psiAnnotation, null)
}
inline fun disableAnnotationWrapping(project: Project, func: () -> Unit) {
val settings = CodeStyle.getSettings(project).getCommonSettings(JavaLanguage.INSTANCE)
val methodWrap = settings.METHOD_ANNOTATION_WRAP
val fieldWrap = settings.FIELD_ANNOTATION_WRAP
settings.METHOD_ANNOTATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP
settings.FIELD_ANNOTATION_WRAP = CommonCodeStyleSettings.DO_NOT_WRAP
try {
func()
} finally {
settings.METHOD_ANNOTATION_WRAP = methodWrap
settings.FIELD_ANNOTATION_WRAP = fieldWrap
}
}
| mit | 640a1a987f27c4143a9b550e9491958f | 36.644444 | 125 | 0.733766 | 4.831717 | false | false | false | false |
google/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/AbstractCommitChangesAction.kt | 7 | 1981 | // 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.openapi.vcs.changes.actions
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.actions.AbstractCommonCheckinAction
import com.intellij.openapi.vcs.actions.VcsContext
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.vcsUtil.VcsUtil.getFilePath
abstract class AbstractCommitChangesAction : AbstractCommonCheckinAction() {
override fun getRoots(dataContext: VcsContext): Array<FilePath> =
ProjectLevelVcsManager.getInstance(dataContext.project!!).allVersionedRoots.map { getFilePath(it) }.toTypedArray()
override fun approximatelyHasRoots(dataContext: VcsContext): Boolean =
ProjectLevelVcsManager.getInstance(dataContext.project!!).hasActiveVcss()
override fun update(vcsContext: VcsContext, presentation: Presentation) {
super.update(vcsContext, presentation)
if (presentation.isEnabledAndVisible) {
val changes = vcsContext.selectedChanges
if (vcsContext.place == ActionPlaces.CHANGES_VIEW_POPUP) {
val changeLists = vcsContext.selectedChangeLists
presentation.isEnabled =
if (changeLists.isNullOrEmpty()) !changes.isNullOrEmpty() else changeLists.size == 1 && !changeLists[0].changes.isEmpty()
}
if (presentation.isEnabled && !changes.isNullOrEmpty()) {
val manager = ChangeListManager.getInstance(vcsContext.project!!)
presentation.isEnabled = changes.all { isActionEnabled(manager, it) }
}
}
}
protected open fun isActionEnabled(manager: ChangeListManager,
it: Change) = manager.getChangeList(it) != null
} | apache-2.0 | bf05b7fd5f989f512c4cc4a10a07670b | 44.045455 | 140 | 0.763756 | 4.785024 | false | false | false | false |
google/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/actions/CommonCheckinFilesAction.kt | 5 | 2842 | // 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.openapi.vcs.actions
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.LocalChangeList
import com.intellij.util.containers.ContainerUtil.intersects
import com.intellij.vcsUtil.VcsUtil.getVcsFor
import kotlin.streams.asSequence
private fun VcsContext.getRoots(): Sequence<FilePath> = selectedFilePathsStream.asSequence()
private fun VcsContext.getCommonVcs(): AbstractVcs? {
val project = project ?: return null
return getRoots().mapNotNull { getVcsFor(project, it) }.distinct().singleOrNull()
}
open class CommonCheckinFilesAction : AbstractCommonCheckinAction() {
override fun getActionName(dataContext: VcsContext): String {
val actionName = dataContext.getCommonVcs()?.checkinEnvironment?.checkinOperationName
return appendSubject(dataContext, actionName ?: message("vcs.command.name.checkin"))
}
private fun appendSubject(dataContext: VcsContext, checkinActionName: String): String {
val roots = dataContext.getRoots().take(2).toList()
if (roots.isEmpty()) return checkinActionName
if (roots[0].isDirectory) {
return message("action.name.checkin.directory", checkinActionName, roots.size)
}
else {
return message("action.name.checkin.file", checkinActionName, roots.size)
}
}
override fun getInitiallySelectedChangeList(context: VcsContext, project: Project): LocalChangeList {
val manager = ChangeListManager.getInstance(project)
val defaultChangeList = manager.defaultChangeList
var result: LocalChangeList? = null
for (root in getRoots(context)) {
if (root.virtualFile == null) continue
val changes = manager.getChangesIn(root)
if (intersects(changes, defaultChangeList.changes)) return defaultChangeList
result = changes.firstOrNull()?.let { manager.getChangeList(it) }
}
return result ?: defaultChangeList
}
override fun approximatelyHasRoots(dataContext: VcsContext): Boolean =
dataContext.getRoots().any { isApplicableRoot(it, dataContext) }
protected open fun isApplicableRoot(path: FilePath, dataContext: VcsContext): Boolean {
val status = ChangeListManager.getInstance(dataContext.project!!).getStatus(path)
return (path.isDirectory || status != FileStatus.NOT_CHANGED) && status != FileStatus.IGNORED
}
override fun getRoots(dataContext: VcsContext): Array<FilePath> = dataContext.selectedFilePaths
override fun isForceUpdateCommitStateFromContext(): Boolean = true
}
| apache-2.0 | 4852175f80c971e5438fb33069985444 | 39.6 | 120 | 0.77164 | 4.682043 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/EditBookmarkAction.kt | 3 | 1736 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.BookmarkBundle
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.Messages
internal class EditBookmarkAction : DumbAwareAction(BookmarkBundle.messagePointer("bookmark.edit.action.text")) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(event: AnActionEvent) = with(event.presentation) {
isEnabledAndVisible = process(event, false) != null
}
override fun actionPerformed(event: AnActionEvent) {
process(event, true)
}
private fun process(event: AnActionEvent, perform: Boolean): String? {
val manager = event.bookmarksManager ?: return null
val component = event.getData(PlatformDataKeys.CONTEXT_COMPONENT) ?: return null
val bookmark = event.contextBookmark ?: return null
val group = manager.getGroups(bookmark).firstOrNull() ?: return null
val description = group.getDescription(bookmark) ?: return null
return if (!perform) description
else Messages.showInputDialog(component,
BookmarkBundle.message("action.bookmark.edit.description.dialog.message"),
BookmarkBundle.message("action.bookmark.edit.description.dialog.title"),
null,
description,
null
)?.also { group.setDescription(bookmark, it) }
}
init {
isEnabledInModalContext = true
}
}
| apache-2.0 | eb1d90b6481b450875a50735027bab6a | 40.333333 | 158 | 0.769009 | 4.756164 | false | false | false | false |
Skatteetaten/boober | src/test/kotlin/no/skatteetaten/aurora/boober/unit/OpenShiftRestTemplateWrapperTest.kt | 1 | 4058 | package no.skatteetaten.aurora.boober.unit
import assertk.all
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isFailure
import assertk.assertions.isInstanceOf
import com.fasterxml.jackson.databind.JsonNode
import no.skatteetaten.aurora.boober.service.openshift.OpenShiftRestTemplateWrapper
import no.skatteetaten.aurora.boober.utils.ResourceLoader
import no.skatteetaten.aurora.boober.utils.RetryLogger
import no.skatteetaten.aurora.mockmvc.extensions.mockwebserver.execute
import okhttp3.mockwebserver.MockWebServer
import org.junit.jupiter.api.Test
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.RequestEntity
import org.springframework.http.ResponseEntity
import org.springframework.web.client.HttpClientErrorException
import java.net.URI
class OpenShiftRestTemplateWrapperTest : ResourceLoader() {
private val server = MockWebServer()
private val baseUrl = server.url("/")
private val restTemplate = RestTemplateBuilder().rootUri(baseUrl.toString()).build()
private val restTemplateWrapper =
OpenShiftRestTemplateWrapper(restTemplate)
val resourceUrl = "$baseUrl/apis/apps.openshift.io/v1/namespaces/aos/deploymentconfigs/webleveranse"
@Test
fun `Succeeds even if the request fails a couple of times`() {
val resourceMergerTestName = ResourceMergerTest::class.simpleName!!
val resource = loadJsonResource("deploymentconfig.json", folder = "$packageName/$resourceMergerTestName")
server.execute(
400 to "",
400 to "",
200 to resource
) {
val entity: ResponseEntity<JsonNode> = restTemplateWrapper.exchange(
RequestEntity<Any>(HttpMethod.GET, URI(resourceUrl)), true
)
assertThat(resource).jsonEquals(entity.body!!, "ResourceMergerTest/deploymentconfig.json", allowOverwrite = false)
}
}
@Test
fun `Fails when exceeds retry attempts`() {
server.execute(
400 to "",
400 to "",
400 to ""
) {
assertThat {
restTemplateWrapper.exchange(
RequestEntity<Any>(HttpMethod.GET, URI(resourceUrl)), true
)
}.isFailure().all {
this.isInstanceOf(HttpClientErrorException::class)
}
}
}
@Test
fun `Fails immediately when retry is disabled`() {
server.execute(
400 to ""
) {
assertThat {
restTemplateWrapper.exchange(
RequestEntity<Any>(HttpMethod.GET, URI(resourceUrl)), false
)
}.isFailure().all {
this.isInstanceOf(HttpClientErrorException::class)
}
// TOOD: hvordan kan jeg her sjekke at den ikke gjør flere kall?
}
}
@Test
fun `Get token snippet from auth header`() {
val token = "some_long_token"
val snippet = "token"
val httpHeaders = HttpHeaders().apply {
add(HttpHeaders.AUTHORIZATION, "Authorization $token")
}
assertThat(RetryLogger.getTokenSnippetFromAuthHeader(httpHeaders)).isEqualTo(snippet)
}
@Test
fun `Get sha256 token snippet from auth header`() {
val token = "sha256~09876"
val snippet = "09876"
val httpHeaders = HttpHeaders().apply {
add(HttpHeaders.AUTHORIZATION, "Bearer $token")
}
assertThat(RetryLogger.getTokenSnippetFromAuthHeader(httpHeaders)).isEqualTo(snippet)
}
@Test
fun `Get token snippet from short token in auth header`() {
val token = "9876"
val snippet = "9876"
val httpHeaders = HttpHeaders().apply {
add(HttpHeaders.AUTHORIZATION, "Bearer $token")
}
assertThat(RetryLogger.getTokenSnippetFromAuthHeader(httpHeaders)).isEqualTo(snippet)
}
}
| apache-2.0 | ba3fccb249721baaed7b3792d654e0e4 | 33.675214 | 126 | 0.662066 | 4.812574 | false | true | false | false |
ttomsu/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/StageDefinitionBuilders.kt | 1 | 5221 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q
import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner
import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder
import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode
import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode.DefinedTask
import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode.TaskGraph
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow
import com.netflix.spinnaker.orca.pipeline.StageExecutionFactory
import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilderImpl
import com.netflix.spinnaker.orca.pipeline.model.TaskExecutionImpl
/**
* Build and append the tasks for [stage].
*/
fun StageDefinitionBuilder.buildTasks(stage: StageExecution) {
buildTaskGraph(stage)
.listIterator()
.forEachWithMetadata { processTaskNode(stage, it) }
}
fun StageDefinitionBuilder.addContextFlags(stage: StageExecution) {
if (canManuallySkip()) {
// Provides a flag for the UI to indicate that the stage can be skipped.
stage.context["canManuallySkip"] = true
}
}
private fun processTaskNode(
stage: StageExecution,
element: IteratorElement<TaskNode>,
isSubGraph: Boolean = false
) {
element.apply {
when (value) {
is DefinedTask -> {
val task = TaskExecutionImpl()
task.id = (stage.tasks.size + 1).toString()
task.name = value.name
task.implementingClass = value.implementingClassName
if (isSubGraph) {
task.isLoopStart = isFirst
task.isLoopEnd = isLast
} else {
task.isStageStart = isFirst
task.isStageEnd = isLast
}
stage.tasks.add(task)
}
is TaskGraph -> {
value
.listIterator()
.forEachWithMetadata {
processTaskNode(stage, it, isSubGraph = true)
}
}
}
}
}
/**
* Build the synthetic stages for [stage] and inject them into the execution.
*/
fun StageDefinitionBuilder.buildBeforeStages(
stage: StageExecution,
callback: (StageExecution) -> Unit = {}
) {
val executionWindow = stage.buildExecutionWindow()
val graph = StageGraphBuilderImpl.beforeStages(stage, executionWindow)
beforeStages(stage, graph)
val beforeStages = graph.build().toList()
stage.execution.apply {
beforeStages.forEach {
it.sanitizeContext()
injectStage(stages.indexOf(stage), it)
callback.invoke(it)
}
}
}
fun StageDefinitionBuilder.buildAfterStages(
stage: StageExecution,
callback: (StageExecution) -> Unit = {}
) {
val graph = StageGraphBuilderImpl.afterStages(stage)
afterStages(stage, graph)
val afterStages = graph.build().toList()
stage.appendAfterStages(afterStages, callback)
}
fun StageDefinitionBuilder.buildFailureStages(
stage: StageExecution,
callback: (StageExecution) -> Unit = {}
) {
val graph = StageGraphBuilderImpl.afterStages(stage)
onFailureStages(stage, graph)
val afterStages = graph.build().toList()
stage.appendAfterStages(afterStages, callback)
}
fun StageExecution.appendAfterStages(
afterStages: Iterable<StageExecution>,
callback: (StageExecution) -> Unit = {}
) {
val index = execution.stages.indexOf(this) + 1
afterStages.reversed().forEach {
it.sanitizeContext()
execution.injectStage(index, it)
callback.invoke(it)
}
}
private typealias SyntheticStages = Map<SyntheticStageOwner, List<StageExecution>>
private fun StageExecution.buildExecutionWindow(): StageExecution? {
if (context.getOrDefault("restrictExecutionDuringTimeWindow", false) as Boolean) {
val execution = execution
val executionWindow = StageExecutionFactory.newStage(
execution,
RestrictExecutionDuringTimeWindow.TYPE,
RestrictExecutionDuringTimeWindow.TYPE,
context.filterKeys { it !in setOf("restrictExecutionDuringTimeWindow", "stageTimeoutMs") },
this,
STAGE_BEFORE
)
executionWindow.refId = "$refId<0"
return executionWindow
} else {
return null
}
}
@Suppress("UNCHECKED_CAST")
private fun PipelineExecution.injectStage(index: Int, stage: StageExecution) {
stages.add(index, stage)
}
private fun StageExecution.sanitizeContext() {
if (type != RestrictExecutionDuringTimeWindow.TYPE) {
context.apply {
remove("restrictExecutionDuringTimeWindow")
remove("restrictedExecutionWindow")
}
}
}
| apache-2.0 | 21e3136dca938ee475dad81dc48a9a60 | 30.077381 | 97 | 0.731852 | 4.314876 | false | false | false | false |
genonbeta/TrebleShot | zxing/src/main/java/org/monora/android/codescanner/Rect.kt | 1 | 2652 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.android.codescanner
import android.graphics.Matrix
import android.graphics.Rect
import kotlin.math.max
import kotlin.math.min
fun Rect.bound(left: Int, top: Int, right: Int, bottom: Int): Rect {
return if (this.left >= left && this.top >= top && this.right <= right && this.bottom <= bottom) {
this
} else Rect(this).also {
it.set(max(it.left, left), max(it.top, top), min(it.right, right), min(it.bottom, bottom))
}
}
fun Rect.fitIn(area: Rect): Rect {
val a = Rect(this)
val b = Rect(area)
if (a.left >= b.left && a.top >= b.top && a.right <= b.right && a.bottom <= b.bottom) return this
val fitWidth = min(a.width(), b.width())
val fitHeight = min(a.height(), b.height())
if (a.left < b.left) {
a.left = b.left
a.right = a.left + fitWidth
} else if (a.right > b.right) {
a.right = b.right
a.left = a.right - fitWidth
}
if (a.top < b.top) {
a.top = b.top
a.bottom = a.top + fitHeight
} else if (a.bottom > b.bottom) {
a.bottom = b.bottom
a.top = a.bottom - fitHeight
}
return Rect(left, top, right, bottom)
}
fun Rect.isPointInside(x: Int, y: Int): Boolean {
return left < x && top < y && right > x && bottom > y
}
fun Rect.rotate(angle: Float, x: Float, y: Float): Rect {
val rect = floatArrayOf(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())
Matrix().apply {
postRotate(angle, x, y)
mapPoints(rect)
}
var left = rect[0].toInt()
var top = rect[1].toInt()
var right = rect[2].toInt()
var bottom = rect[3].toInt()
if (left > right) {
val temp = left
left = right
right = temp
}
if (top > bottom) {
val temp = top
top = bottom
bottom = temp
}
return Rect(left, top, right, bottom)
} | gpl-2.0 | 0207cf16a70005358b307ae5c9c28c61 | 29.136364 | 102 | 0.615994 | 3.438392 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/nativ/linux/Vt.kt | 3 | 1361 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.nativ.linux
object Vt {
val VT_OPENQRY: Short = 0x5600
val VT_GETMODE: Short = 0x5601 /* get mode of active vt */
val VT_SETMODE: Short = 0x5602 /* set mode of active vt */
val VT_AUTO: Byte = 0x00 /* auto vt switching */
val VT_PROCESS: Byte = 0x01 /* process controls switching */
val VT_ACKACQ: Byte = 0x02 /* acknowledge switch */
val VT_ACTIVATE: Short = 0x5606 /* make vt active */
val VT_WAITACTIVE: Short = 0x5607 /* wait for vt active */
val VT_GETSTATE: Short = 0x5603
val VT_RELDISP: Short = 0x5605 /* release display */
}
| agpl-3.0 | 12426db74e7f79b60f02fb86609150d0 | 37.885714 | 75 | 0.693608 | 3.629333 | false | false | false | false |
leafclick/intellij-community | python/src/com/jetbrains/python/console/RunPythonToolwindowAction.kt | 1 | 1209 | // 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.jetbrains.python.console
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.wm.ToolWindowManager
import com.jetbrains.python.actions.PyExecuteSelectionAction
import icons.PythonIcons
class RunPythonToolwindowAction : AnAction(PythonIcons.Python.PythonConsoleToolWindow), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
if (project == null) return
PyExecuteSelectionAction.startNewConsoleInstance(project, {}, null, null)
}
/*
* This action should be available only when Python Console tool window isn't registered yet
* It's used only in Python plugin, because Console tool window is available by default in PyCharm
*/
override fun update(e: AnActionEvent) {
val project = e.project
if (project == null) return
e.presentation.isEnabledAndVisible = ToolWindowManager.getInstance(project).getToolWindow(PythonConsoleToolWindowFactory.ID) == null
}
} | apache-2.0 | 4b5abdc3adfe8ef691dbe155fd2bbd33 | 42.214286 | 140 | 0.790736 | 4.579545 | false | false | false | false |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/common/extentions/Extentions.kt | 1 | 1074 | package com.agoda.kakao.common.extentions
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
internal fun Drawable.toBitmap(): Bitmap {
if (this is BitmapDrawable && this.bitmap != null) {
return this.bitmap
}
if (this is StateListDrawable && this.getCurrent() is BitmapDrawable) {
val bitmapDrawable = this.getCurrent() as BitmapDrawable
if (bitmapDrawable.bitmap != null) {
return bitmapDrawable.bitmap
}
}
val bitmap = if (this.intrinsicWidth <= 0 || this.intrinsicHeight <= 0) {
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) // Single color bitmap will be created of 1x1 pixel
} else {
Bitmap.createBitmap(this.intrinsicWidth, this.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(bitmap)
this.setBounds(0, 0, canvas.width, canvas.height)
this.draw(canvas)
return bitmap
}
| apache-2.0 | cdc2deec883e65a11428416999a4208c | 33.645161 | 110 | 0.697393 | 4.401639 | false | true | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/documentpicker/DocumentPickerOptions.kt | 2 | 1697 | package abi43_0_0.expo.modules.documentpicker
import abi43_0_0.expo.modules.core.Promise
data class DocumentPickerOptions(val copyToCacheDirectory: Boolean, val types: Array<String>) {
companion object {
fun optionsFromMap(options: Map<String, Any?>, promise: Promise): DocumentPickerOptions? {
if (options.containsKey("type") && options["type"] == null) {
promise.reject("ERR_INVALID_OPTION", "type must be a list of strings")
return null
}
var mimeTypes = arrayListOf("*/*")
options["type"]?.let {
val types = it as ArrayList<*>
if (types.isEmpty() || types[0] !is String) {
promise.reject("ERR_INVALID_OPTION", "type must be a list of strings")
return null
} else {
@Suppress("UNCHECKED_CAST")
mimeTypes = types as ArrayList<String>
}
}
val copyToCacheDirectory = options["copyToCacheDirectory"]?.let {
if (it is Boolean) {
return@let it
}
promise.reject("ERR_INVALID_OPTION", "copyToCacheDirectory must be a boolean")
return null
} ?: true
return DocumentPickerOptions(copyToCacheDirectory, mimeTypes.toTypedArray())
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DocumentPickerOptions
if (copyToCacheDirectory != other.copyToCacheDirectory) return false
if (!types.contentEquals(other.types)) return false
return true
}
override fun hashCode(): Int {
var result = copyToCacheDirectory.hashCode()
result = 31 * result + types.contentHashCode()
return result
}
}
| bsd-3-clause | 4f34cee3182232c53f519a0f02c44892 | 32.27451 | 95 | 0.647613 | 4.442408 | false | false | false | false |
android/xAnd11 | core/src/main/java/com/monksanctum/xand11/core/input/XInputProtocol.kt | 1 | 6994 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.monksanctum.xand11.input
import org.monksanctum.xand11.comm.*
import org.monksanctum.xand11.core.Throws
import org.monksanctum.xand11.errors.WindowError
import org.monksanctum.xand11.errors.XError
import org.monksanctum.xand11.windows.XWindow
import org.monksanctum.xand11.windows.XWindowManager
class XInputProtocol(private val mManager: XInputManager, private val mWindowManager: XWindowManager) : Dispatcher.PacketHandler {
override val opCodes: ByteArray
get() = HANDLED_OPS
@Throws(XError::class)
override fun handleRequest(client: Client, reader: PacketReader, writer: PacketWriter) {
when (reader.majorOpCode) {
Request.GET_INPUT_FOCUS.code -> handleGetInputFocus(reader, writer)
Request.GET_KEYBOARD_MAPPING.code -> handleGetKeyboardMapping(reader, writer)
Request.GET_MODIFIER_MAPPING.code -> handleGetModifierMapping(reader, writer)
Request.GET_KEYBOARD_CONTROL.code -> handleGetKeyboardControl(reader, writer)
Request.GET_SELECTION_OWNER.code -> handleGetSelectionOwner(reader, writer)
Request.SET_SELECTION_OWNER.code -> handleSetSelectionOwner(client, reader, writer)
Request.CONVERT_SELECTION.code -> handleConvertSelectionOwner(client, reader, writer)
Request.QUERY_POINTER.code -> handleQueryPointer(reader, writer)
Request.GET_POINTER_CONTROL.code -> handleGetPointerControl(reader, writer)
}
}
@Throws(WindowError::class)
private fun handleConvertSelectionOwner(client: Client, reader: PacketReader,
writer: PacketWriter) {
var requestor = reader.readCard32()
val selection = reader.readCard32()
val target = reader.readCard32()
val prop = reader.readCard32()
var timestamp = reader.readCard32()
val owner = mManager.selection.getOwner(selection)
if (owner != 0) {
// Send SelectionRequest
val window = mWindowManager.getWindow(owner)
window.sendSelectionRequest(timestamp, owner, requestor, selection, target, prop)
} else {
// Send SelectionNotify
val window = mWindowManager.getWindow(requestor)
if (timestamp == 0) timestamp = client.timestamp
requestor = 0
window.sendSelectionNotify(timestamp, requestor, selection, target, prop)
}
}
@Throws(WindowError::class)
private fun handleSetSelectionOwner(client: Client, reader: PacketReader, writer: PacketWriter) {
val owner = reader.readCard32()
val atom = reader.readCard32()
var timestamp = reader.readCard32()
if (timestamp == 0) timestamp = client.timestamp
val currentOwner = mManager.selection.getOwner(atom)
if (currentOwner == owner) {
return
}
if (mManager.selection.setSelection(atom, owner, timestamp)) {
if (currentOwner != 0) {
val window = mWindowManager.getWindow(currentOwner)
window.sendSelectionClear(timestamp, owner, atom)
}
}
}
private fun handleGetSelectionOwner(reader: PacketReader, writer: PacketWriter) {
val atom = reader.readCard32()
val window = mManager.selection.getOwner(atom)
writer.writeCard32(window)
writer.writePadding(20)
}
private fun handleGetInputFocus(reader: PacketReader, writer: PacketWriter) {
val focus = mManager.focusState
writer.minorOpCode = focus.revert
writer.writeCard32(focus.current)
writer.writePadding(20)
}
private fun handleGetKeyboardMapping(reader: PacketReader, writer: PacketWriter) {
reader.readPadding(4)
// TODO: Implement.
writer.minorOpCode = mManager.keyboardManager.keysPerSym.toByte()
writer.writePadding(24)
val keyboardMap = mManager.keyboardManager.keyboardMap
for (i in keyboardMap.indices) {
writer.writeCard32(keyboardMap[i])
}
}
private fun handleGetModifierMapping(reader: PacketReader, writer: PacketWriter) {
// TODO: Implement.
writer.minorOpCode = 2.toByte()
writer.writePadding(24)
val modifiers = mManager.keyboardManager.modifiers
for (i in modifiers.indices) {
if (modifiers[i].toInt() != 0) {
writer.writeByte(mManager.translate(modifiers[i].toInt()).toByte())
} else {
writer.writeByte(0.toByte())
}
}
}
private fun handleGetKeyboardControl(reader: PacketReader, writer: PacketWriter) {
writer.minorOpCode = 1.toByte()
writer.writeCard32(0) // LED Mask.
writer.writeByte(0.toByte())
writer.writeByte(50.toByte())
writer.writeCard16(400)
writer.writeCard16(100)
writer.writePadding(2)
writer.writePadding(32)
}
private fun handleQueryPointer(reader: PacketReader, writer: PacketWriter) {
writer.minorOpCode = 1.toByte()
writer.writeCard32(3) // Root window
writer.writeCard32(0) // No child
// Location, 0
writer.writeCard16(0) // Global X
writer.writeCard16(0) // Global Y
writer.writeCard16(0) // Local X
writer.writeCard16(0) // Local Y
writer.writeCard16(0) // Button mask
writer.writePadding(6)
}
private fun handleGetPointerControl(reader: PacketReader, writer: PacketWriter) {
writer.writeCard16(0) // Acceleration-numerator
writer.writeCard16(0) // Acceleration-denominator
writer.writeCard16(0) // threshold
writer.writePadding(18)
}
companion object {
private val HANDLED_OPS = byteArrayOf(Request.GET_INPUT_FOCUS.code,
Request.GET_KEYBOARD_MAPPING.code,
Request.GET_MODIFIER_MAPPING.code,
Request.GET_KEYBOARD_CONTROL.code,
Request.GET_SELECTION_OWNER.code,
Request.SET_SELECTION_OWNER.code,
Request.CONVERT_SELECTION.code,
Request.QUERY_POINTER.code,
Request.GET_POINTER_CONTROL.code)
}
}
| apache-2.0 | a14142ebf2af4d7c3b18525f4abb22ab | 39.630952 | 130 | 0.641693 | 4.432193 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator25.kt | 12 | 3503 | // 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 org.jetbrains.plugins.groovy.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic
import org.jetbrains.plugins.groovy.transformations.immutable.hasImmutableAnnotation
import org.jetbrains.plugins.groovy.transformations.immutable.isImmutable
import org.jetbrains.plugins.groovy.transformations.impl.namedVariant.collectAllParamsFromNamedVariantMethod
import org.jetbrains.plugins.groovy.transformations.impl.namedVariant.collectNamedParams
/**
* Check features introduced in groovy 2.5
*/
class GroovyAnnotator25(private val holder: AnnotationHolder) : GroovyElementVisitor() {
override fun visitMethod(method: GrMethod) {
collectAllParamsFromNamedVariantMethod(method).groupBy { it.first }.filter { it.value.size > 1 }.forEach { (name, parameters) ->
val parametersList = parameters.joinToString { "'${it.second.name}'" }
val duplicatingParameters = parameters.drop(1).map { (_, parameter) -> parameter }
for (parameter in duplicatingParameters) {
val nameIdentifier = parameter.nameIdentifier ?: continue
holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("duplicating.named.parameter", name, parametersList)).range(nameIdentifier).create()
}
}
super.visitMethod(method)
}
override fun visitField(field: GrField) {
super.visitField(field)
immutableCheck(field)
}
private fun immutableCheck(field: GrField) {
val containingClass = field.containingClass ?: return
if (!field.hasModifierProperty(PsiModifier.STATIC) && hasImmutableAnnotation(containingClass) && !isImmutable(field)) {
holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("field.should.be.immutable", field.name)).range(field.nameIdentifierGroovy).create()
}
}
override fun visitCallExpression(callExpression: GrCallExpression) {
checkRequiredNamedArguments(callExpression)
super.visitCallExpression(callExpression)
}
private fun checkRequiredNamedArguments(callExpression: GrCallExpression) {
if (!isCompileStatic(callExpression)) return
val namedArguments = callExpression.namedArguments.mapNotNull { it.labelName }.toSet()
if (namedArguments.isEmpty()) return
val resolveResult = callExpression.advancedResolve()
val method = resolveResult.element as? PsiMethod ?: return
val parameters = method.parameterList.parameters
val mapParameter = parameters.firstOrNull() ?: return
val requiredNamedParams = collectNamedParams(mapParameter).filter { it.required }
for (namedParam in requiredNamedParams) {
if (!namedArguments.contains(namedParam.name)) {
val message = GroovyBundle.message("missing.required.named.parameter", namedParam.name)
holder.newAnnotation(HighlightSeverity.ERROR, message).create()
}
}
}
} | apache-2.0 | 8fc84d650da21be9c5070934e4da6c87 | 46.351351 | 159 | 0.782472 | 4.69571 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/UnsupportedYieldFix.kt | 5 | 2360 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.MESSAGE_FOR_YIELD_BEFORE_LAMBDA
class UnsupportedYieldFix(psiElement: PsiElement) : KotlinQuickFixAction<PsiElement>(psiElement), CleanupFix {
override fun getFamilyName(): String = KotlinBundle.message("migrate.unsupported.yield.syntax")
override fun getText(): String = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val psiElement = element ?: return
if (psiElement is KtCallExpression) {
val ktExpression = (psiElement as KtCallElement).calleeExpression ?: return
// Add after "yield" reference in call
psiElement.addAfter(KtPsiFactory(psiElement).createCallArguments("()"), ktExpression)
}
if (psiElement.node.elementType == KtTokens.IDENTIFIER) {
psiElement.replace(KtPsiFactory(psiElement).createIdentifier("`yield`"))
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.psiElement.text != "yield") return null
val message = Errors.YIELD_IS_RESERVED.cast(diagnostic).a
if (message == MESSAGE_FOR_YIELD_BEFORE_LAMBDA) {
// Identifier -> Expression -> Call (normal call) or Identifier -> Operation Reference -> Binary Expression (for infix usage)
val grand = diagnostic.psiElement.parent.parent
if (grand is KtBinaryExpression || grand is KtCallExpression) {
return UnsupportedYieldFix(grand)
}
} else {
return UnsupportedYieldFix(diagnostic.psiElement)
}
return null
}
}
} | apache-2.0 | 37d0a4fee84d2f4091480332569332dc | 43.54717 | 158 | 0.699153 | 5.031983 | false | false | false | false |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/revision/RevisionDataProvider.kt | 1 | 1343 | package zielu.gittoolbox.revision
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.impl.NullVirtualFile
import java.time.ZonedDateTime
internal interface RevisionDataProvider {
val baseRevision: VcsRevisionNumber
val file: VirtualFile
val lineCount: Int
fun getRevisionNumber(lineIndex: Int): VcsRevisionNumber
fun getAuthorDateTime(lineIndex: Int): ZonedDateTime?
fun getAuthor(lineIndex: Int): String?
fun getAuthorEmail(lineIndex: Int): String?
fun getSubject(lineIndex: Int): String?
companion object {
val empty = object : RevisionDataProvider {
override val baseRevision: VcsRevisionNumber
get() = VcsRevisionNumber.NULL
override val file: VirtualFile
get() = NullVirtualFile.INSTANCE
override val lineCount: Int
get() = 0
override fun getRevisionNumber(lineIndex: Int): VcsRevisionNumber = VcsRevisionNumber.NULL
override fun getAuthorDateTime(lineIndex: Int): ZonedDateTime? = null
override fun getAuthor(lineIndex: Int): String? = null
override fun getAuthorEmail(lineIndex: Int): String? = null
override fun getSubject(lineIndex: Int): String? = null
override fun toString(): String = "RevisionDataProvider[EMPTY]"
}
}
}
| apache-2.0 | 9dc16f8521be1185372030c15186633c | 28.844444 | 96 | 0.743857 | 4.974074 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt | 1 | 2613 | package info.nightscout.androidaps.utils.protection
import androidx.fragment.app.FragmentActivity
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ProtectionCheck @Inject constructor(
val sp: SP,
val passwordCheck: PasswordCheck
) {
enum class Protection {
PREFERENCES,
APPLICATION,
BOLUS
}
enum class ProtectionType {
NONE,
BIOMETRIC,
MASTER_PASSWORD,
CUSTOM_PASSWORD
}
private val passwordsResourceIDs = listOf(
R.string.key_settings_password,
R.string.key_application_password,
R.string.key_bolus_password)
private val protectionTypeResourceIDs = listOf(
R.string.key_settings_protection,
R.string.key_application_protection,
R.string.key_bolus_protection)
private val titleResourceIDs = listOf(
R.string.settings_password,
R.string.application_password,
R.string.bolus_password)
fun isLocked(protection: Protection): Boolean {
return when (ProtectionType.values()[sp.getInt(protectionTypeResourceIDs[protection.ordinal], ProtectionType.NONE.ordinal)]) {
ProtectionType.NONE -> false
ProtectionType.BIOMETRIC -> true
ProtectionType.MASTER_PASSWORD -> sp.getString(R.string.key_master_password, "") != ""
ProtectionType.CUSTOM_PASSWORD -> sp.getString(passwordsResourceIDs[protection.ordinal], "") != ""
}
}
@JvmOverloads
fun queryProtection(activity: FragmentActivity, protection: Protection,
ok: Runnable?, cancel: Runnable? = null, fail: Runnable? = null) {
when (ProtectionType.values()[sp.getInt(protectionTypeResourceIDs[protection.ordinal], ProtectionType.NONE.ordinal)]) {
ProtectionType.NONE ->
ok?.run()
ProtectionType.BIOMETRIC ->
BiometricCheck.biometricPrompt(activity, titleResourceIDs[protection.ordinal], ok, cancel, fail, passwordCheck)
ProtectionType.MASTER_PASSWORD ->
passwordCheck.queryPassword(activity, R.string.master_password, R.string.key_master_password, { ok?.run() }, { cancel?.run() }, { fail?.run() })
ProtectionType.CUSTOM_PASSWORD ->
passwordCheck.queryPassword(activity, titleResourceIDs[protection.ordinal], passwordsResourceIDs[protection.ordinal], { ok?.run() }, { cancel?.run() }, { fail?.run() })
}
}
} | agpl-3.0 | 53f5e559ccd21e0af4b7253424d51d9a | 38.606061 | 184 | 0.661309 | 4.560209 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt | 1 | 6855 | package info.nightscout.androidaps.plugins.general.overview.dialogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.wizard.QuickWizard
import info.nightscout.androidaps.utils.wizard.QuickWizardEntry
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWizardChange
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SafeParse
import kotlinx.android.synthetic.main.okcancel.*
import kotlinx.android.synthetic.main.overview_editquickwizard_dialog.*
import org.json.JSONException
import java.util.*
import javax.inject.Inject
class EditQuickWizardDialog : DaggerDialogFragment() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var quickWizard: QuickWizard
@Inject lateinit var dateUtil: DateUtil
var position = -1
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
isCancelable = true
dialog?.setCanceledOnTouchOutside(false)
return inflater.inflate(R.layout.overview_editquickwizard_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
(arguments ?: savedInstanceState)?.let { bundle ->
position = bundle.getInt("position", -1)
}
val entry = if (position ==-1) quickWizard.newEmptyItem() else quickWizard[position]
ok.setOnClickListener {
if (overview_editquickwizard_from_spinner.selectedItem == null) return@setOnClickListener
if (overview_editquickwizard_to_spinner.selectedItem == null) return@setOnClickListener
try {
entry.storage.put("buttonText", overview_editquickwizard_button_edit.text.toString())
entry.storage.put("carbs", SafeParse.stringToInt(overview_editquickwizard_carbs_edit.text.toString()))
val validFromInt = DateUtil.toSeconds(overview_editquickwizard_from_spinner.selectedItem.toString())
entry.storage.put("validFrom", validFromInt)
val validToInt = DateUtil.toSeconds(overview_editquickwizard_to_spinner.selectedItem.toString())
entry.storage.put("validTo", validToInt)
entry.storage.put("useBG", overview_editquickwizard_usebg_spinner.selectedItemPosition)
entry.storage.put("useCOB", overview_editquickwizard_usecob_spinner.selectedItemPosition)
entry.storage.put("useBolusIOB", overview_editquickwizard_usebolusiob_spinner.selectedItemPosition)
entry.storage.put("useBasalIOB", overview_editquickwizard_usebasaliob_spinner.selectedItemPosition)
entry.storage.put("useTrend", overview_editquickwizard_usetrend_spinner.selectedItemPosition)
entry.storage.put("useSuperBolus", overview_editquickwizard_usesuperbolus_spinner.selectedItemPosition)
entry.storage.put("useTempTarget", overview_editquickwizard_usetemptarget_spinner.selectedItemPosition)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
quickWizard.addOrUpdate(entry)
rxBus.send(EventQuickWizardChange())
dismiss()
}
cancel.setOnClickListener { dismiss() }
var posFrom = 0
var posTo = 95
val timeList = ArrayList<CharSequence>()
var pos = 0
var t = 0
while (t < 24 * 60 * 60) {
timeList.add(dateUtil.timeString(DateUtil.toDate(t)))
if (entry.validFrom() == t) posFrom = pos
if (entry.validTo() == t) posTo = pos
pos++
t += 15 * 60
}
timeList.add(dateUtil.timeString(DateUtil.toDate(24 * 60 * 60 - 60)))
val adapter = context?.let { context -> ArrayAdapter(context, R.layout.spinner_centered, timeList) }
overview_editquickwizard_from_spinner.adapter = adapter
overview_editquickwizard_to_spinner.adapter = adapter
overview_editquickwizard_button_edit.setText(entry.buttonText())
overview_editquickwizard_carbs_edit.setText(entry.carbs().toString())
overview_editquickwizard_from_spinner.setSelection(posFrom)
overview_editquickwizard_to_spinner.setSelection(posTo)
overview_editquickwizard_usebg_spinner.setSelection(entry.useBG())
overview_editquickwizard_usecob_spinner.setSelection(entry.useCOB())
overview_editquickwizard_usebolusiob_spinner.setSelection(entry.useBolusIOB())
overview_editquickwizard_usebasaliob_spinner.setSelection(entry.useBasalIOB())
overview_editquickwizard_usetrend_spinner.setSelection(entry.useTrend())
overview_editquickwizard_usesuperbolus_spinner.setSelection(entry.useSuperBolus())
overview_editquickwizard_usetemptarget_spinner.setSelection(entry.useTempTarget())
overview_editquickwizard_usecob_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) = processCob()
override fun onNothingSelected(parent: AdapterView<*>) {}
}
processCob()
}
override fun onResume() {
super.onResume()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("position", position)
}
private fun processCob() {
if (overview_editquickwizard_usecob_spinner.selectedItemPosition == QuickWizardEntry.YES) {
overview_editquickwizard_usebolusiob_spinner.isEnabled = false
overview_editquickwizard_usebasaliob_spinner.isEnabled = false
overview_editquickwizard_usebolusiob_spinner.setSelection(QuickWizardEntry.YES)
overview_editquickwizard_usebasaliob_spinner.setSelection(QuickWizardEntry.YES)
} else {
overview_editquickwizard_usebolusiob_spinner.isEnabled = true
overview_editquickwizard_usebasaliob_spinner.isEnabled = true
}
}
}
| agpl-3.0 | 78a1c2a1e601aef9950be68faa731d8a | 50.156716 | 119 | 0.71539 | 4.622387 | false | false | false | false |
kohesive/kohesive-iac | model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/SQS.kt | 1 | 2098 | package uy.kohesive.iac.model.aws.cloudformation.resources.builders
import com.amazonaws.AmazonWebServiceRequest
import com.amazonaws.services.sqs.model.CreateQueueRequest
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder
import uy.kohesive.iac.model.aws.cloudformation.resources.SQS
import uy.kohesive.iac.model.aws.utils.CasePreservingJacksonNamingStrategy
class SQSQueueResourcePropertiesBuilder : ResourcePropertiesBuilder<CreateQueueRequest> {
companion object {
val JSON = jacksonObjectMapper()
.setPropertyNamingStrategy(CasePreservingJacksonNamingStrategy())
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}
override val requestClazz = CreateQueueRequest::class
override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) =
(request as CreateQueueRequest).let {
SQS.Queue(
QueueName = request.queueName,
DelaySeconds = request.attributes["DelaySeconds"],
MaximumMessageSize = request.attributes["MaximumMessageSize"],
MessageRetentionPeriod = request.attributes["MessageRetentionPeriod"],
ReceiveMessageWaitTimeSeconds = request.attributes["ReceiveMessageWaitTimeSeconds"],
RedrivePolicy = request.attributes["RedrivePolicy"]?.let { redrivePolicyJSON ->
val redrivePolicyMap = JSON.readValue<Map<String, String>>(redrivePolicyJSON)
SQS.Queue.RedrivePolicyProperty(
deadLetterTargetArn = redrivePolicyMap["deadLetterTargetArn"],
maxReceiveCount = redrivePolicyMap["maxReceiveCount"]
)
},
VisibilityTimeout = request.attributes["VisibilityTimeout"]
)
}
}
| mit | e96f09579cfca04fe63225a7ba63f510 | 48.952381 | 111 | 0.686368 | 5.506562 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/core/export/TblHandler.kt | 1 | 4746 | package com.cout970.modeler.core.export
import com.cout970.modeler.api.model.IModel
import com.cout970.modeler.api.model.material.IMaterialRef
import com.cout970.modeler.core.model.Model
import com.cout970.modeler.core.model.TRSTransformation
import com.cout970.modeler.core.model.`object`.ObjectCube
import com.cout970.modeler.core.model.material.TexturedMaterial
import com.cout970.modeler.core.model.ref
import com.cout970.modeler.core.resource.ResourcePath
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.*
import com.google.gson.GsonBuilder
/**
* Created by cout970 on 2017/06/08.
*/
class TblImporter {
companion object {
@JvmStatic
val GSON = GsonBuilder()
.registerTypeAdapter(IVector3::class.java, Vector3Serializer())
.registerTypeAdapter(IVector2::class.java, Vector2Serializer())
.create()!!
@JvmStatic
val CENTER_OFFSET = vec3Of(8, 24, 8)
}
fun import(path: ResourcePath): IModel {
val model = parse(path)
val material = TexturedMaterial("texture", path.enterZip("texture.png"))
val texSize = vec2Of(model.textureWidth, model.textureHeight)
val objects = mapCubes(model.cubes, material.ref, texSize) + mapGroups(model.cubeGroups, material.ref, texSize)
return Model.of(objects, listOf(material))
}
fun mapGroups(list: List<CubeGroup>, material: IMaterialRef, texSize: IVector2): List<ObjectCube> {
return list.flatMap {
mapCubes(it.cubes, material, texSize) + mapGroups(it.cubeGroups, material, texSize)
}
}
fun mapCubes(list: List<Cube>, material: IMaterialRef, texSize: IVector2): List<ObjectCube> {
return list.map { cube ->
val pivot = cube.position * vec3Of(1, -1, -1) + CENTER_OFFSET
val newRot = TRSTransformation.fromRotationPivot(pivot, cube.rotation)
ObjectCube(
name = cube.name,
transformation = TRSTransformation(translation = transformPos(cube), scale = cube.dimensions).merge(
newRot),
material = material,
textureOffset = cube.txOffset,
textureSize = texSize,
mirrored = cube.txMirror
)
}
}
private fun transformPos(cube: Cube): IVector3 {
val absPos = (cube.position + cube.offset) * vec3Of(1, -1, -1)
return absPos - cube.dimensions * vec3Of(0, 1, 1) + CENTER_OFFSET
}
fun parse(path: ResourcePath): TblModel {
val modelPath = path.enterZip("model.json")
val stream = modelPath.inputStream()
return GSON.fromJson(stream.reader(), TblModel::class.java)
}
data class TblModel(
val modelName: String,
val authorName: String,
val projVersion: Int,
val metadata: List<Any>,
val textureWidth: Int,
val textureHeight: Int,
val scale: IVector3,
val cubeGroups: List<CubeGroup>,
val cubes: List<Cube>,
val anims: List<Any>,
val cubeCount: Int
) {
override fun toString(): String {
return "TblModel(\n" +
" modelName='$modelName',\n" +
" authorName='$authorName',\n" +
" projVersion=$projVersion,\n" +
" metadata=$metadata,\n" +
" textureWidth=$textureWidth,\n" +
" textureHeight=$textureHeight,\n" +
" scale=$scale,\n" +
" cubeGroups=[... size:${cubeGroups.size}],\n" +
" cubes=[... size:${cubes.size}],\n" +
" anims=$anims,\n" +
" cubeCount=$cubeCount\n" +
")"
}
}
data class CubeGroup(
val cubes: List<Cube>,
val cubeGroups: List<CubeGroup>,
val name: String,
val txMirror: Boolean,
val hidden: Boolean,
val metadata: List<Any>,
val identifier: String
)
data class Cube(
val name: String,
val dimensions: IVector3,
val position: IVector3,
val offset: IVector3,
val rotation: IVector3,
val scale: IVector3,
val txOffset: IVector2,
val txMirror: Boolean,
val mcScale: Int,
val opacity: Int,
val hidden: Boolean,
val metadata: List<Any>,
val children: List<Any>,
val identifier: String
)
} | gpl-3.0 | b644e3a326fc7c5533112f459ed854af | 34.162963 | 120 | 0.570164 | 4.20372 | false | false | false | false |
mdaniel/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/timeline/comment/CommentInputComponentFactory.kt | 3 | 9884 | // 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.collaboration.ui.codereview.timeline.comment
import com.intellij.collaboration.ui.SingleValueModel
import com.intellij.collaboration.ui.codereview.InlineIconButton
import com.intellij.collaboration.ui.codereview.timeline.comment.CommentInputComponentFactory.CancelActionConfig
import com.intellij.collaboration.ui.codereview.timeline.comment.CommentInputComponentFactory.ScrollOnChangePolicy
import com.intellij.collaboration.ui.codereview.timeline.comment.CommentInputComponentFactory.SubmitActionConfig
import com.intellij.collaboration.ui.codereview.timeline.comment.CommentInputComponentFactory.getEditorTextFieldVerticalOffset
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonShortcuts
import com.intellij.openapi.actionSystem.ShortcutSet
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.EditorTextField
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.SingleComponentCenteringLayout
import com.intellij.util.ui.UIUtil
import icons.CollaborationToolsIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import java.awt.Dimension
import java.awt.Rectangle
import java.awt.event.*
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JLayeredPane
import javax.swing.JPanel
import javax.swing.border.EmptyBorder
object CommentInputComponentFactory {
val defaultSubmitShortcut: ShortcutSet = CommonShortcuts.CTRL_ENTER
val defaultCancelShortcut: ShortcutSet = CommonShortcuts.ESCAPE
fun create(
model: CommentTextFieldModel,
textField: EditorTextField,
config: Config
): JComponent {
textField.installSubmitAction(model, config.submitConfig)
textField.installCancelAction(config.cancelConfig)
val contentComponent = JPanel(null).apply {
isOpaque = false
layout = MigLayout(
LC()
.gridGap("0", "0")
.insets("0", "0", "0", "0")
.fillX()
)
border = JBUI.Borders.empty()
}
val busyLabel = JLabel(AnimatedIcon.Default())
val submitButton = createSubmitButton(model, config.submitConfig)
val cancelButton = createCancelButton(config.cancelConfig)
updateUiOnModelChanges(contentComponent, model, textField, busyLabel, submitButton)
installScrollIfChangedController(contentComponent, model, config.scrollOnChange)
val textFieldWithOverlay = createTextFieldWithOverlay(textField, submitButton, busyLabel)
contentComponent.add(textFieldWithOverlay, CC().grow().pushX())
cancelButton?.let { contentComponent.add(it, CC().alignY("top")) }
return contentComponent
}
fun getEditorTextFieldVerticalOffset() = if (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF()) 6 else 4
data class Config(
val scrollOnChange: ScrollOnChangePolicy = ScrollOnChangePolicy.ScrollToField,
val submitConfig: SubmitActionConfig,
val cancelConfig: CancelActionConfig?
)
data class SubmitActionConfig(
val iconConfig: ActionButtonConfig?,
val shortcut: SingleValueModel<ShortcutSet> = SingleValueModel(defaultSubmitShortcut)
)
data class CancelActionConfig(
val iconConfig: ActionButtonConfig?,
val shortcut: ShortcutSet = defaultCancelShortcut,
val action: () -> Unit
)
sealed class ScrollOnChangePolicy {
object DontScroll : ScrollOnChangePolicy()
object ScrollToField : ScrollOnChangePolicy()
class ScrollToComponent(val component: JComponent) : ScrollOnChangePolicy()
}
data class ActionButtonConfig(val name: @NlsContexts.Tooltip String)
}
private fun installScrollIfChangedController(
parent: JComponent,
model: CommentTextFieldModel,
policy: ScrollOnChangePolicy,
) {
if (policy == ScrollOnChangePolicy.DontScroll) {
return
}
fun scroll() {
when (policy) {
ScrollOnChangePolicy.DontScroll -> {
}
is ScrollOnChangePolicy.ScrollToComponent -> {
val componentToScroll = policy.component
parent.scrollRectToVisible(Rectangle(0, 0, componentToScroll.width, componentToScroll.height))
}
ScrollOnChangePolicy.ScrollToField -> {
parent.scrollRectToVisible(Rectangle(0, 0, parent.width, parent.height))
}
}
}
model.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
scroll()
}
})
// previous listener doesn't work properly when text field's size is changed because
// component is not resized at this moment, so we need to handle resizing too
// it also produces such behavior: resize of the ancestor will scroll to the field
parent.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
if (UIUtil.isFocusAncestor(parent)) {
scroll()
}
}
})
}
private fun createSubmitButton(
model: CommentTextFieldModel,
actionConfig: SubmitActionConfig
): InlineIconButton? {
val iconConfig = actionConfig.iconConfig ?: return null
val button = InlineIconButton(
CollaborationToolsIcons.Send, CollaborationToolsIcons.SendHovered,
tooltip = iconConfig.name
).apply {
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
actionListener = ActionListener { model.submitWithCheck() }
}
actionConfig.shortcut.addAndInvokeListener {
button.shortcut = it
}
return button
}
private fun createCancelButton(actionConfig: CancelActionConfig?): InlineIconButton? {
if (actionConfig == null) {
return null
}
val iconConfig = actionConfig.iconConfig ?: return null
return InlineIconButton(
AllIcons.Actions.Close, AllIcons.Actions.CloseHovered,
tooltip = iconConfig.name,
shortcut = actionConfig.shortcut
).apply {
border = JBUI.Borders.empty(getEditorTextFieldVerticalOffset(), 0)
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
actionListener = ActionListener { actionConfig.action() }
}
}
private fun EditorTextField.installSubmitAction(
model: CommentTextFieldModel,
submitConfig: SubmitActionConfig
) {
val submitAction = object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) = model.submitWithCheck()
}
submitConfig.shortcut.addAndInvokeListener {
submitAction.unregisterCustomShortcutSet(this)
submitAction.registerCustomShortcutSet(it, this)
}
}
private fun EditorTextField.installCancelAction(cancelConfig: CancelActionConfig?) {
if (cancelConfig == null) {
return
}
object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
cancelConfig.action()
}
}.registerCustomShortcutSet(cancelConfig.shortcut, this)
}
private fun updateUiOnModelChanges(
parent: JComponent,
model: CommentTextFieldModel,
textField: EditorTextField,
busyLabel: JComponent,
submitButton: InlineIconButton?
) {
fun update() {
busyLabel.isVisible = model.isBusy
submitButton?.isEnabled = model.isSubmitAllowed()
}
textField.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
update()
parent.revalidate()
}
})
model.addStateListener(::update)
update()
}
private fun CommentTextFieldModel.isSubmitAllowed(): Boolean = !isBusy && content.text.isNotBlank()
private fun CommentTextFieldModel.submitWithCheck() {
if (isSubmitAllowed()) {
submit()
}
}
/**
* Returns a component with [busyLabel] in center and [button] in bottom-right corner
*/
private fun createTextFieldWithOverlay(textField: EditorTextField, button: JComponent?, busyLabel: JComponent?): JComponent {
if (button != null) {
val bordersListener = object : ComponentAdapter(), HierarchyListener {
override fun componentResized(e: ComponentEvent?) {
val scrollPane = (textField.editor as? EditorEx)?.scrollPane ?: return
val buttonSize = button.size
JBInsets.removeFrom(buttonSize, button.insets)
scrollPane.viewportBorder = JBUI.Borders.emptyRight(buttonSize.width)
scrollPane.viewport.revalidate()
}
override fun hierarchyChanged(e: HierarchyEvent?) {
val scrollPane = (textField.editor as? EditorEx)?.scrollPane ?: return
button.border = EmptyBorder(scrollPane.border.getBorderInsets(scrollPane))
componentResized(null)
}
}
textField.addHierarchyListener(bordersListener)
button.addComponentListener(bordersListener)
}
val layeredPane = object : JLayeredPane() {
override fun getPreferredSize(): Dimension {
return textField.preferredSize
}
override fun doLayout() {
super.doLayout()
textField.setBounds(0, 0, width, height)
if (button != null) {
val preferredButtonSize = button.preferredSize
button.setBounds(width - preferredButtonSize.width, height - preferredButtonSize.height,
preferredButtonSize.width, preferredButtonSize.height)
}
if (busyLabel != null) {
busyLabel.bounds = SingleComponentCenteringLayout.getBoundsForCentered(textField, busyLabel)
}
}
}
layeredPane.add(textField, JLayeredPane.DEFAULT_LAYER, 0)
var index = 1
if (busyLabel != null) {
layeredPane.add(busyLabel, JLayeredPane.POPUP_LAYER, index)
index++
}
if (button != null) {
layeredPane.add(button, JLayeredPane.POPUP_LAYER, index)
}
return layeredPane
} | apache-2.0 | 9b56c1908069c85be4bcf082b321fae3 | 32.969072 | 126 | 0.752529 | 4.616534 | false | true | false | false |
siosio/intellij-community | plugins/git4idea/src/git4idea/index/GitStageTracker.kt | 1 | 10764 | // 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 git4idea.index
import com.intellij.AppTopics
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileDocumentManagerListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsListener
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.EventDispatcher
import com.intellij.util.messages.MessageBusConnection
import com.intellij.vcs.log.runInEdt
import git4idea.GitVcs
import git4idea.index.vfs.GitIndexVirtualFile
import git4idea.index.vfs.filePath
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.status.GitRefreshListener
import git4idea.util.toShortenedLogString
import org.jetbrains.annotations.NonNls
import java.util.*
private val PROCESSED = Key.create<Boolean>("GitStageTracker.file.processed")
class GitStageTracker(val project: Project) : Disposable {
private val eventDispatcher = EventDispatcher.create(GitStageTrackerListener::class.java)
private val dirtyScopeManager
get() = VcsDirtyScopeManager.getInstance(project)
@Volatile
var state: State = State(gitRoots().associateWith { RootState.empty(it) })
private set
val ignoredPaths: Map<VirtualFile, List<FilePath>>
get() {
return gitRoots().associateWith {
GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(it)?.ignoredFilesHolder?.ignoredFilePaths?.toList()
?: emptyList()
}
}
init {
val connection: MessageBusConnection = project.messageBus.connect(this)
connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
handleIndexFileEvents(events)
}
})
connection.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, VcsListener {
runInEdt(this) {
val roots = gitRoots()
update { oldState -> State(roots.associateWith { oldState.rootStates[it] ?: RootState.empty(it) }) }
}
})
connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, object : FileDocumentManagerListener {
override fun unsavedDocumentDropped(document: Document) {
val file = FileDocumentManager.getInstance().getFile(document) ?: return
file.putUserData(PROCESSED, null)
markDirty(file)
}
override fun fileContentReloaded(file: VirtualFile, document: Document) {
file.putUserData(PROCESSED, null)
markDirty(file)
}
override fun fileWithNoDocumentChanged(file: VirtualFile) {
file.putUserData(PROCESSED, null)
markDirty(file)
}
override fun beforeDocumentSaving(document: Document) {
val file = FileDocumentManager.getInstance().getFile(document) ?: return
file.putUserData(PROCESSED, null)
}
})
connection.subscribe(GitRefreshListener.TOPIC, object : GitRefreshListener {
override fun repositoryUpdated(repository: GitRepository) {
doUpdateState(repository)
}
})
EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
val file = FileDocumentManager.getInstance().getFile(event.document) ?: return
if (file.getUserData(PROCESSED) == null) {
file.putUserData(PROCESSED, true)
markDirty(file)
}
}
}, this)
updateTrackerState()
}
fun updateTrackerState() {
LOG.debug("Update tracker state")
ChangeListManagerImpl.getInstanceImpl(project).executeOnUpdaterThread {
for (root in gitRoots()) {
val repository = GitRepositoryManager.getInstance(project).getRepositoryForFile(root) ?: continue
doUpdateState(repository)
}
}
}
/**
* Update tree on [FileDocumentManager#unsavedDocuments] state change.
*
* We can refresh only [doUpdateState], but this introduces blinking in some cases.
* Ex: when unsaved unstaged changes are saved on disk. We remove file from tree immediately,
* but CLM is slow to notice new saved unstaged changes - so file is removed from thee and added again in a second.
*/
private fun markDirty(file: VirtualFile) {
if (!isStagingAreaAvailable(project)) return
val root = getRoot(project, file) ?: return
if (!gitRoots().contains(root)) return
LOG.debug("Mark dirty ${file.filePath()}")
dirtyScopeManager.fileDirty(file.filePath())
}
private fun handleIndexFileEvents(events: List<VFileEvent>) {
val pathsToDirty = mutableListOf<FilePath>()
for (event in events) {
if (event.isFromRefresh) continue
val file = event.file as? GitIndexVirtualFile ?: continue
pathsToDirty.add(file.filePath)
}
if (pathsToDirty.isNotEmpty()) {
LOG.debug("Mark dirty on index VFiles save: ", pathsToDirty)
VcsDirtyScopeManager.getInstance(project).filePathsDirty(pathsToDirty, emptyList())
}
}
private fun doUpdateState(repository: GitRepository) {
LOG.debug("Updating ${repository.root}")
val untracked = repository.untrackedFilesHolder.untrackedFilePaths.map { untrackedStatus(it) }
val status = repository.stagingAreaHolder.allRecords.union(untracked).associateBy { it.path }.toMutableMap()
for (document in FileDocumentManager.getInstance().unsavedDocuments) {
val file = FileDocumentManager.getInstance().getFile(document) ?: continue
if (!file.isValid || !FileDocumentManager.getInstance().isFileModified(file)) continue
val root = getRoot(project, file) ?: continue
if (root != repository.root) continue
val filePath = file.filePath()
if (repository.ignoredFilesHolder.containsFile(filePath)) continue
val fileStatus: GitFileStatus? = status[filePath]
if (fileStatus?.isTracked() == false) continue
if (file is GitIndexVirtualFile && fileStatus?.getStagedStatus() == null) {
status[filePath] = GitFileStatus('M', fileStatus?.workTree ?: ' ', filePath, fileStatus?.origPath)
}
else if (file.isInLocalFileSystem && fileStatus?.getUnStagedStatus() == null) {
status[filePath] = GitFileStatus(fileStatus?.index ?: ' ', 'M', filePath, fileStatus?.origPath)
}
}
val newRootState = RootState(repository.root, true, status)
runInEdt(this) {
update { it.updatedWith(repository.root, newRootState) }
}
}
fun addListener(listener: GitStageTrackerListener, disposable: Disposable) {
eventDispatcher.addListener(listener, disposable)
}
private fun gitRoots(): List<VirtualFile> = gitRoots(project)
private fun update(updater: (State) -> State) {
state = updater(state)
LOG.debug("New state", state)
eventDispatcher.multicaster.update()
}
override fun dispose() {
state = State.EMPTY
}
companion object {
private val LOG = Logger.getInstance(GitStageTracker::class.java)
@JvmStatic
fun getInstance(project: Project) = project.getService(GitStageTracker::class.java)
}
data class RootState(val root: VirtualFile, val initialized: Boolean,
val statuses: Map<FilePath, GitFileStatus>) {
fun hasStagedFiles(): Boolean {
return statuses.values.any { line -> line.getStagedStatus() != null }
}
fun hasChangedFiles(): Boolean {
return statuses.values.any { line -> line.isTracked() }
}
fun hasConflictedFiles(): Boolean {
return statuses.values.any { line -> line.isConflicted() }
}
fun isEmpty(): Boolean {
return statuses.isEmpty()
}
@NonNls
override fun toString(): String {
return "RootState(root=${root.name}, statuses=${statuses.toShortenedLogString(",\n")})"
}
companion object {
fun empty(root: VirtualFile) = RootState(root, false, emptyMap())
}
}
data class State(val rootStates: Map<VirtualFile, RootState>) {
val allRoots: Set<VirtualFile>
get() = rootStates.keys
val stagedRoots: Set<VirtualFile>
get() = rootStates.filterValues(RootState::hasStagedFiles).keys
val changedRoots: Set<VirtualFile>
get() = rootStates.filterValues(RootState::hasChangedFiles).keys
fun hasStagedRoots(): Boolean = rootStates.any { it.value.hasStagedFiles() }
fun hasChangedRoots(): Boolean = rootStates.any { it.value.hasChangedFiles() }
internal fun updatedWith(root: VirtualFile, newState: RootState): State {
val result = mutableMapOf<VirtualFile, RootState>()
result.putAll(rootStates)
result[root] = newState
return State(result)
}
@NonNls
override fun toString(): String {
return "State(${rootStates.toShortenedLogString(separator = "\n") { "${it.key.name}=${it.value}" }}"
}
companion object {
internal val EMPTY = State(emptyMap())
}
}
}
interface GitStageTrackerListener : EventListener {
fun update()
}
internal fun getRoot(project: Project, file: VirtualFile): VirtualFile? {
return when {
file is GitIndexVirtualFile -> file.root
file.isInLocalFileSystem -> ProjectLevelVcsManager.getInstance(project).getVcsRootFor(file)
else -> null
}
}
private fun gitRoots(project: Project): List<VirtualFile> {
return ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(GitVcs.getInstance(project)).toList()
}
fun GitStageTracker.status(file: VirtualFile): GitFileStatus? {
val root = getRoot(project, file) ?: return null
return status(root, file)
}
fun GitStageTracker.status(root: VirtualFile, file: VirtualFile): GitFileStatus? {
val filePath = file.filePath()
if (GitRepositoryManager.getInstance(project).getRepositoryForRootQuick(root)?.ignoredFilesHolder?.containsFile(filePath) == true) {
return ignoredStatus(filePath)
}
val rootState = state.rootStates[root] ?: return null
if (!rootState.initialized) return null
return rootState.statuses[filePath] ?: return notChangedStatus(filePath)
} | apache-2.0 | c0ef558d00b4e825e8f3b68d9d11f09d | 35.993127 | 140 | 0.724452 | 4.570701 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/project-wizard/maven/src/org/jetbrains/kotlin/idea/maven/projectWizard/MavenProjectImporter.kt | 1 | 1317 | // 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.maven.projectWizard
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.kotlin.idea.PlatformVersion
import java.nio.file.Path
class MavenProjectImporter(private val project: Project) {
fun importProject(path: Path) {
if (PlatformVersion.isAndroidStudio()) {
return // AS does not support Maven
}
val mavenProjectManager = MavenProjectsManager.getInstance(project)
val rootFile = LocalFileSystem.getInstance().findFileByPath(path.toString())!!
mavenProjectManager.addManagedFilesOrUnignore(rootFile.findAllPomFiles())
}
private fun VirtualFile.findAllPomFiles(): List<VirtualFile> {
val result = mutableListOf<VirtualFile>()
fun VirtualFile.find() {
when {
!isDirectory && name == "pom.xml" -> result += this
isDirectory -> children.forEach(VirtualFile::find)
}
}
find()
return result
}
} | apache-2.0 | 3a86f17d74e422de22835025f79d6a6d | 35.611111 | 158 | 0.700076 | 4.73741 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-tooling/test/createKotlinMPPGradleModel.kt | 1 | 4401 | // 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.gradle
internal fun createKotlinMPPGradleModel(
dependencyMap: Map<KotlinDependencyId, KotlinDependency> = emptyMap(),
sourceSets: Set<KotlinSourceSet> = emptySet(),
targets: Iterable<KotlinTarget> = emptyList(),
extraFeatures: ExtraFeatures = createExtraFeatures(),
kotlinNativeHome: String = ""
): KotlinMPPGradleModelImpl {
return KotlinMPPGradleModelImpl(
dependencyMap = dependencyMap,
sourceSetsByName = sourceSets.associateBy { it.name },
targets = targets.toList(),
extraFeatures = extraFeatures,
kotlinNativeHome = kotlinNativeHome
)
}
internal fun createExtraFeatures(
coroutinesState: String? = null,
isHmppEnabled: Boolean = false,
isNativeDependencyPropagationEnabled: Boolean = false
): ExtraFeaturesImpl {
return ExtraFeaturesImpl(
coroutinesState = coroutinesState,
isHMPPEnabled = isHmppEnabled,
isNativeDependencyPropagationEnabled = isNativeDependencyPropagationEnabled
)
}
internal fun createKotlinSourceSet(
name: String,
declaredDependsOnSourceSets: Set<String> = emptySet(),
allDependsOnSourceSets: Set<String> = declaredDependsOnSourceSets,
platforms: Set<KotlinPlatform> = emptySet(),
): KotlinSourceSetImpl = KotlinSourceSetImpl(
name = name,
languageSettings = KotlinLanguageSettingsImpl(
languageVersion = null,
apiVersion = null,
isProgressiveMode = false,
enabledLanguageFeatures = emptySet(),
experimentalAnnotationsInUse = emptySet(),
compilerPluginArguments = emptyArray(),
compilerPluginClasspath = emptySet(),
freeCompilerArgs = emptyArray()
),
sourceDirs = emptySet(),
resourceDirs = emptySet(),
regularDependencies = emptyArray(),
intransitiveDependencies = emptyArray(),
declaredDependsOnSourceSets = declaredDependsOnSourceSets,
allDependsOnSourceSets = allDependsOnSourceSets,
defaultActualPlatforms = KotlinPlatformContainerImpl().apply { pushPlatforms(platforms) },
)
internal fun createKotlinCompilation(
name: String = "main",
defaultSourceSets: Set<KotlinSourceSet> = emptySet(),
allSourceSets: Set<KotlinSourceSet> = emptySet(),
dependencies: Iterable<KotlinDependencyId> = emptyList(),
output: KotlinCompilationOutput = createKotlinCompilationOutput(),
arguments: KotlinCompilationArguments = createKotlinCompilationArguments(),
dependencyClasspath: Iterable<String> = emptyList(),
kotlinTaskProperties: KotlinTaskProperties = createKotlinTaskProperties(),
nativeExtensions: KotlinNativeCompilationExtensions? = null
): KotlinCompilationImpl {
return KotlinCompilationImpl(
name = name,
declaredSourceSets = defaultSourceSets,
allSourceSets = allSourceSets,
dependencies = dependencies.toList().toTypedArray(),
output = output,
arguments = arguments,
dependencyClasspath = dependencyClasspath.toList().toTypedArray(),
kotlinTaskProperties = kotlinTaskProperties,
nativeExtensions = nativeExtensions
)
}
internal fun createKotlinCompilationOutput(): KotlinCompilationOutputImpl {
return KotlinCompilationOutputImpl(
classesDirs = emptySet(),
effectiveClassesDir = null,
resourcesDir = null
)
}
internal fun createKotlinCompilationArguments(): KotlinCompilationArgumentsImpl {
return KotlinCompilationArgumentsImpl(
defaultArguments = emptyArray(),
currentArguments = emptyArray()
)
}
internal fun createKotlinTaskProperties(): KotlinTaskPropertiesImpl {
return KotlinTaskPropertiesImpl(
null, null, null, null
)
}
internal fun createKotlinTarget(
name: String,
platform: KotlinPlatform = KotlinPlatform.COMMON,
compilations: Iterable<KotlinCompilation> = emptyList()
): KotlinTargetImpl {
return KotlinTargetImpl(
name = name,
presetName = null,
disambiguationClassifier = null,
platform = platform,
compilations = compilations.toList(),
testRunTasks = emptyList(),
nativeMainRunTasks = emptyList(),
jar = null,
konanArtifacts = emptyList()
)
}
| apache-2.0 | 4033bffd937aeedc874ac71fb372e2ad | 35.371901 | 158 | 0.723245 | 5.97962 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/dialog/EditBookmarkDialogFragmentViewModel.kt | 1 | 6635 | /*
* Copyright (c) 2017. Rei Matsushita
*
* 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 me.rei_m.hbfavmaterial.viewmodel.widget.dialog
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.databinding.Observable
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.view.View
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.BiFunction
import io.reactivex.subjects.PublishSubject
import me.rei_m.hbfavmaterial.application.HatenaService
import me.rei_m.hbfavmaterial.application.TwitterService
import me.rei_m.hbfavmaterial.model.entity.EditableBookmark
import io.reactivex.Observable as RxObservable
class EditBookmarkDialogFragmentViewModel(articleTitle: String,
articleUrl: String,
private val hatenaService: HatenaService,
private val twitterService: TwitterService) : ViewModel() {
companion object {
private const val MAX_COMMENT_SIZE = 100
}
val isFirstEdit: ObservableBoolean = ObservableBoolean(true)
val articleTitle: ObservableField<String> = ObservableField("")
val articleUrl: ObservableField<String> = ObservableField("")
val comment: ObservableField<String> = ObservableField("")
val commentCount: ObservableField<String> = ObservableField("0 / $MAX_COMMENT_SIZE")
val isEnableComment: ObservableBoolean = ObservableBoolean(true)
val isOpen: ObservableBoolean = ObservableBoolean(true)
val isShareTwitter: ObservableBoolean = ObservableBoolean(false)
val isReadAfter: ObservableBoolean = ObservableBoolean(false)
var isDelete: ObservableBoolean = ObservableBoolean(false)
val hatenaUnauthorizedEvent = hatenaService.unauthorizedEvent
private var twitterUnauthorizedEventSubject = PublishSubject.create<Unit>()
val twitterUnauthorizedEvent: RxObservable<Unit> = twitterUnauthorizedEventSubject
val isLoading = hatenaService.isLoading
val raisedErrorEvent = hatenaService.raisedErrorEvent
private var dismissDialogEventSubject = PublishSubject.create<Unit>()
val dismissDialogEvent: RxObservable<Unit> = dismissDialogEventSubject
private var isAuthorizedTwitter: Boolean = false
private var tags: List<String> = listOf()
private val disposable = CompositeDisposable()
private val commentChangedCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
val size = comment.get().codePointCount(0, comment.get().length)
commentCount.set("$size / $MAX_COMMENT_SIZE")
isEnableComment.set(size <= MAX_COMMENT_SIZE)
}
}
private val isShareTwitterCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(p0: Observable?, p1: Int) {
if (isShareTwitter.get()) {
if (!isAuthorizedTwitter) {
twitterUnauthorizedEventSubject.onNext(Unit)
}
}
}
}
init {
val displayItemStream = RxObservable.zip<EditableBookmark, Boolean, Pair<EditableBookmark, Boolean>>(
hatenaService.editableBookmark,
twitterService.confirmAuthorisedEvent,
BiFunction { t1, t2 ->
return@BiFunction Pair(t1, t2)
}
)
comment.addOnPropertyChangedCallback(commentChangedCallback)
isShareTwitter.addOnPropertyChangedCallback(isShareTwitterCallback)
disposable.addAll(displayItemStream.subscribe { (editableBookmark, isAuthorizedTwitter) ->
isFirstEdit.set(editableBookmark.isFirstEdit)
comment.set(editableBookmark.comment)
isOpen.set(!editableBookmark.isPrivate)
isReadAfter.set(editableBookmark.tags.contains(HatenaService.TAG_READ_AFTER))
this.tags = editableBookmark.tags
this.isAuthorizedTwitter = isAuthorizedTwitter
}, hatenaService.registeredEvent.subscribe {
if (isShareTwitter.get()) {
twitterService.postTweet(this.articleUrl.get(), this.articleTitle.get(), comment.get())
}
dismissDialogEventSubject.onNext(Unit)
}, hatenaService.deletedEvent.subscribe {
dismissDialogEventSubject.onNext(Unit)
})
this.articleTitle.set(articleTitle)
this.articleUrl.set(articleUrl)
hatenaService.findBookmarkByUrl(articleUrl)
twitterService.confirmAuthorised()
}
override fun onCleared() {
comment.removeOnPropertyChangedCallback(commentChangedCallback)
isShareTwitter.removeOnPropertyChangedCallback(isShareTwitterCallback)
disposable.dispose()
super.onCleared()
}
@Suppress("UNUSED_PARAMETER")
fun onClickOk(view: View) {
if (isDelete.get()) {
hatenaService.deleteBookmark(articleUrl.get())
} else {
hatenaService.registerBookmark(articleUrl.get(),
comment.get(),
isOpen.get(),
isReadAfter.get(),
tags)
}
}
@Suppress("UNUSED_PARAMETER")
fun onClickCancel(view: View) {
dismissDialogEventSubject.onNext(Unit)
}
class Factory(private val articleTitle: String,
private val articleUrl: String,
private val hatenaService: HatenaService,
private val twitterService: TwitterService) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(EditBookmarkDialogFragmentViewModel::class.java)) {
return EditBookmarkDialogFragmentViewModel(articleTitle, articleUrl, hatenaService, twitterService) as T
}
throw IllegalArgumentException("Unknown class name")
}
}
}
| apache-2.0 | 490ffab5f320f4f23f75ba804642b69e | 38.730539 | 120 | 0.689073 | 5.092095 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsNativeRttiChecker.kt | 3 | 2579 | /*
* Copyright 2010-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.kotlin.js.resolve.diagnostics
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils
import org.jetbrains.kotlin.psi.KtClassLiteralExpression
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.calls.checkers.RttiExpressionChecker
import org.jetbrains.kotlin.resolve.calls.checkers.RttiExpressionInformation
import org.jetbrains.kotlin.resolve.calls.checkers.RttiOperation
import org.jetbrains.kotlin.resolve.calls.context.ResolutionContext
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.ClassLiteralChecker
class JsNativeRttiChecker : RttiExpressionChecker, ClassLiteralChecker {
override fun check(rttiInformation: RttiExpressionInformation, reportOn: PsiElement, trace: BindingTrace) {
val sourceType = rttiInformation.sourceType
val targetType = rttiInformation.targetType
val targetDescriptor = targetType?.constructor?.declarationDescriptor
if (sourceType != null && targetDescriptor != null && AnnotationsUtils.isNativeInterface(targetDescriptor)) {
when (rttiInformation.operation) {
RttiOperation.IS,
RttiOperation.NOT_IS -> trace.report(ErrorsJs.CANNOT_CHECK_FOR_NATIVE_INTERFACE.on(reportOn, targetType))
RttiOperation.AS,
RttiOperation.SAFE_AS -> trace.report(ErrorsJs.UNCHECKED_CAST_TO_NATIVE_INTERFACE.on(reportOn, sourceType, targetType))
}
}
}
override fun check(expression: KtClassLiteralExpression, type: KotlinType, context: ResolutionContext<*>) {
val descriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return
if (AnnotationsUtils.isNativeInterface(descriptor)) {
context.trace.report(ErrorsJs.NATIVE_INTERFACE_AS_CLASS_LITERAL.on(expression))
}
}
}
| apache-2.0 | ca541360665f2f0ca6a12b41079e4a08 | 47.660377 | 135 | 0.759984 | 4.401024 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/bookmarks/adapter/BookmarksAdapter.kt | 1 | 2374 | package com.sedsoftware.yaptalker.presentation.feature.bookmarks.adapter
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.domain.device.Settings
import com.sedsoftware.yaptalker.presentation.base.adapter.YapEntityDelegateAdapter
import com.sedsoftware.yaptalker.presentation.model.DisplayedItemType
import com.sedsoftware.yaptalker.presentation.model.base.BookmarkedTopicModel
import java.util.ArrayList
import javax.inject.Inject
class BookmarksAdapter @Inject constructor(
clickListener: BookmarksElementsClickListener,
settings: Settings
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: ArrayList<BookmarkedTopicModel>
private var delegateAdapters = SparseArrayCompat<YapEntityDelegateAdapter>()
init {
delegateAdapters.put(
DisplayedItemType.BOOKMARKED_TOPIC, BookmarksDelegateAdapter(clickListener, settings)
)
items = ArrayList()
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
delegateAdapters.get(viewType)!!.onCreateViewHolder(parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
delegateAdapters.get(getItemViewType(position))?.onBindViewHolder(holder, items[position])
with(holder.itemView) {
AnimationUtils.loadAnimation(context, R.anim.recyclerview_fade_in).apply {
startAnimation(this)
}
}
}
override fun onViewDetachedFromWindow(holder: ViewHolder) {
super.onViewDetachedFromWindow(holder)
holder.itemView.clearAnimation()
}
override fun getItemViewType(position: Int): Int =
items[position].getEntityType()
override fun getItemCount() =
items.size
override fun getItemId(position: Int) =
position.toLong()
fun addBookmarkItem(item: BookmarkedTopicModel) {
val insertPosition = items.size
items.add(item)
notifyItemInserted(insertPosition)
}
fun clearBookmarksList() {
notifyItemRangeRemoved(0, items.size)
items.clear()
}
}
| apache-2.0 | 0174cc88e060bc58c03e57e854cfa3f7 | 31.972222 | 98 | 0.742628 | 5.116379 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/ImageSvgPreCompiler.kt | 2 | 15418 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package org.jetbrains.intellij.build.images
import com.intellij.openapi.util.text.Formats
import com.intellij.ui.svg.ImageValue
import com.intellij.ui.svg.SvgCacheManager
import com.intellij.ui.svg.SvgTranscoder
import com.intellij.ui.svg.createSvgDocument
import com.intellij.util.io.DigestUtil
import io.opentelemetry.api.GlobalOpenTelemetry
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import org.apache.batik.transcoder.TranscoderException
import org.jetbrains.ikv.builder.IkvWriter
import org.jetbrains.ikv.builder.sizeUnawareIkvWriter
import org.jetbrains.intellij.build.io.ByteBufferAllocator
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.mvstore.DataUtil
import org.jetbrains.mvstore.MVMap
import org.jetbrains.mvstore.type.IntDataType
import java.awt.image.BufferedImage
import java.awt.image.DataBufferInt
import java.nio.ByteBuffer
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.NotDirectoryException
import java.nio.file.Path
import java.util.concurrent.Callable
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ForkJoinTask
import java.util.concurrent.atomic.AtomicInteger
import kotlin.system.exitProcess
private class FileInfo(val file: Path) {
companion object {
fun digest(file: Path) = digest(loadAndNormalizeSvgFile(file).toByteArray())
fun digest(fileNormalizedData: ByteArray): ByteArray = DigestUtil.sha512().digest(fileNormalizedData)
}
val checksum: ByteArray by lazy(LazyThreadSafetyMode.PUBLICATION) { digest(file) }
}
/**
* Works together with [SvgCacheManager] to generate pre-cached icons
*/
internal class ImageSvgPreCompiler(private val compilationOutputRoot: Path? = null) {
/// the 4.0 scale is used on retina macOS for product icon, adds few more scales for few icons
//private val productIconScales = (scales + scales.map { it * 2 }).toSortedSet().toFloatArray()
//private val productIconPrefixes = mutableListOf<String>()
private val totalFiles = AtomicInteger(0)
private val totalSize = AtomicInteger(0)
companion object {
@JvmStatic
fun main(args: Array<String>) {
try {
mainImpl(args)
}
catch (e: Throwable) {
System.err.println("Unexpected crash: ${e.message}")
e.printStackTrace(System.err)
exitProcess(1)
}
exitProcess(0)
}
@JvmStatic
fun optimize(dbDir: Path, compilationOutputRoot: Path, dirs: List<Path>): List<Path> {
return ImageSvgPreCompiler(compilationOutputRoot).compileIcons(dbDir, dirs)
}
private fun mainImpl(args: Array<String>) {
println("Pre-building SVG images...")
if (args.isEmpty()) {
println("Usage: <tool> dbFile tasks_file product_icons*")
println("")
println("tasks_file: list of paths, every path on a new line: {<input dir>\\n}+")
println("")
exitProcess(1)
}
System.setProperty("java.awt.headless", "true")
val dbDir = args.getOrNull(0) ?: error("only one parameter is supported")
val argsFile = args.getOrNull(1) ?: error("only one parameter is supported")
val dirs = Files.readAllLines(Path.of(argsFile)).map { Path.of(it) }
val productIcons = args.drop(2).toSortedSet()
println("Expecting product icons: $productIcons")
val compiler = ImageSvgPreCompiler()
// todo
//productIcons.forEach(compiler::addProductIconPrefix)
compiler.compileIcons(Path.of(dbDir), dirs)
}
}
fun preCompileIcons(modules: List<JpsModule>, dbFile: Path) {
val javaExtensionService = JpsJavaExtensionService.getInstance()
compileIcons(dbFile, modules.mapNotNull { javaExtensionService.getOutputDirectory(it, false)?.toPath() })
}
@Suppress("PropertyName")
private class Stores(classifier: String, dbDir: Path) {
val s1 = StoreContainer(1f, classifier, dbDir)
val s1_25 = StoreContainer(1.25f, classifier, dbDir)
val s1_5 = StoreContainer(1.5f, classifier, dbDir)
val s2 = StoreContainer(2f, classifier, dbDir)
val s2_5 = StoreContainer(2.5f, classifier, dbDir)
fun close(list: MutableList<Path>) {
s1.close()
s1_25.close()
s1_5.close()
s2.close()
s2_5.close()
s1.file?.let { list.add(it) }
s1_25.file?.let { list.add(it) }
s1_5.file?.let { list.add(it) }
s2.file?.let { list.add(it) }
s2_5.file?.let { list.add(it) }
}
}
private class StoreContainer(private val scale: Float, private val classifier: String, private val dbDir: Path) {
@Volatile
private var store: IkvWriter? = null
var file: Path? = null
private set
fun getOrCreate() = store ?: getSynchronized()
@Synchronized
private fun getSynchronized(): IkvWriter {
var store = store
if (store == null) {
val file = dbDir.resolve("icons-v2-$scale$classifier.db")
this.file = file
store = sizeUnawareIkvWriter(file)
this.store = store
}
return store
}
fun close() {
store?.close()
}
}
fun compileIcons(dbDir: Path, dirs: List<Path>): List<Path> {
Files.createDirectories(dbDir)
val lightStores = Stores("", dbDir)
val darkStores = Stores("-d", dbDir)
val resultFiles = ArrayList<Path>()
try {
val mapBuilder = MVMap.Builder<Int, ImageValue>()
mapBuilder.keyType(IntDataType.INSTANCE)
mapBuilder.valueType(ImageValue.ImageValueSerializer())
val getMapByScale: (scale: Float, isDark: Boolean) -> IkvWriter = { scale, isDark ->
val list = if (isDark) darkStores else lightStores
when (scale) {
1f -> list.s1.getOrCreate()
1.25f -> list.s1_25.getOrCreate()
1.5f -> list.s1_5.getOrCreate()
2f -> list.s2.getOrCreate()
2.5f -> list.s2_5.getOrCreate()
else -> throw UnsupportedOperationException("Scale $scale is not supported")
}
}
val rootRobotData = IconRobotsData(parent = null, ignoreSkipTag = false, usedIconsRobots = null)
val result = ForkJoinTask.invokeAll(dirs.map { dir ->
ForkJoinTask.adapt(Callable {
val result = mutableListOf<IconData>()
processDir(dir, dir, 1, rootRobotData, result)
result
})
}).flatMap { it.rawResult }
val array: Array<IconData?> = result.toTypedArray()
array.sortBy { it!!.variants.first() }
/// the expected scales of images that we have
/// the macOS touch bar uses 2.5x scale
/// the application icon (which one?) is 4x on macOS
val scales = floatArrayOf(
1f,
1.25f, /*Windows*/
1.5f, /*Windows*/
2.0f,
2.5f /*macOS touchBar*/
)
val collisionGuard = ConcurrentHashMap<Int, FileInfo>()
for ((index, icon) in array.withIndex()) {
// key is the same for all variants
// check collision only here - after sorting (so, we produce stable results as we skip same icon every time)
if (checkCollision(icon!!.imageKey, icon.variants[0], icon.light1xData, collisionGuard)) {
array[index] = null
}
}
// cannot be processed concurrently due to IDEA-303866
scales.map { scale ->
ByteBufferAllocator().use { bufferAllocator ->
for (icon in array) {
processImage(icon = icon ?: continue, getMapByScale = getMapByScale, scale = scale, bufferAllocator = bufferAllocator)
}
}
}
//println("${Formats.formatFileSize(totalSize.get().toLong())} (${totalSize.get()}, iconCount=${totalFiles.get()}, resultSize=${result.size})")
}
catch (e: Throwable) {
try {
lightStores.close(resultFiles)
darkStores.close(resultFiles)
}
catch (e1: Throwable) {
e.addSuppressed(e)
}
throw e
}
val span = GlobalOpenTelemetry.getTracer("build-script")
.spanBuilder("close rasterized SVG database")
.setAttribute("path", dbDir.toString())
.setAttribute(AttributeKey.longKey("iconCount"), totalFiles.get().toLong())
.startSpan()
try {
lightStores.close(resultFiles)
darkStores.close(resultFiles)
span.setAttribute(AttributeKey.stringKey("fileSize"), Formats.formatFileSize(totalSize.get().toLong()))
}
finally {
span.end()
}
resultFiles.sort()
return resultFiles
}
private class IconData(val light1xData: ByteArray, val variants: List<Path>, val imageKey: Int)
private fun processDir(dir: Path,
rootDir: Path,
level: Int,
rootRobotData: IconRobotsData,
result: MutableCollection<IconData>) {
val stream = try {
Files.newDirectoryStream(dir)
}
catch (e: NotDirectoryException) {
return
}
catch (e: NoSuchFileException) {
return
}
val idToVariants = stream.use {
var idToVariants: MutableMap<String, MutableList<Path>>? = null
val robotData = rootRobotData.fork(dir, dir)
for (file in stream) {
val fileName = file.fileName.toString()
if (level == 1) {
if (isBlacklistedTopDirectory(fileName)) {
continue
}
}
if (robotData.isSkipped(file)) {
continue
}
if (fileName.endsWith(".svg")) {
if (idToVariants == null) {
idToVariants = HashMap()
}
idToVariants.computeIfAbsent(getImageCommonName(fileName)) { mutableListOf() }.add(file)
}
else if (!fileName.endsWith(".class")) {
processDir(file, rootDir, level + 1, rootRobotData.fork(file, rootDir), result)
}
}
idToVariants ?: return
}
val keys = idToVariants.keys.toTypedArray()
keys.sort()
for (commonName in keys) {
val variants = idToVariants.get(commonName)!!
variants.sort()
val light1x = variants[0]
val light1xPath = light1x.toString()
if (light1xPath.endsWith("@2x.svg") || light1xPath.endsWith("_dark.svg")) {
throw IllegalStateException("$light1x doesn't have 1x light icon")
}
val light1xData = loadAndNormalizeSvgFile(light1x)
if (light1xData.contains("data:image")) {
Span.current().addEvent("image $light1x uses data urls and will be skipped")
continue
}
val light1xBytes = light1xData.toByteArray()
val imageKey = getImageKey(light1xBytes, light1x.fileName.toString())
totalFiles.addAndGet(variants.size)
try {
result.add(IconData(light1xBytes, variants, imageKey))
}
catch (e: TranscoderException) {
throw RuntimeException("Cannot process $commonName (variants=$variants)", e)
}
}
}
private fun processImage(icon: IconData,
getMapByScale: (scale: Float, isDark: Boolean) -> IkvWriter,
scale: Float,
bufferAllocator: ByteBufferAllocator) {
//println("$id: ${variants.joinToString { rootDir.relativize(it).toString() }}")
val variants = icon.variants
// key is the same for all variants
val imageKey = icon.imageKey
val light2x = variants.find { it.toString().endsWith("@2x.svg") }
var document = if (scale >= 2 && light2x != null) {
createSvgDocument(null, Files.newInputStream(light2x))
}
else {
createSvgDocument(null, icon.light1xData)
}
addEntry(getMapByScale(scale, false), SvgTranscoder.createImage(scale, document, null), imageKey, totalSize, bufferAllocator)
val dark2x = variants.find { it.toString().endsWith("@2x_dark.svg") }
val dark1x = variants.find { it !== dark2x && it.toString().endsWith("_dark.svg") } ?: return
document = createSvgDocument(null, Files.newInputStream(if (scale >= 2 && dark2x != null) dark2x else dark1x))
val image = SvgTranscoder.createImage(scale, document, null)
addEntry(getMapByScale(scale, true), image, imageKey, totalSize, bufferAllocator)
}
private fun checkCollision(imageKey: Int, file: Path, fileNormalizedData: ByteArray,
collisionGuard: ConcurrentHashMap<Int, FileInfo>): Boolean {
val duplicate = collisionGuard.putIfAbsent(imageKey, FileInfo(file)) ?: return false
if (duplicate.checksum.contentEquals(FileInfo.digest(fileNormalizedData))) {
assert(duplicate.file !== file)
Span.current().addEvent("${getRelativeToCompilationOutPath(duplicate.file)} duplicates ${getRelativeToCompilationOutPath(file)}")
//println("${getRelativeToCompilationOutPath(duplicate.file)} duplicates ${getRelativeToCompilationOutPath(file)}")
// skip - do not add
return true
}
throw IllegalStateException("Hash collision:\n file1=${duplicate.file},\n file2=${file},\n imageKey=$imageKey")
}
private fun getRelativeToCompilationOutPath(file: Path): Path {
if (compilationOutputRoot != null && file.startsWith(compilationOutputRoot)) {
return compilationOutputRoot.relativize(file)
}
else {
return file
}
}
}
private fun addEntry(map: IkvWriter, image: BufferedImage, imageKey: Int, totalSize: AtomicInteger, bufferAllocator: ByteBufferAllocator) {
val w = image.width
val h = image.height
assert(image.type == BufferedImage.TYPE_INT_ARGB)
assert(!image.colorModel.isAlphaPremultiplied)
val data = (image.raster.dataBuffer as DataBufferInt).data
val buffer = bufferAllocator.allocate(DataUtil.VAR_INT_MAX_SIZE * 3 + data.size * Int.SIZE_BYTES + 1)
writeVar(buffer, imageKey)
if (w == h) {
if (w < 254) {
buffer.put(w.toByte())
}
else {
buffer.put(255.toByte())
writeVar(buffer, w)
}
}
else {
buffer.put(254.toByte())
writeVar(buffer, w)
writeVar(buffer, h)
}
buffer.asIntBuffer().put(data)
buffer.position(buffer.position() + (data.size * Int.SIZE_BYTES))
buffer.flip()
totalSize.addAndGet(buffer.remaining())
map.write(imageKey, buffer)
}
private fun writeVar(buf: ByteBuffer, value: Int) {
if (value ushr 7 == 0) {
buf.put(value.toByte())
}
else if (value ushr 14 == 0) {
buf.put((value and 127 or 128).toByte())
buf.put((value ushr 7).toByte())
}
else if (value ushr 21 == 0) {
buf.put((value and 127 or 128).toByte())
buf.put((value ushr 7 or 128).toByte())
buf.put((value ushr 14).toByte())
}
else if (value ushr 28 == 0) {
buf.put((value and 127 or 128).toByte())
buf.put((value ushr 7 or 128).toByte())
buf.put((value ushr 14 or 128).toByte())
buf.put((value ushr 21).toByte())
}
else {
buf.put((value and 127 or 128).toByte())
buf.put((value ushr 7 or 128).toByte())
buf.put((value ushr 14 or 128).toByte())
buf.put((value ushr 21 or 128).toByte())
buf.put((value ushr 28).toByte())
}
}
private fun getImageCommonName(fileName: String): String {
for (p in listOf("@2x.svg", "@2x_dark.svg", "_dark.svg", ".svg")) {
if (fileName.endsWith(p)) {
return fileName.substring(0, fileName.length - p.length)
}
}
throw IllegalStateException("Not a SVG: $fileName")
} | apache-2.0 | 6e0ecab75e3285a11e4e4516197d5d87 | 33.571749 | 149 | 0.656635 | 3.964515 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/helpers/CallableMetadataProvider.kt | 1 | 10726 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion.contributors.helpers
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.KtStarProjectionTypeArgument
import org.jetbrains.kotlin.analysis.api.components.buildClassType
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithTypeParameters
import org.jetbrains.kotlin.analysis.api.types.KtSubstitutor
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.analysis.api.types.KtTypeParameterType
import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
internal object CallableMetadataProvider {
class CallableMetadata(
val kind: CallableKind,
/**
* The index of the matched receiver. This number makes completion prefer candidates that are available from the innermost receiver
* when all other things are equal. Explicit receiver is pushed to the end because if explicit receiver does not match, the entry
* would not have showed up in the first place.
*
* For example, consider the code below
*
* ```
* class Foo { // receiver 2
* fun String.f1() { // receiver 1
* fun Int.f2() { // receiver 0
* length // receiver index = 1
* listOf("").size // receiver index = 3 (explicit receiver is added to the end)
* "".f1() // receiver index = 3 (explicit receiver is honored over implicit (dispatch) receiver)
* }
* }
* }
* ```
*/
val receiverIndex: Int?
) {
companion object {
val local = CallableMetadata(CallableKind.Local, null)
val globalOrStatic = CallableMetadata(CallableKind.GlobalOrStatic, null)
}
}
sealed class CallableKind(private val index: Int) : Comparable<CallableKind> {
object Local : CallableKind(0) // local non_extension
object ThisClassMember : CallableKind(1)
object BaseClassMember : CallableKind(2)
object ThisTypeExtension : CallableKind(3)
object BaseTypeExtension : CallableKind(4)
object GlobalOrStatic : CallableKind(5) // global non_extension
object TypeParameterExtension : CallableKind(6)
class ReceiverCastRequired(val fullyQualifiedCastType: String) : CallableKind(7)
override fun compareTo(other: CallableKind): Int = this.index - other.index
}
fun KtAnalysisSession.getCallableMetadata(
context: WeighingContext,
symbol: KtSymbol,
substitutor: KtSubstitutor
): CallableMetadata? {
if (symbol !is KtCallableSymbol) return null
if (symbol is KtSyntheticJavaPropertySymbol) {
return getCallableMetadata(context, symbol.javaGetterSymbol, substitutor)
}
val overriddenSymbols = symbol.getDirectlyOverriddenSymbols()
if (overriddenSymbols.isNotEmpty()) {
val weights = overriddenSymbols
.mapNotNull { callableWeightByReceiver(it, context, substitutor, returnCastRequiredOnReceiverMismatch = false) }
.takeUnless { it.isEmpty() }
?: symbol.getAllOverriddenSymbols().map { callableWeightBasic(context, it, substitutor) }
return weights.minByOrNull { it.kind }
}
return callableWeightBasic(context, symbol, substitutor)
}
private fun KtAnalysisSession.callableWeightBasic(
context: WeighingContext,
symbol: KtCallableSymbol,
substitutor: KtSubstitutor
): CallableMetadata {
callableWeightByReceiver(symbol, context, substitutor, returnCastRequiredOnReceiverMismatch = true)?.let { return it }
return when (symbol.getContainingSymbol()) {
null, is KtPackageSymbol, is KtClassifierSymbol -> CallableMetadata.globalOrStatic
else -> CallableMetadata.local
}
}
private fun KtAnalysisSession.callableWeightByReceiver(
symbol: KtCallableSymbol,
context: WeighingContext,
substitutor: KtSubstitutor,
returnCastRequiredOnReceiverMismatch: Boolean
): CallableMetadata? {
val actualExplicitReceiverType = context.explicitReceiver?.let {
getReferencedClassTypeInCallableReferenceExpression(it) ?: it.getKtType()
}
val actualImplicitReceiverTypes = context.implicitReceiver.map { it.type }
val expectedExtensionReceiverType = symbol.receiverType?.let { substitutor.substitute(it) }
val weightBasedOnExtensionReceiver = expectedExtensionReceiverType?.let { receiverType ->
// If a symbol expects an extension receiver, then either
// * the call site explicitly specifies the extension receiver , or
// * the call site specifies no receiver.
// In other words, in this case, an explicit receiver can never be a dispatch receiver.
callableWeightByReceiver(symbol,
actualExplicitReceiverType?.let { listOf(it) } ?: actualImplicitReceiverTypes,
receiverType,
returnCastRequiredOnReceiverMismatch
)
}
if (returnCastRequiredOnReceiverMismatch && weightBasedOnExtensionReceiver?.kind is CallableKind.ReceiverCastRequired) return weightBasedOnExtensionReceiver
// In Fir, a local function takes its containing function's dispatch receiver as its dispatch receiver. But we don't consider a
// local function as a class member. Hence, here we return null so that it's handled by other logic.
if (symbol.callableIdIfNonLocal == null) return null
val expectedDispatchReceiverType = (symbol as? KtCallableSymbol)?.getDispatchReceiverType()
val weightBasedOnDispatchReceiver = expectedDispatchReceiverType?.let { receiverType ->
callableWeightByReceiver(
symbol,
actualImplicitReceiverTypes + listOfNotNull(actualExplicitReceiverType),
receiverType,
returnCastRequiredOnReceiverMismatch
)
}
if (returnCastRequiredOnReceiverMismatch && weightBasedOnDispatchReceiver?.kind is CallableKind.ReceiverCastRequired) return weightBasedOnDispatchReceiver
return weightBasedOnExtensionReceiver ?: weightBasedOnDispatchReceiver
}
/**
* Return the type from the referenced class if this explicit receiver is a receiver in a callable reference expression. For example,
* in the following code, `String` is such a receiver. And this method should return the `String` type in this case.
* ```
* val l = String::length
* ```
*/
private fun KtAnalysisSession.getReferencedClassTypeInCallableReferenceExpression(explicitReceiver: KtExpression): KtType? {
val callableReferenceExpression = explicitReceiver.getParentOfType<KtCallableReferenceExpression>(strict = true) ?: return null
if (callableReferenceExpression.lhs != explicitReceiver) return null
val symbol = when (explicitReceiver) {
is KtDotQualifiedExpression -> explicitReceiver.selectorExpression?.mainReference?.resolveToSymbol()
is KtNameReferenceExpression -> explicitReceiver.mainReference.resolveToSymbol()
else -> return null
}
if (symbol !is KtClassLikeSymbol) return null
return buildClassType(symbol) {
repeat(symbol.typeParameters.size) {
argument(KtStarProjectionTypeArgument(token))
}
}
}
private fun KtAnalysisSession.callableWeightByReceiver(
symbol: KtCallableSymbol,
actualReceiverTypes: List<KtType>,
expectedReceiverType: KtType,
returnCastRequiredOnReceiverTypeMismatch: Boolean
): CallableMetadata? {
if (expectedReceiverType is KtFunctionType) return null
var bestMatchIndex: Int? = null
var bestMatchWeightKind: CallableKind? = null
for ((i, actualReceiverType) in actualReceiverTypes.withIndex()) {
val weightKind = callableWeightKindByReceiverType(symbol, actualReceiverType, expectedReceiverType)
if (weightKind != null) {
if (bestMatchWeightKind == null || weightKind < bestMatchWeightKind) {
bestMatchWeightKind = weightKind
bestMatchIndex = i
}
}
}
// TODO: FE1.0 has logic that uses `null` for receiverIndex if the symbol matches every actual receiver in order to "prevent members
// of `Any` to show up on top". But that seems hacky and can cause collateral damage if the implicit receivers happen to implement
// some common interface. So that logic is left out here for now. We can add it back in future if needed.
if (bestMatchWeightKind == null) {
return if (returnCastRequiredOnReceiverTypeMismatch)
CallableMetadata(CallableKind.ReceiverCastRequired(expectedReceiverType.render()), null)
else null
}
return CallableMetadata(bestMatchWeightKind, bestMatchIndex)
}
private fun KtAnalysisSession.callableWeightKindByReceiverType(
symbol: KtCallableSymbol,
actualReceiverType: KtType,
expectedReceiverType: KtType,
): CallableKind? = when {
actualReceiverType isEqualTo expectedReceiverType -> when {
isExtensionCallOnTypeParameterReceiver(symbol) -> CallableKind.TypeParameterExtension
symbol.isExtension -> CallableKind.ThisTypeExtension
else -> CallableKind.ThisClassMember
}
actualReceiverType isSubTypeOf expectedReceiverType -> when {
symbol.isExtension -> CallableKind.BaseTypeExtension
else -> CallableKind.BaseClassMember
}
else -> null
}
private fun KtAnalysisSession.isExtensionCallOnTypeParameterReceiver(symbol: KtCallableSymbol): Boolean {
val originalSymbol = symbol.originalOverriddenSymbol
val receiverParameterType = originalSymbol?.receiverType as? KtTypeParameterType ?: return false
val parameterTypeOwner = receiverParameterType.symbol.getContainingSymbol() ?: return false
return parameterTypeOwner == originalSymbol
}
} | apache-2.0 | af92e2bb5a5d75694c56fd0da5b62969 | 49.126168 | 164 | 0.688794 | 5.791577 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/TestModuleComponent.kt | 7 | 837 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ComponentNotRegistered")
package com.intellij.workspaceModel.ide
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleComponent
@State(name = "XXX")
class TestModuleComponent: ModuleComponent, PersistentStateComponent<TestModuleComponent> {
var testString: String = ""
override fun getState(): TestModuleComponent = this
override fun loadState(state: TestModuleComponent) {
testString = state.testString
}
companion object {
fun getInstance(module: Module): TestModuleComponent = module.getComponent(TestModuleComponent::class.java)
}
} | apache-2.0 | 21023a7106c3a3631d08254d9407c901 | 35.434783 | 120 | 0.800478 | 4.524324 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/searchHelpers.kt | 4 | 5031 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.search.usagesSearch
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.LightClassUtil.PropertyAccessorsPsiMethods
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
fun PsiNamedElement.getAccessorNames(readable: Boolean = true, writable: Boolean = true): List<String> {
fun PropertyAccessorsPsiMethods.toNameList(): List<String> {
val getter = getter
val setter = setter
val result = ArrayList<String>()
if (readable && getter != null) result.add(getter.name)
if (writable && setter != null) result.add(setter.name)
return result
}
if (this !is KtDeclaration || KtPsiUtil.isLocal(this)) return Collections.emptyList()
when (this) {
is KtProperty ->
return LightClassUtil.getLightClassPropertyMethods(this).toNameList()
is KtParameter ->
if (hasValOrVar()) {
return LightClassUtil.getLightClassPropertyMethods(this).toNameList()
}
}
return Collections.emptyList()
}
fun PsiNamedElement.getClassNameForCompanionObject(): String? {
return if (this is KtObjectDeclaration && this.isCompanion()) {
getNonStrictParentOfType<KtClass>()?.name
} else {
null
}
}
fun KtParameter.dataClassComponentFunction(): FunctionDescriptor? {
if (!isDataClassProperty()) return null
val context = this.analyze()
val paramDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? ValueParameterDescriptor
val constructor = paramDescriptor?.containingDeclaration as? ConstructorDescriptor ?: return null
val index = constructor.valueParameters.indexOf(paramDescriptor)
val correspondingComponentName = DataClassDescriptorResolver.createComponentName(index + 1)
val dataClass = constructor.containingDeclaration as? ClassDescriptor ?: return null
dataClass.unsubstitutedMemberScope.getContributedFunctions(correspondingComponentName, NoLookupLocation.FROM_IDE)
return context[BindingContext.DATA_CLASS_COMPONENT_FUNCTION, paramDescriptor]
}
fun KtParameter.isDataClassProperty(): Boolean {
if (!hasValOrVar()) return false
return this.containingClassOrObject?.hasModifier(KtTokens.DATA_KEYWORD) ?: false
}
fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement> {
val ktCallableDeclaration =
target.safeAs<KtCallableDeclaration>()?.takeIf { it.hasModifier(KtTokens.OVERRIDE_KEYWORD) } ?: return emptyList()
val callableDescriptor = ktCallableDeclaration.resolveToDescriptorIfAny() as? CallableDescriptor
val descriptorsToHighlight = if (callableDescriptor is ParameterDescriptor)
listOf(callableDescriptor)
else
callableDescriptor?.findOriginalTopMostOverriddenDescriptors() ?: emptyList()
return descriptorsToHighlight.mapNotNull { it.source.getPsi() }.filter { it != target }
}
val KtDeclaration.descriptor: DeclarationDescriptor?
get() = if (this is KtParameter) this.descriptor else this.resolveToDescriptorIfAny(BodyResolveMode.FULL)
val KtParameter.descriptor: ValueParameterDescriptor?
get() = this.resolveToParameterDescriptorIfAny(BodyResolveMode.FULL)
fun isCallReceiverRefersToCompanionObject(element: KtElement, companionObject: KtObjectDeclaration): Boolean {
val companionObjectDescriptor = companionObject.descriptor
val bindingContext = element.analyze()
val resolvedCall = bindingContext[BindingContext.CALL, element]?.getResolvedCall(bindingContext) ?: return false
return (resolvedCall.dispatchReceiver as? ImplicitClassReceiver)?.declarationDescriptor == companionObjectDescriptor ||
(resolvedCall.extensionReceiver as? ImplicitClassReceiver)?.declarationDescriptor == companionObjectDescriptor
}
| apache-2.0 | 21f690372db67e731b2fda70bfb009a4 | 46.462264 | 158 | 0.786921 | 5.21888 | false | false | false | false |
asarazan/Bismarck | bismarck-kotlinx-json/src/commonTest/kotlin/net/sarazan/bismarck/test/JsonTests.kt | 1 | 554 | package net.sarazan.bismarck.test
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.serialization.Serializable
import net.sarazan.bismarck.serializers.kotlinx.JsonSerializer
@Serializable
data class Payload(
val foo: String = "",
var bar: Int? = null
)
val serializer = JsonSerializer(Payload.serializer())
class JsonTests {
@Test
fun testSerializer() {
val payload = Payload("hi", 2)
val bytes = serializer.serialize(payload)
assertEquals(serializer.deserialize(bytes), payload)
}
}
| apache-2.0 | 8879b604e928e2298617d4d636466a3b | 22.083333 | 62 | 0.725632 | 4.261538 | false | true | false | false |
zhiayang/pew | core/src/main/kotlin/Items/Inventory.kt | 1 | 1235 | // Copyright (c) 2014 Orion Industries, [email protected]
// Licensed under the Apache License version 2.0
package Items
import java.util.LinkedList
public class Inventory(public val maxSize: Int)
{
public data class Item(public val item: InventoryItem, public var stackSize: Int)
public val items: MutableList<Item> = LinkedList()
public var selected: Int = 0
set(value)
{
if (value < this.items.size)
this.$selected = value
else
throw ArrayIndexOutOfBoundsException()
}
public fun store(item: InventoryItem, size: Int): Boolean
{
// todo: robuster
// check if we have space
if (this.items.size < this.maxSize)
{
this.items.add(Item(item, size))
return true
}
return false
}
public fun get(name: String): Item?
{
for (i in this.items)
{
if (i.item.name == name)
return i
}
return null
}
public fun getSelected(): Item?
{
if (this.selected < this.items.size)
return this.items[this.selected]
return null
}
public fun remove(item: InventoryItem): Boolean
{
// todo: robuster
if (this.items.contains(item))
{
if (this.selected == this.items.size() - 1)
this.selected--
this.items.remove(item)
return true
}
return false
}
}
| apache-2.0 | 0b35c779144d39603412cfe9d73ee303 | 16.898551 | 82 | 0.671255 | 3.095238 | false | false | false | false |
GunoH/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitMalformedDeclarationInspection.kt | 1 | 56197 | // 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.codeInspection.test.junit
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.codeInsight.MetaAnnotationUtil
import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.*
import com.intellij.codeInspection.test.junit.references.MethodSourceReference
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.codeInspection.util.SpecialAnnotationsUtil
import com.intellij.lang.Language
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.JvmModifiersOwner
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmPrimitiveTypeKind
import com.intellij.lang.jvm.types.JvmType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.*
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference
import com.intellij.psi.impl.source.tree.java.PsiNameValuePairImpl
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.util.TypeConversionUtil
import com.intellij.psi.util.isAncestor
import com.intellij.uast.UastHintedVisitorAdapter
import com.intellij.util.asSafely
import com.siyeh.ig.junit.JUnitCommonClassNames.*
import com.siyeh.ig.psiutils.TestUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
import javax.swing.JComponent
import kotlin.streams.asSequence
class JUnitMalformedDeclarationInspection : AbstractBaseUastLocalInspectionTool() {
@JvmField
val ignorableAnnotations = mutableListOf("mockit.Mocked", "org.junit.jupiter.api.io.TempDir")
override fun createOptionsPanel(): JComponent = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
ignorableAnnotations, JvmAnalysisBundle.message("jvm.inspections.junit.malformed.option.ignore.test.parameter.if.annotated.by")
)
private fun shouldInspect(file: PsiFile) = isJUnit3InScope(file) || isJUnit4InScope(file) || isJUnit5InScope(file)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
if (!shouldInspect(holder.file)) return PsiElementVisitor.EMPTY_VISITOR
return UastHintedVisitorAdapter.create(
holder.file.language,
JUnitMalformedSignatureVisitor(holder, isOnTheFly, ignorableAnnotations),
arrayOf(UClass::class.java, UField::class.java, UMethod::class.java),
directOnly = true
)
}
}
private class JUnitMalformedSignatureVisitor(
private val holder: ProblemsHolder,
private val isOnTheFly: Boolean,
private val ignorableAnnotations: List<String>
) : AbstractUastNonRecursiveVisitor() {
override fun visitClass(node: UClass): Boolean {
checkMalformedNestedClass(node)
return true
}
override fun visitField(node: UField): Boolean {
checkMalformedCallbackExtension(node)
dataPoint.report(holder, node)
ruleSignatureProblem.report(holder, node)
classRuleSignatureProblem.report(holder, node)
registeredExtensionProblem.report(holder, node)
return true
}
override fun visitMethod(node: UMethod): Boolean {
checkMalformedParameterized(node)
checkRepeatedTestNonPositive(node)
checkIllegalCombinedAnnotations(node)
dataPoint.report(holder, node)
checkSuite(node)
checkedMalformedSetupTeardown(node)
beforeAfterProblem.report(holder, node)
beforeAfterEachProblem.report(holder, node)
beforeAfterClassProblem.report(holder, node)
beforeAfterAllProblem.report(holder, node)
ruleSignatureProblem.report(holder, node)
classRuleSignatureProblem.report(holder, node)
checkJUnit3Test(node)
junit4TestProblem.report(holder, node)
junit5TestProblem.report(holder, node)
return true
}
private val dataPoint = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_EXPERIMENTAL_THEORIES_DATAPOINT, ORG_JUNIT_EXPERIMENTAL_THEORIES_DATAPOINTS),
shouldBeStatic = true,
validVisibility = { UastVisibility.PUBLIC },
)
private val ruleSignatureProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_RULE),
shouldBeStatic = false,
shouldBeSubTypeOf = listOf(ORG_JUNIT_RULES_TEST_RULE, ORG_JUNIT_RULES_METHOD_RULE),
validVisibility = { UastVisibility.PUBLIC }
)
private val registeredExtensionProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION),
shouldBeSubTypeOf = listOf(ORG_JUNIT_JUPITER_API_EXTENSION),
validVisibility = ::notPrivate
)
private val classRuleSignatureProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_CLASS_RULE),
shouldBeStatic = true,
shouldBeSubTypeOf = listOf(ORG_JUNIT_RULES_TEST_RULE),
validVisibility = { UastVisibility.PUBLIC }
)
private val beforeAfterProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_BEFORE, ORG_JUNIT_AFTER),
shouldBeStatic = false,
shouldBeVoidType = true,
validVisibility = { UastVisibility.PUBLIC },
validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } }
)
private val beforeAfterEachProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_JUPITER_API_BEFORE_EACH, ORG_JUNIT_JUPITER_API_AFTER_EACH),
shouldBeStatic = false,
shouldBeVoidType = true,
validVisibility = ::notPrivate,
validParameters = { method ->
if (method.uastParameters.isEmpty()) emptyList()
else if (method.hasParameterResolver()) method.uastParameters
else method.uastParameters.filter { param ->
param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO
|| param.type.canonicalText == ORG_JUNIT_JUPITER_API_REPETITION_INFO
|| param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_REPORTER
|| MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
|| param.hasParameterResolver()
}
}
)
private val beforeAfterClassProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_BEFORE_CLASS, ORG_JUNIT_AFTER_CLASS),
shouldBeStatic = true,
shouldBeVoidType = true,
validVisibility = { UastVisibility.PUBLIC },
validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } }
)
private val beforeAfterAllProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_JUPITER_API_BEFORE_ALL, ORG_JUNIT_JUPITER_API_AFTER_ALL),
shouldBeInTestInstancePerClass = true,
shouldBeStatic = true,
shouldBeVoidType = true,
validVisibility = ::notPrivate,
validParameters = { method ->
if (method.uastParameters.isEmpty()) emptyList()
else if (method.hasParameterResolver()) method.uastParameters
else method.uastParameters.filter { param ->
param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO
|| MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
|| param.hasParameterResolver()
}
}
)
private val junit4TestProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_TEST),
shouldBeStatic = false,
shouldBeVoidType = true,
validVisibility = { UastVisibility.PUBLIC },
validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } }
)
private val junit5TestProblem = AnnotatedSignatureProblem(
annotations = listOf(ORG_JUNIT_JUPITER_API_TEST),
shouldBeStatic = false,
shouldBeVoidType = true,
validVisibility = ::notPrivate,
validParameters = { method ->
if (method.uastParameters.isEmpty()) emptyList()
else if (MetaAnnotationUtil.isMetaAnnotated(method.javaPsi, listOf(
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCE))) null // handled in parameterized test check
else if (method.hasParameterResolver()) method.uastParameters
else method.uastParameters.filter { param ->
param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO
|| param.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_REPORTER
|| MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
|| param.hasParameterResolver()
}
}
)
fun JvmModifier.nonMessage() = "non-${toString().lowercase()}"
private val PsiAnnotation.shortName get() = qualifiedName?.substringAfterLast(".")
private fun notPrivate(method: UDeclaration): UastVisibility? =
if (method.visibility == UastVisibility.PRIVATE) UastVisibility.PUBLIC else null
private fun UParameter.hasParameterResolver(): Boolean = uAnnotations.any { ann -> ann.resolve()?.hasParameterResolver() == true }
private fun UMethod.hasParameterResolver(): Boolean {
val sourcePsi = this.sourcePsi ?: return false
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
return alternatives.any { it.javaPsi.containingClass?.hasParameterResolver() == true }
}
private fun PsiClass.hasParameterResolver(): Boolean {
val annotation = MetaAnnotationUtil.findMetaAnnotationsInHierarchy(this, listOf(ORG_JUNIT_JUPITER_API_EXTENSION_EXTEND_WITH))
.asSequence()
.firstOrNull()
val attrValue = annotation?.findAttributeValue("value")?.toUElement()
if (attrValue is UClassLiteralExpression) {
return InheritanceUtil.isInheritor(attrValue.type, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER)
}
if (attrValue is UCallExpression && attrValue.kind == UastCallKind.NESTED_ARRAY_INITIALIZER) {
return attrValue.valueArguments.any {
it is UClassLiteralExpression && InheritanceUtil.isInheritor(it.type, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER)
}
}
return false
}
private fun checkMalformedNestedClass(aClass: UClass) {
val javaClass = aClass.javaPsi
val containingClass = javaClass.containingClass
if (containingClass == null || !javaClass.hasAnnotation(ORG_JUNIT_JUPITER_API_NESTED)) return
val problems = mutableListOf<JvmModifier>()
if (aClass.isStatic) problems.add(JvmModifier.STATIC)
if (aClass.visibility == UastVisibility.PRIVATE) problems.add(JvmModifier.PRIVATE)
if (problems.isEmpty()) return
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.nested.class.descriptor",
problems.size,
problems.first().nonMessage(),
problems.last().nonMessage()
)
val fix = ClassSignatureQuickFix(aClass.javaPsi.name ?: return, false, aClass.visibility == UastVisibility.PRIVATE)
holder.registerUProblem(aClass, message, fix)
}
private fun checkMalformedCallbackExtension(field: UField) {
val javaField = field.javaPsi?.asSafely<PsiField>() ?: return
val type = field.javaPsi?.asSafely<PsiField>()?.type ?: return
if (!field.isStatic
&& javaField.hasAnnotation(ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION)
&& type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_BEFORE_ALL_CALLBACK, ORG_JUNIT_JUPITER_API_EXTENSION_AFTER_ALL_CALLBACK)
) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.extension.class.level.descriptor", type.presentableText)
val fixes = createModifierQuickfixes(field, modifierRequest(JvmModifier.STATIC, shouldBePresent = true)) ?: return
holder.registerUProblem(field, message, *fixes)
}
}
private fun UMethod.isNoArg(): Boolean = uastParameters.isEmpty() || uastParameters.all { param ->
param.javaPsi?.asSafely<PsiParameter>()?.let { AnnotationUtil.isAnnotated(it, ignorableAnnotations, 0) } == true
}
private fun checkSuspendFunction(method: UMethod): Boolean {
return if (method.lang == Language.findLanguageByID("kotlin") && method.javaPsi.modifierList.text.contains("suspend")) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.suspend.function.descriptor")
holder.registerUProblem(method, message)
true
} else false
}
private fun checkJUnit3Test(method: UMethod) {
val sourcePsi = method.sourcePsi ?: return
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return
if (method.isConstructor) return
if (!TestUtils.isJUnit3TestMethod(javaMethod.javaPsi)) return
val containingClass = method.javaPsi.containingClass ?: return
if (AnnotationUtil.isAnnotated(containingClass, TestUtils.RUN_WITH, AnnotationUtil.CHECK_HIERARCHY)) return
if (checkSuspendFunction(method)) return
if (PsiType.VOID != method.returnType || method.visibility != UastVisibility.PUBLIC || javaMethod.isStatic
|| (!method.isNoArg() && !method.isParameterizedTest())) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.no.arg.descriptor", "public", "non-static", DOUBLE)
return holder.registerUProblem(method, message, MethodSignatureQuickfix(method.name, false, newVisibility = JvmModifier.PUBLIC))
}
}
private fun UMethod.isParameterizedTest(): Boolean =
uAnnotations.firstOrNull { it.qualifiedName == ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST } != null
private fun checkedMalformedSetupTeardown(method: UMethod) {
if ("setUp" != method.name && "tearDown" != method.name) return
if (!InheritanceUtil.isInheritor(method.javaPsi.containingClass, JUNIT_FRAMEWORK_TEST_CASE)) return
val sourcePsi = method.sourcePsi ?: return
if (checkSuspendFunction(method)) return
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return
if (PsiType.VOID != method.returnType || method.visibility == UastVisibility.PRIVATE || javaMethod.isStatic || !method.isNoArg()) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.no.arg.descriptor", "non-private", "non-static", DOUBLE)
val quickFix = MethodSignatureQuickfix(
method.name, newVisibility = JvmModifier.PUBLIC, makeStatic = false, shouldBeVoidType = true, inCorrectParams = emptyMap()
)
return holder.registerUProblem(method, message, quickFix)
}
}
private fun checkSuite(method: UMethod) {
if ("suite" != method.name) return
if (!InheritanceUtil.isInheritor(method.javaPsi.containingClass, JUNIT_FRAMEWORK_TEST_CASE)) return
val sourcePsi = method.sourcePsi ?: return
if (checkSuspendFunction(method)) return
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return
if (method.visibility == UastVisibility.PRIVATE || !javaMethod.isStatic || !method.isNoArg()) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.no.arg.descriptor", "non-private", "static", SINGLE)
val quickFix = MethodSignatureQuickfix(
method.name, newVisibility = JvmModifier.PUBLIC, makeStatic = true, shouldBeVoidType = false, inCorrectParams = emptyMap()
)
return holder.registerUProblem(method, message, quickFix)
}
}
private fun checkIllegalCombinedAnnotations(decl: UDeclaration) {
val javaPsi = decl.javaPsi.asSafely<PsiModifierListOwner>() ?: return
val annotatedTest = nonCombinedTests.filter { MetaAnnotationUtil.isMetaAnnotated(javaPsi, listOf(it)) }
if (annotatedTest.size > 1) {
val last = annotatedTest.last().substringAfterLast('.')
val annText = annotatedTest.dropLast(1).joinToString { "'@${it.substringAfterLast('.')}'" }
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.test.combination.descriptor", annText, last)
return holder.registerUProblem(decl, message)
}
else if (annotatedTest.size == 1 && annotatedTest.first() != ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST) {
val annotatedArgSource = parameterizedSources.filter { MetaAnnotationUtil.isMetaAnnotated(javaPsi, listOf(it)) }
if (annotatedArgSource.isNotEmpty()) {
val testAnnText = annotatedTest.first().substringAfterLast('.')
val argAnnText = annotatedArgSource.joinToString { "'@${it.substringAfterLast('.')}'" }
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.test.combination.descriptor", argAnnText, testAnnText)
return holder.registerUProblem(decl, message)
}
}
}
private fun checkRepeatedTestNonPositive(method: UMethod) {
val repeatedAnno = method.findAnnotation(ORG_JUNIT_JUPITER_API_REPEATED_TEST) ?: return
val repeatedNumber = repeatedAnno.findDeclaredAttributeValue("value") ?: return
val repeatedSrcPsi = repeatedNumber.sourcePsi ?: return
val constant = repeatedNumber.evaluate()
if (constant is Int && constant <= 0) {
holder.registerProblem(repeatedSrcPsi, JvmAnalysisBundle.message("jvm.inspections.junit.malformed.repetition.number.descriptor"))
}
}
private fun checkMalformedParameterized(method: UMethod) {
if (!MetaAnnotationUtil.isMetaAnnotated(method.javaPsi, listOf(ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST))) return
val usedSourceAnnotations = MetaAnnotationUtil.findMetaAnnotations(method.javaPsi, SOURCE_ANNOTATIONS).toList()
checkConflictingSourceAnnotations(usedSourceAnnotations, method)
usedSourceAnnotations.forEach { annotation ->
when (annotation.qualifiedName) {
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE -> checkMethodSource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE -> checkValuesSource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE -> checkEnumSource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE -> checkCsvSource(annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE -> checkNullSource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE -> checkEmptySource(method, annotation)
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE -> {
checkNullSource(method, annotation)
checkEmptySource(method, annotation)
}
}
}
}
private fun checkConflictingSourceAnnotations(annotations: List<PsiAnnotation>, method: UMethod) {
val isSingleParameterProvider = annotations.firstOrNull { ann ->
singleParamProviders.contains(ann.qualifiedName)
} != null
val isMultipleParameterProvider = annotations.firstOrNull { ann ->
multipleParameterProviders.contains(ann.qualifiedName)
} != null
if (!isMultipleParameterProvider && !isSingleParameterProvider && hasCustomProvider(annotations)) return
if (!isMultipleParameterProvider) {
val message = if (!isSingleParameterProvider) {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.no.sources.are.provided.descriptor")
}
else if (hasMultipleParameters(method.javaPsi)) {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.multiple.parameters.descriptor")
}
else return
holder.registerUProblem(method, message)
}
}
private fun hasCustomProvider(annotations: List<PsiAnnotation>): Boolean {
for (ann in annotations) {
when (ann.qualifiedName) {
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCE -> return true
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCES -> {
val attributes = ann.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)
if ((attributes as? PsiArrayInitializerMemberValue)?.initializers?.isNotEmpty() == true) return true
}
}
}
return false
}
private fun checkMethodSource(method: UMethod, methodSource: PsiAnnotation) {
val psiMethod = method.javaPsi
val containingClass = psiMethod.containingClass ?: return
val annotationMemberValue = methodSource.findDeclaredAttributeValue("value")
if (annotationMemberValue == null) {
if (methodSource.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) == null) return
val foundMethod = containingClass.findMethodsByName(method.name, true).singleOrNull { it.parameters.isEmpty() }
val uFoundMethod = foundMethod.toUElementOfType<UMethod>()
if (uFoundMethod != null) {
return checkSourceProvider(uFoundMethod, containingClass, methodSource, method)
}
else {
return checkAbsentSourceProvider(containingClass, methodSource, method.name, method)
}
}
else {
annotationMemberValue.nestedValues().forEach { attributeValue ->
for (reference in attributeValue.references) {
if (reference is MethodSourceReference) {
val resolve = reference.resolve()
if (resolve !is PsiMethod) {
return checkAbsentSourceProvider(containingClass, attributeValue, reference.value, method)
}
else {
val sourceProvider: PsiMethod = resolve
val uSourceProvider = sourceProvider.toUElementOfType<UMethod>() ?: return
return checkSourceProvider(uSourceProvider, containingClass, attributeValue, method)
}
}
}
}
}
}
private fun checkAbsentSourceProvider(
containingClass: PsiClass, attributeValue: PsiElement, sourceProviderName: String, method: UMethod
) {
val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue
else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.param.method.source.unresolved.descriptor",
sourceProviderName
)
if (isOnTheFly) {
val modifiers = mutableListOf(JvmModifier.PUBLIC)
if (!TestUtils.testInstancePerClass(containingClass)) modifiers.add(JvmModifier.STATIC)
val typeFromText = JavaPsiFacade.getElementFactory(containingClass.project).createTypeFromText(
METHOD_SOURCE_RETURN_TYPE, containingClass
)
val request = methodRequest(containingClass.project, sourceProviderName, modifiers, typeFromText)
val actions = createMethodActions(containingClass, request)
val quickFixes = IntentionWrapper.wrapToQuickFixes(actions, containingClass.containingFile).toTypedArray()
return holder.registerProblem(place, message, *quickFixes)
} else {
return holder.registerProblem(place, message)
}
}
private fun checkSourceProvider(sourceProvider: UMethod, containingClass: PsiClass?, attributeValue: PsiElement, method: UMethod) {
val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue
else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return
val providerName = sourceProvider.name
if (!sourceProvider.isStatic &&
containingClass != null && !TestUtils.testInstancePerClass(containingClass) &&
!implementationsTestInstanceAnnotated(containingClass)
) {
val annotation = JavaPsiFacade.getElementFactory(containingClass.project).createAnnotationFromText(
TEST_INSTANCE_PER_CLASS, containingClass
)
val actions = mutableListOf<IntentionAction>()
val value = (annotation.attributes.first() as PsiNameValuePairImpl).value
if (value != null) {
actions.addAll(createAddAnnotationActions(
containingClass,
annotationRequest(ORG_JUNIT_JUPITER_API_TEST_INSTANCE, constantAttribute("value", value.text))
))
}
actions.addAll(createModifierActions(sourceProvider, modifierRequest(JvmModifier.STATIC, true)))
val quickFixes = IntentionWrapper.wrapToQuickFixes(actions, sourceProvider.javaPsi.containingFile).toTypedArray()
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.method.source.static.descriptor",
providerName)
holder.registerProblem(place, message, *quickFixes)
}
else if (sourceProvider.uastParameters.isNotEmpty() && !classHasParameterResolverField(containingClass)) {
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.param.method.source.no.params.descriptor", providerName)
holder.registerProblem(place, message)
}
else {
val componentType = getComponentType(sourceProvider.returnType, method.javaPsi)
if (componentType == null) {
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.param.method.source.return.type.descriptor", providerName
)
holder.registerProblem(place, message)
}
else if (hasMultipleParameters(method.javaPsi)
&& !InheritanceUtil.isInheritor(componentType, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS)
&& !componentType.equalsToText(JAVA_LANG_OBJECT)
&& !componentType.deepComponentType.equalsToText(JAVA_LANG_OBJECT)
) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.wrapped.in.arguments.descriptor")
holder.registerProblem(place, message)
}
}
}
private fun classHasParameterResolverField(aClass: PsiClass?): Boolean {
if (aClass == null) return false
if (aClass.isInterface) return false
return aClass.fields.any { field ->
AnnotationUtil.isAnnotated(field, ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION, 0) &&
field.type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER)
}
}
private fun implementationsTestInstanceAnnotated(containingClass: PsiClass): Boolean =
ClassInheritorsSearch.search(containingClass, containingClass.resolveScope, true).any { TestUtils.testInstancePerClass(it) }
private fun getComponentType(returnType: PsiType?, method: PsiMethod): PsiType? {
val collectionItemType = JavaGenericsUtil.getCollectionItemType(returnType, method.resolveScope)
if (collectionItemType != null) return collectionItemType
if (InheritanceUtil.isInheritor(returnType, JAVA_UTIL_STREAM_INT_STREAM)) return PsiType.INT
if (InheritanceUtil.isInheritor(returnType, JAVA_UTIL_STREAM_LONG_STREAM)) return PsiType.LONG
if (InheritanceUtil.isInheritor(returnType, JAVA_UTIL_STREAM_DOUBLE_STREAM)) return PsiType.DOUBLE
val streamItemType = PsiUtil.substituteTypeParameter(returnType, JAVA_UTIL_STREAM_STREAM, 0, true)
if (streamItemType != null) return streamItemType
return PsiUtil.substituteTypeParameter(returnType, JAVA_UTIL_ITERATOR, 0, true)
}
private fun hasMultipleParameters(method: PsiMethod): Boolean {
val containingClass = method.containingClass
return containingClass != null && method.parameterList.parameters.count { param ->
!InheritanceUtil.isInheritor(param.type, ORG_JUNIT_JUPITER_API_TEST_INFO) &&
!InheritanceUtil.isInheritor(param.type, ORG_JUNIT_JUPITER_API_TEST_REPORTER) &&
!MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
} > 1 && !MetaAnnotationUtil.isMetaAnnotatedInHierarchy(
containingClass, listOf(ORG_JUNIT_JUPITER_API_EXTENSION_EXTEND_WITH)
)
}
private fun getPassedParameter(method: PsiMethod): PsiParameter? {
return method.parameterList.parameters.firstOrNull { param ->
!InheritanceUtil.isInheritor(param.type, ORG_JUNIT_JUPITER_API_TEST_INFO) &&
!InheritanceUtil.isInheritor(param.type, ORG_JUNIT_JUPITER_API_TEST_REPORTER) &&
!MetaAnnotationUtil.isMetaAnnotated(param, ignorableAnnotations)
}
}
private fun checkNullSource(method: UMethod, annotation: PsiAnnotation) {
if (hasMultipleParameters(method.javaPsi)) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.multiple.parameters.descriptor")
holder.registerProblem(annotation, message)
}
if (getPassedParameter(method.javaPsi) == null) {
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.source.without.params.descriptor",
annotation.shortName
)
holder.registerProblem(annotation.navigationElement, message)
}
}
private fun checkEmptySource(method: UMethod, annotation: PsiAnnotation) {
if (hasMultipleParameters(method.javaPsi)) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.multiple.parameters.descriptor")
return holder.registerProblem(annotation.navigationElement, message)
}
val passedParameter = getPassedParameter(method.javaPsi)
if(passedParameter == null) {
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.source.without.params.descriptor",
annotation.shortName
)
holder.registerProblem(annotation.navigationElement, message)
} else {
var type = passedParameter.type
if (type is PsiClassType) type = type.rawType()
if (type is PsiArrayType
|| type.equalsToText(JAVA_LANG_STRING)
|| type.equalsToText(JAVA_UTIL_LIST)
|| type.equalsToText(JAVA_UTIL_SET)
|| type.equalsToText(JAVA_UTIL_MAP)
) return
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.param.empty.source.unsupported.descriptor",
annotation.shortName, type.presentableText
)
holder.registerProblem(annotation.navigationElement, message)
}
}
private fun checkEnumSource(method: UMethod, enumSource: PsiAnnotation) {
val value = enumSource.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)
if (value !is PsiClassObjectAccessExpression) return // @EnumSource#value type is Class<?>, not an array
val enumType = value.operand.type
checkSourceTypeAndParameterTypeAgree(method, value, enumType)
checkEnumConstants(enumSource, enumType, method)
}
private fun checkSourceTypeAndParameterTypeAgree(method: UMethod, attributeValue: PsiAnnotationMemberValue, componentType: PsiType) {
val parameters = method.uastParameters
if (parameters.size == 1) {
val paramType = parameters.first().type
if (!paramType.isAssignableFrom(componentType) && !InheritanceUtil.isInheritor(
componentType, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS)
) {
if (componentType.equalsToText(JAVA_LANG_STRING)) {
//implicit conversion to primitive/wrapper
if (TypeConversionUtil.isPrimitiveAndNotNullOrWrapper(paramType)) return
val psiClass = PsiUtil.resolveClassInClassTypeOnly(paramType)
//implicit conversion to enum
if (psiClass != null) {
if (psiClass.isEnum && psiClass.findFieldByName((attributeValue as PsiLiteral).value as String?, false) != null) return
//implicit java time conversion
val qualifiedName = psiClass.qualifiedName
if (qualifiedName != null) {
if (qualifiedName.startsWith("java.time.")) return
if (qualifiedName == "java.nio.file.Path") return
}
val factoryMethod: (PsiMethod) -> Boolean = {
!it.hasModifier(JvmModifier.PRIVATE) &&
it.parameterList.parametersCount == 1 &&
it.parameterList.parameters.first().type.equalsToText(JAVA_LANG_STRING)
}
if (!psiClass.hasModifier(JvmModifier.ABSTRACT) && psiClass.constructors.find(factoryMethod) != null) return
if (psiClass.methods.find { it.hasModifier(JvmModifier.STATIC) && factoryMethod(it) } != null) return
}
}
else if (componentType.equalsToText(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_ENUM)) {
val psiClass = PsiUtil.resolveClassInClassTypeOnly(paramType)
if (psiClass != null && psiClass.isEnum) return
}
val param = parameters.first()
val default = param.sourcePsi as PsiNameIdentifierOwner
val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue
else default.nameIdentifier ?: default).toUElement()?.sourcePsi ?: return
if (param.findAnnotation(ORG_JUNIT_JUPITER_PARAMS_CONVERTER_CONVERT_WITH) != null) return
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.param.method.source.assignable.descriptor",
componentType.presentableText, paramType.presentableText
)
holder.registerProblem(place, message)
}
}
}
private fun checkValuesSource(method: UMethod, valuesSource: PsiAnnotation) {
val psiMethod = method.javaPsi
val possibleValues = mapOf(
"strings" to PsiType.getJavaLangString(psiMethod.manager, psiMethod.resolveScope),
"ints" to PsiType.INT,
"longs" to PsiType.LONG,
"doubles" to PsiType.DOUBLE,
"shorts" to PsiType.SHORT,
"bytes" to PsiType.BYTE,
"floats" to PsiType.FLOAT,
"chars" to PsiType.CHAR,
"booleans" to PsiType.BOOLEAN,
"classes" to PsiType.getJavaLangClass(psiMethod.manager, psiMethod.resolveScope)
)
possibleValues.keys.forEach { valueKey ->
valuesSource.nestedAttributeValues(valueKey)?.forEach { value ->
possibleValues[valueKey]?.let { checkSourceTypeAndParameterTypeAgree(method, value, it) }
}
}
val attributesNumber = valuesSource.parameterList.attributes.size
val annotation = (if (method.javaPsi.isAncestor(valuesSource, true)) valuesSource
else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElementOfType<UAnnotation>() ?: return
val message = if (attributesNumber == 0) {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.no.value.source.is.defined.descriptor")
}
else if (attributesNumber > 1) {
JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.param.exactly.one.type.of.input.must.be.provided.descriptor")
}
else return
return holder.registerUProblem(annotation, message)
}
private fun checkEnumConstants(enumSource: PsiAnnotation, enumType: PsiType, method: UMethod) {
val mode = enumSource.findAttributeValue("mode")
val uMode = mode.toUElement()
if (uMode is UReferenceExpression && ("INCLUDE" == uMode.resolvedName || "EXCLUDE" == uMode.resolvedName)) {
var validType = enumType
if (enumType.canonicalText == ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_ENUM) {
val parameters = method.uastParameters
if (parameters.isNotEmpty()) validType = parameters.first().type
}
val allEnumConstants = (PsiUtil.resolveClassInClassTypeOnly(validType) ?: return).fields
.filterIsInstance<PsiEnumConstant>()
.map { it.name }
.toSet()
val definedConstants = mutableSetOf<String>()
enumSource.nestedAttributeValues("names")?.forEach { name ->
if (name is PsiLiteralExpression) {
val value = name.value
if (value is String) {
val sourcePsi = (if (method.javaPsi.isAncestor(name, true)) name
else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return@forEach
val message = if (!allEnumConstants.contains(value)) {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.unresolved.enum.descriptor")
}
else if (!definedConstants.add(value)) {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.duplicated.enum.descriptor")
}
else return@forEach
holder.registerProblem(sourcePsi, message)
}
}
}
}
}
private fun checkCsvSource(methodSource: PsiAnnotation) {
methodSource.nestedAttributeValues("resources")?.forEach { attributeValue ->
for (ref in attributeValue.references) {
if (ref.isSoft) continue
if (ref is FileReference && ref.multiResolve(false).isEmpty()) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.file.source.descriptor", attributeValue.text)
holder.registerProblem(ref.element, message, *ref.quickFixes)
}
}
}
}
private fun PsiAnnotation.nestedAttributeValues(value: String) = findAttributeValue(value)?.nestedValues()
private fun PsiAnnotationMemberValue.nestedValues(): List<PsiAnnotationMemberValue> {
return if (this is PsiArrayInitializerMemberValue) initializers.flatMap { it.nestedValues() } else listOf(this)
}
class AnnotatedSignatureProblem(
private val annotations: List<String>,
private val shouldBeStatic: Boolean? = null,
private val shouldBeInTestInstancePerClass: Boolean = false,
private val shouldBeVoidType: Boolean? = null,
private val shouldBeSubTypeOf: List<String>? = null,
private val validVisibility: ((UDeclaration) -> UastVisibility?)? = null,
private val validParameters: ((UMethod) -> List<UParameter>?)? = null,
) {
private fun modifierProblems(
validVisibility: UastVisibility?, decVisibility: UastVisibility, isStatic: Boolean, isInstancePerClass: Boolean
): List<@NlsSafe String> {
val problems = mutableListOf<String>()
if (shouldBeInTestInstancePerClass) { if (!isStatic && !isInstancePerClass) problems.add("static") }
else if (shouldBeStatic == true && !isStatic) problems.add("static")
else if (shouldBeStatic == false && isStatic) problems.add("non-static")
if (validVisibility != null && validVisibility != decVisibility) problems.add(validVisibility.text)
return problems
}
fun report(holder: ProblemsHolder, element: UField) {
val javaPsi = element.javaPsi.asSafely<PsiField>() ?: return
val annotation = annotations
.firstOrNull { MetaAnnotationUtil.isMetaAnnotated(javaPsi, annotations) }
?.substringAfterLast(".") ?: return
val visibility = validVisibility?.invoke(element)
val problems = modifierProblems(visibility, element.visibility, element.isStatic, false)
if (shouldBeVoidType == true && element.type != PsiType.VOID) {
return holder.fieldTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name)
}
if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.type, it) } == false) {
return holder.fieldTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first())
}
if (problems.isNotEmpty()) return holder.fieldModifierProblem(element, visibility, annotation, problems)
}
private fun ProblemsHolder.fieldModifierProblem(
element: UField, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>
) {
val message = if (problems.size == 1) {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.single.descriptor", FIELD, annotation, problems.first())
} else {
JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.double.descriptor", FIELD, annotation, problems.first(), problems.last()
)
}
reportFieldProblem(message, element, visibility)
}
private fun ProblemsHolder.fieldTypeProblem(
element: UField, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String
) {
if (problems.isEmpty()) {
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.typed.descriptor", FIELD, annotation, type)
registerUProblem(element, message)
}
else if (problems.size == 1) {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.single.typed.descriptor", FIELD,
annotation, problems.first(), type
)
reportFieldProblem(message, element, visibility)
} else {
val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.double.typed.descriptor", FIELD,
annotation, problems.first(), problems.last(), type
)
reportFieldProblem(message, element, visibility)
}
}
private fun ProblemsHolder.reportFieldProblem(message: @InspectionMessage String, element: UField, visibility: UastVisibility?) {
val quickFix = FieldSignatureQuickfix(element.name, shouldBeStatic, visibilityToModifier[visibility])
return registerUProblem(element, message, quickFix)
}
fun report(holder: ProblemsHolder, element: UMethod) {
val javaPsi = element.javaPsi.asSafely<PsiMethod>() ?: return
val sourcePsi = element.sourcePsi ?: return
val annotation = annotations
.firstOrNull { AnnotationUtil.isAnnotated(javaPsi, it, AnnotationUtil.CHECK_HIERARCHY) }
?.substringAfterLast('.') ?: return
val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java))
val elementIsStatic = alternatives.any { it.isStatic }
val visibility = validVisibility?.invoke(element)
val params = validParameters?.invoke(element)
val problems = modifierProblems(
visibility, element.visibility, elementIsStatic, javaPsi.containingClass?.let { cls -> TestUtils.testInstancePerClass(cls) } == true
)
if (element.lang == Language.findLanguageByID("kotlin") && element.javaPsi.modifierList.text.contains("suspend")) {
val message = JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.suspend.function.descriptor", annotation
)
return holder.registerUProblem(element, message)
}
if (params != null && params.size != element.uastParameters.size) {
if (shouldBeVoidType == true && element.returnType != PsiType.VOID) {
return holder.methodParameterTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name, params)
}
if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.returnType, it) } == false) {
return holder.methodParameterTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first(), params)
}
return holder.methodParameterProblem(element, visibility, annotation, problems, params)
}
if (shouldBeVoidType == true && element.returnType != PsiType.VOID) {
return holder.methodTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name)
}
if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.returnType, it) } == false) {
return holder.methodTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first())
}
if (problems.isNotEmpty()) return holder.methodModifierProblem(element, visibility, annotation, problems)
}
private fun ProblemsHolder.methodParameterProblem(
element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, parameters: List<UParameter>
) {
val invalidParams = element.uastParameters.toMutableList().apply { removeAll(parameters) }
val message = when {
problems.isEmpty() && invalidParams.size == 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.param.single.descriptor", annotation, invalidParams.first().name
)
problems.isEmpty() && invalidParams.size > 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.param.double.descriptor",
annotation, invalidParams.joinToString { "'$it'" }, invalidParams.last().name
)
problems.size == 1 && invalidParams.size == 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.single.param.single.descriptor",
annotation, problems.first(), invalidParams.first().name
)
problems.size == 1 && invalidParams.size > 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.single.param.double.descriptor",
annotation, problems.first(), invalidParams.joinToString { "'$it'" },
invalidParams.last().name
)
problems.size == 2 && invalidParams.size == 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.double.param.single.descriptor",
annotation, problems.first(), problems.last(), invalidParams.first().name
)
problems.size == 2 && invalidParams.size > 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.double.param.double.descriptor",
annotation, problems.first(), problems.last(), invalidParams.joinToString { "'$it'" },
invalidParams.last().name
)
else -> error("Non valid problem.")
}
reportMethodProblem(message, element, visibility)
}
private fun ProblemsHolder.methodParameterTypeProblem(
element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String,
parameters: List<UParameter>
) {
val invalidParams = element.uastParameters.toMutableList().apply { removeAll(parameters) }
val message = when {
problems.isEmpty() && invalidParams.size == 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.typed.param.single.descriptor",
annotation, type, invalidParams.first().name
)
problems.isEmpty() && invalidParams.size > 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.typed.param.double.descriptor",
annotation, type, invalidParams.joinToString { "'$it'" }, invalidParams.last().name
)
problems.size == 1 && invalidParams.size == 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.single.typed.param.single.descriptor",
annotation, problems.first(), type, invalidParams.first().name
)
problems.size == 1 && invalidParams.size > 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.single.typed.param.double.descriptor",
annotation, problems.first(), type, invalidParams.joinToString { "'$it'" },
invalidParams.last().name
)
problems.size == 2 && invalidParams.size == 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.double.typed.param.single.descriptor",
annotation, problems.first(), problems.last(), type, invalidParams.first().name
)
problems.size == 2 && invalidParams.size > 1 -> JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.method.double.typed.param.double.descriptor",
annotation, problems.first(), problems.last(), type, invalidParams.joinToString { "'$it'" },
invalidParams.last().name
)
else -> error("Non valid problem.")
}
reportMethodProblem(message, element, visibility)
}
private fun ProblemsHolder.methodTypeProblem(
element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String
) {
val message = if (problems.isEmpty()) {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.typed.descriptor", METHOD, annotation, type)
} else if (problems.size == 1) {
JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.single.typed.descriptor", METHOD, annotation, problems.first(), type
)
} else {
JvmAnalysisBundle.message(
"jvm.inspections.junit.malformed.annotated.double.typed.descriptor", METHOD, annotation, problems.first(), problems.last(), type
)
}
reportMethodProblem(message, element, visibility)
}
private fun ProblemsHolder.methodModifierProblem(
element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>
) {
val message = if (problems.size == 1) {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.single.descriptor", METHOD, annotation, problems.first())
} else {
JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.double.descriptor", METHOD,
annotation, problems.first(), problems.last()
)
}
reportMethodProblem(message, element, visibility)
}
private fun ProblemsHolder.reportMethodProblem(message: @InspectionMessage String,
element: UMethod,
visibility: UastVisibility? = null,
params: List<UParameter>? = null) {
val quickFix = MethodSignatureQuickfix(
element.name, shouldBeStatic, shouldBeVoidType, visibilityToModifier[visibility],
params?.associate { it.name to it.type } ?: emptyMap()
)
return registerUProblem(element, message, quickFix)
}
}
private class ClassSignatureQuickFix(
private val name: @NlsSafe String,
private val makeStatic: Boolean,
private val makePublic: Boolean,
) : LocalQuickFix {
override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.class.signature")
override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.class.signature.descriptor", name)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val containingFile = descriptor.psiElement.containingFile ?: return
val javaDeclaration = getUParentForIdentifier(descriptor.psiElement)?.asSafely<UClass>()?.javaPsi ?: return
val declPtr = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(javaDeclaration)
declPtr.element?.asSafely<JvmModifiersOwner>()?.let { jvmMethod ->
createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic)).forEach {
it.invoke(project, null, containingFile)
}
}
declPtr.element?.asSafely<JvmModifiersOwner>()?.let { jvmMethod ->
createModifierActions(jvmMethod, modifierRequest(JvmModifier.PUBLIC, makePublic)).forEach {
it.invoke(project, null, containingFile)
}
}
}
}
private class FieldSignatureQuickfix(
private val name: @NlsSafe String,
private val makeStatic: Boolean?,
private val newVisibility: JvmModifier? = null
) : LocalQuickFix {
override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.field.signature")
override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.field.signature.descriptor", name)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val containingFile = descriptor.psiElement.containingFile ?: return
val javaDeclaration = getUParentForIdentifier(descriptor.psiElement)?.asSafely<UField>()?.javaPsi ?: return
val declPtr = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(javaDeclaration)
if (newVisibility != null) {
declPtr.element?.asSafely<JvmModifiersOwner>()?.let { jvmMethod ->
createModifierActions(jvmMethod, modifierRequest(newVisibility, true)).forEach {
it.invoke(project, null, containingFile)
}
}
}
if (makeStatic != null) {
declPtr.element?.asSafely<JvmModifiersOwner>()?.let { jvmMethod ->
createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic)).forEach {
it.invoke(project, null, containingFile)
}
}
}
}
}
private class MethodSignatureQuickfix(
private val name: @NlsSafe String,
private val makeStatic: Boolean?,
private val shouldBeVoidType: Boolean? = null,
private val newVisibility: JvmModifier? = null,
@SafeFieldForPreview private val inCorrectParams: Map<String, JvmType>? = null
) : LocalQuickFix {
override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.method.signature")
override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.method.signature.descriptor", name)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val containingFile = descriptor.psiElement.containingFile ?: return
val javaDeclaration = getUParentForIdentifier(descriptor.psiElement)?.asSafely<UMethod>()?.javaPsi ?: return
val declPtr = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(javaDeclaration)
if (shouldBeVoidType == true) {
declPtr.element?.let { jvmMethod ->
createChangeTypeActions(jvmMethod, typeRequest(JvmPrimitiveTypeKind.VOID.name, emptyList())).forEach {
it.invoke(project, null, containingFile)
}
}
}
if (newVisibility != null) {
declPtr.element?.let { jvmMethod ->
createModifierActions(jvmMethod, modifierRequest(newVisibility, true)).forEach {
it.invoke(project, null, containingFile)
}
}
}
if (inCorrectParams != null) {
declPtr.element?.let { jvmMethod ->
createChangeParametersActions(jvmMethod, setMethodParametersRequest(inCorrectParams.entries)).forEach {
it.invoke(project, null, containingFile)
}
}
}
if (makeStatic != null) {
declPtr.element?.let { jvmMethod ->
createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic)).forEach {
it.invoke(project, null, containingFile)
}
}
}
}
}
private companion object {
// message choices
const val FIELD = 0
const val METHOD = 1
const val SINGLE = 0
const val DOUBLE = 1
const val TEST_INSTANCE_PER_CLASS = "@org.junit.jupiter.api.TestInstance(TestInstance.Lifecycle.PER_CLASS)"
const val METHOD_SOURCE_RETURN_TYPE = "java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments>"
val visibilityToModifier = mapOf(
UastVisibility.PUBLIC to JvmModifier.PUBLIC,
UastVisibility.PROTECTED to JvmModifier.PROTECTED,
UastVisibility.PRIVATE to JvmModifier.PRIVATE,
UastVisibility.PACKAGE_LOCAL to JvmModifier.PACKAGE_LOCAL
)
val singleParamProviders = listOf(
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE
)
val multipleParameterProviders = listOf(
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_SOURCE
)
val nonCombinedTests = listOf(
ORG_JUNIT_JUPITER_API_TEST,
ORG_JUNIT_JUPITER_API_TEST_FACTORY,
ORG_JUNIT_JUPITER_API_REPEATED_TEST,
ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST
)
val parameterizedSources = listOf(
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE,
ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE
)
}
}
| apache-2.0 | 841baf22cc2e2a8fd0195e7321132d36 | 48.908526 | 140 | 0.71664 | 4.759634 | false | true | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenProjectImporter.kt | 2 | 4888 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.importing
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.idea.maven.importing.tree.MavenProjectTreeLegacyImporter
import org.jetbrains.idea.maven.importing.workspaceModel.WorkspaceProjectImporter
import org.jetbrains.idea.maven.project.*
import org.jetbrains.idea.maven.utils.MavenLog
import java.util.concurrent.atomic.AtomicInteger
@ApiStatus.Internal
interface MavenProjectImporter {
fun importProject(): List<MavenProjectsProcessorTask>?
fun createdModules(): List<Module>
companion object {
@JvmStatic
fun createImporter(project: Project,
projectsTree: MavenProjectsTree,
projectsToImportWithChanges: Map<MavenProject, MavenProjectChanges>,
importModuleGroupsRequired: Boolean,
modelsProvider: IdeModifiableModelsProvider,
importingSettings: MavenImportingSettings,
previewModule: Module?,
importingActivity: StructuredIdeActivity): MavenProjectImporter {
val importer = createImporter(project, projectsTree, projectsToImportWithChanges, importModuleGroupsRequired, modelsProvider,
importingSettings, previewModule)
return object : MavenProjectImporter {
override fun importProject(): List<MavenProjectsProcessorTask>? {
val activity = MavenImportStats.startApplyingModelsActivity(project, importingActivity)
val startTime = System.currentTimeMillis()
try {
importingInProgress.incrementAndGet()
return importer.importProject()
}
finally {
importingInProgress.decrementAndGet()
activity.finished()
MavenLog.LOG.info(
"[maven import] applying models to workspace model took ${System.currentTimeMillis() - startTime}ms")
}
}
override fun createdModules(): List<Module> {
return importer.createdModules()
}
}
}
private fun createImporter(project: Project,
projectsTree: MavenProjectsTree,
projectsToImportWithChanges: Map<MavenProject, MavenProjectChanges>,
importModuleGroupsRequired: Boolean,
modelsProvider: IdeModifiableModelsProvider,
importingSettings: MavenImportingSettings,
previewModule: Module?): MavenProjectImporter {
if (isImportToWorkspaceModelEnabled(project)) {
return WorkspaceProjectImporter(projectsTree, projectsToImportWithChanges,
importingSettings, modelsProvider, project)
}
if (isLegacyImportToTreeStructureEnabled(project)) {
return MavenProjectTreeLegacyImporter(project, projectsTree, projectsToImportWithChanges,
modelsProvider, importingSettings)
}
return MavenProjectLegacyImporter(project, projectsTree,
projectsToImportWithChanges,
importModuleGroupsRequired,
modelsProvider, importingSettings,
previewModule)
}
@JvmStatic
fun tryUpdateTargetFolders(project: Project) {
if (isImportToWorkspaceModelEnabled(project)) {
WorkspaceProjectImporter.updateTargetFolders(project)
}
else {
MavenLegacyFoldersImporter.updateProjectFolders(/* project = */ project, /* updateTargetFoldersOnly = */ true)
}
}
private val importingInProgress = AtomicInteger()
@JvmStatic
fun isImportingInProgress(): Boolean {
return importingInProgress.get() > 0
}
@JvmStatic
fun isImportToWorkspaceModelEnabled(project: Project?): Boolean {
val property = System.getProperty("maven.import.to.workspace.model")
if ("true" == property) return true
if ("false" == property) return false
if (project == null) return false
return MavenProjectsManager.getInstance(project).importingSettings.isWorkspaceImportEnabled
}
@JvmStatic
fun isLegacyImportToTreeStructureEnabled(project: Project?): Boolean {
if (isImportToWorkspaceModelEnabled(project)) return false
return "true" == System.getProperty("maven.import.use.tree.import")
}
}
} | apache-2.0 | e6003afc77f018abed65d5cbefc93ce7 | 43.045045 | 131 | 0.661007 | 5.990196 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/psi/PsiDocumentationLinkResolver.kt | 1 | 1558 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.documentation.psi
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol
import com.intellij.lang.documentation.*
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
internal class PsiDocumentationLinkResolver : DocumentationLinkResolver {
override fun resolveLink(target: DocumentationTarget, url: String): LinkResult? {
if (target !is PsiElementDocumentationTarget) {
return null
}
val element = target.targetElement
if (url.startsWith(DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL)) {
val project = element.project
val (resolved, anchor) = DocumentationManager.targetAndRef(project, url, element)
?: return null
return LinkResult.resolvedTarget(PsiElementDocumentationTarget(project, resolved, sourceElement = null, anchor))
}
val provider = DocumentationManager.getProviderFromElement(element)
if (provider is CompositeDocumentationProvider) {
for (p in provider.allProviders) {
if (p !is ExternalDocumentationHandler) {
continue
}
if (p.canFetchDocumentationLink(url)) {
return LinkResult.resolvedTarget(PsiExternalDocumentationHandlerTarget(p, url, element))
}
}
}
return null
}
}
| apache-2.0 | 453876f349d7f00d3024b8ea530ba835 | 42.277778 | 158 | 0.742619 | 4.853583 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterFromUsageFix.kt | 3 | 7922 | // 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.quickfix.createFromUsage.createTypeParameter
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.ElementDescriptionUtil
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.usageView.UsageViewTypeLocation
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.addTypeParameter
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.intentions.InsertExplicitTypeArgumentsIntention
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.TypeProjectionImpl
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.isNullableAny
import org.jetbrains.kotlin.utils.SmartList
class CreateTypeParameterFromUsageFix(
originalElement: KtElement,
private val data: CreateTypeParameterData,
private val presentTypeParameterNames: Boolean
) : CreateFromUsageFixBase<KtElement>(originalElement) {
override fun getText(): String {
val prefix = KotlinBundle.message("text.type.parameter", data.typeParameters.size)
val typeParametersText = if (presentTypeParameterNames) data.typeParameters.joinToString(prefix = " ") { "'${it.name}'" } else ""
val containerText = ElementDescriptionUtil.getElementDescription(data.declaration, UsageViewTypeLocation.INSTANCE) +
" '${data.declaration.name}'"
return KotlinBundle.message("create.0.in.1", prefix + typeParametersText, containerText)
}
override fun startInWriteAction() = false
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
doInvoke()
}
fun doInvoke(): List<KtTypeParameter> {
val declaration = data.declaration
if (!declaration.isWritable) return emptyList()
val project = declaration.project
val usages = project.runSynchronouslyWithProgress(KotlinBundle.message("searching.0", declaration.name.toString()), true) {
runReadAction {
val expectedTypeArgumentCount = declaration.typeParameters.size + data.typeParameters.size
ReferencesSearch
.search(declaration)
.mapNotNull {
it.element.getParentOfTypeAndBranch<KtUserType> { referenceExpression }
?: it.element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
}
.filter {
val arguments = when (it) {
is KtUserType -> it.typeArguments
is KtCallElement -> it.typeArguments
else -> return@filter false
}
arguments.size != expectedTypeArgumentCount
}
.toSet()
}
} ?: return emptyList()
return runWriteAction {
val psiFactory = KtPsiFactory(project)
val elementsToShorten = SmartList<KtElement>()
val newTypeParameters = data.typeParameters.map { typeParameter ->
val upperBoundType = typeParameter.upperBoundType
val upperBoundText = if (upperBoundType != null && !upperBoundType.isNullableAny()) {
IdeDescriptorRenderers.SOURCE_CODE.renderType(upperBoundType)
} else null
val upperBound = upperBoundText?.let { psiFactory.createType(it) }
val typeParameterName = typeParameter.name.quoteIfNeeded()
val newTypeParameterText = if (upperBound != null) "$typeParameterName : ${upperBound.text}" else typeParameterName
val newTypeParameter = declaration.addTypeParameter(psiFactory.createTypeParameter(newTypeParameterText))
?: error("Couldn't create type parameter from '$newTypeParameterText' for '$declaration'")
elementsToShorten += newTypeParameter
val anonymizedTypeParameter = createFakeTypeParameterDescriptor(
typeParameter.fakeTypeParameter.containingDeclaration, "_", typeParameter.fakeTypeParameter.storageManager
)
val anonymizedUpperBoundText = upperBoundType?.let {
TypeSubstitutor.create(
mapOf(
typeParameter.fakeTypeParameter.typeConstructor to TypeProjectionImpl(
anonymizedTypeParameter.defaultType
)
)
)
.substitute(upperBoundType, Variance.INVARIANT)
}?.let {
IdeDescriptorRenderers.SOURCE_CODE.renderType(it)
}
val anonymizedUpperBoundAsTypeArg = psiFactory.createTypeArgument(anonymizedUpperBoundText ?: "kotlin.Any?")
val callsToExplicateArguments = SmartList<KtCallElement>()
usages.forEach {
when (it) {
is KtUserType -> {
val typeArgumentList = it.typeArgumentList
elementsToShorten += typeArgumentList?.addArgument(anonymizedUpperBoundAsTypeArg) ?: it.addAfter(
psiFactory.createTypeArguments("<${anonymizedUpperBoundAsTypeArg.text}>"),
it.referenceExpression!!
) as KtTypeArgumentList
}
is KtCallElement -> {
if (it.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS).diagnostics.forElement(it.calleeExpression!!)
.any { diagnostic -> diagnostic.factory in Errors.TYPE_INFERENCE_ERRORS }
) {
callsToExplicateArguments += it
}
}
}
}
callsToExplicateArguments.forEach {
val typeArgumentList = it.typeArgumentList
elementsToShorten += if (typeArgumentList == null) {
InsertExplicitTypeArgumentsIntention.applyTo(it, shortenReferences = false)
val newTypeArgument = it.typeArguments.lastOrNull()
if (anonymizedUpperBoundText != null && newTypeArgument != null && newTypeArgument.text == "kotlin.Any") {
newTypeArgument.replaced(anonymizedUpperBoundAsTypeArg)
}
it.typeArgumentList
} else {
typeArgumentList.addArgument(anonymizedUpperBoundAsTypeArg)
}
}
newTypeParameter
}
ShortenReferences.DEFAULT.process(elementsToShorten)
newTypeParameters
}
}
} | apache-2.0 | e50437603f3debb53b2099299a0a7806 | 50.116129 | 158 | 0.625852 | 6.06585 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/AbstractPullPushMembersHandler.kt | 6 | 4224 | // 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.refactoring
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.lang.ElementsHandler
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
abstract class AbstractPullPushMembersHandler(
@Nls private val refactoringName: String,
private val helpId: String,
@NlsContexts.DialogMessage private val wrongPositionMessage: String
) : RefactoringActionHandler, ElementsHandler {
private fun reportWrongPosition(project: Project, editor: Editor?) {
val message = RefactoringBundle.getCannotRefactorMessage(wrongPositionMessage)
CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId)
}
private fun KtParameter.getContainingClass() =
if (hasValOrVar()) (ownerFunction as? KtPrimaryConstructor)?.containingClassOrObject else null
protected fun reportWrongContext(project: Project, editor: Editor?) {
val message = RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message("is.not.supported.in.the.current.context", refactoringName)
)
CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId)
}
protected abstract operator fun invoke(
project: Project,
editor: Editor?,
classOrObject: KtClassOrObject?,
member: KtNamedDeclaration?,
dataContext: DataContext?
)
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
val offset = editor.caretModel.offset
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
val target = (file.findElementAt(offset) ?: return).parentsWithSelf.firstOrNull {
it is KtClassOrObject
|| ((it is KtNamedFunction || it is KtProperty) && it.parent is KtClassBody)
|| it is KtParameter && it.hasValOrVar() && it.ownerFunction is KtPrimaryConstructor
}
if (target == null) {
reportWrongPosition(project, editor)
return
}
if (!target.canRefactor()) return
invoke(project, arrayOf(target), dataContext)
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) {
val element = elements.singleOrNull() ?: return
val editor = dataContext?.let { CommonDataKeys.EDITOR.getData(it) }
val (classOrObject, member) = when (element) {
is KtNamedFunction, is KtProperty -> element.getStrictParentOfType<KtClassOrObject>() to element as KtNamedDeclaration?
is KtParameter -> element.getContainingClass() to element
is KtClassOrObject -> element to null
else -> {
reportWrongPosition(project, editor)
return
}
}
invoke(project, editor, classOrObject, member, dataContext)
}
override fun isEnabledOnElements(elements: Array<out PsiElement>): Boolean {
return elements.mapTo(HashSet<PsiElement>()) {
when (it) {
is KtNamedFunction, is KtProperty -> (it.parent as? KtClassBody)?.parent as? KtClassOrObject
is KtParameter -> it.getContainingClass()
is KtClassOrObject -> it
else -> null
} ?: return false
}.size == 1
}
}
| apache-2.0 | daf1a4ca562dba85c7ac6d94b8b8c642 | 42.102041 | 158 | 0.70786 | 5.195572 | false | false | false | false |
shalupov/idea-cloudformation | src/main/kotlin/com/intellij/aws/cloudformation/ParameterPropertyNameMatch.kt | 2 | 997 | package com.intellij.aws.cloudformation
import com.intellij.aws.cloudformation.model.CfnNameValueNode
import com.intellij.aws.cloudformation.model.CfnParameterNode
import com.intellij.aws.cloudformation.model.CfnScalarValueNode
import com.intellij.psi.PsiElement
class ParameterPropertyNameMatch private constructor(
val name: CfnScalarValueNode,
val property: CfnNameValueNode,
val parameter: CfnParameterNode) {
companion object {
fun match(position: PsiElement, parsed: CloudFormationParsedFile): ParameterPropertyNameMatch? {
val nameNode = parsed.getCfnNodes(position).ofType<CfnScalarValueNode>().singleOrNull() ?: return null
val propertyNode = nameNode.parent(parsed) as? CfnNameValueNode ?: return null
val parameterNode = propertyNode.parent(parsed) as? CfnParameterNode ?: return null
if (propertyNode.name == nameNode) {
return ParameterPropertyNameMatch(nameNode, propertyNode, parameterNode)
}
return null
}
}
} | apache-2.0 | a4bbdb6d6a43137fafcba51313d89a2d | 38.92 | 108 | 0.774323 | 4.59447 | false | false | false | false |
vivchar/RendererRecyclerViewAdapter | example/src/main/java/com/github/vivchar/example/pages/simple/PayloadFragment.kt | 1 | 3007 | package com.github.vivchar.example.pages.simple
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.vivchar.example.BaseScreenFragment
import com.github.vivchar.example.R
import com.github.vivchar.example.widgets.ItemOffsetDecoration
import com.github.vivchar.example.widgets.MyAdapter
import com.github.vivchar.rendererrecyclerviewadapter.*
/**
* Created by Vivchar Vitaly on 12/29/17.
*/
class PayloadFragment : BaseScreenFragment() {
private val yourDataProvider = YourDataProvider()
private var adapter: RendererRecyclerViewAdapter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.fragment_list, container, false)
adapter = MyAdapter()
adapter?.setDiffCallback(PayloadDiffCallback())
adapter?.registerRenderer(
ViewRenderer<PayloadViewModel, ViewFinder>(
R.layout.item_payload_square,
PayloadViewModel::class.java
) { model, finder, payloads: List<Any> ->
finder.setOnClickListener(R.id.text) { changeItem(model) }
val textView = finder.find<TextView>(R.id.text)
if (payloads.isEmpty()) {
/* full bind */
textView.text = model.text
finder.setText(R.id.desciption, model.description)
} else {
/* partially bind */
val payload = payloads[0]
if (payload == TEXT_CHANGED) {
textView.rotation = 0f
textView.animate().rotation(360f).start()
textView.text = model.text
} else if (payload == DESCRIPTION_CHANGED) {
finder.setText(R.id.desciption, model.description)
}
}
}
)
// adapter.registerRenderer(...);
// adapter.registerRenderer(...);
adapter?.setItems(yourDataProvider.payloadItems)
val recyclerView = view.findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.adapter = adapter
recyclerView.layoutManager = GridLayoutManager(context, 3)
recyclerView.addItemDecoration(ItemOffsetDecoration(10))
return view
}
private fun changeItem(model: PayloadViewModel) {
adapter?.setItems(yourDataProvider.getChangedPayloadItems(model))
}
private inner class PayloadDiffCallback : DefaultDiffCallback<PayloadViewModel>() {
override fun areItemsTheSame(oldItem: PayloadViewModel, newItem: PayloadViewModel): Boolean {
return oldItem.id == newItem.id
}
override fun getChangePayload(oldItem: PayloadViewModel, newItem: PayloadViewModel): Any? {
return when {
oldItem.text != newItem.text -> TEXT_CHANGED
oldItem.description != newItem.description -> DESCRIPTION_CHANGED
else -> super.getChangePayload(oldItem, newItem)
}
}
}
data class PayloadViewModel(val id: Int, val text: String, val description: String) : ViewModel
companion object {
const val TEXT_CHANGED = 1
const val DESCRIPTION_CHANGED = 2
}
} | apache-2.0 | 21b42842b82c671e749394212ad3024d | 33.181818 | 112 | 0.75158 | 3.875 | false | false | false | false |
aosp-mirror/platform_frameworks_support | navigation/runtime/ktx/src/main/java/androidx/navigation/ActivityNavigatorDestinationBuilder.kt | 1 | 2018 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
package androidx.navigation
import android.app.Activity
import android.content.ComponentName
import android.net.Uri
import android.support.annotation.IdRes
import kotlin.reflect.KClass
/**
* Construct a new [ActivityNavigator.Destination]
*/
inline fun NavGraphBuilder.activity(
@IdRes id: Int,
block: ActivityNavigatorDestinationBuilder.() -> Unit
) = destination(ActivityNavigatorDestinationBuilder(
provider[ActivityNavigator::class],
id
).apply(block))
/**
* DSL for constructing a new [ActivityNavigator.Destination]
*/
@NavDestinationDsl
class ActivityNavigatorDestinationBuilder(
navigator: ActivityNavigator,
@IdRes id: Int
) : NavDestinationBuilder<ActivityNavigator.Destination>(navigator, id) {
private val context = navigator.context
var activityClass: KClass<out Activity>? = null
var action: String? = null
var data: Uri? = null
var dataPattern: String? = null
override fun build(): ActivityNavigator.Destination =
super.build().also { destination ->
activityClass?.let { clazz ->
destination.setComponentName(ComponentName(context, clazz.java))
}
destination.action = action
destination.data = data
destination.dataPattern = dataPattern
}
}
| apache-2.0 | 2fb8697cbe1e2da9f4eda90124b00543 | 30.046154 | 84 | 0.698712 | 4.660508 | false | false | false | false |
bixlabs/bkotlin | bkotlin/src/main/java/com/bixlabs/bkotlin/String.kt | 1 | 1051 | package com.bixlabs.bkotlin
import android.util.Patterns
import java.util.regex.Pattern
/**
* Short for `foo: String = ""`
*/
fun String.Companion.EMPTY(): String = ""
/**
* Returns true if this string is not empty nor composed by whitespaces
*/
fun String.isNotBlankOrEmpty(): Boolean = !this.isEmpty() || !all { it.isWhitespace() }
/**
* Returns true if this string is a valid URL
*/
fun String.isValidUrl() : Boolean = Patterns.WEB_URL.matcher(this.toLowerCase()).matches()
/**
* Returns true if this string contains exactly the provided string.
* This method uses RegEx to evaluate and its case-sensitive. What makes it different from the classic
* [contains] is that it doesn't uses [indexOf], hence it's more performant when used on long char sequences
* and has much higher probabilities of not returning false positives per approximation.
*/
fun String.containsExact(string: String): Boolean =
Pattern.compile("(?<=^|[^a-zA-Z0-9])\\Q$string\\E(?=\$|[^a-zA-Z0-9])")
.matcher(this)
.find() | apache-2.0 | 02463c0b77d9b07ff7a5d4bc156b196a | 34.066667 | 108 | 0.688868 | 3.863971 | false | false | false | false |
Duke1/UnrealMedia | UnrealMedia/app/src/main/java/com/qfleng/um/viewmodel/MainViewModel.kt | 1 | 4134 | package com.qfleng.um.viewmodel
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.qfleng.um.audio.AudioPlayManager
import com.qfleng.um.bean.ArtistMedia
import com.qfleng.um.bean.MediaInfo
import com.qfleng.um.database.AppDbHelper
import com.qfleng.um.database.entity.MusicInfo
import com.qfleng.um.database.entity.StringKeyData
import com.qfleng.um.audio.MusicUtils
import com.qfleng.um.util.coroutines.doAsync
import com.qfleng.um.util.gsonObjectFrom
import com.qfleng.um.util.toJsonString
import java.util.ArrayList
/**
* Created by Duke
*/
class MainViewModel : ViewModel() {
val mediaLd = MutableLiveData<ArrayList<MediaInfo>>()
val artistMediasLd = MutableLiveData<ArrayList<ArtistMedia>>()
fun loadMedias(ctx: Context, loadCache: Boolean = true) {
doAsync(
asyncFunc = suspend {
val result = ArrayList<MediaInfo>()
val list = AppDbHelper.getInstance(ctx).appDataBase.musicInfoDao().loadAll()
if (list.isEmpty() || !loadCache) {
result.addAll(MusicUtils.getMp3Infos(ctx))
//缓存
cacheMediaInfos(ctx, result)
} else {
result.clear()
for (mi in list) {
val tmp = gsonObjectFrom(MediaInfo::class.java, mi.data)
if (null != tmp) result.add(tmp)
}
}
mediaLd.postValue(result)
val artistMedias = ArrayList<ArtistMedia>()
for (mi in result) {
val am = ArtistMedia()
am.artistName = if (mi.artist.isNullOrEmpty()) "未知歌手" else mi.artist!!
if (am.artistCover.isEmpty())
am.artistCover = mi.cover ?: ""
val index = artistMedias.indexOf(am)
if (index >= 0) {
val tmp = artistMedias[index]
tmp.medias.add(mi)
if (tmp.artistCover.isEmpty())
tmp.artistCover = am.artistCover
} else {
am.medias.add(mi)
artistMedias.add(am)
}
}
if (artistMedias.isNotEmpty()) {
artistMediasLd.postValue(artistMedias)
}
result
},
observer = {
Log.e("", "扫描完毕--媒体文件数:${it?.size ?: 0}")
}
)
}
private fun cacheMediaInfos(ctx: Context, list: ArrayList<MediaInfo>) {
val dao = AppDbHelper.getInstance(ctx).appDataBase.musicInfoDao()
val result = ArrayList<MusicInfo>()
for (mi in list) {
val tmp = MusicInfo()
tmp.name = mi.title ?: ""
tmp.path = mi.url ?: ""
tmp.data = mi.toJsonString()
result.add(tmp)
}
dao.deleteAll()
dao.insertAll(result)
}
@SuppressLint("CheckResult")
fun loadLastPlayInfo(ctx: Context) {
doAsync(
asyncFunc = suspend {
val skd = AppDbHelper.getInstance(ctx).appDataBase.stringKeyDataDao().loadByKey(StringKeyData.KEY_LAST_PLAY_AUDIO_URL)
skd?.data ?: ""
},
observer = {
val medias = mediaLd.value
if (null != medias) {
for (mi in medias) {
if (it == mi.url) {
AudioPlayManager.INSTANCE.mediaInfoLd.postValue(mi)
break
}
}
}
}
)
}
} | mit | 6ad079b545369bc563f853cd83f0c30d | 32.104839 | 138 | 0.48806 | 4.974545 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/controller/requests/account/login/login.kt | 1 | 2724 | package koma.controller.requests.account.login
import javafx.scene.control.Alert
import koma.InvalidData
import koma.Server
import koma.koma_app.AppData
import koma.matrix.UserId
import koma.matrix.UserPassword
import koma.util.testFailure
import kotlinx.coroutines.*
import kotlinx.coroutines.javafx.JavaFx
import link.continuum.desktop.action.startChat
import link.continuum.desktop.database.KeyValueStore
import link.continuum.desktop.util.gui.alert
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
/**
* when the login button is clicked
* accept text of text fields as parameters
*/
suspend fun onClickLogin(httpClient: OkHttpClient,
appData: Deferred<AppData>,
userid: UserId, password: String, server: String,
keyValueStore: KeyValueStore
) {
val url = server.toHttpUrlOrNull()
if (url == null) {
alert(Alert.AlertType.ERROR, "Invalid server url",
"$server not parsed")
return
}
keyValueStore.serverToAddress.put(userid.server, server)
val client = Server(url, httpClient)
val token = if (!password.isBlank()) {
getTokenWithPassword(userid, password, keyValueStore, client)
} else {
val t =keyValueStore.userToToken.get(userid.full)
if (t == null) {
GlobalScope.launch(Dispatchers.JavaFx) {
alert(Alert.AlertType.ERROR, "Failed to login as $userid",
"No access token")
}
}
t
}
keyValueStore.activeAccount.put(userid.full)
token ?: return
withContext(Dispatchers.Main) {
startChat(httpClient,
userid, token, url,
keyValueStore,
appData)
}
}
/**
* get token from server
* saves the token to disk
*/
private suspend fun getTokenWithPassword(userid: UserId, password: String,
keyValueStore: KeyValueStore,
server: Server): String? {
val (it, ex, result) = server.login(UserPassword(user = userid.user, password = password))
if (!result.testFailure(it, ex)) {
val u = it.user_id
val t = it.access_token
keyValueStore.userToToken.put(u.full, t)
return t
} else {
val mes = ex.toString()
System.err.println(mes)
val message = if (ex is InvalidData) {
"Does ${server} have a valid JSON API?"
} else mes
GlobalScope.launch(Dispatchers.JavaFx) {
alert(Alert.AlertType.ERROR, "Login Fail with Error",
message)
}
}
return null
}
| gpl-3.0 | efdce9a1a9c14ea180cb6a84f50d3578 | 31.819277 | 94 | 0.620778 | 4.45098 | false | false | false | false |
cmcpasserby/MayaCharm | src/main/kotlin/logconsole/LogConsole.kt | 1 | 1907 | package logconsole
import com.intellij.diagnostic.logging.DefaultLogFilterModel
import mayacomms.LOG_FILENAME_STRING
import resources.PythonStrings
import settings.ProjectSettings
import com.intellij.diagnostic.logging.LogConsoleImpl
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import java.io.File
import java.io.PrintWriter
import java.nio.charset.Charset
class LogConsole(
private val project: Project,
file: File,
charset: Charset,
skippedContents: Long,
title: String,
buildInActions: Boolean,
searchScope: GlobalSearchScope?
) : LogConsoleImpl(project, file, charset, skippedContents, title, buildInActions, searchScope) {
init {
super.setFilterModel(object : DefaultLogFilterModel(project) {
override fun processLine(line: String?): MyProcessingResult {
line ?: return MyProcessingResult(ProcessOutputTypes.STDOUT, false, null)
val checks = line.startsWith(PythonStrings.PYSTDERR.message) || line.startsWith(PythonStrings.PYSTDWRN.message)
val outType = if (checks) ProcessOutputTypes.STDERR else ProcessOutputTypes.STDOUT
return MyProcessingResult(outType, true, null)
}
})
}
override fun isActive(): Boolean {
return true
}
override fun clear() {
super.clear()
val sdk = ProjectSettings.getInstance(project).selectedSdk ?: return
val mayaLogPath = PathManager.getPluginTempPath() + String.format(LOG_FILENAME_STRING, sdk.port)
var writer: PrintWriter? = null
try {
writer = PrintWriter(mayaLogPath)
writer.print("")
writer.close()
} finally {
writer?.close()
}
}
}
| mit | 48c9d346536cb26a93b9e9097e41fade | 32.45614 | 127 | 0.697955 | 4.685504 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/gesture/multiFinger/detector/MultiFingerGestureDetector.kt | 1 | 3460 | /*
* Copyright (C) 2017 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.legacy.gesture.multiFinger.detector
import android.content.Context
import android.view.MotionEvent
class MultiFingerGestureDetector(context: Context, private val gestureListener: OnMultiFingerGestureListener) {
var isTracking: Boolean = false
private set
private var showName: Boolean = false
private var beforeDuration: Int = 0
private val analyzer = MfGestureAnalyzer(context)
private val info = MultiFingerGestureInfo()
fun onTouchEvent(event: MotionEvent): Boolean {
var flag = false
when (event.action and 0xff) {
MotionEvent.ACTION_DOWN -> startTracking(event)
MotionEvent.ACTION_POINTER_DOWN -> startTracking(event)
MotionEvent.ACTION_MOVE -> moveTracking(event)
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
flag = execute()
stopTracking()
}
MotionEvent.ACTION_OUTSIDE, MotionEvent.ACTION_CANCEL -> stopTracking()
}
return flag
}
private fun execute(): Boolean {
if (isTracking) {
isTracking = false
return gestureListener.onGesturePerformed(info)
}
return false
}
private fun moveTracking(motionEvent: MotionEvent) {
if (analyzer.fingers >= 1 && analyzer.isGesture(motionEvent)) {
val gestureData = analyzer.getGesture(motionEvent)
if (gestureData.gestureFlag != 0) {
if (beforeDuration != gestureData.gestureFlag) {
info.fingers = gestureData.gesturePointer
info.trace = gestureData.gestureFlag
if (showName)
gestureListener.onShowGestureName(info)
}
beforeDuration = gestureData.gestureFlag
}
analyzer.unTrackGesture()
analyzer.trackGesture(motionEvent)
}
}
private fun startTracking(event: MotionEvent) {
isTracking = true
info.clear()
beforeDuration = 0
analyzer.trackGesture(event)
}
fun stopTracking() {
isTracking = false
analyzer.unTrackGesture()
gestureListener.onDismissGestureName()
}
fun setShowName(showName: Boolean) {
this.showName = showName
}
fun setSensitivity(sensitivity: Int) {
analyzer.setSensitivity(sensitivity)
}
interface OnMultiFingerGestureListener {
fun onGesturePerformed(info: MultiFingerGestureInfo): Boolean
fun onShowGestureName(info: MultiFingerGestureInfo)
fun onDismissGestureName()
}
companion object {
const val SWIPE_UNKNOWN = 0
const val SWIPE_UP = 1
const val SWIPE_DOWN = 2
const val SWIPE_LEFT = 3
const val SWIPE_RIGHT = 4
}
}
| apache-2.0 | d399214a313b6e4c23aaf724e95b2795 | 31.336449 | 111 | 0.642197 | 4.859551 | false | false | false | false |
battagliandrea/kotlinmvp | app/src/main/java/com/andreadev/kotlinmvp/ui/base/activity/BaseToolbarActivity.kt | 1 | 1050 | package com.andreadev.kotlinmvp.ui.base.activity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.andreadev.kotlinmvp.R
import com.andreadev.poikotlin.ui.base.BaseActivity
/**
* Created by andrea on 14/09/2017.
*/
open class BaseToolbarActivity : BaseActivity() {
private lateinit var toolBarView : View
private lateinit var toolbar : Toolbar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
toolBarView = layoutInflater.inflate(R.layout.toolbar, null)
toolbar = toolBarView.findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val rootView = findViewById(R.id.main_container) as FrameLayout
val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
params.gravity = Gravity.TOP
rootView.addView(toolBarView, params)
}
} | apache-2.0 | 85c98e7850f579f030eb9b98903eb1be | 30.848485 | 119 | 0.757143 | 4.411765 | false | false | false | false |
theostanton/LFGSS | app/src/main/java/com/theostanton/lfgss/listitem/viewholder/CommentViewHolder.kt | 1 | 1790 | package com.theostanton.lfgss.listitem.viewholder
import android.text.Html
import android.text.method.LinkMovementMethod
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.squareup.picasso.Picasso
import com.theostanton.lfgss.R
import com.theostanton.lfgss.api.get.Comment
import com.theostanton.lfgss.global.PicassoImageGetter
import com.theostanton.lfgss.global.ago
import com.theostanton.lfgss.listitem.ListItem
/**
* Created by theostanton on 22/02/16.
*/
class CommentViewHolder(itemView: View) : ListItemViewHolder(itemView) {
val userTextView = itemView.findViewById(R.id.user_textView) as TextView
val commentTextView = itemView.findViewById(R.id.comment_textView) as TextView
val avatarImageView = itemView.findViewById(R.id.avatar_imageview) as ImageView
val agoTextView = itemView.findViewById(R.id.ago_textView) as TextView
override fun setItem(listItem: ListItem) {
super.setItem(listItem)
if (listItem is Comment) {
userTextView.text = listItem.meta.createdBy?.profileName
commentTextView.text = Html.fromHtml(
listItem.html,
PicassoImageGetter(
commentTextView,
commentTextView.resources,
Picasso.with(commentTextView.context)
),
null
)
commentTextView.movementMethod = LinkMovementMethod.getInstance()
agoTextView.text = listItem.meta.created?.ago()
Picasso.with(avatarImageView.context)
.load(listItem.meta.createdBy?.avatar)
.fit().centerCrop()
.into(avatarImageView)
}
}
} | mit | 28a56acd0cd25822754a4b00f5debd36 | 37.106383 | 83 | 0.664246 | 4.798928 | false | false | false | false |
frendyxzc/KotlinNews | video/src/main/java/vip/frendy/video/DetailActivity.kt | 1 | 3287 | package vip.frendy.video
import android.media.MediaPlayer
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.view.ViewGroup
import kotlinx.android.synthetic.main.activity_detail_video.*
import vip.frendy.model.router.Router
import me.frendy.xvideoview.XVideoView
class DetailActivity : FragmentActivity(), XVideoView.VideoViewCallback {
private var videoPath: String? = null
private var videoTitle: String = ""
private var cachedHeight: Int = 0
private var isFullscreen: Boolean = false
private var seekPosition: Int = 0
private val SEEK_POSITION_KEY = "SEEK_POSITION_KEY"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail_video)
videoPath = intent.getStringExtra(Router.VIDEO_PATH)
videoTitle = intent.getStringExtra(Router.VIDEO_TITLE)
xmediaController.attachActivity(this)
xmediaController.setTitle(videoTitle)
videoView.setMediaController(xmediaController)
setVideoAreaSize()
videoView.setVideoViewCallback(this)
videoView.start()
}
override fun onPause() {
super.onPause()
if (videoView != null && videoView.isPlaying()) {
seekPosition = videoView.getCurrentPosition()
videoView.pause()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(SEEK_POSITION_KEY, seekPosition)
}
override fun onRestoreInstanceState(outState: Bundle) {
super.onRestoreInstanceState(outState)
seekPosition = outState.getInt(SEEK_POSITION_KEY)
}
override fun onBackPressed() {
if (this.isFullscreen) {
videoView.setFullscreen(false)
} else {
super.onBackPressed()
}
}
private fun setVideoAreaSize() {
videoLayout.post({
cachedHeight = (videoLayout.getWidth() * 405f / 720f).toInt()
val videoLayoutParams = videoLayout.getLayoutParams()
videoLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
videoLayoutParams.height = cachedHeight
videoLayout.setLayoutParams(videoLayoutParams)
videoView.setVideoPath(videoPath)
videoView.requestFocus()
})
}
override fun onScaleChange(isFullscreen: Boolean) {
this.isFullscreen = isFullscreen
if (isFullscreen) {
val layoutParams = videoLayout.getLayoutParams()
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
videoLayout.setLayoutParams(layoutParams)
} else {
val layoutParams = videoLayout.getLayoutParams()
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
layoutParams.height = this.cachedHeight
videoLayout.setLayoutParams(layoutParams)
}
}
override fun onPause(mediaPlayer: MediaPlayer) { }
override fun onStart(mediaPlayer: MediaPlayer) { }
override fun onBufferingStart(mediaPlayer: MediaPlayer) { }
override fun onBufferingEnd(mediaPlayer: MediaPlayer) { }
}
| mit | 83915f1c650449d991fefce0f69a4a33 | 33.239583 | 73 | 0.682385 | 4.942857 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/command/profession/ProfessionCommand.kt | 1 | 2217 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.professions.bukkit.command.profession
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
class ProfessionCommand(private val plugin: RPKProfessionsBukkit) : CommandExecutor {
private val professionListCommand = ProfessionListCommand(plugin)
private val professionSetCommand = ProfessionSetCommand(plugin)
private val professionUnsetCommand = ProfessionUnsetCommand(plugin)
private val professionViewCommand = ProfessionViewCommand(plugin)
private val professionExperienceCommand = ProfessionExperienceCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["profession-usage"])
return true
}
val newArgs = args.drop(1).toTypedArray()
return when (args[0]) {
"list" -> professionListCommand.onCommand(sender, command, label, newArgs)
"set" -> professionSetCommand.onCommand(sender, command, label, newArgs)
"unset" -> professionUnsetCommand.onCommand(sender, command, label, newArgs)
"view" -> professionViewCommand.onCommand(sender, command, label, newArgs)
"experience", "exp", "xp" -> professionExperienceCommand.onCommand(sender, command, label, newArgs)
else -> {
sender.sendMessage(plugin.messages["profession-usage"])
true
}
}
}
} | apache-2.0 | 1bc419e46ae693ef224c615d07c46d40 | 41.653846 | 118 | 0.714479 | 4.628392 | false | false | false | false |
LorittaBot/Loritta | web/dashboard/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/backend/routes/LocalizedRoute.kt | 1 | 1147 | package net.perfectdreams.loritta.cinnamon.dashboard.backend.routes
import io.ktor.server.application.*
import io.ktor.server.request.*
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.cinnamon.dashboard.backend.LorittaDashboardBackend
import net.perfectdreams.loritta.i18n.I18nKeys
import net.perfectdreams.sequins.ktor.BaseRoute
abstract class LocalizedRoute(val m: LorittaDashboardBackend, val originalPath: String) : BaseRoute("/{localeId}$originalPath") {
override suspend fun onRequest(call: ApplicationCall) {
val localeIdFromPath = call.parameters["localeId"]
val locale = m.languageManager.languageContexts.values.firstOrNull { it.language.textBundle.strings[I18nKeys.Website.Dashboard.LocalePathId.key] == localeIdFromPath }
if (locale != null) {
return onLocalizedRequest(
call,
locale
)
}
}
abstract suspend fun onLocalizedRequest(call: ApplicationCall, i18nContext: I18nContext)
fun getPathWithoutLocale(call: ApplicationCall) = call.request.path().split("/").drop(2).joinToString("/")
} | agpl-3.0 | 45ccfb120aeef0d5eefc87ddb7b2d989 | 41.518519 | 174 | 0.743679 | 4.411538 | false | false | false | false |
davidwhitman/deep-link-launcher | app/src/main/kotlin/com/thunderclouddev/deeplink/data/DeepLinkInfoJsonSerializer.kt | 1 | 3369 | package com.thunderclouddev.deeplink.data
import android.util.Log
import com.thunderclouddev.deeplink.logging.timberkt.TimberKt
import com.thunderclouddev.deeplink.utils.empty
import org.json.JSONException
import org.json.JSONObject
/**
* Serialize and deserialize [DeepLinkInfo] to/from Json.
* Created by David Whitman on 21 Jan, 2017.
*/
class DeepLinkInfoJsonSerializer() {
val KEY_SCHEMA_VERSION = "schema_version"
val KEY_ID = "id"
val KEY_DEEP_LINK = "deep_link"
val KEY_LINK_HANDLERS = "link_handlers"
val KEY_ACTIVITY_LABEL = "label"
val KEY_UPDATED_TIME = "update_time"
fun toJson(deepLinkInfo: DeepLinkInfo, schemaVersion: Int): Long {
try {
val jsonObject = JSONObject()
jsonObject.put(KEY_SCHEMA_VERSION, schemaVersion)
jsonObject.put(KEY_ID, deepLinkInfo.id)
jsonObject.put(KEY_DEEP_LINK, deepLinkInfo.deepLink)
jsonObject.put(KEY_ACTIVITY_LABEL, deepLinkInfo.label)
jsonObject.put(KEY_UPDATED_TIME, deepLinkInfo.updatedTime)
jsonObject.put(KEY_LINK_HANDLERS, deepLinkInfo.deepLinkHandlers)
return deepLinkInfo.id
} catch (jsonException: JSONException) {
TimberKt.e(jsonException, { "Failed to write deep link with item=$deepLinkInfo" })
return deepLinkInfo.id
}
}
fun fromJson(deepLinkJson: String): DeepLinkInfo? {
Log.d("deeplink", "json string = " + deepLinkJson)
try {
val jsonObject = JSONObject(deepLinkJson)
val schemaVersion = parseField<Int>(jsonObject, KEY_SCHEMA_VERSION) ?: 0
val id = parseField<Long>(jsonObject, KEY_ID) ?: 0
val deepLink = parseField<String>(jsonObject, KEY_DEEP_LINK) ?: String.empty
val activityLabel = parseField<String>(jsonObject, KEY_ACTIVITY_LABEL) ?: String.empty
val handlers = parseField<Array<String>>(jsonObject, KEY_LINK_HANDLERS)?.toMutableList() ?: mutableListOf()
val updatedTime = parseField<Long>(jsonObject, KEY_UPDATED_TIME) ?: 0
// Migration
if (schemaVersion < 3) {
val packageName = if (schemaVersion < 1)
parseField<String>(jsonObject, "pacakage_name") ?: String.empty
else parseField<String>(jsonObject, "package_name") ?: String.empty
handlers.add(packageName)
}
return DeepLinkInfo(id, deepLink, activityLabel, updatedTime, handlers)
} catch (exception: Exception) {
TimberKt.e(exception, { "Failed to parse deep link entirely with json: $deepLinkJson" })
return null
}
}
private fun <T> parseField(jsonObject: JSONObject, key: String): T? {
try {
return jsonObject.get(key) as T
} catch (exception: Exception) {
when (exception) {
is JSONException,
is ClassCastException -> {
TimberKt.d(exception, {
"Failed to parse deep link property with key=$key " +
"and value=${if (jsonObject.has(key)) jsonObject[key] else String.empty} " +
"and jsonObject=$jsonObject "
})
}
}
return null
}
}
} | gpl-3.0 | 860107ccac0fd8030afd846b8f530698 | 39.119048 | 119 | 0.605224 | 4.659751 | false | false | false | false |
JiangKlijna/leetcode-learning | kt/026 Remove Duplicates from Sorted Array/RemoveDuplicatesfromSortedArray.kt | 1 | 504 |
/**
* Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
* Do not allocate extra space for another array, you must do this in place with constant memory.
*/
class RemoveDuplicatesfromSortedArray {
fun removeDuplicates(nums: IntArray): Int {
if (nums.size == 0)
return 0
var value = nums[0]
var size = 1
for (i in nums)
if (i != value) {
value = i
nums[size++] = value
}
return size
}
}
k
| mit | 233bb256585eaaf51ed1765494f139d5 | 24.2 | 122 | 0.654762 | 3.294118 | false | false | false | false |
daring2/fms | common/src/test/kotlin/com/gitlab/daring/fms/common/config/ConfigExtensionTest.kt | 1 | 1252 | package com.gitlab.daring.fms.common.config
import com.gitlab.daring.fms.common.config.ConfigUtils.configFromString
import com.google.common.net.HostAndPort
import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.FunSpec
class ConfigExtensionTest : FunSpec({
test("getMillis") {
configFromString("p=10").getMillis("p") shouldBe 10L
configFromString("p=10s").getMillis("p") shouldBe 10000L
configFromString("p=10m").getMillis("p") shouldBe 600000L
}
test("toMap") {
val c1 = configFromString("p1=v1,p2=2")
hashMapOf("p1" to "v1", "p2" to 2) shouldBe c1.toMap()
}
test("toBean") {
val c1 = configFromString("b1 { p1=v1,p2=2 }")
val b1 = TestBean("v1", 2)
c1.getConfig("b1").toBean<TestBean>() shouldBe b1
c1.getBean<TestBean>("b1") shouldBe b1
}
test("getOpt") {
val c1 = configFromString("p1=10")
c1.getOpt { getInt("p1") } shouldBe 10
c1.getOpt { getInt("p2") } shouldBe null
}
test("getHostAndPort") {
val cl = configFromString("p1=\"h1:10\"")
cl.getHostAndPort("p1") shouldBe HostAndPort.fromParts("h1", 10)
}
})
data class TestBean(
val p1: String,
val p2: Int
) | apache-2.0 | 3f3fa00798ba5fb8273818f86f1b80a5 | 27.477273 | 72 | 0.627796 | 3.402174 | false | true | false | false |
ryuta46/eval-spec-maker | project/src/main/kotlin/com/ryuta46/evalspecmaker/TestItem.kt | 1 | 2224 | package com.ryuta46.evalspecmaker
internal class TestItem {
internal enum class TextContainer {
// 項目本文
BODY,
// 試験手順
METHOD,
// 確認点
CONFIRM
}
private val _children = mutableListOf<TestItem>()
val children: List<TestItem>
get() = _children
private val bodyList = mutableListOf<String>()
private val methodList = mutableListOf<String>()
private val confirmList = mutableListOf<String>()
private var mAddTarget = TextContainer.BODY
var level = 0
val bodies: String
get() = textListToString(bodyList)
val methods: String
get() = textListToString(methodList)
val confirms: String
get() = textListToString(confirmList)
private fun textListToString(list: List<String>): String {
if (list.isEmpty()) {
return ""
}
val builder = StringBuilder(list[0])
for (i in 1..list.size - 1) {
builder.append("\n")
builder.append(list[i])
}
return builder.toString()
}
fun addChild(child: TestItem) {
_children.add(child)
}
fun setAddTarget(target: TextContainer) {
mAddTarget = target
}
fun addText(text: String) {
when (mAddTarget) {
TextContainer.BODY -> bodyList.add(text)
TextContainer.METHOD -> methodList.add((methodList.size + 1).toString() + ". " + text)
TextContainer.CONFIRM -> confirmList.add("・" + text)
}
}
fun printInformation(level: Int) {
val builder = StringBuilder()
for (i in 0..level - 1) {
builder.append("-")
}
val prefix = builder.toString()
println(String.format("%sL:%d", prefix, level))
for (text in bodyList) {
println(String.format("%sT:%s", prefix, text))
}
for (text in methodList) {
println(String.format("%sM:%s", prefix, text))
}
for (text in confirmList) {
println(String.format("%sC:%s", prefix, text))
}
for (childNode in _children) {
childNode.printInformation(level + 1)
}
}
}
| mit | b66ba5e2b4babd5465e00ceb9ce4ae47 | 23.719101 | 98 | 0.559545 | 4.11985 | false | false | false | false |
vafin-mk/codingame | src/main/java/multiplayer/Code4Life.kt | 1 | 10816 | import java.util.*
import kotlin.collections.ArrayList
/**
* Bring data on patient samples from the diagnosis machine to the laboratory with enough molecules to produce medicine!
**/
fun main(args: Array<String>) = C4LBot(Scanner(System.`in`)).start()
private class C4LBot(val scanner: Scanner) {
private val PLAYERS_COUNT = 2
private val MAX_CARRY_SAMPLES = 3
private val MAX_CARRY_MOLECULES = 10
private val projects = ArrayList<Storage>()
private val samples = ArrayList<Sample>()
private var gameStorage = zeroStorage()
private var ally: Player = Player(Module.LABORATORY, 0, 0, zeroStorage(), zeroStorage())
private var rival: Player = Player(Module.LABORATORY, 0, 0, zeroStorage(), zeroStorage())
private val commandsQueue = LinkedList<C4LCommand>()
fun start() {
while (true) {
readInput()
if (commandsQueue.isNotEmpty()) {
val nextCommand = commandsQueue.poll()
if (isStillValidCommand(nextCommand)) {
println(nextCommand.execute())
continue
} else {
debug("invalidate commands")
commandsQueue.clear()
}
}
val commands = think()
debug("commands: $commands")
commandsQueue.addAll(commands)
println(commandsQueue.poll().execute())
}
}
private fun isStillValidCommand(command: C4LCommand): Boolean {
if (command is ConnectSample) {
val sample = samples.firstOrNull { it.id == command.sample.id }
if (sample == null || sample.carrier == Carrier.RIVAL) return false
}
return true
}
private fun readInput() {
for (i in 0 until PLAYERS_COUNT) {
val target = scanner.next()
val eta = scanner.nextInt()
val score = scanner.nextInt()
val storageA = scanner.nextInt()
val storageB = scanner.nextInt()
val storageC = scanner.nextInt()
val storageD = scanner.nextInt()
val storageE = scanner.nextInt()
val expertiseA = scanner.nextInt()
val expertiseB = scanner.nextInt()
val expertiseC = scanner.nextInt()
val expertiseD = scanner.nextInt()
val expertiseE = scanner.nextInt()
val storage = Storage(storageA, storageB, storageC, storageD, storageE)
val expertise = Storage(expertiseA, expertiseB, expertiseC, expertiseD, expertiseE)
if (i == 0) {
ally = Player(Module.valueOf(target), eta, score, storage, expertise)
} else {
rival = Player(Module.valueOf(target), eta, score, storage, expertise)
}
}
val availableA = scanner.nextInt()
val availableB = scanner.nextInt()
val availableC = scanner.nextInt()
val availableD = scanner.nextInt()
val availableE = scanner.nextInt()
gameStorage = Storage(availableA, availableB, availableC, availableD, availableE)
samples.clear()
val sampleCount = scanner.nextInt()
for (i in 0 until sampleCount) {
val sampleId = scanner.nextInt()
val carriedBy = scanner.nextInt()
val rank = scanner.nextInt()
val expertiseGain = scanner.next()
val health = scanner.nextInt()
val costA = scanner.nextInt()
val costB = scanner.nextInt()
val costC = scanner.nextInt()
val costD = scanner.nextInt()
val costE = scanner.nextInt()
val sampleCost = Storage(costA, costB, costC, costD, costE)
samples.add(Sample(sampleId, Carrier.fromId(carriedBy), Rank.fromRank(rank), Molecule.fromStr(expertiseGain), health, sampleCost - ally.expertise))
}
}
private fun think(): List<C4LCommand> {
val carriedSamples = carriedSamples()
if (carriedSamples.isEmpty()) {
return pickupSamples()
}
val undiagnosedSamples = carriedSamples.filter { !it.diagnosed() }
if (undiagnosedSamples.isNotEmpty()) {
return diagnoseSamples(undiagnosedSamples)
}
if (!canFinishSamples(carriedSamples)) {
return pickupMolecules(carriedSamples)
}
return finishSamples(carriedSamples)
}
private fun pickupSamples(): List<C4LCommand> {
val commands = ArrayList<C4LCommand>()
if (ally.position != Module.SAMPLES) {
commands.add(C4LMove(Module.SAMPLES))
}
// commands.add(FetchSample(Rank.LOW))
// commands.add(FetchSample(Rank.LOW))
commands.add(FetchSample(Rank.MEDIUM))
// val combinations = combineSamples()
// if (combinations.isNotEmpty()) {
// val bestCombination = combinations.filter { it.combinedStorage.sum() <= MAX_CARRY_MOLECULES }.sortedByDescending { it.score }.firstOrNull()
// debug("best combo -- $bestCombination")
// bestCombination?.samples?.forEach { commands.add(ConnectSample(it)) }
// }
return commands
}
private fun diagnoseSamples(undiagnosedSamples: List<Sample>): List<C4LCommand> {
val commands = ArrayList<C4LCommand>()
if (ally.position != Module.DIAGNOSIS) {
commands.add(C4LMove(Module.DIAGNOSIS))
}
undiagnosedSamples.mapTo(commands) { ConnectSample(it) }
return commands
}
private fun pickupMolecules(carriedSamples: List<Sample>): List<C4LCommand> {
val commands = ArrayList<C4LCommand>()
if (ally.position != Module.MOLECULES) {
commands.add(C4LMove(Module.MOLECULES))
}
val combinedCost = carriedSamples.combinedCost()
val required = combinedCost - ally.storage
for (i in 0 until required.aCount) commands.add(ConnectMolecule(Molecule.A))
for (i in 0 until required.bCount) commands.add(ConnectMolecule(Molecule.B))
for (i in 0 until required.cCount) commands.add(ConnectMolecule(Molecule.C))
for (i in 0 until required.dCount) commands.add(ConnectMolecule(Molecule.D))
for (i in 0 until required.eCount) commands.add(ConnectMolecule(Molecule.E))
return commands
}
private fun finishSamples(carriedSamples: List<Sample>): List<C4LCommand> {
val commands = ArrayList<C4LCommand>()
if (ally.position != Module.LABORATORY) {
commands.add(C4LMove(Module.LABORATORY))
}
carriedSamples.mapTo(commands) { ConnectSample(it) }
return commands
}
private fun canFinishSamples(carriedSamples: List<Sample>): Boolean {
val combinedCost = carriedSamples.combinedCost()
return (combinedCost - ally.storage).empty()
}
//todo some refactor required
private fun combineSamples(): List<SampleCombination> {
val samples = cloudSamples()
if (samples.size > 10) {
debug("Too much samples; bottleneck here!!!")
}
val combinations = ArrayList<SampleCombination>()
for (i in 0 until samples.size) {
val firstSample = samples[i]
combinations.add(combine(firstSample))
for (j in i + 1 until samples.size) {
val secondSample = samples[j]
combinations.add(combine(firstSample, secondSample))
for (k in j + 1 until samples.size) {
val thirdSample = samples[k]
combinations.add(combine(firstSample, secondSample, thirdSample))
}
}
}
return combinations
}
private fun combine(vararg samples: Sample): SampleCombination {
val combinedSamples = ArrayList<Sample>()
var score = 0
var cost = zeroStorage()
for (sample in samples) {
combinedSamples.add(sample)
score += sample.score
cost += sample.cost
}
return SampleCombination(combinedSamples, score, cost)
}
private fun carriedSamples(): List<Sample> = samples.filter { it.carrier == Carrier.ALLY }
private fun cloudSamples() = samples.filter { it.carrier == Carrier.CLOUD }
private fun debug(message: String) = System.err.println(message)
private fun zeroStorage() = Storage(0, 0, 0, 0, 0)
val projectCount: Int
init {
projectCount = scanner.nextInt()
for (i in 0 until projectCount) {
val a = scanner.nextInt()
val b = scanner.nextInt()
val c = scanner.nextInt()
val d = scanner.nextInt()
val e = scanner.nextInt()
projects.add(Storage(a, b, c, d, e))
}
}
}
enum class Molecule {
A, B, C, D, E, UNKNOWN;
companion object {
fun fromStr(str: String): Molecule = values().firstOrNull { str == it.name } ?: UNKNOWN
}
}
private enum class Module {
DIAGNOSIS, MOLECULES, LABORATORY, SAMPLES, START_POS
}
enum class Rank(val rank: Int) {
LOW(1), MEDIUM(2), HIGH(3);
companion object {
fun fromRank(rank: Int): Rank {
return when(rank) {
1 -> LOW
2 -> MEDIUM
3 -> HIGH
else -> throw IllegalStateException("oops: $rank")
}
}
}
}
enum class Carrier {
ALLY, RIVAL, CLOUD;
companion object {
fun fromId(id: Int): Carrier {
return when (id) {
0 -> ALLY
1 -> RIVAL
-1 -> CLOUD
else -> throw IllegalStateException("the fuck?: $id")
}
}
}
}
//private data class Project(val aCost: Int, val bCost: Int, val cCost: Int, val dCost: Int, val eCost: Int)
data class Sample(val id: Int, val carrier: Carrier, val rank: Rank, val reward: Molecule, val score: Int, val cost: Storage)
private data class Player(val position: Module, val eta: Int, val score: Int, val storage: Storage, val expertise: Storage)
data class Storage(val aCount: Int, val bCount: Int, val cCount: Int, val dCount: Int, val eCount: Int)
//private data class Expertise(val aExp: Int, val bExp: Int, val cExp: Int, val dExp: Int, val eExp: Int)
private data class SampleCombination(val samples: List<Sample>, val score: Int, val combinedStorage: Storage)
operator fun Storage.plus(other: Storage): Storage = Storage(
aCount + other.aCount,
bCount + other.bCount,
cCount + other.cCount,
dCount + other.dCount,
eCount + other.eCount
)
operator fun Storage.minus(other: Storage): Storage = Storage(
aCount - other.aCount,
bCount - other.bCount,
cCount - other.cCount,
dCount - other.dCount,
eCount - other.eCount
)
fun Storage.sum(): Int = aCount + bCount + cCount + dCount + eCount
fun Storage.empty(): Boolean = aCount <= 0 && bCount <= 0 && cCount <= 0 && dCount <= 0 && eCount <= 0
fun Iterable<Sample>.combinedCost(): Storage {
var cost = Storage(0, 0, 0, 0, 0)
for (sample in this) {
cost += sample.cost
}
return cost
}
fun Sample.diagnosed() = score > 0
private sealed class C4LCommand {
abstract fun execute(): String
}
private data class C4LMove(val module: Module) : C4LCommand() {
override fun execute(): String = "GOTO $module"
}
private data class ConnectSample(val sample: Sample) : C4LCommand() {
override fun execute(): String = "CONNECT ${sample.id}"
}
private data class FetchSample(val rank: Rank) : C4LCommand() {
override fun execute(): String = "CONNECT ${rank.rank}"
}
private data class ConnectMolecule(val molecule: Molecule) : C4LCommand() {
override fun execute(): String = "CONNECT $molecule"
}
private class C4LWait: C4LCommand() {
override fun execute(): String = "WAIT"
} | mit | acad473faed4a32cdf0581c82cbd7a89 | 31.483483 | 153 | 0.668454 | 3.612558 | false | false | false | false |
ProgramLeague/EmailEverything | src/main/kotlin/ray/eldath/ew/handler/Wake.kt | 1 | 3728 | package ray.eldath.ew.handler
import org.slf4j.LoggerFactory
import ray.eldath.ew.core.Sender
import ray.eldath.ew.tool.Config
import ray.eldath.ew.util.ReceivedEmail
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.util.regex.Pattern
object Wake : Handler {
private val LOGGER = LoggerFactory.getLogger(this.javaClass)
override fun handle(receivedEmail: ReceivedEmail, sender: Sender) {
val name = receivedEmail.subject.replace("wake ", "")
val target = parseTarget(name)
if (target == null) {
receivedEmail.reply(sender, "Fatal error", "No target named $name.")
LOGGER.info("handle failed. no target named $name")
return
}
LOGGER.info("waking device ${target.name} - ${target.ip}[${target.mac}]...")
try {
WakeNow.wake(target.mac, target.ip, target.port)
} catch (exception: IllegalArgumentException) {
LOGGER.error("invalid MAC address, exited")
return
}
LOGGER.info("magic package sent to ${target.name} successfully")
receivedEmail.reply(
sender,
"Magic package sent",
"Magic package sent to ${target.name} - ${target.ip}[${target.mac}] successfully"
)
}
override fun titleRegex(): Regex = Regex("wake .+")
private class TargetEntry(val name: String, val mac: String, val ip: String, val port: Int)
/**
* Most copied from [MagicPacket.java](https://github.com/mafrosis/Wake-On-Lan/blob/master/src/net/mafro/android/wakeonlan/MagicPacket.java)
*/
private object WakeNow {
private const val SEPARATOR = ':'
fun wake(mac: String, ip: String, port: Int): String {
// validate MAC and chop into array
val hex = validateMac(mac)
// convert to base16 bytes
val macBytes = ByteArray(6)
for (i in 0..5)
macBytes[i] = Integer.parseInt(hex[i], 16).toByte()
val bytes = ByteArray(102)
// fill first 6 bytes
for (i in 0..5)
bytes[i] = 0xff.toByte()
// fill remaining bytes with target MAC
var i = 6
while (i < bytes.size) {
System.arraycopy(macBytes, 0, bytes, i, macBytes.size)
i += macBytes.size
}
// create socket to IP
val address = InetAddress.getByName(ip)
val packet = DatagramPacket(bytes, bytes.size, address, port)
val socket = DatagramSocket()
socket.send(packet)
socket.close()
return hex[0] + SEPARATOR + hex[1] + SEPARATOR + hex[2] + SEPARATOR + hex[3] + SEPARATOR + hex[4] + SEPARATOR + hex[5]
}
// like C6:19:58:D8:73:3F
private fun validateMac(mac: String): Array<String> {
var mac1 = mac
// error handle semi colons
mac1 = mac1.replace(";", ":").replace("-", ":")
// attempt to assist the user a little
var newMac = ""
if (mac1.matches("([a-zA-Z0-9]){12}".toRegex())) {
// expand 12 chars into a valid mac address
for (i in 0 until mac1.length) {
if (i > 1 && i % 2 == 0)
newMac += ":"
newMac += mac1[i]
}
} else
newMac = mac1
// regexp pattern match a valid MAC address
val pat = Pattern.compile("((([0-9a-fA-F]){2}[-:]){5}([0-9a-fA-F]){2})")
val m = pat.matcher(newMac)
if (m.find()) {
val result = m.group()
return result.split("([:-])".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
} else
throw IllegalArgumentException("invalid MAC address")
}
}
private fun parseTarget(name: String): TargetEntry? {
val config = Config.getHandlerConfig("Wake").getJSONArray("target")
for (i in 0 until config.length()) {
val target = config.getJSONObject(i)
val nameT = target.getString("name")
if (name.contentEquals(nameT))
return TargetEntry(
nameT,
target.getString("mac"),
target.getString("ip"),
if (target.has("port")) target.getInt("port") else 9
)
}
return null
}
} | gpl-3.0 | 0bf62e53b0d1f19ebd1f364f33f78c01 | 30.871795 | 141 | 0.659067 | 3.205503 | false | true | false | false |
meh/watch_doge | src/main/java/meh/watchdoge/util.kt | 1 | 4646 | package meh.watchdoge.util;
import android.os.Messenger;
import android.os.Message;
import android.os.Bundle;
import org.msgpack.value.Value;
import org.msgpack.value.ValueType;
import org.msgpack.core.MessageTypeException;
import meh.watchdoge.Request;
import meh.watchdoge.request.Request as RequestBuilder;
import meh.watchdoge.request.build as buildRequest;
import meh.watchdoge.Response;
import meh.watchdoge.response.Response as ResponseBuilder;
import meh.watchdoge.response.Control;
import meh.watchdoge.response.build as buildResponse;
inline fun<T: Any, R> T.tap(tap: (T) -> R): T {
tap(this)
return this
}
fun Message.isRequest(): Boolean {
return this.what == 0xBADB01 && this.replyTo != null;
}
fun Message.isResponse(): Boolean {
return origin() == 0xBADB01 && replyTo == null
}
fun Message.origin(): Int {
return what
}
fun Message.family(): Int {
return (arg1) and 0xff
}
fun Message.command(): Int {
return (arg1 shr 8) and 0xff
}
fun Message.status(): Int {
return (arg1 shr 16) and 0xff
}
fun Message.intoResponse(): Response {
return Response(family(), command(), status(), arg2, peekData());
}
fun Message.intoRequest(id: Int = 0): Request {
return Request(id, family(), command(), arg2, peekData(), replyTo!!);
}
infix fun Messenger.to(other: Messenger): Pair<Messenger, Messenger> {
return Pair(this, other);
}
fun Pair<Messenger, Messenger>.request(body: RequestBuilder.() -> Unit) {
this.first.send(buildRequest(body).tap { it.replyTo = this.second });
}
fun Messenger.response(request: Request, result: Int, body: (Control.() -> Unit)? = null) {
if (request.id() == 0) {
return;
}
this.send(buildResponse {
control {
family = request.family()
command = request.command()
status = result
if (body != null) {
this.body();
}
}
})
}
fun Bundle.putValue(key: String, value: Value) {
when {
value.isNilValue() ->
this.putParcelable(key, null)
value.isBooleanValue() ->
this.putBoolean(key, value.asBooleanValue().getBoolean())
value.isIntegerValue() ->
when {
value.asIntegerValue().isInByteRange() ->
this.putByte(key, value.asIntegerValue().asByte())
value.asIntegerValue().isInShortRange() ->
this.putShort(key, value.asIntegerValue().asShort())
value.asIntegerValue().isInIntRange() ->
this.putInt(key, value.asIntegerValue().asInt())
value.asIntegerValue().isInLongRange() ->
this.putLong(key, value.asIntegerValue().asLong())
}
value.isFloatValue() ->
this.putDouble(key, value.asNumberValue().toDouble())
value.isStringValue() ->
this.putString(key, value.asStringValue().asString())
value.isBinaryValue() ->
this.putByteArray(key, value.asBinaryValue().asByteArray())
value.isArrayValue() -> {
val values = value.asArrayValue();
when {
values.size() == 0 ->
this.putParcelable(key, null);
values[0].isIntegerValue() -> {
}
values[0].isIntegerValue() && values[0].asIntegerValue().isInByteRange() ->
this.putByteArray(key, ByteArray(values.size()) {
values[it].asIntegerValue().asByte()
})
values[0].isIntegerValue() && values[0].asIntegerValue().isInShortRange() ->
this.putShortArray(key, ShortArray(values.size()) {
values[it].asIntegerValue().asShort()
})
values[0].isIntegerValue() && values[0].asIntegerValue().isInIntRange() ->
this.putIntArray(key, IntArray(values.size()) {
values[it].asIntegerValue().asInt()
})
values[0].isIntegerValue() && values[0].asIntegerValue().isInLongRange() ->
this.putLongArray(key, LongArray(values.size()) {
values[it].asIntegerValue().asLong()
})
values[0].isFloatValue() ->
this.putDoubleArray(key, DoubleArray(values.size()) {
values[it].asFloatValue().toDouble()
})
values[0].isStringValue() ->
this.putStringArray(key, Array(values.size()) {
values[it].asStringValue().asString()
})
else ->
throw MessageTypeException("unknown conversion")
}
}
value.isMapValue() -> {
this.putParcelable(key, Bundle().tap {
for ((k, v) in value.asMapValue().map()) {
it.putValue(k.asStringValue().asString(), v);
}
})
}
else ->
throw MessageTypeException("unknown conversion")
}
}
fun String.toDuration(): Double {
val match = Regex("""(\d(?:\.\d+)?)(s|ms|us)?""").find(this.trim().toLowerCase());
if (match == null) {
return 0.0;
}
val value = match.groups.get(1)!!.value.toDouble();
val unit = match.groups.get(2);
return when (unit?.value) {
"s" -> value
"ms" -> value * 1000.0
"us" -> value * 1000000.0
else -> value
}
}
| agpl-3.0 | 3858996730519abec7f21b9fc1750cb5 | 23.452632 | 91 | 0.662505 | 3.276446 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/main/java/org/wordpress/android/fluxc/example/PluginsFragment.kt | 1 | 5354 | package org.wordpress.android.fluxc.example
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import dagger.android.support.AndroidSupportInjection
import kotlinx.android.synthetic.main.fragment_plugins.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.example.ui.common.showSiteSelectorDialog
import org.wordpress.android.fluxc.example.utils.showSingleLineDialog
import org.wordpress.android.fluxc.generated.PluginActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.PluginStore
import org.wordpress.android.fluxc.store.PluginStore.FetchSitePluginPayload
import org.wordpress.android.fluxc.store.PluginStore.InstallSitePluginPayload
import org.wordpress.android.fluxc.store.PluginStore.OnSitePluginConfigured
import org.wordpress.android.fluxc.store.PluginStore.OnSitePluginFetched
import org.wordpress.android.fluxc.store.PluginStore.OnSitePluginInstalled
import javax.inject.Inject
class PluginsFragment : Fragment() {
@Inject internal lateinit var dispatcher: Dispatcher
@Inject internal lateinit var pluginStore: PluginStore
private var selectedSite: SiteModel? = null
private var selectedPos: Int = -1
override fun onStart() {
super.onStart()
dispatcher.register(this)
}
override fun onStop() {
super.onStop()
dispatcher.unregister(this)
}
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_plugins, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
plugins_select_site.setOnClickListener {
showSiteSelectorDialog(selectedPos, object : SiteSelectorDialog.Listener {
override fun onSiteSelected(site: SiteModel, pos: Int) {
selectedSite = site
selectedPos = pos
plugins_selected_site.text = site.name ?: site.displayName
}
})
}
install_activate_plugin.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(
activity,
"Enter a plugin slug.\n(Hint: If testing Jetpack CP sites, don't use `jetpack`)"
) { pluginSlugText ->
if (pluginSlugText.text.isEmpty()) {
prependToLog("Slug is null so doing nothing")
return@showSingleLineDialog
}
pluginSlugText.text.toString().apply {
prependToLog("Installing plugin: $this")
val payload = InstallSitePluginPayload(site, this)
dispatcher.dispatch(PluginActionBuilder.newInstallSitePluginAction(payload))
}
}
} ?: prependToLog("Please select a site first.")
}
fetch_plugin.setOnClickListener {
selectedSite?.let { site ->
showSingleLineDialog(activity, "Enter the plugin name.") { pluginNameText ->
if (pluginNameText.text.isEmpty()) {
prependToLog("Name is null so doing nothing")
return@showSingleLineDialog
}
pluginNameText.text.toString().apply {
prependToLog("Fetching plugin: $this")
val payload = FetchSitePluginPayload(
site,
this
)
dispatcher.dispatch(PluginActionBuilder.newFetchSitePluginAction(payload))
}
}
} ?: prependToLog("Please select a site first.")
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onSitePluginInstalled(event: OnSitePluginInstalled) {
if (!event.isError) {
prependToLog("${event.slug} is installed to ${event.site.name}.")
} else {
event.error.message?.let {
prependToLog("Installation failed: $it")
}
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onSitePluginFetched(event: OnSitePluginFetched) {
if (!event.isError) {
prependToLog("${event.plugin.displayName}: ${event.plugin.description}")
} else {
prependToLog("Fetching failed: ${event.error.type}")
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onSitePluginConfigured(event: OnSitePluginConfigured) {
if (!event.isError) {
// If there is no error, we can assume that the configuration (activating in our case) is successful.
prependToLog("${event.pluginName} is activated.")
}
}
}
| gpl-2.0 | e85fbb15852d477cedfef4b0816cdc76 | 38.659259 | 116 | 0.631117 | 5.138196 | false | false | false | false |
xfournet/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/javaUCallExpressions.kt | 1 | 8105 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTypesUtil
import org.jetbrains.uast.*
import org.jetbrains.uast.java.expressions.JavaUExpressionList
import org.jetbrains.uast.psi.UElementWithLocation
class JavaUCallExpression(
override val psi: PsiMethodCallExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx, UElementWithLocation {
override val kind: UastCallKind
get() = UastCallKind.METHOD_CALL
override val methodIdentifier by lz {
val methodExpression = psi.methodExpression
val nameElement = methodExpression.referenceNameElement ?: return@lz null
UIdentifier(nameElement, this)
}
override val classReference: UReferenceExpression?
get() = null
override val valueArgumentCount by lz { psi.argumentList.expressions.size }
override val valueArguments by lz { psi.argumentList.expressions.map { JavaConverter.convertOrEmpty(it, this) } }
override fun getArgumentForParameter(i: Int): UExpression? {
val psiMethod = resolve() ?: return null
val isVarArgs = psiMethod.parameterList.parameters.getOrNull(i)?.isVarArgs ?: return null
if (isVarArgs) {
return JavaUExpressionList(null, UastSpecialExpressionKind.VARARGS, this).apply {
expressions = valueArguments.drop(i)
}
}
return valueArguments.getOrNull(i)
}
override val typeArgumentCount by lz { psi.typeArguments.size }
override val typeArguments: List<PsiType>
get() = psi.typeArguments.toList()
override val returnType: PsiType?
get() = psi.type
override val methodName: String?
get() = psi.methodExpression.referenceName
override fun resolve() = psi.resolveMethod()
override fun getStartOffset(): Int =
psi.methodExpression.referenceNameElement?.textOffset ?: psi.methodExpression.textOffset
override fun getEndOffset() = psi.textRange.endOffset
override val receiver: UExpression?
get() {
uastParent.let { uastParent ->
return if (uastParent is UQualifiedReferenceExpression && uastParent.selector == this)
uastParent.receiver
else
null
}
}
override val receiverType: PsiType?
get() {
val qualifierType = psi.methodExpression.qualifierExpression?.type
if (qualifierType != null) {
return qualifierType
}
val method = resolve() ?: return null
if (method.hasModifierProperty(PsiModifier.STATIC)) return null
val psiManager = psi.manager
val containingClassForMethod = method.containingClass ?: return null
val containingClass = PsiTreeUtil.getParentOfType(psi, PsiClass::class.java)
val containingClassSequence = generateSequence(containingClass) {
if (it.hasModifierProperty(PsiModifier.STATIC))
null
else
PsiTreeUtil.getParentOfType(it, PsiClass::class.java)
}
val receiverClass = containingClassSequence.find { containingClassForExpression ->
psiManager.areElementsEquivalent(containingClassForMethod, containingClassForExpression) ||
containingClassForExpression.isInheritor(containingClassForMethod, true)
}
return receiverClass?.let { PsiTypesUtil.getClassType(it) }
}
}
class JavaConstructorUCallExpression(
override val psi: PsiNewExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx {
override val kind by lz {
when {
psi.arrayInitializer != null -> UastCallKind.NEW_ARRAY_WITH_INITIALIZER
psi.arrayDimensions.isNotEmpty() -> UastCallKind.NEW_ARRAY_WITH_DIMENSIONS
else -> UastCallKind.CONSTRUCTOR_CALL
}
}
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference by lz {
psi.classReference?.let { ref ->
JavaConverter.convertReference(ref, this, null) as? UReferenceExpression
}
}
override val valueArgumentCount: Int
get() {
val initializer = psi.arrayInitializer
return when {
initializer != null -> initializer.initializers.size
psi.arrayDimensions.isNotEmpty() -> psi.arrayDimensions.size
else -> psi.argumentList?.expressions?.size ?: 0
}
}
override val valueArguments by lz {
val initializer = psi.arrayInitializer
when {
initializer != null -> initializer.initializers.map { JavaConverter.convertOrEmpty(it, this) }
psi.arrayDimensions.isNotEmpty() -> psi.arrayDimensions.map { JavaConverter.convertOrEmpty(it, this) }
else -> psi.argumentList?.expressions?.map { JavaConverter.convertOrEmpty(it, this) } ?: emptyList()
}
}
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val typeArgumentCount by lz { psi.classReference?.typeParameters?.size ?: 0 }
override val typeArguments: List<PsiType>
get() = psi.classReference?.typeParameters?.toList() ?: emptyList()
override val returnType: PsiType?
get() = (psi.classReference?.resolve() as? PsiClass)?.let { PsiTypesUtil.getClassType(it) } ?: psi.type
override val methodName: String?
get() = null
override fun resolve() = psi.resolveMethod()
}
class JavaArrayInitializerUCallExpression(
override val psi: PsiArrayInitializerExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx {
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val valueArgumentCount by lz { psi.initializers.size }
override val valueArguments by lz { psi.initializers.map { JavaConverter.convertOrEmpty(it, this) } }
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = psi.type
override val kind: UastCallKind
get() = UastCallKind.NESTED_ARRAY_INITIALIZER
override fun resolve() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
}
class JavaAnnotationArrayInitializerUCallExpression(
override val psi: PsiArrayInitializerMemberValue,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx {
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val kind: UastCallKind
get() = UastCallKind.NESTED_ARRAY_INITIALIZER
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val valueArgumentCount by lz { psi.initializers.size }
override val valueArguments by lz {
psi.initializers.map {
JavaConverter.convertPsiElement(it, this) as? UExpression ?: UnknownJavaExpression(it, this)
}
}
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = null
override fun resolve() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
} | apache-2.0 | 287eb8f60ae664bfcafcff06e3b1e22d | 30.540856 | 115 | 0.727082 | 4.975445 | false | false | false | false |
Ekito/koin | koin-projects/examples/androidx-compose-jetnews/src/androidTest/java/com/example/jetnews/HomeScreenSnackbarTest.kt | 1 | 2901 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.SnackbarHostState
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.ExperimentalComposeApi
import androidx.compose.runtime.snapshots.snapshotFlow
import androidx.test.platform.app.InstrumentationRegistry
import androidx.ui.test.assertIsDisplayed
import androidx.ui.test.createComposeRule
import androidx.ui.test.onNodeWithText
import com.example.jetnews.ui.home.HomeScreen
import com.example.jetnews.ui.state.UiState
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
/**
* Checks that the Snackbar is shown when the HomeScreen data contains an error.
*/
class HomeScreenSnackbarTest {
@get:Rule
val composeTestRule = createComposeRule(disableTransitions = true)
@OptIn(
ExperimentalMaterialApi::class,
ExperimentalComposeApi::class
)
@Test
fun postsContainError_snackbarShown() {
val snackbarHostState = SnackbarHostState()
composeTestRule.setContent {
val scaffoldState = rememberScaffoldState(snackbarHostState = snackbarHostState)
// When the Home screen receives data with an error
HomeScreen(
posts = UiState(exception = IllegalStateException()),
favorites = emptySet(),
onToggleFavorite = {},
onRefreshPosts = {},
onErrorDismiss = {},
navigateTo = {},
scaffoldState = scaffoldState
)
}
// Then the first message received in the Snackbar is an error message
val snackbarText = InstrumentationRegistry.getInstrumentation()
.targetContext.resources.getString(R.string.load_error)
runBlocking {
// snapshotFlow converts a State to a Kotlin Flow so we can observe it
// wait for the first a non-null `currentSnackbarData`
snapshotFlow { snackbarHostState.currentSnackbarData }.filterNotNull().first()
composeTestRule.onNodeWithText(snackbarText, false, false).assertIsDisplayed()
}
}
}
| apache-2.0 | 27785e5210e947077c9b24b551fda930 | 37.171053 | 92 | 0.717339 | 5.180357 | false | true | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/repository/StatsSqlRepository.kt | 1 | 4196 | package com.github.shynixn.blockball.core.logic.persistence.repository
import com.github.shynixn.blockball.api.persistence.context.SqlDbContext
import com.github.shynixn.blockball.api.persistence.entity.Stats
import com.github.shynixn.blockball.api.persistence.repository.StatsRepository
import com.github.shynixn.blockball.core.logic.persistence.entity.PlayerMetaEntity
import com.github.shynixn.blockball.core.logic.persistence.entity.StatsEntity
import com.google.inject.Inject
/**
* Handles storing and retrieving arena from a stats medium.
*/
class StatsSqlRepository @Inject constructor(private val sqlDbContext: SqlDbContext) : StatsRepository {
/**
* Returns the [Stats] for the given player uniqueId. Creates
* a new one if it does not exist yet.
*/
override fun getOrCreateFromPlayer(name: String, uuid: String): Stats {
return sqlDbContext.transaction<Stats, Any> { connection ->
getStats(connection, uuid) ?: insert(connection, StatsEntity(PlayerMetaEntity(uuid, name)))
}
}
/**
* Saves the given [item] to the storage.
*/
override fun save(item: Stats): Stats {
return sqlDbContext.transaction<Stats, Any> { connection ->
if (item.id == 0L) {
val optStats = getStats(connection, item.playerMeta.uuid)
if (optStats == null) {
insert(connection, item)
} else {
item.id = optStats.id
item.playerMeta.id = optStats.playerMeta.id
update(connection, item)
}
} else {
update(connection, item)
}
}
}
/**
* Inserts the [stats] into the database.
*/
private fun insert(connection: Any, stats: Stats): Stats {
val playerMeta = stats.playerMeta
sqlDbContext.singleQuery(connection, "SELECT * from SHY_PLAYER WHERE uuid = ?", { resultSet ->
playerMeta.id = (resultSet["id"] as Int).toLong()
}, playerMeta.uuid)
if (playerMeta.id == 0L) {
playerMeta.id = sqlDbContext.insert(
connection, "SHY_PLAYER"
, "uuid" to playerMeta.uuid
, "name" to playerMeta.name
)
}
stats.id = sqlDbContext.insert(
connection, "SHY_BLOCKBALL_STATS"
, "shy_player_id" to playerMeta.id
, "wins" to stats.amountOfWins
, "games" to stats.amountOfPlayedGames
, "goals" to stats.amountOfGoals
)
return stats
}
/**
* Updates the [stats] in the database.
*/
private fun update(connection: Any, stats: Stats): Stats {
val playerMeta = stats.playerMeta
sqlDbContext.update(
connection, "SHY_PLAYER", "WHERE id=" + playerMeta.id
, "uuid" to playerMeta.uuid
, "name" to playerMeta.name
)
sqlDbContext.update(
connection, "SHY_BLOCKBALL_STATS", "WHERE id=" + stats.id
, "wins" to stats.amountOfWins
, "games" to stats.amountOfPlayedGames
, "goals" to stats.amountOfGoals
)
return stats
}
/**
* Gets the stats from the database.
*/
private fun getStats(connection: Any, uuid: String): Stats? {
val statement = "SELECT * " +
"FROM SHY_BLOCKBALL_STATS stats, SHY_PLAYER player " +
"WHERE player.uuid = ? " +
"AND stats.shy_player_id = player.id "
return sqlDbContext.singleQuery(connection, statement, { resultSet ->
val playerMeta = PlayerMetaEntity(resultSet["uuid"] as String, resultSet["name"] as String)
playerMeta.id = (resultSet["shy_player_id"] as Int).toLong()
val stats = StatsEntity(playerMeta)
with(stats) {
id = (resultSet["id"] as Int).toLong()
amountOfGoals = resultSet["goals"] as Int
amountOfWins = resultSet["wins"] as Int
amountOfPlayedGames = resultSet["games"] as Int
}
stats
}, uuid)
}
}
| apache-2.0 | add186dec9059eea2804b3875608969d | 33.113821 | 104 | 0.585319 | 4.29478 | false | false | false | false |
rahulsom/grooves | grooves-example-springboot-kotlin/src/main/kotlin/grooves/boot/kotlin/queries/PatientHealthQuery.kt | 1 | 3498 | package grooves.boot.kotlin.queries
import com.github.rahulsom.grooves.api.EventApplyOutcome.CONTINUE
import com.github.rahulsom.grooves.queries.QuerySupport
import com.github.rahulsom.grooves.queries.internal.SimpleExecutor
import com.github.rahulsom.grooves.queries.internal.SimpleQuery
import grooves.boot.kotlin.domain.Patient
import grooves.boot.kotlin.domain.PatientEvent
import grooves.boot.kotlin.domain.PatientHealth
import grooves.boot.kotlin.domain.Procedure
import grooves.boot.kotlin.repositories.PatientEventRepository
import grooves.boot.kotlin.repositories.PatientHealthRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono.just
import java.lang.Exception
import java.util.Date
@Component
class PatientHealthQuery constructor(
@Autowired val patientEventRepository: PatientEventRepository,
@Autowired val patientHealthRepository: PatientHealthRepository
) :
QuerySupport<Patient, String, PatientEvent, String, PatientHealth>,
SimpleQuery<Patient, String, PatientEvent, PatientEvent.Applicable, String, PatientHealth> {
override fun getExecutor() = SimpleExecutor<Patient, String, PatientEvent,
PatientEvent.Applicable, String, PatientHealth, PatientHealthQuery>()
override fun createEmptySnapshot() = PatientHealth()
override fun getSnapshot(maxPosition: Long, aggregate: Patient) =
patientHealthRepository.findByAggregateIdAndLastEventPositionLessThan(
aggregate.id!!, maxPosition
)
override fun getSnapshot(maxTimestamp: Date?, aggregate: Patient) =
patientHealthRepository.findByAggregateIdAndLastEventTimestampLessThan(
aggregate.id!!, maxTimestamp!!
)
override fun shouldEventsBeApplied(snapshot: PatientHealth) = true
override fun addToDeprecates(snapshot: PatientHealth, deprecatedAggregate: Patient) {
snapshot.deprecatesIds.add(deprecatedAggregate.id!!)
}
override fun onException(e: Exception, snapshot: PatientHealth, event: PatientEvent) =
just(CONTINUE)
override fun getUncomputedEvents(
aggregate: Patient,
lastSnapshot: PatientHealth?,
version: Long
) =
patientEventRepository.findAllByPositionRange(
aggregate.id!!,
lastSnapshot?.lastEventPosition ?: 0, version
)
override fun getUncomputedEvents(
aggregate: Patient,
lastSnapshot: PatientHealth?,
snapshotTime: Date
) =
lastSnapshot?.lastEventTimestamp?.let {
patientEventRepository.findAllByTimestampRange(
aggregate.id!!, it, snapshotTime
)
} ?: patientEventRepository.findAllByAggregateIdAndTimestampLessThan(
aggregate.id!!,
snapshotTime
)
override fun applyEvent(event: PatientEvent.Applicable, snapshot: PatientHealth) =
when (event) {
is PatientEvent.Applicable.Created -> {
if (event.aggregateId == snapshot.aggregateId) {
snapshot.name = event.name
}
just(CONTINUE)
}
is PatientEvent.Applicable.ProcedurePerformed -> {
snapshot.procedures.add(Procedure(event.code, event.timestamp))
just(CONTINUE)
}
is PatientEvent.Applicable.PaymentMade -> {
just(CONTINUE)
}
}
} | apache-2.0 | adff10b8df774ba8a63d5970a594bbe6 | 37.450549 | 96 | 0.708691 | 4.56658 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/user/model/CachedUser.kt | 1 | 1909 | package mixit.user.model
import mixit.talk.model.Language
import mixit.user.handler.dto.UserDto
import mixit.user.handler.logoType
import mixit.user.handler.logoWebpUrl
import mixit.util.cache.Cached
import mixit.util.toHTML
data class CachedUser(
val login: String,
val firstname: String,
val lastname: String,
val company: String?,
var email: String?,
val photoUrl: String?,
val photoShape: PhotoShape? = null,
val emailHash: String?,
val description: Map<Language, String>,
val links: List<Link>,
val legacyId: Long? = null,
val role: Role,
var newsletterSubscriber: Boolean,
override val id: String = login
) : Cached {
constructor(user: User) : this(
user.login,
user.firstname,
user.lastname,
user.company,
user.email,
user.photoUrl,
user.photoShape,
user.emailHash,
user.description,
user.links,
user.legacyId,
user.role,
user.newsletterSubscriber
)
fun toDto(language: Language) =
UserDto(
login,
firstname,
lastname,
null,
company,
description[language]?.toHTML() ?: "",
emailHash,
photoUrl,
photoShape,
role,
links,
logoType(photoUrl),
logoWebpUrl(photoUrl),
newsletterSubscriber = newsletterSubscriber
)
fun toUser() =
User(
login,
firstname,
lastname,
email,
company,
description,
emailHash,
photoUrl,
photoShape,
role,
links,
legacyId,
newsletterSubscriber = newsletterSubscriber
)
val organizationName
get() = company ?: "$firstname $lastname"
}
| apache-2.0 | eb9add2c3f53e24edf65e968621f436f | 23.164557 | 55 | 0.555265 | 4.667482 | false | false | false | false |
pdvrieze/ProcessManager | java-common/src/commonMain/kotlin/net/devrieze/util/Handle.kt | 1 | 2684 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package net.devrieze.util
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.nullable
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import nl.adaptivity.util.multiplatform.URI
import kotlin.jvm.JvmInline
@JvmInline
@Serializable(HandleSerializer::class)
value class Handle<out T : Any?>(val handleValue: Long) : Comparable<Handle<@UnsafeVariance T>> {
constructor(handleString: String) : this(handleString.toLong())
constructor(handleUri: URI): this(handleUri.toHandleValue())
val isValid get() = handleValue >= 0L
override fun compareTo(other: Handle<@UnsafeVariance T>): Int {
return handleValue.compareTo(other.handleValue)
}
override fun toString(): String {
return "H:$handleValue"
}
companion object {
fun <T> invalid(): Handle<T> = Handle(-1L)
private fun URI.toHandleValue(): Long {
val path: String = getPath()
val slashPos = path.lastIndexOf('/')
return if (slashPos > 0) {
path.substring(slashPos + 1).toLong()
} else {
path.toLong()
}
}
}
}
class HandleSerializer<T>(@Suppress("UNUSED_PARAMETER") elemSerializer: KSerializer<T>) : KSerializer<Handle<T>> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("net.devrieze.util.Handle", PrimitiveKind.LONG)
override fun deserialize(decoder: Decoder): Handle<T> {
return Handle(decoder.decodeLong())
}
override fun serialize(encoder: Encoder, value: Handle<T>) {
when {
value.isValid -> encoder.encodeLong(value.handleValue)
else -> Unit //encoder.encodeNull()
}
}
}
| lgpl-3.0 | df050c3f052850d23024d18ed0d27433 | 32.974684 | 114 | 0.705663 | 4.572402 | false | false | false | false |
davidwhitman/Tir | app/src/main/kotlin/com/thunderclouddev/tirforgoodreads/api/OAuth1Interceptor.kt | 1 | 2454 | package com.thunderclouddev.tirforgoodreads.api
import com.github.scribejava.core.model.OAuth1AccessToken
import com.github.scribejava.core.model.OAuthConstants
import com.github.scribejava.core.model.OAuthRequest
import com.github.scribejava.core.model.Verb
import com.github.scribejava.core.oauth.OAuth10aService
import io.reactivex.Observable
import okhttp3.Interceptor
import okhttp3.Response
import org.fuckboilerplate.rx_social_connect.NotActiveTokenFoundException
import org.fuckboilerplate.rx_social_connect.RxSocialConnect
import java.io.IOException
class OAuth1Interceptor(protected val service: OAuth10aService) : Interceptor {
@Throws(IOException::class, NotActiveTokenFoundException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val url = request.url().toString()
val verb = apply(request.method())
val requestOAuth = OAuthRequest(verb, url, service)
val builderRequest = request.newBuilder()
val token = oToken.blockingFirst()
service.signRequest(token, requestOAuth)
val headers = requestOAuth.headers
for ((key, value) in headers) {
builderRequest.addHeader(key, value)
}
// NOTE: ADDED BY DAVID WHITMAN because for some reason, OAuth10aService isn't adding it.
builderRequest.addHeader(OAuthConstants.TOKEN_SECRET, token.tokenSecret)
val response = chain.proceed(builderRequest.build())
return response
}
private fun apply(method: String): Verb? {
if (method.equals("GET", ignoreCase = true))
return Verb.GET
else if (method.equals("POST", ignoreCase = true))
return Verb.POST
else if (method.equals("PUT", ignoreCase = true))
return Verb.PUT
else if (method.equals("DELETE", ignoreCase = true))
return Verb.DELETE
else if (method.equals("HEAD", ignoreCase = true))
return Verb.HEAD
else if (method.equals("OPTIONS", ignoreCase = true))
return Verb.OPTIONS
else if (method.equals("TRACE", ignoreCase = true))
return Verb.TRACE
else if (method.equals("PATCH", ignoreCase = true)) return Verb.PATCH
return null
}
//Exists for testing purposes
protected val oToken: Observable<OAuth1AccessToken>
get() = RxSocialConnect.getTokenOAuth1(service.api.javaClass)
} | gpl-3.0 | 505f2329b281913b5ded533df00a6edd | 36.769231 | 97 | 0.695599 | 4.421622 | false | false | false | false |
pdvrieze/ProcessManager | PMEditor/src/main/java/nl/adaptivity/process/ui/model/ProcessModelDetailActivity.kt | 1 | 5463 | /*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.ui.model
import android.content.Intent
import android.os.Bundle
import android.os.RemoteException
import android.support.v4.app.NavUtils
import android.view.MenuItem
import android.widget.Toast
import nl.adaptivity.android.util.GetNameDialogFragment
import nl.adaptivity.android.util.GetNameDialogFragment.GetNameDialogFragmentCallbacks
import nl.adaptivity.process.editor.android.R
import nl.adaptivity.process.models.ProcessModelProvider
import nl.adaptivity.process.ui.main.OverviewActivity
import nl.adaptivity.process.ui.main.ProcessBaseActivity
import nl.adaptivity.process.ui.main.SettingsActivity
import nl.adaptivity.process.ui.model.ProcessModelDetailFragment.ProcessModelDetailFragmentCallbacks
/**
* An activity representing a single ProcessModel detail screen. This activity
* is only used on handset devices. On tablet-size devices, item details are
* presented side-by-side with a list of items in a
* [ProcessModelListOuterFragment].
*
*
* This activity is mostly just a 'shell' activity containing nothing more than
* a [ProcessModelDetailFragment].
*/
class ProcessModelDetailActivity : ProcessBaseActivity(), ProcessModelDetailFragmentCallbacks, GetNameDialogFragmentCallbacks {
private var mModelHandleToInstantiate: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_processmodel_detail)
// Show the Up button in the action bar.
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
val arguments = Bundle()
arguments.putLong(ProcessModelDetailFragment.ARG_ITEM_ID,
intent.getLongExtra(ProcessModelDetailFragment.ARG_ITEM_ID, -1))
val fragment = ProcessModelDetailFragment()
fragment.arguments = arguments
supportFragmentManager.beginTransaction()
.add(R.id.processmodel_detail_container, fragment)
.commit()
}
requestAccount(SettingsActivity.getAuthBase(this))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, Intent(this, OverviewActivity::class.java))
return true
}
return super.onOptionsItemSelected(item)
}
override fun onProcessModelSelected(processModelRowId: Long) {
if (processModelRowId >= 0) {
val intent = Intent(this, ProcessModelDetailActivity::class.java)
intent.putExtra(ProcessModelDetailFragment.ARG_ITEM_ID, processModelRowId)
startActivity(intent)
}
finish()
}
override fun onInstantiateModel(modelHandle: Long, suggestedName: String) {
mModelHandleToInstantiate = modelHandle
GetNameDialogFragment.show(supportFragmentManager, DLG_MODEL_INSTANCE_NAME, "Instance name",
"Provide a name for the process instance", this, suggestedName)
}
override fun onNameDialogCompletePositive(dialog: GetNameDialogFragment, id: Int, name: String) {
try {
ProcessModelProvider.instantiate(this, mModelHandleToInstantiate, name)
} catch (e: RemoteException) {
Toast.makeText(this, "Unfortunately the process could not be instantiated: " + e.message,
Toast.LENGTH_SHORT).show()
}
}
override fun onNameDialogCompleteNegative(dialog: GetNameDialogFragment, id: Int) {
mModelHandleToInstantiate = -1L
}
companion object {
private val DLG_MODEL_INSTANCE_NAME = 1
}
}
| lgpl-3.0 | e1b8d6be02641202e9e811b4aff4aaf9 | 41.348837 | 127 | 0.6987 | 4.838795 | false | false | false | false |
naosim/rtmjava | src/main/java/com/naosim/someapp/infra/datasource/TaskRepositoryWithRTM.kt | 1 | 4492 | package com.naosim.someapp.infra.datasource
import com.naosim.rtm.domain.model.Filter
import com.naosim.rtm.domain.model.auth.Token
import com.naosim.rtm.domain.model.task.*
import com.naosim.rtm.domain.model.timeline.TransactionalResponse
import com.naosim.rtm.domain.repository.RtmRepository
import com.naosim.someapp.domain.*
class タスクRepositoryWithRTM(val token: Token, val rtmRepository: RtmRepository): タスクRepository {
val タスクIDConverter = タスクIDConverter()
override fun 追加(タスク名: タスク名, タスク消化予定日Optional: タスク消化予定日Optional): タスクEntity {
val timeline = rtmRepository.createTimeline(token)
val taskDueDateTimeOptional = タスク消化予定日Optional.get().map{ TaskDueDateTime(it.localDate.atStartOfDay()) }
val taskIdSet = rtmRepository.addTask(token, timeline, TaskSeriesName(タスク名.value)).response.taskIdSet
rtmRepository.updateDueDateTime(token, timeline, taskIdSet, taskDueDateTimeOptional)
val タスクID = タスクIDConverter.createタスクID(taskIdSet)
return タスクEntityWithRTM(
タスクID,
タスク更新RepositoryWithRTM(token, taskIdSet, this, rtmRepository),
タスク名,
タスク消化予定日Optional,
タスク完了日NotExist()
)
}
fun convertTaskSeriesEntityToタスクEntity(taskSeriesEntity: TaskSeriesEntity): タスクEntityWithRTM {
val タスクID = タスクIDConverter.createタスクID(taskSeriesEntity.taskIdSet)
val タスク消化予定日Optional = taskSeriesEntity.taskEntity.taskDateTimes.taskDueDateTime
.map { タスク消化予定日(it.dateTime.toLocalDate()) as タスク消化予定日Optional }
.orElse(タスク消化予定日NotExist())
val タスク完了日Optional = taskSeriesEntity.taskEntity.taskDateTimes.taskCompletedDateTime
.map { タスク完了日(it.dateTime.toLocalDate()) as タスク完了日Optional }
.orElse(タスク完了日NotExist())
return タスクEntityWithRTM(
タスクID,
タスク更新RepositoryWithRTM(token, taskSeriesEntity.taskIdSet, this, rtmRepository),
タスク名(taskSeriesEntity.taskSeriesName.rtmParamValue),
タスク消化予定日Optional,
タスク完了日Optional
)
}
override fun すべてのタスク取得(): List<タスクEntity> {
val タスクEntityList: List<タスクEntity> = rtmRepository.getTaskList(token, Filter("(status:incomplete)or(completedAfter:25/06/2016)"))
.map { it.taskSeriesEntityList }
.reduce { a, b -> a.plus(b) }
.map { convertTaskSeriesEntityToタスクEntity(it) }
// .sorted()
return タスクEntityList
}
override fun 完了(タスクID: タスクID): タスクEntity {
val timelineId = rtmRepository.createTimeline(token)
val result = rtmRepository.completeTask(token, timelineId, タスクIDConverter.createTaskIdSet(タスクID)).response
return convertTaskSeriesEntityToタスクEntity(result);
}
}
class タスク更新RepositoryWithRTM(
val token: Token,
val taskIdSet: TaskIdSet,
val タスクRepositoryWithRTM: タスクRepositoryWithRTM,
val rtmRepository: RtmRepository
): タスク更新Repository {
override fun タスク消化予定日変更(タスク消化予定日Optional: タスク消化予定日Optional): タスクEntity {
val res = rtmRepository.updateStartDateTime(
token,
rtmRepository.createTimeline(token),
taskIdSet,
タスク消化予定日Optional.get().map { TaskStartDateTime(it.localDate.atStartOfDay()) }
)
return タスクRepositoryWithRTM.convertTaskSeriesEntityToタスクEntity(res.response)
}
override fun リネーム(タスク名: タスク名): タスクEntity {
throw NotImplementedError()
}
override fun タスクDONE(): タスクEntity {
val res = rtmRepository.completeTask(
token,
rtmRepository.createTimeline(token),
taskIdSet
)
return タスクRepositoryWithRTM.convertTaskSeriesEntityToタスクEntity(res.response)
}
}
| mit | 54786d0b83515b4d628794f8b094d330 | 40.397849 | 137 | 0.678182 | 3.973168 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/registry/LanternFactoryRegistry.kt | 1 | 1581 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry
import com.google.common.reflect.TypeToken
import org.lanternpowered.api.registry.DuplicateRegistrationException
import org.lanternpowered.api.registry.FactoryRegistry
import org.lanternpowered.api.registry.UnknownTypeException
object LanternFactoryRegistry : FactoryRegistry {
private val factories = mutableMapOf<Class<*>, Any>()
@Suppress("UNCHECKED_CAST")
override fun <T : Any> provideFactory(clazz: Class<T>): T =
this.factories[clazz] as? T ?: throw UnknownTypeException("There's no factory registered with the type ${clazz.simpleName}.")
fun register(factory: Any) {
val factoryTypes = TypeToken.of(factory.javaClass).types.rawTypes()
.filterNot { it as Class<*> == Object::class.java }
.filter { it.isInterface }
for (factoryType in factoryTypes)
this.factories.putIfAbsent(factoryType, factory)
}
fun <T : Any> register(factoryClass: Class<T>, factory: T): T {
val old = this.factories.putIfAbsent(factoryClass, factory)
if (old != null)
throw DuplicateRegistrationException("There's already a factory registered fot the type: $factoryClass")
return factory
}
}
| mit | bc98df95c7a5e1ac158600625e87391e | 38.525 | 137 | 0.700822 | 4.343407 | false | false | false | false |
OpenWeen/OpenWeen.Droid | app/src/main/java/moe/tlaster/openween/core/api/friendships/Friends.kt | 1 | 3036 | package moe.tlaster.openween.core.api.friendships
import android.support.v4.util.ArrayMap
import moe.tlaster.openween.core.api.Constants
import moe.tlaster.openween.core.model.user.UserListModel
import moe.tlaster.openween.core.model.user.UserModel
import moe.tlaster.openween.common.helpers.HttpHelper
/**
* Created by Tlaster on 2016/9/7.
*/
object Friends {
private fun <T> getUsers(uid: T, count: Int, cursor: Int, url: String) : UserListModel {
val param = ArrayMap<String, String>()
param.put("uid", uid.toString())
param.put("count", count.toString())
param.put("cursor", cursor.toString())
return HttpHelper.getAsync(url, param)
}
fun getFriends(uid: Long, count: Int, cursor: Int) : UserListModel {
return getUsers(uid, count, cursor, Constants.FRIENDSHIPS_FRIENDS)
}
fun getFriends(screen_name: String, count: Int, cursor: Int) : UserListModel {
return getUsers(screen_name, count, cursor, Constants.FRIENDSHIPS_FRIENDS)
}
fun getFriendsInCommon(uid: Long, suid: Long, count: Int, page: Int) : UserListModel {
val param = ArrayMap<String, String>()
param.put("uid", uid.toString())
param.put("count", count.toString())
param.put("page", page.toString())
if (suid != -1L) param.put("suid", suid.toString())
return HttpHelper.getAsync(Constants.FRIENDSHIPS_FRIENDS_IN_COMMON, param)
}
fun getBliateral(uid: Long, count: Int, page: Int, sort: Int) : UserListModel {
val param = ArrayMap<String, String>()
param.put("uid", uid.toString())
param.put("count", count.toString())
param.put("page", page.toString())
param.put("sort", sort.toString())
return HttpHelper.getAsync(Constants.FRIENDSHIPS_FRIENDS_BILATERAL, param)
}
fun getFollowers(uid: Long, count: Int, cursor: Int) : UserListModel {
return getUsers(uid, count, cursor, Constants.FRIENDSHIPS_FOLLOWERS)
}
fun getFollowers(screen_name: String, count: Int, cursor: Int) : UserListModel {
return getUsers(screen_name, count, cursor, Constants.FRIENDSHIPS_FOLLOWERS)
}
fun follow(uid: Long) : UserModel {
val param = ArrayMap<String, String>()
param.put("uid", uid.toString())
return HttpHelper.postAsync(Constants.FRIENDSHIPS_CREATE, param)
}
fun follow(screen_name: String) : UserModel {
val param = ArrayMap<String, String>()
param.put("screen_name", screen_name)
return HttpHelper.postAsync(Constants.FRIENDSHIPS_CREATE, param)
}
fun unfollow(uid: Long) : UserModel {
val param = ArrayMap<String, String>()
param.put("uid", uid.toString())
return HttpHelper.postAsync(Constants.FRIENDSHIPS_DESTROY, param)
}
fun unfollow(screen_name: String) : UserModel {
val param = ArrayMap<String, String>()
param.put("screen_name", screen_name)
return HttpHelper.postAsync(Constants.FRIENDSHIPS_DESTROY, param)
}
}
| mit | 944560e239063418ff00cf7fbbe6df47 | 37.43038 | 92 | 0.665679 | 3.852792 | false | false | false | false |
sabi0/intellij-community | python/src/com/jetbrains/python/sdk/pipenv/pipenv.kt | 1 | 18422 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk.pipenv
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.annotations.SerializedName
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.execution.ExecutionException
import com.intellij.execution.RunCanceledByUserException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.PathEnvironmentVariableUtil
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessOutput
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import com.jetbrains.python.inspections.PyPackageRequirementsInspection
import com.jetbrains.python.packaging.*
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import icons.PythonIcons
import org.jetbrains.annotations.SystemDependent
import org.jetbrains.annotations.TestOnly
import java.io.File
import javax.swing.Icon
/**
* @author vlan
*/
const val PIP_FILE: String = "Pipfile"
const val PIP_FILE_LOCK: String = "Pipfile.lock"
const val PIPENV_DEFAULT_SOURCE_URL: String = "https://pypi.org/simple"
const val PIPENV_PATH_SETTING: String = "PyCharm.Pipenv.Path"
// TODO: Provide a special icon for pipenv
val PIPENV_ICON: Icon = PythonIcons.Python.PythonClosed
/**
* The Pipfile found in the main content root of the module.
*/
val Module.pipFile: VirtualFile?
get() =
baseDir?.findChild(PIP_FILE)
/**
* Tells if the SDK was added as a pipenv.
*/
var Sdk.isPipEnv: Boolean
get() = sdkAdditionalData is PyPipEnvSdkAdditionalData
set(value) {
val oldData = sdkAdditionalData
val newData = if (value) {
when (oldData) {
is PythonSdkAdditionalData -> PyPipEnvSdkAdditionalData(oldData)
else -> PyPipEnvSdkAdditionalData()
}
}
else {
when (oldData) {
is PyPipEnvSdkAdditionalData -> PythonSdkAdditionalData(PythonSdkFlavor.getFlavor(this))
else -> oldData
}
}
val modificator = sdkModificator
modificator.sdkAdditionalData = newData
ApplicationManager.getApplication().runWriteAction { modificator.commitChanges() }
}
/**
* The user-set persisted path to the pipenv executable.
*/
var PropertiesComponent.pipEnvPath: @SystemDependent String?
get() = getValue(PIPENV_PATH_SETTING)
set(value) {
setValue(PIPENV_PATH_SETTING, value)
}
/**
* Detects the pipenv executable in `$PATH`.
*/
fun detectPipEnvExecutable(): File? {
val name = when {
SystemInfo.isWindows -> "pipenv.exe"
else -> "pipenv"
}
return PathEnvironmentVariableUtil.findInPath(name)
}
/**
* Returns the configured pipenv executable or detects it automatically.
*/
fun getPipEnvExecutable(): File? =
PropertiesComponent.getInstance().pipEnvPath?.let { File(it) } ?: detectPipEnvExecutable()
/**
* Sets up the pipenv environment under the modal progress window.
*
* The pipenv is associated with the first valid object from this list:
*
* 1. New project specified by [newProjectPath]
* 2. Existing module specified by [module]
* 3. Existing project specified by [project]
*
* @return the SDK for pipenv, not stored in the SDK table yet.
*/
fun setupPipEnvSdkUnderProgress(project: Project?,
module: Module?,
existingSdks: List<Sdk>,
newProjectPath: String?,
python: String?,
installPackages: Boolean): Sdk? {
val projectPath = newProjectPath ?:
module?.basePath ?:
project?.basePath ?:
return null
val task = object : Task.WithResult<String, ExecutionException>(project, "Setting Up Pipenv Environment", true) {
override fun compute(indicator: ProgressIndicator): String {
indicator.isIndeterminate = true
val pipEnv = setupPipEnv(FileUtil.toSystemDependentName(projectPath), python, installPackages)
return PythonSdkType.getPythonExecutable(pipEnv) ?: FileUtil.join(pipEnv, "bin", "python")
}
}
val suggestedName = "Pipenv (${PathUtil.getFileName(projectPath)})"
return createSdkByGenerateTask(task, existingSdks, null, projectPath, suggestedName)?.apply {
isPipEnv = true
associateWithModule(module, newProjectPath)
}
}
/**
* Sets up the pipenv environment for the specified project path.
*
* @return the path to the pipenv environment.
*/
fun setupPipEnv(projectPath: @SystemDependent String, python: String?, installPackages: Boolean): @SystemDependent String {
when {
installPackages -> {
val pythonArgs = if (python != null) listOf("--python", python) else emptyList()
val command = pythonArgs + listOf("install", "--dev")
runPipEnv(projectPath, *command.toTypedArray())
}
python != null ->
runPipEnv(projectPath, "--python", python)
else ->
runPipEnv(projectPath, "run", "python", "-V")
}
return runPipEnv(projectPath, "--venv").trim()
}
/**
* Runs the configured pipenv for the specified Pipenv SDK with the associated project path.
*/
fun runPipEnv(sdk: Sdk, vararg args: String): String {
val projectPath = sdk.associatedModulePath ?:
throw PyExecutionException("Cannot find the project associated with this Pipenv environment",
"Pipenv", emptyList(), ProcessOutput())
return runPipEnv(projectPath, *args)
}
/**
* Runs the configured pipenv for the specified project path.
*/
fun runPipEnv(projectPath: @SystemDependent String, vararg args: String): String {
val executable = getPipEnvExecutable()?.path ?:
throw PyExecutionException("Cannot find Pipenv", "pipenv", emptyList(), ProcessOutput())
val command = listOf(executable) + args
val commandLine = GeneralCommandLine(command).withWorkDirectory(projectPath)
val handler = CapturingProcessHandler(commandLine)
val indicator = ProgressManager.getInstance().progressIndicator
val result = with(handler) {
when {
indicator != null -> {
addProcessListener(PyPackageManagerImpl.IndicatedProcessOutputListener(indicator))
runProcessWithProgressIndicator(indicator)
}
else ->
runProcess()
}
}
return with(result) {
when {
isCancelled ->
throw RunCanceledByUserException()
exitCode != 0 ->
throw PyExecutionException("Error Running Pipenv", executable, args.asList(),
stdout, stderr, exitCode, emptyList())
else -> stdout
}
}
}
/**
* Detects and sets up pipenv SDK for a module with Pipfile.
*/
fun detectAndSetupPipEnv(project: Project?, module: Module?, existingSdks: List<Sdk>): Sdk? {
if (module?.pipFile == null || getPipEnvExecutable() == null) {
return null
}
return setupPipEnvSdkUnderProgress(project, module, existingSdks, null, null, false)
}
/**
* The URLs of package sources configured in the Pipfile.lock of the module associated with this SDK.
*/
val Sdk.pipFileLockSources: List<String>
get() = parsePipFileLock()?.meta?.sources?.mapNotNull { it.url } ?:
listOf(PIPENV_DEFAULT_SOURCE_URL)
/**
* The list of requirements defined in the Pipfile.lock of the module associated with this SDK.
*/
val Sdk.pipFileLockRequirements: List<PyRequirement>?
get() {
return pipFileLock?.let { getPipFileLockRequirements(it, packageManager) }
}
/**
* A quick-fix for setting up the pipenv for the module of the current PSI element.
*/
class UsePipEnvQuickFix(sdk: Sdk?, module: Module) : LocalQuickFix {
private val quickFixName = when {
sdk != null && sdk.associatedModule != module -> "Fix Pipenv interpreter"
else -> "Use Pipenv interpreter"
}
companion object {
fun isApplicable(module: Module): Boolean = module.pipFile != null
fun setUpPipEnv(project: Project, module: Module) {
val sdksModel = ProjectSdksModel().apply {
reset(project)
}
val existingSdks = sdksModel.sdks.filter { it.sdkType is PythonSdkType }
// XXX: Should we show an error message on exceptions and on null?
val newSdk = setupPipEnvSdkUnderProgress(project, module, existingSdks, null, null, false) ?: return
val existingSdk = existingSdks.find { it.isPipEnv && it.homePath == newSdk.homePath }
val sdk = existingSdk ?: newSdk
if (sdk == newSdk) {
SdkConfigurationUtil.addSdk(newSdk)
}
else {
sdk.associateWithModule(module, null)
}
project.pythonSdk = sdk
module.pythonSdk = sdk
}
}
override fun getFamilyName() = quickFixName
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement ?: return
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return
// Invoke the setup later to escape the write action of the quick fix in order to show the modal progress dialog
ApplicationManager.getApplication().invokeLater {
if (project.isDisposed || module.isDisposed) return@invokeLater
setUpPipEnv(project, module)
}
}
}
/**
* A quick-fix for installing packages specified in Pipfile.lock.
*/
class PipEnvInstallQuickFix : LocalQuickFix {
companion object {
fun pipEnvInstall(project: Project, module: Module) {
val sdk = module.pythonSdk ?: return
if (!sdk.isPipEnv) return
val listener = PyPackageRequirementsInspection.RunningPackagingTasksListener(module)
val ui = PyPackageManagerUI(project, sdk, listener)
ui.install(null, listOf("--dev"))
}
}
override fun getFamilyName() = "Install requirements from Pipfile.lock"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement ?: return
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return
pipEnvInstall(project, module)
}
}
/**
* Watches for edits in Pipfiles inside modules with a pipenv SDK set.
*/
class PipEnvPipFileWatcherComponent(val project: Project) : ProjectComponent {
override fun projectOpened() {
val editorFactoryListener = object : EditorFactoryListener {
private val changeListenerKey = Key.create<DocumentListener>("Pipfile.change.listener")
private val notificationActive = Key.create<Boolean>("Pipfile.notification.active")
override fun editorCreated(event: EditorFactoryEvent) {
if (!isPipFileEditor(event.editor)) return
val listener = object : DocumentListener {
override fun documentChanged(event: DocumentEvent?) {
val module = event?.document?.virtualFile?.getModule(project) ?: return
notifyPipFileChanged(module)
}
}
with(event.editor.document) {
addDocumentListener(listener)
putUserData(changeListenerKey, listener)
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val listener = event.editor.getUserData(changeListenerKey) ?: return
event.editor.document.removeDocumentListener(listener)
}
private fun notifyPipFileChanged(module: Module) {
if (module.getUserData(notificationActive) == true) return
val what = when {
module.pipFileLock == null -> "not found"
else -> "out of date"
}
val title = "$PIP_FILE_LOCK is $what"
val content = "Run <a href='#lock'>pipenv lock</a> or <a href='#update'>pipenv update</a>"
val notification = LOCK_NOTIFICATION_GROUP.createNotification(title, null, content,
NotificationType.INFORMATION) { notification, event ->
notification.expire()
module.putUserData(notificationActive, null)
FileDocumentManager.getInstance().saveAllDocuments()
when (event.description) {
"#lock" ->
runPipEnvInBackground(module, listOf("lock"), "Locking $PIP_FILE")
"#update" ->
runPipEnvInBackground(module, listOf("update", "--dev"), "Updating Pipenv environment")
}
}
module.putUserData(notificationActive, true)
notification.whenExpired {
module.putUserData(notificationActive, null)
}
notification.notify(project)
}
private fun runPipEnvInBackground(module: Module, args: List<String>, description: String) {
val task = object : Task.Backgroundable(module.project, StringUtil.toTitleCase(description), true) {
override fun run(indicator: ProgressIndicator) {
val sdk = module.pythonSdk ?: return
indicator.text = "$description..."
try {
runPipEnv(sdk, *args.toTypedArray())
}
catch (e: RunCanceledByUserException) {}
catch (e: ExecutionException) {
runInEdt {
Messages.showErrorDialog(project, e.toString(), "Error Running Pipenv")
}
}
}
}
ProgressManager.getInstance().run(task)
}
private fun isPipFileEditor(editor: Editor): Boolean {
if (editor.project != project) return false
val file = editor.document.virtualFile ?: return false
if (file.name != PIP_FILE) return false
val module = file.getModule(project) ?: return false
if (module.pipFile != file) return false
return module.pythonSdk?.isPipEnv == true
}
}
EditorFactory.getInstance().addEditorFactoryListener(editorFactoryListener, project)
}
}
private val Document.virtualFile: VirtualFile?
get() = FileDocumentManager.getInstance().getFile(this)
private fun VirtualFile.getModule(project: Project): Module? =
ModuleUtil.findModuleForFile(this, project)
private val LOCK_NOTIFICATION_GROUP = NotificationGroup("$PIP_FILE Watcher", NotificationDisplayType.STICKY_BALLOON, false)
private val Sdk.packageManager: PyPackageManager
get() = PyPackageManagers.getInstance().forSdk(this)
@TestOnly
fun getPipFileLockRequirements(virtualFile: VirtualFile, packageManager: PyPackageManager): List<PyRequirement>? {
fun toRequirements(packages: Map<String, PipFileLockPackage>): List<PyRequirement> =
packages
.asSequence()
.filterNot { (_, pkg) -> pkg.editable ?: false }
// TODO: Support requirements markers (PEP 496), currently any packages with markers are ignored due to PY-30803
.filter { (_, pkg) -> pkg.markers == null }
.flatMap { (name, pkg) -> packageManager.parseRequirements("$name${pkg.version ?: ""}").asSequence() }
.toList()
val pipFileLock = parsePipFileLock(virtualFile) ?: return null
val packages = pipFileLock.packages?.let { toRequirements(it) } ?: emptyList()
val devPackages = pipFileLock.devPackages?.let { toRequirements(it) } ?: emptyList()
return packages + devPackages
}
private fun Sdk.parsePipFileLock(): PipFileLock? {
// TODO: Log errors if Pipfile.lock is not found
val file = pipFileLock ?: return null
return parsePipFileLock(file)
}
private fun parsePipFileLock(virtualFile: VirtualFile): PipFileLock? {
val text = ReadAction.compute<String, Throwable> { FileDocumentManager.getInstance().getDocument(virtualFile)?.text }
return try {
Gson().fromJson(text, PipFileLock::class.java)
}
catch (e: JsonSyntaxException) {
// TODO: Log errors
return null
}
}
private val Sdk.pipFileLock: VirtualFile?
get() =
associatedModulePath?.let { StandardFileSystems.local().findFileByPath(it)?.findChild(PIP_FILE_LOCK) }
private val Module.pipFileLock: VirtualFile?
get() = baseDir?.findChild(PIP_FILE_LOCK)
private data class PipFileLock(@SerializedName("_meta") var meta: PipFileLockMeta?,
@SerializedName("default") var packages: Map<String, PipFileLockPackage>?,
@SerializedName("develop") var devPackages: Map<String, PipFileLockPackage>?)
private data class PipFileLockMeta(@SerializedName("sources") var sources: List<PipFileLockSource>?)
private data class PipFileLockSource(@SerializedName("url") var url: String?)
private data class PipFileLockPackage(@SerializedName("version") var version: String?,
@SerializedName("editable") var editable: Boolean?,
@SerializedName("hashes") var hashes: List<String>?,
@SerializedName("markers") var markers: String?)
| apache-2.0 | e73397d6bf27c4435b006b75958c6f79 | 38.195745 | 140 | 0.702475 | 4.562159 | false | false | false | false |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/events/EventQueueService.kt | 1 | 9350 | package io.rover.sdk.core.events
import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import io.rover.sdk.core.data.NetworkResult
import io.rover.sdk.core.data.domain.DeviceContext
import io.rover.sdk.core.data.domain.EventSnapshot
import io.rover.sdk.core.data.graphql.GraphQlApiServiceInterface
import io.rover.sdk.core.data.graphql.getObjectIterable
import io.rover.sdk.core.data.graphql.operations.data.asJson
import io.rover.sdk.core.data.graphql.operations.data.decodeJson
import io.rover.sdk.core.events.domain.Event
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.core.platform.DateFormattingInterface
import io.rover.sdk.core.platform.LocalStorage
import io.rover.sdk.core.streams.PublishSubject
import io.rover.sdk.core.streams.Scheduler
import io.rover.sdk.core.streams.observeOn
import io.rover.sdk.core.streams.share
import org.json.JSONArray
import org.reactivestreams.Publisher
import java.lang.AssertionError
import java.util.Deque
import java.util.LinkedList
import java.util.concurrent.Executors
class EventQueueService(
private val graphQlApiService: GraphQlApiServiceInterface,
localStorage: LocalStorage,
private val dateFormatting: DateFormattingInterface,
application: Application,
mainScheduler: Scheduler,
private val flushAt: Int,
private val flushIntervalSeconds: Double,
private val maxBatchSize: Int,
private val maxQueueSize: Int
) : EventQueueServiceInterface {
private val serialQueueExecutor = Executors.newSingleThreadExecutor()
private val contextProviders: MutableList<ContextProvider> = mutableListOf()
private val keyValueStorage = localStorage.getKeyValueStorageFor(STORAGE_CONTEXT_IDENTIFIER)
private val eventSubject = PublishSubject<Event>()
// state:
private val eventQueue: Deque<EventSnapshot> = LinkedList()
private var deviceContext: DeviceContext? = null
private var isFlushingEvents: Boolean = false
override val trackedEvents: Publisher<Event> = eventSubject.observeOn(mainScheduler).share()
override fun addContextProvider(contextProvider: ContextProvider) {
serialQueueExecutor.execute {
contextProviders.add(contextProvider)
}
contextProvider.registeredWithEventQueue(this)
}
override fun trackEvent(event: Event, namespace: String?) {
try {
log.v("Tracking event: $event")
} catch (e: AssertionError) {
// Workaround for a bug in Android that can cause crashes on Android 8.0 and 8.1 when
// calling toString() on a java.util.Date
log.w("Logging tracking event failed: $e")
}
captureContext()
enqueueEvent(event, namespace)
eventSubject.onNext(event)
flushEvents(flushAt)
}
override fun trackScreenViewed(screenName: String, contentID: String?, contentName: String?) {
val attributes = mutableMapOf<String, Any>("screenName" to screenName)
contentName?.let { attributes.put("contentName", it) }
contentID?.let { attributes.put("contentID", it) }
trackEvent(Event("Screen Viewed", attributes))
}
override fun flushNow() {
flushEvents(1)
}
private fun enqueueEvent(event: Event, namespace: String?) {
serialQueueExecutor.execute {
if (eventQueue.count() == maxQueueSize) {
log.w("Event queue is at capacity ($maxQueueSize) -- removing oldest event.")
eventQueue.removeFirst()
}
val snapshot = EventSnapshot.fromEvent(
event,
deviceContext ?: throw RuntimeException("enqueueEvent() occurred before Context set up?"),
namespace
)
eventQueue.add(snapshot)
persistEvents()
}
}
private fun persistEvents() {
serialQueueExecutor.execute {
val json = JSONArray(eventQueue.map { event -> event.asJson(dateFormatting) }).toString(4)
keyValueStorage.set(QUEUE_KEY, json)
}
}
private fun restoreEvents() {
// load the current events from key value storage.
eventQueue.clear()
val storedJson = keyValueStorage.get(QUEUE_KEY)
if (storedJson != null) {
val decoded = try {
JSONArray(storedJson).getObjectIterable().map { jsonObject ->
EventSnapshot.decodeJson(jsonObject, dateFormatting)
}
} catch (e: Throwable) {
log.w("Invalid persisted events queue. Ignoring and starting fresh. ${e.message}")
null
}
eventQueue.addAll(
decoded ?: emptyList()
)
if (eventQueue.isNotEmpty()) {
log.v("Events queue with ${eventQueue.count()} events waiting has been restored.")
}
}
}
private fun flushEvents(minBatchSize: Int) {
serialQueueExecutor.execute {
if (isFlushingEvents) {
log.v("Skipping flush, already in progress")
return@execute
}
if (eventQueue.isEmpty()) {
log.v("Skipping flush -- no events in the queue.")
return@execute
}
if (eventQueue.count() < minBatchSize) {
log.v("Skipping flush -- less than $minBatchSize events in the queue.")
return@execute
}
val events = eventQueue.take(maxBatchSize)
log.v("Uploading ${events.count()} event(s) to the Rover API.")
isFlushingEvents = true
graphQlApiService.submitEvents(events).subscribe { networkResult ->
when (networkResult) {
is NetworkResult.Error -> {
log.i("Error delivering ${events.count()} events to the Rover API: ${networkResult.throwable.message}")
if (networkResult.shouldRetry) {
log.i("... will leave them enqueued for a future retry.")
} else {
removeEvents(events)
}
}
is NetworkResult.Success -> {
log.v("Successfully uploaded ${events.count()} events.")
removeEvents(events)
}
}
isFlushingEvents = false
}
}
}
private fun removeEvents(eventsToRemove: List<EventSnapshot>) {
val idsToRemove = eventsToRemove.associateBy { it.id }
serialQueueExecutor.execute {
eventQueue.clear()
eventQueue.addAll(
eventQueue.filter { existingEvent ->
!idsToRemove.containsKey(existingEvent.id)
}
)
log.v("Removed ${eventsToRemove.count()} event(s) from the queue -- it now contains ${eventQueue.count()} event(s).")
persistEvents()
}
}
private fun captureContext() {
serialQueueExecutor.execute {
log.v("Capturing context...")
deviceContext = contextProviders.fold(DeviceContext.blank()) { current, provider ->
provider.captureContext(current)
}
log.v("Context is now: $deviceContext.")
}
}
init {
log.v("Starting up.")
if (singletonStartedGuard) {
throw RuntimeException("EventQueueService started twice.")
}
singletonStartedGuard = true
restoreEvents()
log.v("Starting $flushIntervalSeconds timer for submitting events.")
// run a timer
val handler = Handler(Looper.getMainLooper())
fun scheduleFlushPoll() {
handler.postDelayed({
flushEvents(1)
scheduleFlushPoll()
}, flushIntervalSeconds.toLong() * 1000)
}
scheduleFlushPoll()
// TODO: wire up Application-level activity callbacks after all to flush queue whenever an activity pauses.
application.registerActivityLifecycleCallbacks(
object : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity) {
log.d("An Activity is pausing, flushing Rover events queue.")
flushNow()
}
override fun onActivityResumed(activity: Activity) { }
override fun onActivityStarted(activity: Activity) { }
override fun onActivityDestroyed(activity: Activity) { }
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { }
override fun onActivityStopped(activity: Activity) { }
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { }
}
)
}
companion object {
private const val STORAGE_CONTEXT_IDENTIFIER = "events-queue"
private const val QUEUE_KEY = "queue"
const val ROVER_NAMESPACE = "rover"
private var singletonStartedGuard = false
}
}
| apache-2.0 | e32f1829ad74b7c67791819fa588b31b | 35.24031 | 129 | 0.615187 | 5.005353 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/highlighting/LatexSyntaxHighlighter.kt | 1 | 5503 | package nl.hannahsten.texifyidea.highlighting
import com.intellij.lexer.Lexer
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import nl.hannahsten.texifyidea.LatexLexerAdapter
import nl.hannahsten.texifyidea.psi.LatexTypes
/**
* @author Hannah Schellekens, Sten Wessel
*/
class LatexSyntaxHighlighter : SyntaxHighlighterBase() {
override fun getHighlightingLexer(): Lexer {
return LatexLexerAdapter()
}
override fun getTokenHighlights(tokenType: IElementType): Array<out TextAttributesKey?> {
return if (tokenType == LatexTypes.OPEN_BRACE || tokenType == LatexTypes.CLOSE_BRACE) {
BRACES_KEYS
}
else if (tokenType == LatexTypes.OPEN_BRACKET || tokenType == LatexTypes.CLOSE_BRACKET) {
BRACKET_KEYS
}
else if (tokenType == LatexTypes.MAGIC_COMMENT_TOKEN) {
MAGIC_COMMENT_KEYS
}
else if (tokenType == LatexTypes.COMMENT_TOKEN) {
COMMENT_KEYS
}
else if (COMMAND_TOKENS.contains(tokenType)) {
COMMAND_KEYS
}
else if (tokenType == LatexTypes.INLINE_MATH_END) {
INLINE_MATH_KEYS
}
else if (tokenType == LatexTypes.DISPLAY_MATH_START || tokenType == LatexTypes.DISPLAY_MATH_END) {
DISPLAY_MATH_KEYS
}
else if (tokenType == LatexTypes.STAR) {
STAR_KEYS
}
else {
EMPTY_KEYS
}
}
companion object {
/*
* TextAttributesKeys
*/
val BRACES = createKey("LATEX_BRACES", DefaultLanguageHighlighterColors.BRACES)
val BRACKETS = createKey("LATEX_BRACKETS", DefaultLanguageHighlighterColors.BRACKETS)
val OPTIONAL_PARAM = createKey("LATEX_OPTIONAL_PARAM", DefaultLanguageHighlighterColors.PARAMETER)
val COMMAND = createKey("LATEX_COMMAND", DefaultLanguageHighlighterColors.KEYWORD)
val COMMAND_MATH_INLINE = createKey("LATEX_COMMAND_MATH_INLINE", DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE)
val COMMAND_MATH_DISPLAY = createKey("LATEX_COMMAND_MATH_DISPLAY", DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE)
val COMMENT = createKey("LATEX_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT)
val MAGIC_COMMENT = createKey("LATEX_MAGIC_COMMENT", DefaultLanguageHighlighterColors.DOC_COMMENT)
val INLINE_MATH = createKey("LATEX_INLINE_MATH", DefaultLanguageHighlighterColors.STRING)
val DISPLAY_MATH = createKey("LATEX_DISPLAY_MATH", DefaultLanguageHighlighterColors.STRING)
val STAR = createKey("LATEX_STAR", DefaultLanguageHighlighterColors.DOT)
val LABEL_DEFINITION = createKey("LATEX_LABEL_DEFINITION", DefaultLanguageHighlighterColors.IDENTIFIER)
val LABEL_REFERENCE = createKey("LATEX_LABEL_REFERENCE", DefaultLanguageHighlighterColors.IDENTIFIER)
val BIBLIOGRAPHY_DEFINITION = createKey("LATEX_BIBLIOGRAPHY_DEFINITION", LABEL_DEFINITION)
val BIBLIOGRAPHY_REFERENCE = createKey("LATEX_BIBLIOGRAPHY_REFERENCE", LABEL_REFERENCE)
val STYLE_BOLD = createKey("LATEX_STYLE_BOLD", DefaultLanguageHighlighterColors.IDENTIFIER)
val STYLE_ITALIC = createKey("LATEX_STYLE_ITALIC", DefaultLanguageHighlighterColors.IDENTIFIER)
val STYLE_UNDERLINE = createKey("LATEX_STYLE_UNDERLINE", DefaultLanguageHighlighterColors.IDENTIFIER)
val STYLE_STRIKETHROUGH = createKey("LATEX_STYLE_STRIKETHROUGH", DefaultLanguageHighlighterColors.IDENTIFIER)
val STYLE_SMALL_CAPITALS = createKey("LATEX_STYLE_SMALL_CAPITALS", DefaultLanguageHighlighterColors.IDENTIFIER)
val STYLE_OVERLINE = createKey("LATEX_STYLE_OVERLINE", DefaultLanguageHighlighterColors.IDENTIFIER)
val STYLE_TYPEWRITER = createKey("LATEX_STYLE_TYPEWRITER", DefaultLanguageHighlighterColors.IDENTIFIER)
val STYLE_SLANTED = createKey("LATEX_STYLE_SLANTED", DefaultLanguageHighlighterColors.IDENTIFIER)
val MATH_NESTED_TEXT = createKey("LATEX_MATH_NESTED_TEXT", DefaultLanguageHighlighterColors.IDENTIFIER)
private val COMMAND_TOKENS = TokenSet.create(
LatexTypes.COMMAND_TOKEN,
LatexTypes.COMMAND_IFNEXTCHAR,
LatexTypes.BEGIN_TOKEN,
LatexTypes.END_TOKEN,
LatexTypes.BEGIN_PSEUDOCODE_BLOCK,
LatexTypes.MIDDLE_PSEUDOCODE_BLOCK,
LatexTypes.END_PSEUDOCODE_BLOCK
)
/*
* TextAttributeKey[]s
*/
private val BRACES_KEYS = keys(BRACES)
private val BRACKET_KEYS = keys(BRACKETS)
private val COMMAND_KEYS = keys(COMMAND)
private val COMMENT_KEYS = keys(COMMENT)
private val MAGIC_COMMENT_KEYS = keys(MAGIC_COMMENT)
private val INLINE_MATH_KEYS = keys(INLINE_MATH)
private val DISPLAY_MATH_KEYS = keys(DISPLAY_MATH)
private val STAR_KEYS = keys(STAR)
private val EMPTY_KEYS = arrayOfNulls<TextAttributesKey>(0)
private fun createKey(externalName: String, defaultStyle: TextAttributesKey): TextAttributesKey {
return TextAttributesKey.createTextAttributesKey(externalName, defaultStyle)
}
private fun keys(vararg keys: TextAttributesKey): Array<out TextAttributesKey> {
return keys
}
}
} | mit | a7297e23f158589dd0ef0142e8f9c35d | 48.585586 | 128 | 0.70616 | 4.90901 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-affirmations | app/src/main/java/com/example/affirmations/ui/theme/Theme.kt | 1 | 1508 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.affirmations.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
)
@Composable
fun AffirmationsTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
| apache-2.0 | 276e8ab019b403c368a9ef47cf6ad2d8 | 29.16 | 100 | 0.729443 | 4.569697 | false | false | false | false |
jamieadkins95/Roach | app/src/main/java/com/jamieadkins/gwent/deck/builder/DeckCardItem.kt | 1 | 1046 | package com.jamieadkins.gwent.deck.builder
import android.view.View
import com.jamieadkins.gwent.R
import com.jamieadkins.gwent.domain.card.model.GwentCard
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.view_deck_card.*
data class DeckCardItem(
val card: GwentCard,
val countInDeck: Int
) : Item(card.id.toLongOrNull() ?: card.id.hashCode().toLong()) {
override fun getLayout(): Int = R.layout.view_deck_card
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.name.text = card.name
viewHolder.tooltip.text = card.tooltip
viewHolder.provisionCost.text = card.provisions.toString()
viewHolder.count.text = "x$countInDeck"
if (card.strength > 0) {
viewHolder.strength.visibility = View.VISIBLE
viewHolder.strength.text = card.strength.toString()
} else {
viewHolder.strength.visibility = View.INVISIBLE
}
}
} | apache-2.0 | 7a5547007e1fefd38a4bee0d1a94e54e | 33.9 | 66 | 0.710325 | 4.101961 | false | false | false | false |
B515/Schedule | app/src/main/kotlin/xyz/b515/schedule/ui/view/CourseDetailActivity.kt | 1 | 5420 | package xyz.b515.schedule.ui.view
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.inputmethod.InputMethodManager
import com.jrummyapps.android.colorpicker.ColorPanelView
import com.jrummyapps.android.colorpicker.ColorPickerDialog
import com.jrummyapps.android.colorpicker.ColorPickerDialogListener
import com.jrummyapps.android.colorpicker.ColorShape
import kotlinx.android.synthetic.main.activity_course_detail.*
import kotlinx.android.synthetic.main.app_bar.*
import xyz.b515.schedule.Constant
import xyz.b515.schedule.R
import xyz.b515.schedule.db.CourseManager
import xyz.b515.schedule.entity.Course
import xyz.b515.schedule.entity.Spacetime
import xyz.b515.schedule.ui.adapter.SpacetimeAdapter
class CourseDetailActivity : AppCompatActivity() {
val colorPanelView: ColorPanelView by lazy { findViewById<ColorPanelView>(R.id.cpv_color_panel_view) }
lateinit var manager: CourseManager
lateinit var adapter: SpacetimeAdapter
lateinit var course: Course
private var flag: Boolean = true
private var list = arrayListOf<Spacetime>()
private var courseId: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_course_detail)
manager = CourseManager(this)
flag = intent.getBooleanExtra(Constant.TOOLBAR_TITLE, true)
adapter = SpacetimeAdapter(list, this, manager, flag)
recycler.adapter = adapter
courseId = intent.getIntExtra(Constant.COURSE_ID, 0)
toolbar.setTitle(if (flag) R.string.course_new else R.string.course_edit)
setSupportActionBar(toolbar)
if (flag) {
course = Course()
manager.insertCourse(course)
} else {
course = manager.getCourse(courseId)
}
loadSpacetime()
colorPanelView.setOnClickListener {
val dialog = ColorPickerDialog.newBuilder()
.setColor(course.color)
.setColorShape(ColorShape.CIRCLE)
.setShowAlphaSlider(true)
.create()
dialog.setColorPickerDialogListener(object : ColorPickerDialogListener {
override fun onColorSelected(dialogId: Int, color: Int) {
course.color = color
colorPanelView.color = color
}
override fun onDialogDismissed(dialogId: Int) = Unit
})
dialog.show(fragmentManager, "")
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
toolbar.setNavigationOnClickListener { onBackPressed() }
toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.action_confirm -> {
course.name = course_name.text.toString()
course.teacher = course_teacher.text.toString()
manager.updateCourse(course)
adapter.items.forEach { manager.updateSpacetime(it) }
finish()
}
R.id.action_delete_forever -> showDeleteConfirm()
R.id.action_add_spacetime -> {
val spacetime = Spacetime()
spacetime.course = course
manager.insertSpacetime(spacetime)
adapter.items.add(spacetime)
adapter.notifyDataSetChanged()
}
}
true
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_course_detail, menu)
val deleteAction = menu.findItem(R.id.action_delete_forever)
deleteAction.isVisible = !flag
return true
}
override fun onBackPressed() {
if (flag)
showDiscardConfirm()
else
super.onBackPressed()
}
private fun showDeleteConfirm() {
AlertDialog.Builder(this)
.setTitle(R.string.alert_title)
.setMessage(R.string.alert_message)
.setPositiveButton(R.string.alert_pos) { _, _ ->
manager.deleteCourse(course)
finish()
}
.setNegativeButton(R.string.alert_neg) { _, _ -> }
.show()
}
private fun showDiscardConfirm() {
AlertDialog.Builder(this)
.setTitle(R.string.alert_title)
.setMessage(R.string.alert_discard)
.setPositiveButton(R.string.alert_pos) { _, _ ->
if (flag) {
manager.deleteCourse(course)
}
finish()
}
.setNegativeButton(R.string.alert_neg) { _, _ -> }
.show()
}
private fun loadSpacetime() {
adapter.items.clear()
if (!flag) {
list.addAll(manager.getCourse(courseId).spacetimes!!)
course_name.setText(course.name)
course_teacher.setText(course.teacher)
colorPanelView.color = course.color
}
adapter.notifyDataSetChanged()
}
}
| apache-2.0 | bdea795535d9497237c1b7005ff2dba1 | 37.439716 | 170 | 0.610148 | 4.852283 | false | false | false | false |
didi/DoraemonKit | Android/dokit-plugin/src/main/kotlin/com/didichuxing/doraemonkit/plugin/asmtransformer/BaseDoKitAsmTransformer.kt | 2 | 3264 | package com.didichuxing.doraemonkit.plugin.asmtransformer
import com.didichuxing.doraemonkit.plugin.println
import com.didiglobal.booster.annotations.Priority
import com.didiglobal.booster.transform.TransformContext
import com.didiglobal.booster.transform.Transformer
import com.didiglobal.booster.transform.asm.ClassTransformer
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.tree.ClassNode
import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
import java.util.*
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/5/21-16:44
* 描 述:
* 修订历史:
* ================================================
*/
open class BaseDoKitAsmTransformer : Transformer {
private val threadMxBean = ManagementFactory.getThreadMXBean()
private val durations = mutableMapOf<ClassTransformer, Long>()
private val classLoader: ClassLoader
internal val transformers: Iterable<ClassTransformer>
constructor() : this(Thread.currentThread().contextClassLoader)
constructor(classLoader: ClassLoader = Thread.currentThread().contextClassLoader) : this(
ServiceLoader.load(ClassTransformer::class.java, classLoader).sortedBy {
it.javaClass.getAnnotation(Priority::class.java)?.value ?: 0
}, classLoader
)
constructor(
transformers: Iterable<ClassTransformer>,
classLoader: ClassLoader = Thread.currentThread().contextClassLoader
) {
this.classLoader = classLoader
this.transformers = transformers
}
override fun onPreTransform(context: TransformContext) {
this.transformers.forEach { transformer ->
this.threadMxBean.sumCpuTime(transformer) {
transformer.onPreTransform(context)
}
}
}
override fun transform(context: TransformContext, bytecode: ByteArray): ByteArray {
return ClassWriter(ClassWriter.COMPUTE_MAXS).also { writer ->
this.transformers.fold(ClassNode().also { klass ->
ClassReader(bytecode).accept(klass, 0)
}) { klass, transformer ->
this.threadMxBean.sumCpuTime(transformer) {
transformer.transform(context, klass)
}
}.accept(writer)
}.toByteArray()
}
override fun onPostTransform(context: TransformContext) {
this.transformers.forEach { transformer ->
this.threadMxBean.sumCpuTime(transformer) {
transformer.onPostTransform(context)
}
}
val w1 = this.durations.keys.map {
it.javaClass.name.length
}.max() ?: 20
this.durations.forEach { (transformer, ns) ->
println("${transformer.javaClass.name.padEnd(w1 + 1)}: ${ns / 1000000} ms")
}
}
private fun <R> ThreadMXBean.sumCpuTime(transformer: ClassTransformer, action: () -> R): R {
val ct0 = this.currentThreadCpuTime
val result = action()
val ct1 = this.currentThreadCpuTime
durations[transformer] = durations.getOrDefault(transformer, 0) + (ct1 - ct0)
return result
}
}
| apache-2.0 | 932812c19faf28f695cbfd43548421bd | 33.234043 | 96 | 0.650715 | 4.824588 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/Project.kt | 1 | 11311 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.project
import com.eclipsesource.json.Json
import com.eclipsesource.json.JsonArray
import com.eclipsesource.json.JsonObject
import com.eclipsesource.json.PrettyPrint
import javafx.stage.Stage
import uk.co.nickthecoder.paratask.*
import uk.co.nickthecoder.paratask.gui.TaskPrompter
import uk.co.nickthecoder.paratask.parameters.BooleanParameter
import uk.co.nickthecoder.paratask.parameters.FileParameter
import uk.co.nickthecoder.paratask.parameters.SimpleGroupParameter
import uk.co.nickthecoder.paratask.parameters.addParameters
import uk.co.nickthecoder.paratask.tools.ExceptionTool
import uk.co.nickthecoder.paratask.JsonHelper
import java.io.*
class Project(val projectWindow: ProjectWindow) {
var projectFile: File? = null
var projectDirectoryP = FileParameter("directory", expectFile = false, required = true, value = File("").absoluteFile)
val saveHistoryP = BooleanParameter("saveHistory", value = false)
var projectDataP = SimpleGroupParameter("projectData")
init {
projectDataP.addParameters(projectDirectoryP, saveHistoryP)
}
val directoryResolver = object : DirectoryResolver() {
override fun directory() = projectDirectoryP.value
}
val resolver = CompoundParameterResolver(directoryResolver)
private val projectPreferences = mutableMapOf<String, Task>()
val saveProjectTask: SaveProjectTask by lazy { SaveProjectTask(this) }
fun storePreferences(task: Task) {
projectPreferences[task.creationString()] = task.copy()
}
fun retrievePreferences(task: Task) {
projectPreferences[task.creationString()]?.let {
task.taskD.copyValuesFrom(it.taskD)
}
}
fun save() {
TaskPrompter(saveProjectTask).placeOnStage(Stage())
}
/*
Example JSON file :
{
"title" : "My Project",
"width" : 600,
"height" : 800,
"projectData" : [
{ "name" : "directory", "value" : "/home/me/myproject" },
{ "name" : "codeHeader", "value" : "/* ... */" }
],
"tabs" : [
{
"tabTemplate"="{0}",
"left" = {
"tool" : "uk.co.nickthecoder.paratask.whatever",
"parameters" : [
{ "name" : "foo", "value" : "fooValue" },
{ "name" : "bar", "value" : "barValue" }
]
}
}
]
}
*/
fun save(projectFile: File) {
this.projectFile = projectFile
val jroot = JsonObject()
jroot.set("width", projectWindow.scene.width)
jroot.set("height", projectWindow.scene.height)
val jprojectData = JsonHelper.parametersAsJsonArray(projectDataP)
jroot.add("projectData", jprojectData)
val jprojectPreferences = JsonArray()
jroot.add("preferences", jprojectPreferences)
projectPreferences.values.forEach { pref ->
val jpref = JsonHelper.taskAsJsonObject(pref)
jprojectPreferences.add(jpref)
}
val jtoolbars = JsonArray()
projectWindow.toolBarTools().forEach { toolBarTool ->
if (toolBarTool.toolPane == null) {
val jtool = JsonHelper.taskAsJsonObject(toolBarTool)
jtoolbars.add(jtool)
}
}
if (!jtoolbars.isEmpty) {
jroot.add("toolbars", jtoolbars)
}
val jtabs = JsonArray()
for (tab in projectWindow.tabs.listTabs()) {
val jtab = JsonObject()
jtabs.add(jtab)
val jtabProperties = JsonHelper.parametersAsJsonArray((tab as ProjectTab_Impl).tabProperties)
jtab.add("properties", jtabProperties)
val jleft = createHalfTab(tab.left)
jtab.set("left", jleft)
val right = tab.right
if (right != null) {
val jright = createHalfTab(right)
jtab.set("right", jright)
}
}
jroot.add("tabs", jtabs)
BufferedWriter(OutputStreamWriter(FileOutputStream(projectFile))).use {
jroot.writeTo(it, PrettyPrint.indentWithSpaces(4))
}
}
private fun createHalfTab(halfTab: HalfTab): JsonObject {
val jhalfTab = JsonObject()
val tool = halfTab.toolPane.tool
jhalfTab.set("tool", tool.creationString())
val jparameters = JsonHelper.parametersAsJsonArray(tool)
jhalfTab.add("parameters", jparameters)
if (saveHistoryP.value == true) {
// Save the history of this half tab
val history = halfTab.history.save()
val jhistory = JsonArray()
val jfuture = JsonArray()
history.first.forEachIndexed { i, moment ->
if (i != history.second) {
val jpart = if (i < history.second) jhistory else jfuture
val jitem = JsonObject()
jpart.add(jitem)
jitem.add("tool", moment.creationString)
jitem.add("parameters", JsonHelper.parametersAsJsonArray(moment.tool))
}
}
if (!jhistory.isEmpty) {
jhalfTab.add("history", jhistory)
}
if (!jfuture.isEmpty) {
jhalfTab.add("future", jfuture)
}
}
return jhalfTab
}
companion object {
fun load(projectFile: File): Project {
val jroot = Json.parse(InputStreamReader(FileInputStream(projectFile))).asObject()
val width = jroot.getDouble("width", 600.0)
val height = jroot.getDouble("height", 600.0)
val projectWindow = ProjectWindow(width, height)
projectWindow.placeOnStage(Stage())
val project = projectWindow.project
project.projectFile = projectFile
try {
val jprojectData = jroot.get("projectData")
if (jprojectData != null) {
JsonHelper.read(jprojectData.asArray(), project.projectDataP)
}
} catch(e: Exception) {
projectWindow.addTool(ExceptionTool(e))
}
try {
val jprojectPreferences = jroot.get("preferences")
if (jprojectPreferences != null) {
(jprojectPreferences as JsonArray).forEach { jpref ->
val task = JsonHelper.readTask(jpref as JsonObject)
project.storePreferences(task)
}
}
} catch(e: Exception) {
projectWindow.addTool(ExceptionTool(e))
}
try {
val jtoolbars = jroot.get("toolbars")
// These are ToolBarTools, which were not visible in ProjectTabs, only visible as toolbars.
// Load them, and remove the tab straight away.
jtoolbars?.let {
for (jtoolbar in it.asArray()) {
val tool = JsonHelper.readTask(jtoolbar.asObject())
if (tool is Tool) {
val projectTab = projectWindow.tabs.addTool(tool, run = false)
// Run single threaded, rather than the normal way, so that we can remove the tab as soon as it has finished.
try {
tool.check()
tool.run()
} catch (e: Exception) {
projectTab.add(ExceptionTool(e))
}
projectTab.projectTabs.removeTab(projectTab)
}
}
}
} catch (e: Exception) {
projectWindow.addTool(ExceptionTool(e))
}
try {
val jtabs = jroot.get("tabs")
jtabs?.let {
for (jtab in jtabs.asArray().map { it.asObject() }) {
try {
val jleft = jtab.get("left").asObject()
jleft?.let {
val tool = loadTool(jleft)
val projectTab = projectWindow.addTool(tool, select = false)
updateHistory(jleft, projectTab.left)
val jright = jtab.get("right")
if (jright != null) {
val toolR = loadTool(jright.asObject())
projectTab.split(toolR)
updateHistory(jright.asObject(), projectTab.right!!)
}
val jtabProperties = jtab.get("properties")
jtabProperties?.let {
JsonHelper.read(jtabProperties as JsonArray, (projectTab as ProjectTab_Impl).tabProperties)
}
}
} catch (e: Exception) {
projectWindow.addTool(ExceptionTool(e))
}
}
}
} catch (e: Exception) {
projectWindow.addTool(ExceptionTool(e))
}
return project
}
private fun updateHistory(jhalfTab: JsonObject, halfTab: HalfTab) {
val jhistory = jhalfTab.get("history")
val jfuture = jhalfTab.get("future")
if (jhistory != null) {
updatePartHistory(jhistory as JsonArray) { tool ->
halfTab.history.insertHistory(tool)
}
}
if (jfuture != null) {
updatePartHistory(jfuture as JsonArray) { tool ->
halfTab.history.addFuture(tool)
}
}
}
private fun updatePartHistory(jhistory: JsonArray, add: (Tool) -> Unit) {
jhistory.forEach { jmoment ->
val tool = loadTool(jmoment as JsonObject)
add(tool)
}
}
private fun loadTool(jhalfTab: JsonObject): Tool {
val creationString = jhalfTab.get("tool").asString()
val tool = TaskFactory.createTask(creationString) as Tool
val jparameters = jhalfTab.get("parameters")
if (jparameters != null) {
JsonHelper.read(jparameters.asArray(), tool)
}
return tool
}
}
}
| gpl-3.0 | 35600a0e5034f50963ed8f7320f8d0dc | 33.590214 | 137 | 0.543365 | 4.858677 | false | false | false | false |
kotlin-everywhere/rpc-servlet | src/main/kotlin/com/github/kotlin_everywhere/rpc/Endpoint.kt | 1 | 1621 | package com.github.kotlin_everywhere.rpc
import com.google.gson.Gson
import javax.servlet.http.HttpServletRequest
abstract class Endpoint<P, R>(internal val url: String?, val method: Method,
protected val parameterClass: Class<P>) {
protected lateinit var handler: (P) -> R
internal fun handle(gson: Gson, request: HttpServletRequest): R {
@Suppress("UNCHECKED_CAST")
val param: P =
if (parameterClass == Unit::class.java) {
Unit as P
} else {
gson.fromJson(
when (method) {
Method.GET, Method.DELETE -> request.getParameter("data")
Method.POST, Method.PUT -> request.reader.readText()
},
parameterClass
)
}
return handler(param)
}
val isHandlerInitialized: Boolean
get() = try {
@Suppress("UNUSED_VARIABLE")
val h = handler;
true
} catch (e: UninitializedPropertyAccessException) {
false
}
}
class Producer<R>(url: String? = null, method: Method) : Endpoint<Unit, R>(url, method, Unit::class.java) {
operator fun invoke(handler: () -> R) {
this.handler = { handler() }
}
}
class Function<P, R>(url: String? = null, method: Method, parameterClass: Class<P>) : Endpoint<P, R>(url, method, parameterClass) {
operator fun invoke(handler: (P) -> R) {
this.handler = { handler(it) }
}
}
| mit | 15c7a64c10e9b13fec7460f0e8eff2d2 | 31.42 | 131 | 0.525601 | 4.527933 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/PsiElement.kt | 1 | 2498 | package org.rust.lang.core.psi.ext
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtilCore
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.stubs.RsFileStub
/**
* Returns module for this PsiElement.
*
* If the element is in a library, returns the module which depends on
* the library.
*/
val PsiElement.module: Module?
get() {
// It's important to look the module for `containingFile` file
// and not the element itself. Otherwise this will break for
// elements in libraries.
return ModuleUtilCore.findModuleForPsiElement(containingFile)
}
val PsiElement.ancestors: Sequence<PsiElement> get() = generateSequence(this) { it.parent }
/**
* Extracts node's element type
*/
val PsiElement.elementType: IElementType
// XXX: be careful not to switch to AST
get() = if (this is RsFile) RsFileStub.Type else PsiUtilCore.getElementType(this)
inline fun <reified T : PsiElement> PsiElement.parentOfType(strict: Boolean = true, minStartOffset: Int = -1): T? =
PsiTreeUtil.getParentOfType(this, T::class.java, strict, minStartOffset)
inline fun <reified T : PsiElement> PsiElement.parentOfType(strict: Boolean = true, stopAt: Class<out PsiElement>): T? =
PsiTreeUtil.getParentOfType(this, T::class.java, strict, stopAt)
inline fun <reified T : PsiElement> PsiElement.contextOfType(strict: Boolean = true): T? =
PsiTreeUtil.getContextOfType(this, T::class.java, strict)
inline fun <reified T : PsiElement> PsiElement.childOfType(strict: Boolean = true): T? =
PsiTreeUtil.findChildOfType(this, T::class.java, strict)
inline fun <reified T : PsiElement> PsiElement.descendantsOfType(): Collection<T> =
PsiTreeUtil.findChildrenOfType(this, T::class.java)
/**
* Finds first sibling that is neither comment, nor whitespace before given element.
*/
fun PsiElement?.getPrevNonCommentSibling(): PsiElement? =
PsiTreeUtil.skipSiblingsBackward(this, PsiWhiteSpace::class.java, PsiComment::class.java)
/**
* Finds first sibling that is neither comment, nor whitespace after given element.
*/
fun PsiElement?.getNextNonCommentSibling(): PsiElement? =
PsiTreeUtil.skipSiblingsForward(this, PsiWhiteSpace::class.java, PsiComment::class.java)
| mit | 201062906bfb6216ff1d623df4647d51 | 38.650794 | 120 | 0.757406 | 4.191275 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.