path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/dscoding/paging3caching/data/remote/BeerDto.kt
|
diogosantos41
| 706,395,695
| false
|
{"Kotlin": 18856}
|
package com.dscoding.paging3caching.data.remote
data class BeerDto(
val id: Int,
val name: String,
val tagline: String,
val description: String,
val first_brewed: String,
val image_url: String?
)
| 0
|
Kotlin
|
0
| 0
|
41e4b2f58fef284d2bd18d4d54cce760117d75c8
| 220
|
paging3-cache-android
|
MIT License
|
app/src/main/java/com/herry/test/app/main/MainActivity.kt
|
HerryPark
| 273,154,769
| false
| null |
package com.herry.test.app.main
import com.herry.test.R
import com.herry.test.app.base.nav.BaseNavActivity
class MainActivity : BaseNavActivity() {
override fun getGraph(): Int = R.navigation.main_navigation
}
| 0
|
Kotlin
|
1
| 3
|
d30435c01387614ec24a79ffd5afcdb89edf5298
| 216
|
HerryApiDemo
|
Apache License 2.0
|
format/d2v-format-common/src/test/kotlin/io/data2viz/format/FormatSpecifierTests.kt
|
yijunwu
| 207,939,886
| true
|
{"Kotlin": 1013995, "HTML": 45385, "JavaScript": 6548}
|
@file:Suppress("FunctionName", "unused")
package io.data2viz.format
import io.data2viz.test.TestBase
import io.data2viz.test.shouldThrow
import kotlin.test.Test
class FormatSpecifierTests : TestBase() {
@Test fun formatSpecifier_throws_an_error_for_invalid_formats () {
shouldThrow<IllegalArgumentException> { specify("foo") }
shouldThrow<IllegalArgumentException> { specify(".-2s") }
shouldThrow<IllegalArgumentException> { specify(".f") }
}
@Test fun formatSpecifier__has_the_expected_defaults () {
val s = specify("")
(s.fill == ' ') shouldBe true
s.align shouldBe Align.RIGTH
s.sign shouldBe Sign.MINUS
s.symbol shouldBe null
s.zero shouldBe false
s.width shouldBe null
s.groupSeparation shouldBe false
s.precision shouldBe null
s.type shouldBe Type.NONE
}
@Test fun specifier__has_the_expected_defaults () {
val s = specify()
(s.fill == ' ') shouldBe true
s.align shouldBe Align.RIGTH
s.sign shouldBe Sign.MINUS
s.symbol shouldBe null
s.zero shouldBe false
s.width shouldBe null
s.groupSeparation shouldBe false
s.precision shouldBe null
s.type shouldBe Type.NONE
}
@Test fun formatSpecifier_specifier_uses_the_none_type_for_unknown_types () {
specify("q").type shouldBe Type.NONE
specify("S").type shouldBe Type.NONE
}
@Test fun formatSpecifier_n_is_an_alias_for_g() {
val s = specify("n")
s.groupSeparation shouldBe true
s.type shouldBe Type.DECIMAL_OR_EXPONENT
}
@Test fun formatSpecifier_0_is_an_alias_for_0() {
val s = specify("0")
s.zero shouldBe true
(s.fill == '0') shouldBe true
s.align shouldBe Align.RIGHT_WITHOUT_SIGN
}
@Test fun formatSpecifier_specifier_toString_reflects_current_field_values () {
var s = specify("")
s = s.copy(fill = '_')
s.toString() shouldBe "_>-"
s = s.copy(align = Align.CENTER)
s.toString() shouldBe "_^-"
s = s.copy(sign = Sign.PLUS)
s.toString() shouldBe "_^+"
s = s.copy(symbol = Symbol.CURRENCY)
s.toString() shouldBe "_^+$"
s = s.copy(zero = true)
s.toString() shouldBe "_^+$0"
s = s.copy(width = 12)
s.toString() shouldBe "_^+$012"
s = s.copy(groupSeparation = true)
s.toString() shouldBe "_^+$012,"
s = s.copy(precision = 2)
s.toString() shouldBe "_^+$012,.2"
s = s.copy(type = Type.FIXED_POINT)
s.toString() shouldBe "_^+$012,.2f"
Locale().formatter(s.toString())(42.0) shouldBe "+$0,000,042.00"
}
@Test fun formatSpecifier_specifier_toString_clamps_exponent_to_zero () {
val s = specify("").copy(precision = -1)
s.toString() shouldBe " >-.0"
}
@Test fun formatSpecifier_specifier_toString_clamps_width_to_one () {
val s = specify("")
s.copy(width = -1).toString() shouldBe " >-1"
}
}
| 0
|
Kotlin
|
0
| 0
|
733f9ac458755ab065becd16d7f001be21080f59
| 3,071
|
data2viz
|
Apache License 2.0
|
generators/test-generator/tests/org/jetbrains/kotlin/generators/util/TestGeneratorUtil.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.generators.util
import org.intellij.lang.annotations.Language
import java.io.File
import java.lang.StringBuilder
object TestGeneratorUtil {
@Language("RegExp") const val KT_OR_KTS = """^(.+)\.(kt|kts)$"""
@Language("RegExp") const val KT = """^(.+)\.(kt)$"""
@Language("RegExp") const val KTS = """^(.+)\.(kts)$"""
@Language("RegExp") const val KT_OR_KTS_WITHOUT_DOTS_IN_NAME = """^([^.]+)\.(kt|kts)$"""
@Language("RegExp") const val KT_WITHOUT_DOTS_IN_NAME = """^([^.]+)\.kt$"""
@Language("RegExp") const val KT_WITHOUT_FIR_PREFIX = """^(.+)(?<!\.fir)\.kt$"""
@JvmStatic
fun escapeForJavaIdentifier(fileName: String): String {
// A file name may contain characters (like ".") that can't be a part of method name
val result = StringBuilder()
for (c in fileName) {
if (Character.isJavaIdentifierPart(c)) {
result.append(c)
} else {
result.append("_")
}
}
return result.toString()
}
@JvmStatic
fun fileNameToJavaIdentifier(file: File): String {
return escapeForJavaIdentifier(file.name).replaceFirstChar(Char::uppercaseChar)
}
fun getMainClassName(): String? =
Throwable().stackTrace.lastOrNull()?.className
}
private val defaultPackages = listOf(
"java.lang",
"kotlin",
"kotlin.annotations",
"kotlin.collections"
)
fun Class<*>.isDefaultImportedClass(): Boolean {
val outerName = canonicalName.removeSuffix(".$simpleName")
return outerName in defaultPackages
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 1,806
|
kotlin
|
Apache License 2.0
|
time/src/iosMain/kotlin/com/merseyside/merseyLib/time/utils/PatternUtils.kt
|
Merseyside
| 396,607,192
| false
| null |
package com.merseyside.merseyLib.time.utils
import com.merseyside.merseyLib.time.utils.Pattern.*
import com.merseyside.merseyLib.time.exception.TimeParseException
import platform.Foundation.*
internal fun patternToFormattedOptions(pattern: Pattern): ULong {
return when(pattern) {
is ISO_DATE_TIME -> {
NSISO8601DateFormatWithFullDate
.or(NSISO8601DateFormatWithDashSeparatorInDate)
.or(patternToFormattedOptions(ISO_LOCAL_FULL_TIME))
}
is ISO_INSTANT -> {
patternToFormattedOptions(ISO_DATE_TIME)
.or(NSISO8601DateFormatWithTimeZone)
.or(NSISO8601DateFormatWithColonSeparatorInTimeZone)
}
is Offset.ISO_OFFSET_DATE_TIME -> {
NSISO8601DateFormatWithInternetDateTime
.or(NSISO8601DateFormatWithTimeZone)
}
is Offset.ISO_OFFSET_DATE -> {
NSISO8601DateFormatWithFullDate
.or(NSISO8601DateFormatWithDashSeparatorInDate)
.or(NSISO8601DateFormatWithTimeZone)
.or(NSISO8601DateFormatWithColonSeparatorInTimeZone)
}
is Offset.ISO_OFFSET_TIME -> {
patternToFormattedOptions(ISO_LOCAL_TIME)
.or(NSISO8601DateFormatWithTimeZone)
.or(NSISO8601DateFormatWithColonSeparatorInTimeZone)
}
is Offset.ISO_OFFSET_FULL_TIME -> {
patternToFormattedOptions(ISO_LOCAL_FULL_TIME)
.or(NSISO8601DateFormatWithTimeZone)
.or(NSISO8601DateFormatWithColonSeparatorInTimeZone)
}
is ISO_LOCAL_DATE -> {
NSISO8601DateFormatWithFullDate.or(NSISO8601DateFormatWithDashSeparatorInDate)
}
is ISO_LOCAL_TIME -> {
NSISO8601DateFormatWithTime
.or(NSISO8601DateFormatWithColonSeparatorInTime)
}
is ISO_LOCAL_FULL_TIME -> {
NSISO8601DateFormatWithFullTime
.or(NSISO8601DateFormatWithColonSeparatorInTime)
}
is EMPTY -> throw TimeParseException("Can not obtain formattedOptions with empty pattern!")
else -> throw TimeParseException() //TODO handle Custom pattern
}
}
| 0
|
Kotlin
|
0
| 0
|
ebef4db3b924440bdeaf0711164cab446e41ec5b
| 2,228
|
mersey-kmp-time
|
Apache License 2.0
|
jar-filter/src/test/kotlin/net/corda/gradle/jarfilter/RemoveAnnotationsTest.kt
|
corda
| 120,318,601
| false
|
{"Kotlin": 810473, "Java": 383021, "Groovy": 76556, "Shell": 4346, "Batchfile": 106}
|
package net.corda.gradle.jarfilter
import net.corda.gradle.unwanted.HasUnwantedFun
import net.corda.gradle.unwanted.HasUnwantedVal
import net.corda.gradle.unwanted.HasUnwantedVar
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
class RemoveAnnotationsTest {
companion object {
private const val ANNOTATED_CLASS = "net.corda.gradle.HasUnwantedAnnotations"
private const val REMOVE_ME_CLASS = "net.corda.gradle.jarfilter.RemoveMe"
private lateinit var testProject: JarFilterProject
@BeforeAll
@JvmStatic
fun setup(@TempDir testProjectDir: Path) {
testProject = JarFilterProject(testProjectDir, "remove-annotations").build()
}
}
@Test
fun deleteFromClass() {
classLoaderFor(testProject.sourceJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<Any>(ANNOTATED_CLASS).apply {
assertNotNull(getAnnotation(removeMe))
}
}
classLoaderFor(testProject.filteredJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<Any>(ANNOTATED_CLASS).apply {
assertNull(getAnnotation(removeMe))
}
}
}
@Test
fun deleteFromDefaultConstructor() {
classLoaderFor(testProject.sourceJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<Any>(ANNOTATED_CLASS).apply {
getDeclaredConstructor().also { con ->
assertNotNull(con.getAnnotation(removeMe))
}
}
}
classLoaderFor(testProject.filteredJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<Any>(ANNOTATED_CLASS).apply {
getDeclaredConstructor().also { con ->
assertNull(con.getAnnotation(removeMe))
}
}
}
}
@Test
fun deleteFromPrimaryConstructor() {
classLoaderFor(testProject.sourceJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<Any>(ANNOTATED_CLASS).apply {
getDeclaredConstructor(Long::class.java, String::class.java).also { con ->
assertNotNull(con.getAnnotation(removeMe))
}
}
}
classLoaderFor(testProject.filteredJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<Any>(ANNOTATED_CLASS).apply {
getDeclaredConstructor(Long::class.java, String::class.java).also { con ->
assertNull(con.getAnnotation(removeMe))
}
}
}
}
@Test
fun deleteFromField() {
classLoaderFor(testProject.sourceJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<Any>(ANNOTATED_CLASS).apply {
getField("longField").also { field ->
assertNotNull(field.getAnnotation(removeMe))
}
}
}
classLoaderFor(testProject.filteredJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<Any>(ANNOTATED_CLASS).apply {
getField("longField").also { field ->
assertNull(field.getAnnotation(removeMe))
}
}
}
}
@Test
fun deleteFromMethod() {
classLoaderFor(testProject.sourceJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<HasUnwantedFun>(ANNOTATED_CLASS).apply {
getMethod("unwantedFun", String::class.java).also { method ->
assertNotNull(method.getAnnotation(removeMe))
}
}
}
classLoaderFor(testProject.filteredJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<HasUnwantedFun>(ANNOTATED_CLASS).apply {
getMethod("unwantedFun", String::class.java).also { method ->
assertNull(method.getAnnotation(removeMe))
}
}
}
}
@Test
fun deleteFromValProperty() {
classLoaderFor(testProject.sourceJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<HasUnwantedVal>(ANNOTATED_CLASS).apply {
getMethod("getUnwantedVal").also { method ->
assertNotNull(method.getAnnotation(removeMe))
}
}
}
classLoaderFor(testProject.filteredJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<HasUnwantedVal>(ANNOTATED_CLASS).apply {
getMethod("getUnwantedVal").also { method ->
assertNull(method.getAnnotation(removeMe))
}
}
}
}
@Test
fun deleteFromVarProperty() {
classLoaderFor(testProject.sourceJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<HasUnwantedVar>(ANNOTATED_CLASS).apply {
getMethod("getUnwantedVar").also { method ->
assertNotNull(method.getAnnotation(removeMe))
}
getMethod("setUnwantedVar", String::class.java).also { method ->
assertNotNull(method.getAnnotation(removeMe))
}
}
}
classLoaderFor(testProject.filteredJar).use { cl ->
val removeMe = cl.load<Annotation>(REMOVE_ME_CLASS)
cl.load<HasUnwantedVar>(ANNOTATED_CLASS).apply {
getMethod("getUnwantedVar").also { method ->
assertNull(method.getAnnotation(removeMe))
}
getMethod("setUnwantedVar", String::class.java).also { method ->
assertNull(method.getAnnotation(removeMe))
}
}
}
}
}
| 17
|
Kotlin
|
35
| 24
|
aeb324e3b9cb523f55bc32541688b2e90d920791
| 6,235
|
corda-gradle-plugins
|
Apache License 2.0
|
processor/testuut/kotlin/src/main/java/com/instagram/common/json/annotation/processor/SomeKotlinStuff.kt
|
classicvalues
| 398,375,428
| false
| null |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.instagram.common.json.annotation.processor
import com.instagram.common.json.annotation.JsonField
import com.instagram.common.json.annotation.JsonType
@JsonType
data class SomeKotlinStuff(
@JsonField(fieldName = "data") var data: String = "",
// 'is' prefix is a special case in kotlin, getters become isFun() instead of getIsFun() and
// similar with setters
@JsonField(fieldName = "fun") var isFun: Nested = Nested(),
@JsonField(fieldName = "some_map") var someMap: HashMap<String, Int> = hashMapOf()
)
@JsonType
data class Nested(
@JsonField(fieldName = "foo") var foo: Int? = null,
@JsonField(fieldName = "bar") var bar: String? = null
)
| 1
| null |
0
| 1
|
896b663c2fefe09f00f841ae715aba5bc523f497
| 873
|
ig-json-parser
|
MIT License
|
projects/manage-supervision-and-delius/src/test/kotlin/uk/gov/justice/digital/hmpps/service/UserServiceTest.kt
|
ministryofjustice
| 500,855,647
| false
|
{"Kotlin": 3705021, "HTML": 57595, "D2": 27334, "Ruby": 25392, "Shell": 12351, "SCSS": 6240, "HCL": 2712, "Dockerfile": 2414, "JavaScript": 1344, "Python": 268}
|
package uk.gov.justice.digital.hmpps.service
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.whenever
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.Pageable
import uk.gov.justice.digital.hmpps.data.generator.ContactGenerator.DEFAULT_PROVIDER
import uk.gov.justice.digital.hmpps.data.generator.ContactGenerator.DEFAULT_STAFF
import uk.gov.justice.digital.hmpps.data.generator.ContactGenerator.DEFAULT_TEAM
import uk.gov.justice.digital.hmpps.data.generator.ContactGenerator.STAFF_1
import uk.gov.justice.digital.hmpps.data.generator.ContactGenerator.USER
import uk.gov.justice.digital.hmpps.data.generator.PersonGenerator.CASELOAD_PERSON_1
import uk.gov.justice.digital.hmpps.data.generator.PersonGenerator.OVERVIEW
import uk.gov.justice.digital.hmpps.integrations.delius.user.entity.CaseloadRepository
import uk.gov.justice.digital.hmpps.integrations.delius.user.entity.StaffRepository
import uk.gov.justice.digital.hmpps.integrations.delius.user.entity.TeamRepository
import uk.gov.justice.digital.hmpps.integrations.delius.user.entity.UserRepository
@ExtendWith(MockitoExtension::class)
internal class UserServiceTest {
@Mock
lateinit var userRepository: UserRepository
@Mock
lateinit var caseloadRepository: CaseloadRepository
@Mock
lateinit var staffRepository: StaffRepository
@Mock
lateinit var teamRepository: TeamRepository
@InjectMocks
lateinit var service: UserService
@Test
fun `calls get person activity function`() {
val username = "username"
whenever(userRepository.findByUsername(username)).thenReturn(USER)
whenever(caseloadRepository.findByStaffCode(USER.staff!!.code)).thenReturn(listOf(CASELOAD_PERSON_1))
val res = service.getUserCaseload(username)
assertThat(
res.provider, equalTo(DEFAULT_PROVIDER.description)
)
}
@Test
fun `calls get user teams function`() {
val username = "username"
whenever(userRepository.findByUsername(username)).thenReturn(USER)
whenever(staffRepository.findTeamsByStaffCode(USER.staff!!.code)).thenReturn(listOf(DEFAULT_TEAM))
val res = service.getUserTeams(username)
assertThat(
res.provider, equalTo(DEFAULT_PROVIDER.description)
)
assertThat(
res.teams[0].description, equalTo(DEFAULT_TEAM.description)
)
assertThat(
res.teams[0].code, equalTo(DEFAULT_TEAM.code)
)
}
@Test
fun `calls get team staff function`() {
val teamCode = DEFAULT_TEAM.code
whenever(teamRepository.findProviderByTeamCode(teamCode)).thenReturn(DEFAULT_PROVIDER.description)
whenever(teamRepository.findStaffByTeamCode(teamCode)).thenReturn(listOf(DEFAULT_STAFF, STAFF_1))
val res = service.getTeamStaff(teamCode)
assertThat(
res.provider, equalTo(DEFAULT_PROVIDER.description)
)
assertThat(
res.staff[0].code.trim(), equalTo(DEFAULT_STAFF.code.trim())
)
assertThat(
res.staff[1].code, equalTo(STAFF_1.code)
)
}
@Test
fun `calls get team caseload function`() {
val teamCode = DEFAULT_TEAM.code
whenever(teamRepository.findByTeamCode(teamCode)).thenReturn(DEFAULT_TEAM)
whenever(caseloadRepository.findByTeamCode(teamCode, Pageable.ofSize(1))).thenReturn(
PageImpl(
listOf(
CASELOAD_PERSON_1
)
)
)
val res = service.getTeamCaseload(teamCode, Pageable.ofSize(1))
assertThat(res.provider, equalTo(DEFAULT_PROVIDER.description))
assertThat(res.caseload[0].staff.code, equalTo(CASELOAD_PERSON_1.staff.code))
assertThat(res.team.code, equalTo(DEFAULT_TEAM.code))
}
@Test
fun `calls get caseload for staff function`() {
val staffCode = DEFAULT_STAFF.code
whenever(staffRepository.findByStaffCode(staffCode)).thenReturn(DEFAULT_STAFF)
whenever(caseloadRepository.findByStaffCode(staffCode)).thenReturn(listOf(CASELOAD_PERSON_1))
val res = service.getStaffCaseload(staffCode)
assertThat(
res.provider, equalTo(DEFAULT_PROVIDER.description)
)
assertThat(
res.caseload[0].crn, equalTo(OVERVIEW.crn)
)
assertThat(
res.caseload[0].caseName.forename, equalTo(OVERVIEW.forename)
)
}
}
| 5
|
Kotlin
|
0
| 2
|
bafb32470fd72f96026e8e8c53a636778c6abacf
| 4,740
|
hmpps-probation-integration-services
|
MIT License
|
android/app/src/main/kotlin/by/matskevich/arkham_horror_statistic/MainActivity.kt
|
amatskevich
| 442,608,723
| false
|
{"Dart": 38737, "Swift": 404, "Kotlin": 142, "Objective-C": 38}
|
package by.matskevich.arkham_horror_statistic
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
a10c2492738b068f3ea9fd7ff5eaddf9460d6b72
| 142
|
arkham_horror_statistic
|
MIT License
|
js/js.translator/testData/box/extensionFunction/virtualExtensionOverride.kt
|
JakeWharton
| 99,388,807
| false
| null |
package foo
open class A(var a: Int) {
open fun Int.modify(): Int {
return this * 3;
}
fun eval() = a.modify();
}
class B(a: Int) : A(a) {
override fun Int.modify(): Int {
return this - 2;
}
}
fun box(): Boolean {
return (A(4).eval() == 12) && (A(2).eval() == 6) && (B(3).eval() == 1)
}
| 184
| null |
5691
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 332
|
kotlin
|
Apache License 2.0
|
plugins/kotlin-serialization/kotlin-serialization-compiler/src/org/jetbrains/kotlinx/serialization/compiler/resolve/KSerializationUtil.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlinx.serialization.compiler.resolve
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.konan.isNative
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.descriptorUtil.platform
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyAnnotationDescriptor
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.representativeUpperBound
import org.jetbrains.kotlinx.serialization.compiler.resolve.SerializationAnnotations.serialInfoFqName
internal fun isAllowedToHaveAutoGeneratedSerializerMethods(
classDescriptor: ClassDescriptor,
serializableClassDescriptor: ClassDescriptor
): Boolean {
if (serializableClassDescriptor.isSerializableEnum()) return true
// don't generate automatically anything for enums or interfaces or other strange things
if (serializableClassDescriptor.kind != ClassKind.CLASS) return false
// it is either GeneratedSerializer implementation
// or user implementation which does not have type parameters (to be able to correctly initialize descriptor)
return classDescriptor.typeConstructor.supertypes.any(::isGeneratedKSerializer) ||
(classDescriptor.typeConstructor.supertypes.any(::isKSerializer) && classDescriptor.declaredTypeParameters.isEmpty())
}
internal fun isKSerializer(type: KotlinType?): Boolean =
type != null && KotlinBuiltIns.isConstructedFromGivenClass(type, SerialEntityNames.KSERIALIZER_NAME_FQ)
internal fun isGeneratedKSerializer(type: KotlinType?): Boolean =
type != null && KotlinBuiltIns.isConstructedFromGivenClass(type, SerialEntityNames.GENERATED_SERIALIZER_FQ)
internal fun ClassDescriptor.getGeneratedSerializerDescriptor(): ClassDescriptor =
module.getClassFromInternalSerializationPackage(SerialEntityNames.GENERATED_SERIALIZER_CLASS.identifier)
internal fun ClassDescriptor.createSerializerTypeFor(argument: SimpleType, baseSerializerInterface: FqName): SimpleType {
val projectionType = Variance.INVARIANT
val types = listOf(TypeProjectionImpl(projectionType, argument))
val descriptor = module.findClassAcrossModuleDependencies(ClassId.topLevel(baseSerializerInterface))
?: throw IllegalArgumentException("Can't locate $baseSerializerInterface. Is kotlinx-serialization library present in compile classpath?")
return KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, descriptor, types)
}
internal fun extractKSerializerArgumentFromImplementation(implementationClass: ClassDescriptor): KotlinType? {
val supertypes = implementationClass.typeConstructor.supertypes
val kSerializerSupertype = supertypes.find { isGeneratedKSerializer(it) }
?: supertypes.find { isKSerializer(it) }
?: return null
return kSerializerSupertype.arguments.first().type
}
internal val DeclarationDescriptor.serializableWith: KotlinType?
get() = annotations.serializableWith(module)
internal fun Annotations.serializableWith(module: ModuleDescriptor): KotlinType? =
this.findAnnotationKotlinTypeValue(SerializationAnnotations.serializableAnnotationFqName, module,"with")
internal val DeclarationDescriptor.serializerForClass: KotlinType?
get() = annotations.findAnnotationKotlinTypeValue(SerializationAnnotations.serializerAnnotationFqName, module, "forClass")
internal val ClassDescriptor.isSerialInfoAnnotation: Boolean
get() = annotations.hasAnnotation(serialInfoFqName)
internal val Annotations.serialNameValue: String?
get() = findAnnotationConstantValue(SerializationAnnotations.serialNameAnnotationFqName, "value")
internal val Annotations.serialRequired: Boolean
get() = hasAnnotation(SerializationAnnotations.requiredAnnotationFqName)
internal val Annotations.serialTransient: Boolean
get() = hasAnnotation(SerializationAnnotations.serialTransientFqName)
// ----------------------------------------
val KotlinType?.toClassDescriptor: ClassDescriptor?
@JvmName("toClassDescriptor")
get() = this?.constructor?.declarationDescriptor?.let { descriptor ->
when(descriptor) {
is ClassDescriptor -> descriptor
is TypeParameterDescriptor -> descriptor.representativeUpperBound.toClassDescriptor
else -> null
}
}
internal val ClassDescriptor.shouldHaveGeneratedMethodsInCompanion: Boolean
get() = this.isSerializableObject || this.isSerializableEnum() || this.kind == ClassKind.CLASS && annotations.hasAnnotation(SerializationAnnotations.serializableAnnotationFqName)
internal val ClassDescriptor.isSerializableObject: Boolean
get() = kind == ClassKind.OBJECT && hasSerializableAnnotationWithoutArgs
internal val ClassDescriptor.isInternalSerializable: Boolean //todo normal checking
get() {
if (kind != ClassKind.CLASS) return false
return hasSerializableAnnotationWithoutArgs
}
internal fun ClassDescriptor.isSerializableEnum(): Boolean {
if (this.kind != ClassKind.ENUM_CLASS) return false
if (hasSerializableAnnotationWithoutArgs) return true
return false
}
internal val ClassDescriptor.shouldHaveGeneratedSerializer: Boolean
get() = (isInternalSerializable && (modality == Modality.FINAL || modality == Modality.OPEN)) || isSerializableEnum()
internal fun ClassDescriptor.enumEntries(): List<ClassDescriptor> {
check(this.kind == ClassKind.ENUM_CLASS)
return unsubstitutedMemberScope.getContributedDescriptors().asSequence()
.filterIsInstance<ClassDescriptor>()
.filter { it.kind == ClassKind.ENUM_ENTRY }
.toList()
}
internal val Annotations.hasAnySerialAnnotation: Boolean
get() = serialNameValue != null || any { it.annotationClass?.isSerialInfoAnnotation == true }
internal val ClassDescriptor.hasSerializableAnnotationWithoutArgs: Boolean
get() {
if (!annotations.hasAnnotation(SerializationAnnotations.serializableAnnotationFqName)) return false
// If provided descriptor is lazy, carefully look at psi in order not to trigger full resolve which may be recursive.
// Otherwise, this descriptor is deserialized from another module and it is OK to check value right away.
val psi = findSerializableAnnotationDeclaration() ?: return (serializableWith == null)
return psi.valueArguments.isEmpty()
}
internal fun Annotated.findSerializableAnnotationDeclaration(): KtAnnotationEntry? {
val lazyDesc = annotations.findAnnotation(SerializationAnnotations.serializableAnnotationFqName) as? LazyAnnotationDescriptor
return lazyDesc?.annotationEntry
}
// For abstract classes marked with @Serializable,
// methods are generated anyway although they shouldn't have
// generated $serializer and use Polymorphic one.
internal fun ClassDescriptor.isAbstractSerializableClass(): Boolean =
isInternalSerializable && modality == Modality.ABSTRACT
internal fun ClassDescriptor.isSealedSerializableClass(): Boolean =
isInternalSerializable && modality == Modality.SEALED
internal fun ClassDescriptor.polymorphicSerializerIfApplicableAutomatically(): ClassDescriptor? {
val serializer = when {
this.isAbstractSerializableClass()
|| kind == ClassKind.INTERFACE -> SpecialBuiltins.polymorphicSerializer
this.isSealedSerializableClass() -> SpecialBuiltins.sealedSerializer
else -> null
}
return serializer?.let { module.getClassFromSerializationPackage(it) }
}
// serializer that was declared for this type
internal val ClassDescriptor?.classSerializer: ClassDescriptor?
get() = this?.let {
// serializer annotation on class?
serializableWith?.let { return it.toClassDescriptor }
// companion object serializer?
if (hasCompanionObjectAsSerializer) return companionObjectDescriptor
// can infer @Poly?
polymorphicSerializerIfApplicableAutomatically()?.let { return it }
// default serializable?
if (shouldHaveGeneratedSerializer) {
// $serializer nested class
return this.unsubstitutedMemberScope
.getDescriptorsFiltered(nameFilter = { it == SerialEntityNames.SERIALIZER_CLASS_NAME })
.filterIsInstance<ClassDescriptor>().singleOrNull()
}
return null
}
internal val ClassDescriptor.hasCompanionObjectAsSerializer: Boolean
get() = isSerializableObject || companionObjectDescriptor?.serializerForClass == this.defaultType
// returns only user-overriden Serializer
internal val KotlinType.overridenSerializer: KotlinType?
get() {
val desc = this.toClassDescriptor ?: return null
desc.serializableWith?.let { return it }
return null
}
internal val KotlinType.genericIndex: Int?
get() = (this.constructor.declarationDescriptor as? TypeParameterDescriptor)?.index
internal fun getSerializableClassDescriptorByCompanion(thisDescriptor: ClassDescriptor): ClassDescriptor? {
if (thisDescriptor.isSerializableObject) return thisDescriptor
if (!thisDescriptor.isCompanionObject) return null
val classDescriptor = (thisDescriptor.containingDeclaration as? ClassDescriptor) ?: return null
if (!classDescriptor.shouldHaveGeneratedMethodsInCompanion) return null
return classDescriptor
}
internal fun ClassDescriptor.needSerializerFactory(): Boolean {
if (this.platform?.isNative() != true) return false
val serializableClass = getSerializableClassDescriptorByCompanion(this) ?: return false
if (serializableClass.isSerializableObject) return true
if (serializableClass.declaredTypeParameters.isEmpty()) return false
return true
}
internal fun getSerializableClassDescriptorBySerializer(serializerDescriptor: ClassDescriptor): ClassDescriptor? {
val serializerForClass = serializerDescriptor.serializerForClass
if (serializerForClass != null) return serializerForClass.toClassDescriptor
if (serializerDescriptor.name !in setOf(
SerialEntityNames.SERIALIZER_CLASS_NAME,
SerialEntityNames.GENERATED_SERIALIZER_CLASS
)
) return null
val classDescriptor = (serializerDescriptor.containingDeclaration as? ClassDescriptor) ?: return null
if (!classDescriptor.shouldHaveGeneratedSerializer) return null
return classDescriptor
}
internal fun ClassDescriptor.checkSerializableClassPropertyResult(prop: PropertyDescriptor): Boolean =
prop.returnType!!.isSubtypeOf(getClassFromSerializationPackage(SerialEntityNames.SERIAL_DESCRIPTOR_CLASS).toSimpleType(false)) // todo: cache lookup
// todo: serialization: do an actual check better that just number of parameters
internal fun ClassDescriptor.checkSaveMethodParameters(parameters: List<ValueParameterDescriptor>): Boolean =
parameters.size == 2
internal fun ClassDescriptor.checkSaveMethodResult(type: KotlinType): Boolean =
KotlinBuiltIns.isUnit(type)
// todo: serialization: do an actual check better that just number of parameters
internal fun ClassDescriptor.checkLoadMethodParameters(parameters: List<ValueParameterDescriptor>): Boolean =
parameters.size == 1
internal fun ClassDescriptor.checkLoadMethodResult(type: KotlinType): Boolean =
getSerializableClassDescriptorBySerializer(this)?.defaultType == type
| 157
| null |
5209
| 42,102
|
65f712ab2d54e34c5b02ffa3ca8c659740277133
| 12,342
|
kotlin
|
Apache License 2.0
|
cmpe/common/src/desktopMain/kotlin/xyz/mcxross/cohesive/mellow/UriConverter.kt
|
mcxross
| 514,846,313
| false
| null |
package com.mcxross.cohesive.mellow
import io.ktor.utils.io.core.*
import io.ktor.utils.io.streams.*
import java.io.File
import java.nio.file.Files
actual class UriConverter {
actual fun toInput(uri: Uri): Input = when {
uri.path.startsWith("http") -> TODO("unimplemented")
else -> File(uri.path).inputStream().asInput()
}
actual suspend fun name(uri: Uri): String = when {
uri.path.startsWith("http") -> TODO("unimplemented")
else -> File(uri.path).name
}
}
data class FileUri(
val file: File
) : Uri {
override val path: String
get() = file.path
override val mimeType: String?
get() = Files.probeContentType(file.toPath())
}
| 0
|
Kotlin
|
0
| 3
|
29bc632d6e9ce746b3eedacdfe18e617ebcad175
| 670
|
cohesive
|
Apache License 2.0
|
app/src/main/java/dev/jx/pokedex/ui/PokemonListFragment.kt
|
Jeff-Soares
| 407,314,984
| false
| null |
package dev.jx.pokedex.ui
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.SimpleItemAnimator
import dagger.hilt.android.AndroidEntryPoint
import dev.jx.pokedex.databinding.FragmentPokemonListBinding
import dev.jx.pokedex.model.FilterOptions
import dev.jx.pokedex.model.Pokemon
import dev.jx.pokedex.ui.adapter.PokemonListAdapter
import dev.jx.pokedex.ui.animation.BounceEdgeEffectFactory
import dev.jx.pokedex.ui.state.ViewState
import dev.jx.pokedex.ui.viewmodel.PokemonListViewModel
import dev.jx.pokedex.util.toast
@AndroidEntryPoint
class PokemonListFragment : Fragment(), FilterDialogFragment.FilterDialog {
private lateinit var binding: FragmentPokemonListBinding
private val viewModel by viewModels<PokemonListViewModel>()
private val pokemonListAdapter by lazy { PokemonListAdapter(::goToDetails) }
private val filterDialog by lazy { FilterDialogFragment() }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentPokemonListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.pokemonList.apply {
adapter = pokemonListAdapter
edgeEffectFactory = BounceEdgeEffectFactory()
}
(binding.pokemonList.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
viewModel.pokemonList.observe(viewLifecycleOwner) { result ->
when (result) {
is ViewState.Success -> onSuccess(result.value!!)
is ViewState.Error -> onFailure(result.message!!)
is ViewState.Loading -> onLoading(true)
}
}
setupSearchView()
setupFilter()
if (viewModel.recyclerState == RecyclerState.EMPTY) viewModel.getPokemonList()
}
private fun setupSearchView() {
binding.search.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?) = true
override fun onQueryTextChange(newText: String?): Boolean {
if (newText != null) pokemonListAdapter.setFilter(newText) {
binding.pokemonList.layoutManager?.scrollToPosition(0)
}
return true
}
})
binding.search.setOnSearchClickListener {
binding.pokedexTitle.visibility = View.GONE
}
binding.search.setOnCloseListener {
binding.pokedexTitle.visibility = View.VISIBLE
false
}
}
private fun setupFilter() {
binding.filter.setOnClickListener {
filterDialog.show(childFragmentManager, "FilterDialogFragment")
}
}
private fun onSuccess(result: List<Pokemon>) {
onLoading(false)
viewModel.recyclerState = RecyclerState.POPULATED
pokemonListAdapter.setPokemonList(result)
binding.pokemonList.scheduleLayoutAnimation()
}
private fun onFailure(result: String) {
onLoading(false)
result.toast(requireContext())
pokemonListAdapter.submitList(mutableListOf())
}
private fun onLoading(isLoading: Boolean) {
binding.loading.visibility = if (isLoading) View.VISIBLE else View.GONE
}
private fun goToDetails(pokemons: List<Pokemon>, pos: Int, sharedImage: ImageView) {
resetSearchView()
val extras = FragmentNavigatorExtras(sharedImage to sharedImage.transitionName)
findNavController().navigate(
PokemonListFragmentDirections
.actionPokemonListFragmentToFragmentPokemonDetail(
pokemons.toTypedArray(),
pos,
sharedImage.transitionName
), extras
)
}
private fun resetSearchView() {
activity?.currentFocus?.let { view ->
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
binding.search.onActionViewCollapsed()
binding.search.setQuery("", false)
binding.search.clearFocus()
}
enum class RecyclerState {
POPULATED, EMPTY
}
override fun setFilter(options: FilterOptions) {
pokemonListAdapter.setMultiFilter(options) {
binding.pokemonList.layoutManager?.scrollToPosition(0)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
65984150050b3b1e517ffa92f90721160fd39d3a
| 5,041
|
Pokedex-App
|
MIT License
|
app/src/main/java/com/example/challengecovid/Constants.kt
|
michaelmeckl
| 274,500,062
| false
| null |
package com.example.challengecovid
object Constants {
const val SHARED_PREFS_NAME = "challengeCovidSharedPrefs"
const val PREFS_USER_ID = "CurrentUserId"
const val PREFS_LAST_DAY = "LastDay"
const val PREFS_LAST_DAILY_CHALLENGE = "LastDailyChallenge"
//const val PREFS_ALREADY_RESET = "AlreadyReset"
const val PREFS_SWITCH_STATE = "PublicPrivateSwitchState"
const val PREFS_FIRST_TIME_CHALLENGE_COMPLETED = "FirstTimeChallengeCompleted"
const val PREFS_FIRST_TIME_CHALLENGE_PUBLISHED = "FirstTimeChallengePublished"
const val PREFS_FIRST_TIME_MAX_LEVEL_REACHED = "FirstTimeMaxLevelReached"
const val PREFS_IS_CHALLENGE_BY_THIS_USER = "IsChallengeByThisUser"
const val PREFS_COUNT_TOTAL_XP = "CountTotalXP"
const val PREFS_ALL_SHARED_CHALLENGES = "AllSharedChallenges"
const val PREFS_COUNT_COMPLETED_CHALLENGES = "CountCompletedChallenges"
const val PREFS_COUNT_CREATED_CHALLENGES = "CountCreatedChallenges"
//const val PREFS_LAST_DAY_CHALLENGE_COMPLETED = "LastDayChallengeCompleted"
const val PREFS_COUNT_CONSECUTIVE_DAYS = "CountConsecutiveDaysChallengeCompleted"
const val PREFS_LAST_DAY_CHALLENGES_RESET = "LastDayChallengesReset"
}
| 0
|
Kotlin
|
0
| 0
|
b9bb96fca621c9a494e2abedfc3cf656da7f4595
| 1,208
|
Forschungsseminar_I3C_ChallengeApp
|
MIT License
|
lib/src/main/java/com/sd/lib/libkt/coroutine/scope/FViewScope.kt
|
zj565061763
| 366,790,731
| false
| null |
package com.sd.lib.libkt.coroutine.scope
import android.view.View
import com.sd.lib.libkt.utils.LibUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
class FViewScope : FCoroutineScope {
private val _view: View
private val _mainScope by lazy { FMainScope() }
constructor(view: View) {
_view = view
}
/**
* 协程
*/
override fun launch(
context: CoroutineContext,
start: CoroutineStart,
block: suspend CoroutineScope.() -> Unit
): Job? {
if (!LibUtils.isAttached(_view)) {
// view没有被添加到UI上面,不处理
return null
}
if (LibUtils.isFinishing(_view)) {
// view所在的Activity正在被关闭,不处理
return null
}
if (_mainScope.init()) {
_view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View?) {
}
override fun onViewDetachedFromWindow(v: View?) {
_mainScope.destroy()
_view.removeOnAttachStateChangeListener(this)
}
})
}
return _mainScope.launch(
context = context,
start = start,
block = block
)
}
}
| 0
|
Kotlin
|
0
| 0
|
565969b174a01dd16edeb548f48806ef944af9c5
| 1,408
|
libkt
|
MIT License
|
ui/collections/src/main/java/ly/david/ui/collections/instruments/InstrumentsByCollectionViewModel.kt
|
lydavid
| 458,021,427
| false
| null |
package ly.david.ui.collections.instruments
import ly.david.musicsearch.core.models.listitem.InstrumentListItemModel
import ly.david.musicsearch.core.models.network.MusicBrainzEntity
import ly.david.musicsearch.domain.instrument.usecase.GetInstrumentsByEntity
import ly.david.ui.common.EntitiesByEntityViewModel
import org.koin.android.annotation.KoinViewModel
@KoinViewModel
internal class InstrumentsByCollectionViewModel(
getInstrumentsByEntity: GetInstrumentsByEntity,
) : EntitiesByEntityViewModel<InstrumentListItemModel>(
entity = MusicBrainzEntity.COLLECTION,
getEntitiesByEntity = getInstrumentsByEntity,
)
| 110
| null |
0
| 6
|
5e15119a3c55efa932e37afced1b56609e988fe6
| 630
|
MusicSearch
|
Apache License 2.0
|
android/gradle/demo/src/main/java/com/example/demo/MainActivity.kt
|
maplibre
| 432,679,159
| false
|
{"Rust": 567395, "TypeScript": 10749, "Just": 9647, "WGSL": 6773, "JavaScript": 5807, "Nix": 2112, "Swift": 1905, "Java": 987, "HTML": 612, "Kotlin": 453, "Objective-C": 408, "EJS": 333, "Shell": 8}
|
package com.example.demo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import org.maplibre_rs.MapLibreRs
// Currently not used. Instead the NativeActivity referenced in AndroidManifest.xml is used.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MapLibreRs.start()
}
}
| 68
|
Rust
|
78
| 1,346
|
c0032f959769c5d2116dac4f462773b46c17b8e6
| 453
|
maplibre-rs
|
Apache License 2.0
|
src/main/kotlin/org/opensearch/indexmanagement/indexstatemanagement/transport/action/indexpolicy/TransportIndexPolicyAction.kt
|
lezzago
| 387,870,264
| true
|
{"Kotlin": 1905550, "Python": 1396}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.opensearch.indexmanagement.indexstatemanagement.transport.action.indexpolicy
import org.opensearch.indexmanagement.IndexManagementIndices
import org.opensearch.indexmanagement.IndexManagementPlugin
import org.opensearch.indexmanagement.indexstatemanagement.opensearchapi.filterNotNullValues
import org.opensearch.indexmanagement.indexstatemanagement.opensearchapi.getPolicyToTemplateMap
import org.opensearch.indexmanagement.indexstatemanagement.findConflictingPolicyTemplates
import org.opensearch.indexmanagement.util.IndexManagementException
import org.opensearch.indexmanagement.indexstatemanagement.util.ISM_TEMPLATE_FIELD
import org.opensearch.indexmanagement.indexstatemanagement.validateFormat
import org.opensearch.indexmanagement.util.IndexUtils
import org.apache.logging.log4j.LogManager
import org.opensearch.OpenSearchStatusException
import org.opensearch.ExceptionsHelper
import org.opensearch.action.ActionListener
import org.opensearch.action.DocWriteRequest
import org.opensearch.action.index.IndexRequest
import org.opensearch.action.index.IndexResponse
import org.opensearch.action.search.SearchRequest
import org.opensearch.action.search.SearchResponse
import org.opensearch.action.support.ActionFilters
import org.opensearch.action.support.HandledTransportAction
import org.opensearch.action.support.master.AcknowledgedResponse
import org.opensearch.client.node.NodeClient
import org.opensearch.common.inject.Inject
import org.opensearch.common.xcontent.NamedXContentRegistry
import org.opensearch.common.xcontent.XContentFactory
import org.opensearch.index.query.QueryBuilders
import org.opensearch.index.seqno.SequenceNumbers
import org.opensearch.rest.RestStatus
import org.opensearch.search.builder.SearchSourceBuilder
import org.opensearch.tasks.Task
import org.opensearch.transport.TransportService
private val log = LogManager.getLogger(TransportIndexPolicyAction::class.java)
class TransportIndexPolicyAction @Inject constructor(
val client: NodeClient,
transportService: TransportService,
actionFilters: ActionFilters,
val ismIndices: IndexManagementIndices,
val xContentRegistry: NamedXContentRegistry
) : HandledTransportAction<IndexPolicyRequest, IndexPolicyResponse>(
IndexPolicyAction.NAME, transportService, actionFilters, ::IndexPolicyRequest
) {
override fun doExecute(task: Task, request: IndexPolicyRequest, listener: ActionListener<IndexPolicyResponse>) {
IndexPolicyHandler(client, listener, request).start()
}
inner class IndexPolicyHandler(
private val client: NodeClient,
private val actionListener: ActionListener<IndexPolicyResponse>,
private val request: IndexPolicyRequest
) {
fun start() {
ismIndices.checkAndUpdateIMConfigIndex(object : ActionListener<AcknowledgedResponse> {
override fun onResponse(response: AcknowledgedResponse) {
onCreateMappingsResponse(response)
}
override fun onFailure(t: Exception) {
actionListener.onFailure(ExceptionsHelper.unwrapCause(t) as Exception)
}
})
}
private fun onCreateMappingsResponse(response: AcknowledgedResponse) {
if (response.isAcknowledged) {
log.info("Successfully created or updated ${IndexManagementPlugin.INDEX_MANAGEMENT_INDEX} with newest mappings.")
// if there is template field, we will check
val reqTemplate = request.policy.ismTemplate
if (reqTemplate != null) {
checkTemplate(reqTemplate.indexPatterns, reqTemplate.priority)
} else putPolicy()
} else {
log.error("Unable to create or update ${IndexManagementPlugin.INDEX_MANAGEMENT_INDEX} with newest mapping.")
actionListener.onFailure(OpenSearchStatusException(
"Unable to create or update ${IndexManagementPlugin.INDEX_MANAGEMENT_INDEX} with newest mapping.",
RestStatus.INTERNAL_SERVER_ERROR))
}
}
private fun checkTemplate(indexPatterns: List<String>, priority: Int) {
val possibleEx = validateFormat(indexPatterns)
if (possibleEx != null) {
actionListener.onFailure(possibleEx)
return
}
val searchRequest = SearchRequest()
.source(
SearchSourceBuilder().query(
QueryBuilders.existsQuery(ISM_TEMPLATE_FIELD)))
.indices(IndexManagementPlugin.INDEX_MANAGEMENT_INDEX)
client.search(searchRequest, object : ActionListener<SearchResponse> {
override fun onResponse(response: SearchResponse) {
val policyToTemplateMap = getPolicyToTemplateMap(response, xContentRegistry).filterNotNullValues()
val conflictingPolicyTemplates = policyToTemplateMap.findConflictingPolicyTemplates(request.policyID, indexPatterns, priority)
if (conflictingPolicyTemplates.isNotEmpty()) {
val errorMessage = "New policy ${request.policyID} has an ISM template with index pattern $indexPatterns " +
"matching existing policy templates," +
" please use a different priority than $priority"
actionListener.onFailure(IndexManagementException.wrap(IllegalArgumentException(errorMessage)))
return
}
putPolicy()
}
override fun onFailure(t: Exception) {
actionListener.onFailure(ExceptionsHelper.unwrapCause(t) as Exception)
}
})
}
private fun putPolicy() {
request.policy.copy(schemaVersion = IndexUtils.indexManagementConfigSchemaVersion)
val indexRequest = IndexRequest(IndexManagementPlugin.INDEX_MANAGEMENT_INDEX)
.setRefreshPolicy(request.refreshPolicy)
.source(request.policy.toXContent(XContentFactory.jsonBuilder()))
.id(request.policyID)
.timeout(IndexRequest.DEFAULT_TIMEOUT)
if (request.seqNo == SequenceNumbers.UNASSIGNED_SEQ_NO || request.primaryTerm == SequenceNumbers.UNASSIGNED_PRIMARY_TERM) {
indexRequest.opType(DocWriteRequest.OpType.CREATE)
} else {
indexRequest.setIfSeqNo(request.seqNo)
.setIfPrimaryTerm(request.primaryTerm)
}
client.index(indexRequest, object : ActionListener<IndexResponse> {
override fun onResponse(response: IndexResponse) {
val failureReasons = checkShardsFailure(response)
if (failureReasons != null) {
actionListener.onFailure(OpenSearchStatusException(failureReasons.toString(), response.status()))
return
}
actionListener.onResponse(IndexPolicyResponse(
response.id,
response.version,
response.primaryTerm,
response.seqNo,
request.policy,
response.status()
))
}
override fun onFailure(t: Exception) {
// TODO should wrap document already exists exception
// provide a direct message asking user to use seqNo and primaryTerm
actionListener.onFailure(ExceptionsHelper.unwrapCause(t) as Exception)
}
})
}
private fun checkShardsFailure(response: IndexResponse): String? {
val failureReasons = StringBuilder()
if (response.shardInfo.failed > 0) {
response.shardInfo.failures.forEach {
entry -> failureReasons.append(entry.reason())
}
return failureReasons.toString()
}
return null
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d042b0a259e7104a93676ddc45a155a86cd665a0
| 9,095
|
opensearch-project-index-management
|
Apache License 2.0
|
protocol/osrs-226/osrs-226-desktop/src/main/kotlin/net/rsprot/protocol/game/outgoing/codec/misc/client/SetInteractionModeEncoder.kt
|
blurite
| 771,753,685
| false
|
{"Kotlin": 11355829}
|
package net.rsprot.protocol.game.outgoing.codec.misc.client
import net.rsprot.buffer.JagByteBuf
import net.rsprot.crypto.cipher.StreamCipher
import net.rsprot.protocol.ServerProt
import net.rsprot.protocol.game.outgoing.misc.client.SetInteractionMode
import net.rsprot.protocol.game.outgoing.prot.GameServerProt
import net.rsprot.protocol.message.codec.MessageEncoder
import net.rsprot.protocol.metadata.Consistent
@Consistent
public class SetInteractionModeEncoder : MessageEncoder<SetInteractionMode> {
override val prot: ServerProt = GameServerProt.SET_INTERACTION_MODE
override fun encode(
streamCipher: StreamCipher,
buffer: JagByteBuf,
message: SetInteractionMode,
) {
buffer.p2(message.worldId)
buffer.p1(message.tileInteractionMode)
buffer.p1(message.entityInteractionMode)
}
}
| 5
|
Kotlin
|
6
| 27
|
d08cb7c11ae758b5dcabd6e85d34a4bfdba7ad3c
| 853
|
rsprot
|
MIT License
|
app/src/main/java/com/github/wnebyte/workoutapp/ui/workout/ForegroundService.kt
|
wnebyte
| 381,744,339
| false
| null |
package com.github.wnebyte.workoutapp.ui.workout
import java.util.*
import android.app.Notification
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.*
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.github.wnebyte.workoutapp.R
import com.github.wnebyte.workoutapp.MainActivity
import com.github.wnebyte.workoutapp.NOTIFICATION_CHANNEL_ID
import com.github.wnebyte.workoutapp.util.ContextHelper
import com.github.wnebyte.workoutapp.util.Stopwatch
private const val TAG = "ForegroundService"
private const val NOTIFICATION_ID = 1
private const val WORKOUT_ID_EXTRA = "WorkoutId"
private const val START_VALUE_EXTRA = "StartValue"
class ForegroundService : Service() {
private lateinit var broadcast: LocalBroadcastManager
private lateinit var stopwatch: Stopwatch
override fun onCreate() {
super.onCreate()
broadcast = LocalBroadcastManager.getInstance(this)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.i(TAG, "onStartCommand(startId: $startId)")
val workoutId: UUID = intent.getSerializableExtra(WORKOUT_ID_EXTRA) as UUID
val startValue: Long = intent.getLongExtra(START_VALUE_EXTRA, 0L)
val tickRate = 100L
stopwatch = object : Stopwatch(tickRate, startValue) {
override fun onTick(value: Long) {
sendResult(value)
if (value % 1000 == 0L) {
showBackgroundNotification(
NOTIFICATION_ID,
getNotification(formatMillis(value, "mm:ss"), workoutId)
)
}
}
}
stopwatch.start()
return START_STICKY
}
override fun onDestroy() {
Log.i(TAG, "onDestroy()")
stopwatch.stop()
stopSelf()
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
private fun showBackgroundNotification(
requestCode: Int,
notification: Notification
) {
val intent = Intent(ContextHelper
.prependPackageName(applicationContext, ACTION_SHOW_NOTIFICATION)).apply {
putExtra(REQUEST_CODE, requestCode)
putExtra(NOTIFICATION, notification)
}
this.sendOrderedBroadcast(intent, ContextHelper
.prependPackageName(applicationContext, PERM_PRIVATE))
}
private fun getNotification(
contentText: String,
workoutId: UUID
): Notification {
val pendingIntent = MainActivity.newPendingWorkoutIntent(this, workoutId)
return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_timer_24)
.setContentTitle(resources.getString(R.string.nav_workout_stopwatch))
.setContentText(contentText)
.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.setAutoCancel(true)
.setSilent(true)
.setOngoing(true)
.setTimeoutAfter(1500)
.build()
}
private fun sendResult(value: Long?) {
val intent = Intent(SERVICE_RESULT)
value?.let {
intent.putExtra(SERVICE_MESSAGE, value)
}
broadcast.sendBroadcast(intent)
}
companion object {
const val SERVICE_MESSAGE = "message"
const val SERVICE_RESULT = "result"
const val ACTION_SHOW_NOTIFICATION = ".SHOW_NOTIFICATION"
const val PERM_PRIVATE = ".permission.PRIVATE"
const val REQUEST_CODE = "REQUEST_CODE"
const val NOTIFICATION = "NOTIFICATION"
/**
* Creates a new intent where the [workoutId] will be used when the application is
* relaunched from the navigation drawer.
*/
fun newIntent(
context: Context,
workoutId: UUID?,
startValue: Long?
): Intent =
Intent(context, ForegroundService::class.java).apply {
putExtra(WORKOUT_ID_EXTRA, workoutId)
putExtra(START_VALUE_EXTRA, startValue)
}
}
}
| 0
|
Kotlin
|
0
| 3
|
7ec18589b24726b8c09247e8c03d7040ddf08d05
| 4,264
|
workout-app
|
Matrix Template Library License
|
client/src/commonMain/kotlin/com/algolia/client/model/querysuggestions/SourceIndex.kt
|
algolia
| 153,273,215
| false
|
{"Kotlin": 1464911}
|
/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */
package com.algolia.client.model.querysuggestions
import kotlinx.serialization.*
import kotlinx.serialization.json.*
/**
* Configuration of an Algolia index for Query Suggestions.
*
* @param indexName Name of the Algolia index to use as source for query suggestions.
* @param replicas If true, Query Suggestions uses all replica indices to find popular searches. If false, only the primary index is used.
* @param analyticsTags
* @param facets
* @param minHits Minimum number of hits required to be included as a suggestion. A search query must at least generate `minHits` search results to be included in the Query Suggestions index.
* @param minLetters Minimum letters required to be included as a suggestion. A search query must be at least `minLetters` long to be included in the Query Suggestions index.
* @param generate
* @param `external`
*/
@Serializable
public data class SourceIndex(
/** Name of the Algolia index to use as source for query suggestions. */
@SerialName(value = "indexName") val indexName: String,
/** If true, Query Suggestions uses all replica indices to find popular searches. If false, only the primary index is used. */
@SerialName(value = "replicas") val replicas: Boolean? = null,
@SerialName(value = "analyticsTags") val analyticsTags: List<String>? = null,
@SerialName(value = "facets") val facets: List<Facet>? = null,
/** Minimum number of hits required to be included as a suggestion. A search query must at least generate `minHits` search results to be included in the Query Suggestions index. */
@SerialName(value = "minHits") val minHits: Int? = null,
/** Minimum letters required to be included as a suggestion. A search query must be at least `minLetters` long to be included in the Query Suggestions index. */
@SerialName(value = "minLetters") val minLetters: Int? = null,
@SerialName(value = "generate") val generate: List<List<String>>? = null,
@SerialName(value = "external") val `external`: List<String>? = null,
)
| 15
|
Kotlin
|
8
| 59
|
686cdfb400aa4254fc3b62dac6ca3d10c7aac846
| 2,199
|
algoliasearch-client-kotlin
|
MIT License
|
app/src/main/java/com/urbandroid/sleep/addon/stats/model/socialjetlag/ChronoRecord.kt
|
petrnalevka
| 456,982,453
| false
|
{"Java": 183480, "Kotlin": 17905}
|
package com.urbandroid.sleep.addon.stats.model.socialjetlag
import com.urbandroid.sleep.addon.stats.model.StatRecord
import java.util.*
class ChronoRecord @JvmOverloads constructor(
val from: Date, val to: Date,
//Fractional hours (e.g. 22:30 is 22.5) in the user's local time.
val fromHour: Float, val toHour: Float,
//Net sleep time in hours (to - from - awake_pauses).
val length: Float, val timeZone: TimeZone = TimeZone.getDefault())
{
//Fractional hours (e.g. 22:30 is 22.5) in the user's local time.
val fromHourUTC = getHourUTC(from)
val toHourUTC = getHourUTC(to)
//Midpoint between from and to
val midSleep = getMidSleep(fromHour, toHour)
val midSleepUTC = getMidSleep(fromHourUTC, toHourUTC)
init {
if (from.time > to.time) {
throw IllegalArgumentException("$from > $to")
}
//Max sleep length is 20 hours. It needs to be less than one day
//in order to midpoint calculation to work, and the four hours
//are a buffer for DST time change, or timezone change, etc.
if (to.time - from.time > 1000 * 60 * 60 * 20) {
throw IllegalArgumentException("$to - $from > one day")
}
if (fromHour < 0 || fromHour >= 24) {
throw IllegalArgumentException("Invalid fromHour: $fromHour")
}
if (toHour < 0 || toHour >= 24) {
throw IllegalArgumentException("Invalid toHour: $toHour")
}
}
private fun getHourUTC(d: Date): Float {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { time = d }
val hour = calendar.get(Calendar.HOUR_OF_DAY).toFloat()
val minute = calendar.get(Calendar.MINUTE).toFloat()
val second = calendar.get(Calendar.SECOND).toFloat()
return hour + minute/60f + second/3600f
}
private fun getMidSleep(fromHour: Float, toHour: Float): Float = if (fromHour <= toHour) {
(fromHour + toHour) / 2f
} else {
val midPoint = (fromHour + toHour) / 2f + 12f
if (midPoint < 24f) midPoint else midPoint - 24f
}
fun getEndDayOfWeek() = Calendar.getInstance(timeZone).run {
time = to
get(Calendar.DAY_OF_WEEK)
}
//Indeed, we are dealing with records from a single user, so "to" fully identifies the record.
override fun equals(other: Any?) = other is ChronoRecord && other.to == to
override fun hashCode() = to.hashCode()
override fun toString(): String {
return "ChronoRecord(from=$from, to=$to, length=$length, midSleep=$midSleep)"
}
}
fun StatRecord.toChronoRecord(): ChronoRecord? {
try {
return ChronoRecord(
from = fromDate,
to = toDate,
fromHour = fromHour.toFloat(),
toHour = toHour.toFloat(),
length = trackLengthInHours,
timeZone = timeZone ?: TimeZone.getDefault()
)
} catch (e: RuntimeException) {
return null
}
}
| 6
|
Java
|
1
| 0
|
e5d247c4636ad51fc186a60daae9bea309a2c6a0
| 3,033
|
sleep-irregularity
|
Apache License 2.0
|
compiler/testData/diagnostics/tests/resolve/noCandidates/resolvedToClassifier.kt
|
JetBrains
| 3,432,266
| false
| null |
// DIAGNOSTICS: -UNUSED_VARIABLE
interface A
object B
class C
fun test() {
val interface_as_fun = <!RESOLUTION_TO_CLASSIFIER!>A<!>()
val interface_as_val = <!NO_COMPANION_OBJECT!>A<!>
val object_as_fun = <!FUNCTION_EXPECTED!>B<!>()
val class_as_val = <!NO_COMPANION_OBJECT!>C<!>
}
fun <T> bar() {
val typeParameter_as_val = <!TYPE_PARAMETER_IS_NOT_AN_EXPRESSION!>T<!>
val typeParameter_as_fun = <!RESOLUTION_TO_CLASSIFIER!>T<!>()
baz(<!TYPE_PARAMETER_IS_NOT_AN_EXPRESSION!>T<!>)
baz("$<!TYPE_PARAMETER_IS_NOT_AN_EXPRESSION!>T<!>")
1 + <!TYPE_PARAMETER_IS_NOT_AN_EXPRESSION!>T<!>
B::class.equals(<!TYPE_PARAMETER_IS_NOT_AN_EXPRESSION!>T<!>)
<!TYPE_PARAMETER_IS_NOT_AN_EXPRESSION!>T<!> = ""
}
fun baz(a: Any) {}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 764
|
kotlin
|
Apache License 2.0
|
src/commonMain/kotlin/me/devnatan/yoki/models/Healthcheck.kt
|
DevNatan
| 392,883,613
| false
|
{"Kotlin": 195907}
|
package me.devnatan.yoki.models
import kotlinx.datetime.Instant
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
public data class Healthcheck internal constructor(
// TODO create sealed class for status
@SerialName("Status") public val statusString: String,
@SerialName("FailingStreak") public val failingStreak: Int,
@SerialName("Log") public val logs: List<HealthcheckResult> = emptyList(),
)
@Serializable
public data class HealthcheckResult internal constructor(
@SerialName("Start") public val startedAtString: String,
@SerialName("End") public val endedAtString: String? = null,
@SerialName("ExitCode") public val exitCode: Int? = null,
@SerialName("Output") public val output: String? = null,
) {
public val startedAt: Instant by lazy { Instant.parse(startedAtString) }
public val endedAt: Instant? by lazy { endedAtString?.let(Instant::parse) }
}
| 9
|
Kotlin
|
4
| 19
|
dfe370c33247ccc88b4dcf36737598874bcd4b92
| 946
|
yoki
|
MIT License
|
CanadianInvestor/src/Compound.kt
|
bassamriman
| 98,359,661
| false
| null |
interface ICompoundPerTime<T : TimeUnit<T>> : TemporalRate.UnitPerTime<Compound.UNIT, T>
interface ICompoundFrequency<T : TimeUnit<T>> : ICompoundPerTime<T>, TemporalRate.UnitPerTime.Frequency<Compound.UNIT, T>
interface ITimePerCompound<T : TimeUnit<T>> : TemporalRate.TimePerUnit<T, Compound.UNIT>
interface ICompoundPeriod<T : TimeUnit<T>> : ITimePerCompound<T>, TemporalRate.TimePerUnit.Period<T, Compound.UNIT>
data class CompoundPeriod<T : TimeUnit<T>>(override val timeNumerator : Amount<T>) : ICompoundPeriod<T>, TemporalRate.TimePerUnit.Period<T, Compound.UNIT> by TimePerUnit.Period.per(timeNumerator, Compound.UNIT)
| 0
|
Kotlin
|
0
| 0
|
bb232001b120ab0e38a23ba33524f56ea09ca9b4
| 626
|
AdvancedCompoundCalculator
|
Apache License 2.0
|
selekt-android/src/test/kotlin/com/bloomberg/selekt/android/SQLDatabaseSampleInputTest.kt
|
bloomberg
| 281,998,984
| false
| null |
/*
* Copyright 2022 Bloomberg Finance L.P.
*
* 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.bloomberg.selekt.android
import com.bloomberg.selekt.commons.times
import com.bloomberg.selekt.ContentValues
import com.bloomberg.selekt.SQLDatabase
import com.bloomberg.selekt.SQLiteJournalMode
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
import java.nio.charset.StandardCharsets
import java.util.stream.Stream
import kotlin.io.path.createTempFile
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@Suppress("ArrayInDataClass")
internal data class SQLSampleInputs(
val resourceFileName: String,
val journalMode: SQLiteJournalMode,
val key: ByteArray?
) {
override fun toString() = "$resourceFileName-$journalMode-${if (key != null) { "keyed" } else { null }}"
}
internal class SampleArgumentsProvider : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext): Stream<out Arguments> = (arrayOf(
"html.json",
"japanese.txt",
"magic_spaces.txt",
"sample.json",
"sample.txt",
"tricky.txt"
) * arrayOf(SQLiteJournalMode.DELETE)).map {
SQLSampleInputs(it.first, it.second, ByteArray(32) { 0x42 })
}.stream().map { Arguments.of(it) }
}
private fun createFile(
input: SQLSampleInputs
) = createTempFile("test-samples-$input-", ".db").toFile().also { it.deleteOnExit() }
internal class SQLDatabaseSampleTests {
@ParameterizedTest
@ArgumentsSource(SampleArgumentsProvider::class)
fun insertSample(
inputs: SQLSampleInputs
): Unit = SQLDatabase(
createFile(inputs).absolutePath,
SQLite,
inputs.journalMode.databaseConfiguration,
key = null
).use {
it.transact {
exec("CREATE TABLE 'Foo' (bar TEXT)")
val json = javaClass.classLoader!!.getResource(inputs.resourceFileName).readText(StandardCharsets.UTF_8)
insert("Foo", ContentValues().apply { put("bar", json) }, ConflictAlgorithm.REPLACE)
query(false, "Foo", arrayOf("bar"), "", emptyArray(), null, null, null, null).use { cursor ->
assertTrue(cursor.moveToNext())
assertEquals(json, cursor.getString(0))
assertFalse(cursor.moveToNext())
}
}
}
}
| 4
| null |
9
| 46
|
510eb128dce97c7b1357e279e92d9dd4e50b71e2
| 3,080
|
selekt
|
Apache License 2.0
|
android/rctmgl/src/main/java-v10/com/mapbox/rctmgl/components/images/RCTMGLImagesManager.kt
|
rnmapbox
| 180,028,389
| false
| null |
package com.mapbox.rctmgl.components.images
import android.graphics.drawable.BitmapDrawable
import android.view.View
import com.facebook.react.bridge.*
import com.facebook.react.common.MapBuilder
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.annotations.ReactProp
import com.mapbox.maps.ImageContent
import com.mapbox.maps.ImageStretches
import com.mapbox.rctmgl.components.AbstractEventEmitter
import com.mapbox.rctmgl.events.constants.EventKeys
import com.mapbox.rctmgl.utils.ImageEntry
import com.mapbox.rctmgl.utils.Logger
import com.mapbox.rctmgl.utils.ResourceUtils
import com.mapbox.rctmgl.utils.extensions.forEach
import java.util.*
class RCTMGLImagesManager(private val mContext: ReactApplicationContext) :
AbstractEventEmitter<RCTMGLImages?>(
mContext
) {
override fun getName(): String {
return "RCTMGLImages"
}
public override fun createViewInstance(context: ThemedReactContext): RCTMGLImages {
return RCTMGLImages(context, this)
}
fun imageInfo(name: String, map: ReadableMap): ImageInfo {
var sdf = false
var stretchX = listOf<ImageStretches>()
var stretchY = listOf<ImageStretches>()
var content : ImageContent? = null
var scale : Double? = null
if (map.hasKey("sdf")) {
sdf = map.getBoolean("sdf");
}
if (map.hasKey("stretchX")) {
stretchX = convertStretch(map.getDynamic("stretchX")) ?: listOf()
}
if (map.hasKey("stretchY")) {
stretchY = convertStretch(map.getDynamic("stretchY")) ?: listOf()
}
if (map.hasKey("content")) {
content = convertContent(map.getDynamic("content")) ?: null
}
if (map.hasKey("scale")) {
if (map.getType("scale") != ReadableType.Number) {
Logger.e("RCTMGLImages", "scale should be a number found: $scale in $map")
}
scale = map.getDouble("scale")
}
return ImageInfo(name=name, sdf=sdf, scale=scale, content=content, stretchX = stretchX, stretchY = stretchY)
}
@ReactProp(name = "images")
fun setImages(images: RCTMGLImages, map: ReadableMap) {
val imagesList = mutableListOf<Map.Entry<String, ImageEntry>>()
map.forEach { imageName, imageInfo ->
when (imageInfo) {
is ReadableMap -> {
val uri = imageInfo.getString("uri") ?: imageInfo.getString("url")
if (uri != null) {
imagesList.add(AbstractMap.SimpleEntry(imageName, ImageEntry(uri, imageInfo(imageName, imageInfo))))
} else {
Logger.e("RCTMGLImagesManager", "Unexpected value for key: $imageName in images property, no uri/url found!")
}
}
is String -> {
val name = imageInfo
imagesList.add(AbstractMap.SimpleEntry(imageName, ImageEntry(name, ImageInfo(name=imageName))))
}
else -> {
Logger.e("RCTMGLImagesManager", "Unexpected value for key: $imageName in images property, only string/object is supported")
}
}
}
images.setImages(imagesList)
}
@ReactProp(name = "hasOnImageMissing")
fun setHasOnImageMissing(images: RCTMGLImages, value: Boolean?) {
images.setHasOnImageMissing(value!!)
}
fun toNativeImage(dynamic: Dynamic): NativeImage? {
when (dynamic.type) {
ReadableType.String -> {
val resourceName = dynamic.asString();
val drawable =
ResourceUtils.getDrawableByName(mContext, resourceName) as BitmapDrawable?
if (drawable != null) {
return NativeImage(ImageInfo(name=resourceName), drawable)
} else {
Logger.e("RCTMGLImages", "cound not get native drawable with name: $resourceName")
return null
}
}
ReadableType.Map -> {
val map = dynamic.asMap()
val resourceName = map.getString("name")
val drawable =
ResourceUtils.getDrawableByName(mContext, resourceName) as BitmapDrawable?
if (drawable != null && resourceName != null) {
return NativeImage(imageInfo(resourceName, map), drawable)
} else {
Logger.e("RCTMGLImages", "cound not get native drawable with name: $resourceName")
return null
}
}
else -> {
Logger.e("RCTMGLImages", "nativeImages element should be a string or a object, but was: $dynamic")
return null
}
}
}
@ReactProp(name = "nativeImages")
fun setNativeImages(images: RCTMGLImages, arr: ReadableArray) {
val nativeImages = mutableListOf<NativeImage>();
for (i in 0 until arr.size()) {
val nativeImage = toNativeImage(arr.getDynamic(i))
if (nativeImage != null) {
nativeImages.add(nativeImage)
}
}
images.setNativeImages(nativeImages)
}
override fun customEvents(): Map<String, String>? {
return MapBuilder.builder<String, String>()
.put(EventKeys.IMAGES_MISSING, "onImageMissing")
.build()
}
// region RCTMGLImage children
override fun addView(parent: RCTMGLImages?, childView: View?, childPosition: Int) {
if (parent == null || childView == null) {
Logger.e("RCTMGLImages", "addView: parent or childView is null")
return
}
if (childView !is RCTMGLImage) {
Logger.e("RCTMGLImages", "child view should be RCTMGLImage")
return
}
parent.mImageViews.add(childPosition, childView)
childView.nativeImageUpdater = parent
}
override fun removeView(parent: RCTMGLImages?, view: View?) {
if (parent == null || view == null) {
Logger.e("RCTMGLImages", "removeView: parent or view is null")
return
}
parent.mImageViews.remove(view)
}
override fun removeAllViews(parent: RCTMGLImages?) {
if (parent == null) {
Logger.e("RCTMGLImages", "removeAllViews parent is null")
return
}
parent.mImageViews.clear()
}
// endregion
companion object {
const val REACT_CLASS = "RCTMGLImages"
fun convertStretch(stretch: Dynamic) : List<ImageStretches>? {
if (stretch.type != ReadableType.Array) {
Logger.e("RCTMGLImages", "stretch should be an array, got $stretch")
return null
}
val array = stretch.asArray()
var result = mutableListOf<ImageStretches>();
for (i in 0 until array.size()) {
if (array.getType(i) != ReadableType.Array) {
Logger.e("RTMGLImages", "each element of strech should be an array but was: ${array.getDynamic(i)}")
} else {
val pair = array.getArray(i)
if (pair.size() != 2 || pair.getType(0) != ReadableType.Number || pair.getType(1) != ReadableType.Number) {
Logger.e("RCTMGLImages", "each element of stretch should be pair of 2 integers but was ${pair}")
}
result.add(ImageStretches(pair.getDouble(0).toFloat(), pair.getDouble(1).toFloat()))
}
}
return result;
}
fun convertContent(content: Dynamic) : ImageContent? {
if (content.type != ReadableType.Array) {
Logger.e("RCTMGLImages", "content should be an array, got $content")
return null
}
val array = content.asArray()
if (array.size() != 4) {
Logger.e("RCTMGLImages", "content should be an array of 4 numbers, got $content")
return null
}
val result = arrayOf(0.0, 0.0, 0.0, 0.0, 0.0)
for (i in 0 until array.size()) {
if (array.getType(i) != ReadableType.Number) {
Logger.e("RTMGLImages", "each element of content should be an number but was : ${array}")
return null
} else {
result[i] = array.getDouble(i)
}
}
return ImageContent(result[0].toFloat(), result[1].toFloat() ,result[2].toFloat(), result[3].toFloat())
}
}
}
| 34
| null |
786
| 1,786
|
5e87a8d33d311d04c15d0c9489179e69d4b6d3ba
| 8,757
|
maps
|
MIT License
|
test2code/src/main/kotlin/com/epam/drill/test2code/coverage/ProbesProvider.kt
|
Drill4J
| 240,284,351
| false
|
{"Kotlin": 218235, "Java": 57214, "Batchfile": 410, "Shell": 329}
|
/**
* Copyright 2020 - 2022 EPAM Systems
*
* 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.epam.drill.test2code.coverage
import com.epam.drill.jacoco.AgentProbes
/**
* Provides boolean array for the probe.
* Implementations must be kotlin singleton objects.
*/
typealias IProbesProxy = (ClassId, Int, String, Int) -> AgentProbes
const val SESSION_CONTEXT_NONE = "SESSION_CONTEXT_NONE"
const val TEST_CONTEXT_NONE = "TEST_CONTEXT_NONE"
const val SESSION_CONTEXT_AMBIENT = "GLOBAL"
data class ContextKey(
private val _sessionId: SessionId? = null, // TODO there must be a better way to avoid nullability and assign defaults
private val _testId: TestId? = null
) {
val sessionId: SessionId = _sessionId ?: SESSION_CONTEXT_NONE
val testId: TestId = _testId ?: TEST_CONTEXT_NONE
}
internal val CONTEXT_AMBIENT = ContextKey(SESSION_CONTEXT_AMBIENT)
| 7
|
Kotlin
|
2
| 6
|
8d286d6f5d4cee9b1db94d6960140584f247477e
| 1,387
|
java-agent
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/joetr/sync/sphere/ui/icon/IconSelectionScreen.kt
|
j-roskopf
| 712,951,839
| false
|
{"Kotlin": 1502373, "Ruby": 3083, "Shell": 1352, "Swift": 588}
|
package com.joetr.sync.sphere.ui.icon
import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.lifecycle.LifecycleEffect
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.koin.getScreenModel
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.joetr.sync.sphere.design.toolbar.DefaultToolbar
import com.joetr.sync.sphere.design.toolbar.backOrNull
import com.joetr.sync.sphere.ui.ProgressIndicator
import com.joetr.sync.sphere.ui.icon.data.IconSelection
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
class IconSelectionScreen : Screen {
@Composable
override fun Content() {
val screenModel = getScreenModel<IconSelectionModel>()
val state = screenModel.state.collectAsState().value
LifecycleEffect(
onStarted = {
screenModel.init()
},
)
Scaffold(
topBar = {
DefaultToolbar(
onBack = LocalNavigator.currentOrThrow.backOrNull(),
)
},
) { paddingValues ->
AnimatedContent(
targetState = state,
contentKey = {
it.key
},
) { targetState ->
when (targetState) {
is IconSelectionViewState.Content -> ContentState(
modifier = Modifier.padding(paddingValues),
images = targetState.images,
imageSelected = {
screenModel.selectImage(it)
},
)
is IconSelectionViewState.Loading -> LoadingState(
modifier = Modifier.padding(paddingValues),
)
}
}
}
}
@Composable
private fun ContentState(
modifier: Modifier = Modifier,
images: List<IconSelection>,
imageSelected: (DrawableResource) -> Unit,
) {
LazyVerticalGrid(
modifier = modifier.fillMaxSize(),
columns = GridCells.Adaptive(minSize = 128.dp),
) {
items(images) { image ->
ImageItem(
image = image,
imageSelected = imageSelected,
)
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
private fun ImageItem(image: IconSelection, imageSelected: (DrawableResource) -> Unit) {
Box(
contentAlignment = Alignment.Center,
) {
Image(
painter = painterResource(image.image),
contentDescription = "Icon",
contentScale = ContentScale.Crop,
modifier = Modifier
.padding(8.dp)
.size(96.dp)
.clickable {
imageSelected(image.image)
},
)
if (image.selected) {
Icon(
imageVector = Icons.Filled.Check,
contentDescription = null,
modifier = Modifier.size(96.dp),
tint = MaterialTheme.colorScheme.primary,
)
}
}
}
@Composable
private fun LoadingState(modifier: Modifier = Modifier) {
Box(
modifier = modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
ProgressIndicator()
}
}
}
| 0
|
Kotlin
|
0
| 9
|
9566fd5ee3a7bd5dfcf5e37d2900cbe601534783
| 4,668
|
SyncSphere
|
MIT License
|
app/src/main/java/softspark/com/inventorypilot/common/di/CommonUseCaseModule.kt
|
Landony04
| 836,511,304
| false
|
{"Kotlin": 300138}
|
package softspark.com.inventorypilot.common.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.scopes.ViewModelScoped
import softspark.com.inventorypilot.common.domain.useCases.GenerateCurrentDateUTCUseCase
import softspark.com.inventorypilot.common.domain.useCases.GenerateCurrentDateUTCUseCaseImpl
import softspark.com.inventorypilot.common.domain.useCases.GenerateIdUseCase
import softspark.com.inventorypilot.common.domain.useCases.GenerateIdUseCaseImpl
import softspark.com.inventorypilot.common.domain.useCases.GetUserIdUseCase
import softspark.com.inventorypilot.common.domain.useCases.GetUserIdUseCaseImpl
import softspark.com.inventorypilot.common.utils.preferences.InventoryPilotPreferences
@Module
@InstallIn(ViewModelComponent::class)
object CommonUseCaseModule {
@ViewModelScoped
@Provides
fun provideGetUserIdUseCase(
inventoryPilotPreferences: InventoryPilotPreferences
): GetUserIdUseCase = GetUserIdUseCaseImpl(inventoryPilotPreferences)
@ViewModelScoped
@Provides
fun provideGenerateIdUseCase(): GenerateIdUseCase = GenerateIdUseCaseImpl()
@ViewModelScoped
@Provides
fun provideGenerateCurrentDateUTCUseCase(): GenerateCurrentDateUTCUseCase =
GenerateCurrentDateUTCUseCaseImpl()
}
| 2
|
Kotlin
|
0
| 0
|
a6778291c9ec4079f826299720486a7c590023ec
| 1,369
|
inventory-pilot
|
MIT License
|
okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/package-info.kt
|
yschimke
| 42,286,486
| true
|
{"Kotlin": 2601894, "Java": 877352, "Shell": 3288}
|
/** A DNS over HTTPS implementation for OkHttp. */
package okhttp3.dnsoverhttps
| 1
|
Kotlin
|
3
| 6
|
ef459b1d8b0530c915386c527e8a141c88cd5c15
| 81
|
okhttp
|
Apache License 2.0
|
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/util/Views.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.util
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.URLSpan
import android.text.util.Linkify
import android.util.Patterns
import android.widget.TextView
import androidx.core.text.util.LinkifyCompat
import androidx.recyclerview.widget.RecyclerView
import de.rki.coronawarnapp.R
import de.rki.coronawarnapp.util.ContextExtensions.getColorCompat
fun TextView.convertToHyperlink(url: String) {
setText(
SpannableString(text).apply { setSpan(URLSpan(url), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) },
TextView.BufferType.SPANNABLE
)
movementMethod = LinkMovementMethod.getInstance()
}
fun TextView.linkifyPhoneNumbers() {
LinkifyCompat.addLinks(
this,
Patterns.PHONE,
"tel:",
Linkify.sPhoneNumberMatchFilter,
Linkify.sPhoneNumberTransformFilter
)
movementMethod = LinkMovementMethod.getInstance()
setLinkTextColor(context.getColorCompat(R.color.colorTextTint))
}
/**
* [RecyclerView.OnScrollListener] listener wrapper
* @param block Callback to scroll changes, passes `true` if scrolling up and `false` otherwise
*/
fun RecyclerView.onScroll(block: (Boolean) -> Unit) {
val threshold = 50
addOnScrollListener(
object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
// Scrolling down
if (dy > threshold) block(false)
// Scrolling up
if (dy < -threshold) block(true)
// At the top
if (!recyclerView.canScrollVertically(-1)) block(true)
}
}
)
}
| 6
|
Kotlin
|
514
| 2,495
|
d3833a212bd4c84e38a1fad23b282836d70ab8d5
| 1,757
|
cwa-app-android
|
Apache License 2.0
|
definitions/src/main/kotlin-gen/xyz/urbanmatrix/mavlink/definitions/avssuas/AvssDroneImu.kt
|
urbanmatrix
| 484,943,163
| false
| null |
package com.divpundir.mavlink.definitions.avssuas
import com.divpundir.mavlink.api.GeneratedMavField
import com.divpundir.mavlink.api.GeneratedMavMessage
import com.divpundir.mavlink.api.MavMessage
import com.divpundir.mavlink.serialization.decodeFloat
import com.divpundir.mavlink.serialization.decodeUInt32
import com.divpundir.mavlink.serialization.encodeFloat
import com.divpundir.mavlink.serialization.encodeUInt32
import com.divpundir.mavlink.serialization.truncateZeros
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.Byte
import kotlin.ByteArray
import kotlin.Float
import kotlin.Int
import kotlin.UInt
import kotlin.Unit
/**
* Drone IMU data. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0
* 0).
*/
@GeneratedMavMessage(
id = 60_052u,
crcExtra = 101,
)
public data class AvssDroneImu(
/**
* Timestamp (time since FC boot).
*/
@GeneratedMavField(type = "uint32_t")
public val timeBootMs: UInt = 0u,
/**
* Quaternion component 1, w (1 in null-rotation)
*/
@GeneratedMavField(type = "float")
public val q1: Float = 0F,
/**
* Quaternion component 2, x (0 in null-rotation)
*/
@GeneratedMavField(type = "float")
public val q2: Float = 0F,
/**
* Quaternion component 3, y (0 in null-rotation)
*/
@GeneratedMavField(type = "float")
public val q3: Float = 0F,
/**
* Quaternion component 4, z (0 in null-rotation)
*/
@GeneratedMavField(type = "float")
public val q4: Float = 0F,
/**
* X acceleration
*/
@GeneratedMavField(type = "float")
public val xacc: Float = 0F,
/**
* Y acceleration
*/
@GeneratedMavField(type = "float")
public val yacc: Float = 0F,
/**
* Z acceleration
*/
@GeneratedMavField(type = "float")
public val zacc: Float = 0F,
/**
* Angular speed around X axis
*/
@GeneratedMavField(type = "float")
public val xgyro: Float = 0F,
/**
* Angular speed around Y axis
*/
@GeneratedMavField(type = "float")
public val ygyro: Float = 0F,
/**
* Angular speed around Z axis
*/
@GeneratedMavField(type = "float")
public val zgyro: Float = 0F,
) : MavMessage<AvssDroneImu> {
public override val instanceCompanion: MavMessage.MavCompanion<AvssDroneImu> = Companion
public override fun serializeV1(): ByteArray {
val outputBuffer = ByteBuffer.allocate(SIZE_V1).order(ByteOrder.LITTLE_ENDIAN)
outputBuffer.encodeUInt32(timeBootMs)
outputBuffer.encodeFloat(q1)
outputBuffer.encodeFloat(q2)
outputBuffer.encodeFloat(q3)
outputBuffer.encodeFloat(q4)
outputBuffer.encodeFloat(xacc)
outputBuffer.encodeFloat(yacc)
outputBuffer.encodeFloat(zacc)
outputBuffer.encodeFloat(xgyro)
outputBuffer.encodeFloat(ygyro)
outputBuffer.encodeFloat(zgyro)
return outputBuffer.array()
}
public override fun serializeV2(): ByteArray {
val outputBuffer = ByteBuffer.allocate(SIZE_V2).order(ByteOrder.LITTLE_ENDIAN)
outputBuffer.encodeUInt32(timeBootMs)
outputBuffer.encodeFloat(q1)
outputBuffer.encodeFloat(q2)
outputBuffer.encodeFloat(q3)
outputBuffer.encodeFloat(q4)
outputBuffer.encodeFloat(xacc)
outputBuffer.encodeFloat(yacc)
outputBuffer.encodeFloat(zacc)
outputBuffer.encodeFloat(xgyro)
outputBuffer.encodeFloat(ygyro)
outputBuffer.encodeFloat(zgyro)
return outputBuffer.array().truncateZeros()
}
public companion object : MavMessage.MavCompanion<AvssDroneImu> {
private const val SIZE_V1: Int = 44
private const val SIZE_V2: Int = 44
public override val id: UInt = 60_052u
public override val crcExtra: Byte = 101
public override fun deserialize(bytes: ByteArray): AvssDroneImu {
val inputBuffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val timeBootMs = inputBuffer.decodeUInt32()
val q1 = inputBuffer.decodeFloat()
val q2 = inputBuffer.decodeFloat()
val q3 = inputBuffer.decodeFloat()
val q4 = inputBuffer.decodeFloat()
val xacc = inputBuffer.decodeFloat()
val yacc = inputBuffer.decodeFloat()
val zacc = inputBuffer.decodeFloat()
val xgyro = inputBuffer.decodeFloat()
val ygyro = inputBuffer.decodeFloat()
val zgyro = inputBuffer.decodeFloat()
return AvssDroneImu(
timeBootMs = timeBootMs,
q1 = q1,
q2 = q2,
q3 = q3,
q4 = q4,
xacc = xacc,
yacc = yacc,
zacc = zacc,
xgyro = xgyro,
ygyro = ygyro,
zgyro = zgyro,
)
}
public operator fun invoke(builderAction: Builder.() -> Unit): AvssDroneImu =
Builder().apply(builderAction).build()
}
public class Builder {
public var timeBootMs: UInt = 0u
public var q1: Float = 0F
public var q2: Float = 0F
public var q3: Float = 0F
public var q4: Float = 0F
public var xacc: Float = 0F
public var yacc: Float = 0F
public var zacc: Float = 0F
public var xgyro: Float = 0F
public var ygyro: Float = 0F
public var zgyro: Float = 0F
public fun build(): AvssDroneImu = AvssDroneImu(
timeBootMs = timeBootMs,
q1 = q1,
q2 = q2,
q3 = q3,
q4 = q4,
xacc = xacc,
yacc = yacc,
zacc = zacc,
xgyro = xgyro,
ygyro = ygyro,
zgyro = zgyro,
)
}
}
| 1
| null |
4
| 9
|
8f480256eeaac5755a2ce5582c338a4b30c7e178
| 5,331
|
mavlink-kotlin
|
Apache License 2.0
|
module_home/src/main/java/com/quyunshuo/wanandroid/home/bean/ArticleBean.kt
|
Quyunshuo
| 389,148,840
| false
| null |
package com.quyunshuo.wanandroid.home.bean
/**
* 文章数据类
*
* @property apkLink String?
* @property audit Int?
* @property author String? 作者
* @property canEdit Boolean?
* @property chapterId Int?
* @property chapterName String?
* @property collect Boolean?
* @property courseId Int?
* @property desc String?
* @property descMd String?
* @property envelopePic String?
* @property fresh Boolean?
* @property host String?
* @property id Int?
* @property link String 文章链接
* @property niceDate String?
* @property niceShareDate String?
* @property origin String?
* @property prefix String?
* @property projectLink String?
* @property publishTime Long?
* @property realSuperChapterId Int?
* @property selfVisible Int?
* @property shareDate Long?
* @property shareUser String? 分享人
* @property superChapterId Int?
* @property superChapterName String? 一级分类的名称
* @property tags List<Tag>?
* @property title String 文章标题
* @property type Int?
* @property userId Int?
* @property visible Int?
* @property zan Int?
* @property top Boolean? 是否置顶 自定义属性
*
* 示例:
* ```
* {
* "apkLink": "",
* "audit": 1,
* "author": "扔物线",
* "canEdit": false,
* "chapterId": 249,
* "chapterName": "干货资源",
* "collect": false,
* "courseId": 13,
* "desc": "",
* "descMd": "",
* "envelopePic": "",
* "fresh": true,
* "host": "",
* "id": 12554,
* "link": "https://mp.weixin.qq.com/s/I8cI2SOBazsM8sdDWCchLw",
* "niceDate": "13小时前",
* "niceShareDate": "2020-03-23 16:36",
* "origin": "",
* "prefix": "",
* "projectLink": "",
* "publishTime": 1628563792000,
* "realSuperChapterId": 248,
* "selfVisible": 0,
* "shareDate": 1584952597000,
* "shareUser": "",
* "superChapterId": 249,
* "superChapterName": "干货资源",
* "tags": [],
* "title": "LiveData:还没普及就让我去世?我去你的 Kotlin 协程",
* "type": 1,
* "userId": -1,
* "visible": 1,
* "zan": 0
* }
* ```
*
* @author <NAME>
* @since 2021/8/11 12:41 上午
*/
data class ArticleBean(
val apkLink: String?,
val audit: Int?,
val author: String?,
val canEdit: Boolean?,
val chapterId: Int?,
val chapterName: String?,
val collect: Boolean?,
val courseId: Int?,
val desc: String?,
val descMd: String?,
val envelopePic: String?,
val fresh: Boolean?,
val host: String?,
val id: Int?,
val link: String,
val niceDate: String?,
val niceShareDate: String?,
val origin: String?,
val prefix: String?,
val projectLink: String?,
val publishTime: Long?,
val realSuperChapterId: Int?,
val selfVisible: Int?,
val shareDate: Long?,
val shareUser: String?,
val superChapterId: Int?,
val superChapterName: String?,
val tags: List<Tag>?,
val title: String,
val type: Int?,
val userId: Int?,
val visible: Int?,
val zan: Int?,
var top: Boolean?
) {
data class Tag(
val name: String,
val url: String
)
}
| 1
|
Kotlin
|
7
| 34
|
b00274fb9ad349dc8b9d2f32ed1af5e2864246c6
| 3,034
|
WanAndroidMVVM
|
Apache License 2.0
|
app/src/main/java/org/fossasia/openevent/general/auth/ProfileViewModel.kt
|
G-LOKi
| 178,464,508
| true
|
{"Kotlin": 379840, "Java": 3836, "Shell": 3765}
|
package org.fossasia.openevent.general.auth
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Resource
import timber.log.Timber
class ProfileViewModel(private val authService: AuthService, private val resource: Resource) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableProgress = MutableLiveData<Boolean>()
val progress: LiveData<Boolean> = mutableProgress
private val mutableUser = MutableLiveData<User>()
val user: LiveData<User> = mutableUser
private val mutableError = SingleLiveEvent<String>()
val error: LiveData<String> = mutableError
val avatarPicked = MutableLiveData<String>()
fun isLoggedIn() = authService.isLoggedIn()
fun logout() {
compositeDisposable.add(authService.logout()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
Timber.d("Logged out!")
}) {
Timber.e(it, "Failure Logging out!")
})
}
fun fetchProfile() {
compositeDisposable.add(authService.getProfile()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({ user ->
Timber.d("Response Success")
this.mutableUser.value = user
}) {
Timber.e(it, "Failure")
mutableError.value = resource.getString(R.string.failure)
})
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| 0
|
Kotlin
|
0
| 1
|
7e6d70dbfcbeb014ac9dc02ccfd66cc575697c87
| 2,104
|
open-event-android
|
Apache License 2.0
|
core/src/main/kotlin/in/specmatic/core/pattern/BooleanPattern.kt
|
znsio
| 247,710,440
| false
| null |
package `in`.specmatic.core.pattern
import `in`.specmatic.core.Resolver
import `in`.specmatic.core.Result
import `in`.specmatic.core.mismatchResult
import `in`.specmatic.core.value.BooleanValue
import `in`.specmatic.core.value.JSONArrayValue
import `in`.specmatic.core.value.Value
import java.util.*
data class BooleanPattern(override val example: String? = null) : Pattern, ScalarType, HasDefaultExample {
override fun matches(sampleData: Value?, resolver: Resolver): Result =
when(sampleData) {
is BooleanValue -> Result.Success()
else -> mismatchResult("boolean", sampleData, resolver.mismatchMessages)
}
override fun generate(resolver: Resolver): Value =
resolver.resolveExample(example, this) ?: randomBoolean()
override fun newBasedOn(row: Row, resolver: Resolver): Sequence<Pattern> = sequenceOf(this)
override fun newBasedOn(resolver: Resolver): Sequence<Pattern> = sequenceOf(this)
override fun negativeBasedOn(row: Row, resolver: Resolver): Sequence<Pattern> {
return sequenceOf(NullPattern)
}
override fun parse(value: String, resolver: Resolver): Value = when (value.lowercase()) {
!in listOf("true", "false") -> throw ContractException(mismatchResult(BooleanPattern(), value, resolver.mismatchMessages).toFailureReport())
else -> BooleanValue(value.toBoolean())
}
override fun encompasses(otherPattern: Pattern, thisResolver: Resolver, otherResolver: Resolver, typeStack: TypeStack): Result {
return encompasses(this, otherPattern, thisResolver, otherResolver, typeStack)
}
override fun listOf(valueList: List<Value>, resolver: Resolver): Value {
return JSONArrayValue(valueList)
}
override val typeAlias: String?
get() = null
override val typeName: String = "boolean"
override val pattern: Any = "(boolean)"
override fun toString(): String = pattern.toString()
}
fun randomBoolean() = when (Random().nextInt(2)) {
0 -> BooleanValue(false)
else -> BooleanValue(true)
}
| 66
| null |
8
| 92
|
b3eb9b6e0f7d42bde35d95b83ea187cd1d6aa3bc
| 2,059
|
specmatic
|
MIT License
|
features/accounts/src/main/java/com/yuriikonovalov/accounts/framework/ui/AccountsFragment.kt
|
yuriikonovalov
| 563,974,428
| false
|
{"Kotlin": 872022}
|
package com.yuriikonovalov.accounts.framework.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.yuriikonovalov.accounts.databinding.FragmentAccountsBinding
import com.yuriikonovalov.accounts.presentation.AccountsEvent
import com.yuriikonovalov.accounts.presentation.AccountsIntent
import com.yuriikonovalov.common.framework.common.extentions.collectEvent
import com.yuriikonovalov.common.framework.common.extentions.launchSafely
import com.yuriikonovalov.common.framework.ui.addeditaccount.AddEditAccountFragment
import com.yuriikonovalov.common.framework.ui.addedittransaction.AddEditTransferFragment
import com.yuriikonovalov.common.framework.utils.doOnApplyWindowInsetsCompat
import com.yuriikonovalov.common.framework.utils.systemBars
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
@AndroidEntryPoint
class AccountsFragment : Fragment() {
private lateinit var binding: FragmentAccountsBinding
private val viewModel: AccountsViewModel by viewModels()
private val accountAdapter: AccountAdapter by lazy { AccountAdapter(::showMenu) }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentAccountsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.applyWindowInsets()
binding.bindAccountList()
binding.bindCreateAccountButton()
binding.bindTransferButton()
binding.bindPlaceholder()
collectEvents()
}
private fun collectEvents() {
collectEvent(viewModel.eventFlow, viewModel.eventConsumer) { event ->
when (event) {
is AccountsEvent.AddTransfer -> onAddTransferEvent()
is AccountsEvent.CreateAccount -> onCreateAccountEvent()
is AccountsEvent.EditAccount -> onEditAccountEvent(event.id)
}
}
}
private fun onEditAccountEvent(id: Long) {
findNavController().navigate(AccountsFragmentDirections.toAddEditAccountFragment(id))
}
private fun onCreateAccountEvent() {
findNavController().navigate(
AccountsFragmentDirections.toAddEditAccountFragment(AddEditAccountFragment.ARGUMENT_NEW_ACCOUNT)
)
}
private fun onAddTransferEvent() {
findNavController().navigate(
AccountsFragmentDirections.toAddEditTransferFragment(AddEditTransferFragment.ARGUMENT_NEW_TRANSFER)
)
}
private fun FragmentAccountsBinding.bindPlaceholder() {
placeholderContainer.updatePadding(top = appBar.height)
createAccountPlaceholderButton.setOnClickListener {
viewModel.handleIntent(AccountsIntent.CreateAccount)
}
launchSafely {
viewModel.stateFlow
.map { it.placeholderVisible }
.distinctUntilChanged()
.collect { visible ->
placeholderContainer.isVisible = visible
}
}
}
private fun FragmentAccountsBinding.bindCreateAccountButton() {
createAccountButton.setOnClickListener {
viewModel.handleIntent(AccountsIntent.CreateAccount)
}
launchSafely {
viewModel.stateFlow
.map { it.createButtonVisible }
.distinctUntilChanged()
.collect { visible ->
createAccountButton.isVisible = visible
}
}
}
private fun FragmentAccountsBinding.bindTransferButton() {
transferButton.setOnClickListener {
viewModel.handleIntent(AccountsIntent.AddTransfer)
}
launchSafely {
viewModel.stateFlow
.map { it.transferButtonVisible }
.distinctUntilChanged()
.collect { visible ->
transferButton.isVisible = visible
}
}
}
private fun FragmentAccountsBinding.bindAccountList() {
accountList.layoutManager = LinearLayoutManager(requireContext())
accountList.adapter = accountAdapter
launchSafely {
viewModel.stateFlow
.map { it.accounts }
.distinctUntilChanged()
.collect(accountAdapter::submitList)
}
}
private fun showMenu(accountId: Long, name: String) {
val menu = MenuBottomSheetDialog(accountId)
menu.setMenuListener(object : MenuBottomSheetDialog.Listener {
override fun onEditMenuItemClick(id: Long) {
viewModel.handleIntent(AccountsIntent.EditAccount(id))
}
override fun onDeleteMenuItemClick(id: Long) {
showConfirmationDialog(id, name)
}
})
menu.show(childFragmentManager, MenuBottomSheetDialog.TAG)
}
private fun showConfirmationDialog(id: Long, name: String) {
MaterialAlertDialogBuilder(requireContext())
.setIcon(ConfirmationDialog.icon)
.setTitle(name)
.setMessage(getString(ConfirmationDialog.message))
.setPositiveButton(getString(ConfirmationDialog.positiveButtonText)) { dialog, _ ->
dialog?.dismiss()
viewModel.handleIntent(AccountsIntent.DeleteAccount(id))
}
.setNegativeButton(getString(ConfirmationDialog.negativeButtonText)) { dialog, _ ->
dialog?.dismiss()
}
.show()
}
private fun FragmentAccountsBinding.applyWindowInsets() {
appBar.doOnApplyWindowInsetsCompat { appBar, windowInsetsCompat, initialPadding ->
appBar.updatePadding(top = initialPadding.top + windowInsetsCompat.systemBars.top)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8063508f836512fc8f8a0ba18f794bb895ee2449
| 6,357
|
budgethub
|
MIT License
|
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/js/npm/resolved/KotlinRootNpmResolution.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
|
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.targets.js.npm.resolved
import org.gradle.api.logging.Logger
import org.gradle.internal.service.ServiceRegistry
import org.jetbrains.kotlin.gradle.targets.js.npm.KotlinNpmResolutionManager
import org.jetbrains.kotlin.gradle.targets.js.npm.NpmEnvironment
import org.jetbrains.kotlin.gradle.targets.js.npm.YarnEnvironment
import org.jetbrains.kotlin.gradle.targets.js.yarn.toVersionString
import java.io.Serializable
class KotlinRootNpmResolution(
val projects: Map<String, KotlinProjectNpmResolution>,
val rootProjectName: String,
val rootProjectVersion: String
) : Serializable {
operator fun get(project: String) = projects[project] ?: KotlinProjectNpmResolution.empty()
/**
* Don't use directly, use [KotlinNpmResolutionManager.installIfNeeded] instead.
*/
internal fun prepareInstallation(
logger: Logger,
npmEnvironment: NpmEnvironment,
yarnEnvironment: YarnEnvironment,
npmResolutionManager: KotlinNpmResolutionManager
): Installation {
synchronized(projects) {
npmResolutionManager.parameters.gradleNodeModulesProvider.get().close()
val projectResolutions: List<PreparedKotlinCompilationNpmResolution> = projects.values.flatMap { it.npmProjects }.map { it.close(npmResolutionManager, logger) }
npmEnvironment.packageManager.prepareRootProject(
npmEnvironment,
rootProjectName,
rootProjectVersion,
logger,
projectResolutions,
yarnEnvironment.yarnResolutions
.associate { it.path to it.toVersionString() },
)
return Installation(
projectResolutions
)
}
}
}
class Installation(val compilationResolutions: Collection<PreparedKotlinCompilationNpmResolution>) {
internal fun install(
args: List<String>,
services: ServiceRegistry,
logger: Logger,
npmEnvironment: NpmEnvironment,
yarnEnvironment: YarnEnvironment,
) {
synchronized(compilationResolutions) {
npmEnvironment.packageManager.resolveRootProject(
services,
logger,
npmEnvironment,
yarnEnvironment,
compilationResolutions,
args
)
}
}
}
| 166
|
Kotlin
|
5771
| 46,772
|
bef0946ab7e5acd5b24b971eca532c43c8eba750
| 2,627
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/mrspd/letschat/fragments/one_to_one_chat/ChatAdapter.kt
|
satyamurti
| 275,247,716
| false
| null |
package com.mrspd.letschat.fragments.one_to_one_chat
import android.content.Context
import android.media.MediaPlayer
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.mrspd.letschat.R
import com.mrspd.letschat.databinding.*
import com.mrspd.letschat.models.*
import com.mrspd.letschat.util.AuthUtil
import com.mrspd.letschat.util.eventbus_events.UpdateRecycleItemEvent
import org.greenrobot.eventbus.EventBus
import java.io.IOException
import kotlin.properties.Delegates
var positionDelegate: Int by Delegates.observable(-1) { prop, old, new ->
println("<positionDelegate>.:${old},,,,$new")
if (old != new && old != -1) //if old =-1 or old=new don't update item
EventBus.getDefault().post(UpdateRecycleItemEvent(old))
}
class ChatAdapter(private val context: Context?, private val clickListener: MessageClickListener) :
ListAdapter<Message, RecyclerView.ViewHolder>(DiffCallbackMessages()) {
companion object {
private const val TYPE_SENT_MESSAGE = 0
private const val TYPE_RECEIVED_MESSAGE = 1
private const val TYPE_SENT_IMAGE_MESSAGE = 2
private const val TYPE_RECEIVED_IMAGE_MESSAGE = 3
private const val TYPE_SENT_FILE_MESSAGE = 4
private const val TYPE_RECEIVED_FILE_MESSAGE = 5
private const val TYPE_SENT_RECORD = 6
private const val TYPE_RECEIVED_RECORD = 7
private const val TYPE_SENT_RECORD_PLACEHOLDER = 8
lateinit var messageList: MutableList<Message>
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
TYPE_SENT_MESSAGE -> {
SentMessageViewHolder.from(parent)
}
TYPE_RECEIVED_MESSAGE -> {
ReceivedMessageViewHolder.from(parent)
}
TYPE_SENT_IMAGE_MESSAGE -> {
SentImageMessageViewHolder.from(parent)
}
TYPE_RECEIVED_IMAGE_MESSAGE -> {
ReceivedImageMessageViewHolder.from(parent)
}
TYPE_SENT_FILE_MESSAGE -> {
SentFileMessageViewHolder.from(parent)
}
TYPE_RECEIVED_FILE_MESSAGE -> {
ReceivedFileMessageViewHolder.from(parent)
}
TYPE_SENT_RECORD -> {
SentRecordViewHolder.from(parent)
}
TYPE_RECEIVED_RECORD -> {
ReceivedRecordViewHolder.from(parent)
}
TYPE_SENT_RECORD_PLACEHOLDER -> {
SentRecordPlaceHolderViewHolder.from(parent)
}
else -> throw IllegalArgumentException("Invalid view type")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is SentMessageViewHolder -> {
holder.bind(clickListener, getItem(position) as TextMessage)
}
is ReceivedMessageViewHolder -> {
holder.bind(clickListener, getItem(position) as TextMessage)
}
is SentImageMessageViewHolder -> {
holder.bind(clickListener, getItem(position) as ImageMessage)
}
is ReceivedImageMessageViewHolder -> {
holder.bind(clickListener, getItem(position) as ImageMessage)
}
is ReceivedFileMessageViewHolder -> {
holder.bind(clickListener, getItem(position) as FileMessage)
}
is SentFileMessageViewHolder -> {
holder.bind(clickListener, getItem(position) as FileMessage)
}
is SentRecordViewHolder -> {
holder.bind(clickListener, getItem(position) as RecordMessage)
}
is ReceivedRecordViewHolder -> {
holder.bind(clickListener, getItem(position) as RecordMessage)
}
is SentRecordPlaceHolderViewHolder -> {
holder.bind(clickListener, getItem(position) as RecordMessage)
}
else -> throw IllegalArgumentException("Invalid ViewHolder type")
}
}
override fun getItemViewType(position: Int): Int {
val currentMessage = getItem(position)
if (currentMessage.from == AuthUtil.getAuthId() && currentMessage.type == 0.0) {
return TYPE_SENT_MESSAGE
} else if (currentMessage.from != AuthUtil.getAuthId() && currentMessage.type == 0.0) {
return TYPE_RECEIVED_MESSAGE
} else if (currentMessage.from == AuthUtil.getAuthId() && currentMessage.type == 1.0) {
return TYPE_SENT_IMAGE_MESSAGE
} else if (currentMessage.from != AuthUtil.getAuthId() && currentMessage.type == 1.0) {
return TYPE_RECEIVED_IMAGE_MESSAGE
} else if (currentMessage.from == AuthUtil.getAuthId() && currentMessage.type == 2.0) {
return TYPE_SENT_FILE_MESSAGE
} else if (currentMessage.from != AuthUtil.getAuthId() && currentMessage.type == 2.0) {
return TYPE_RECEIVED_FILE_MESSAGE
} else if (currentMessage.from == AuthUtil.getAuthId() && currentMessage.type == 3.0) {
return TYPE_SENT_RECORD
} else if (currentMessage.from != AuthUtil.getAuthId() && currentMessage.type == 3.0) {
return TYPE_RECEIVED_RECORD
} else if (currentMessage.type == 8.0) {
return TYPE_SENT_RECORD_PLACEHOLDER
} else {
throw IllegalArgumentException("Invalid ItemViewType")
}
}
//----------------SentMessageViewHolder------------
class SentMessageViewHolder private constructor(val binding: SentMessageItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: TextMessage) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): SentMessageViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = SentMessageItemBinding.inflate(layoutInflater, parent, false)
return SentMessageViewHolder(binding)
}
}
}
//----------------ReceivedMessageViewHolder------------
class ReceivedMessageViewHolder private constructor(val binding: IncomingMessageItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: TextMessage) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): ReceivedMessageViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = IncomingMessageItemBinding.inflate(layoutInflater, parent, false)
return ReceivedMessageViewHolder(binding)
}
}
}
//----------------SentImageMessageViewHolder------------
class SentImageMessageViewHolder private constructor(val binding: SentChatImageItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: ImageMessage) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): SentImageMessageViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = SentChatImageItemBinding.inflate(layoutInflater, parent, false)
return SentImageMessageViewHolder(binding)
}
}
}
//----------------ReceivedImageMessageViewHolder------------
class ReceivedImageMessageViewHolder private constructor(val binding: IncomingChatImageItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: ImageMessage) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()//
}
companion object {
fun from(parent: ViewGroup): ReceivedImageMessageViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = IncomingChatImageItemBinding.inflate(layoutInflater, parent, false)
return ReceivedImageMessageViewHolder(binding)
}
}
}
//----------------SentFileMessageViewHolder------------
class SentFileMessageViewHolder private constructor(val binding: SentChatFileItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: FileMessage) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): SentFileMessageViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = SentChatFileItemBinding.inflate(layoutInflater, parent, false)
return SentFileMessageViewHolder(binding)
}
}
}
//----------------ReceivedFileMessageViewHolder------------
class ReceivedFileMessageViewHolder private constructor(val binding: IncomingChatFileItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: FileMessage) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()//
}
companion object {
fun from(parent: ViewGroup): ReceivedFileMessageViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = IncomingChatFileItemBinding.inflate(layoutInflater, parent, false)
return ReceivedFileMessageViewHolder(binding)
}
}
}
//----------------SentRecordViewHolder------------
class SentRecordViewHolder private constructor(val binding: SentAudioItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: RecordMessage) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()
//reset views (to reset other records other than the one playing)
val recordMessage = messageList[adapterPosition] as RecordMessage
recordMessage.isPlaying = false
binding.playPauseImage.setImageResource(R.drawable.ic_play_arrow_black_24dp)
binding.progressbar.max = 0
binding.durationTextView.text = ""
binding.playPauseImage.setOnClickListener {
startPlaying(
item.uri!!,
adapterPosition,
recordMessage,
binding.playPauseImage,
binding.progressbar
)
}
}
companion object {
fun from(parent: ViewGroup): SentRecordViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = SentAudioItemBinding.inflate(layoutInflater, parent, false)
return SentRecordViewHolder(binding)
}
}
}
//----------------SentRecordPlaceHolderViewHolder------------
class SentRecordPlaceHolderViewHolder private constructor(val binding: SentAudioPlaceholderItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: Message) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): SentRecordPlaceHolderViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = SentAudioPlaceholderItemBinding.inflate(layoutInflater, parent, false)
return SentRecordPlaceHolderViewHolder(binding)
}
}
}
//----------------ReceivedRecordViewHolder------------
class ReceivedRecordViewHolder private constructor(val binding: ReceivedAudioItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(clickListener: MessageClickListener, item: RecordMessage) {
binding.message = item
binding.clickListener = clickListener
binding.position = adapterPosition
binding.executePendingBindings()
//reset views (to reset other records other than the one playing)
val recordMessage = messageList[adapterPosition] as RecordMessage
recordMessage.isPlaying = false
binding.playPauseImage.setImageResource(R.drawable.ic_play_arrow_black_24dp)
binding.progressbar.max = 0
binding.durationTextView.text = ""
binding.playPauseImage.setOnClickListener {
startPlaying(
item.uri!!,
adapterPosition,
recordMessage,
binding.playPauseImage,
binding.progressbar
)
}
}
companion object {
fun from(parent: ViewGroup): ReceivedRecordViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ReceivedAudioItemBinding.inflate(layoutInflater, parent, false)
return ReceivedRecordViewHolder(binding)
}
}
}
}
private var player = MediaPlayer()
private lateinit var countDownTimer: CountDownTimer
private fun startPlaying(
audioUri: String,
adapterPosition: Int,
recordMessage: RecordMessage,
playPauseImage: ImageView,
progressbar: ProgressBar
) {
//update last clicked item to be reset
positionDelegate = adapterPosition
//show temporary loading while audio is downloaded
playPauseImage.setImageResource(R.drawable.loading_animation)
if (recordMessage.isPlaying == null || recordMessage.isPlaying == false) {
stopPlaying()
recordMessage.isPlaying = false
player.apply {
try {
setDataSource(audioUri)
prepareAsync()
} catch (e: IOException) {
println("ChatFragment.startPlaying:prepare failed")
}
setOnPreparedListener {
//media downloaded and will play
recordMessage.isPlaying = true
//play the record
start()
//change image to stop and show progress of record
progressbar.max = player.duration
playPauseImage.setImageResource(R.drawable.ic_stop_black_24dp)
//count down timer to show record progess but on when record is playing
countDownTimer = object : CountDownTimer(player.duration.toLong(), 50) {
override fun onFinish() {
progressbar.progress = (player.duration)
playPauseImage.setImageResource(R.drawable.ic_play_arrow_black_24dp)
}
override fun onTick(millisUntilFinished: Long) {
progressbar.progress = (player.duration.minus(millisUntilFinished)).toInt()
}
}.start()
}
}
} else {
//stop the record
playPauseImage.setImageResource(R.drawable.ic_play_arrow_black_24dp)
stopPlaying()
recordMessage.isPlaying = false
progressbar.progress = 0
}
}
private fun stopPlaying() {
if (::countDownTimer.isInitialized)
countDownTimer.cancel()
player.reset()
}
interface MessageClickListener {
fun onMessageClick(position: Int, message: Message)
}
class DiffCallbackMessages : DiffUtil.ItemCallback<Message>() {
override fun areItemsTheSame(oldItem: Message, newItem: Message): Boolean {
return oldItem.created_at == newItem.created_at
}
override fun areContentsTheSame(oldItem: Message, newItem: Message): Boolean {
return oldItem.equals(newItem)
}
}
| 1
| null |
30
| 80
|
62f0f0ae22b38d8c48c5c27800005039f2030987
| 17,325
|
LetsChat
|
MIT License
|
common/src/commonMain/kotlin/io/config4k/NameCase.kt
|
Matt1Krause
| 323,059,657
| false
| null |
package io.config4k
sealed class NameCase {
abstract fun computeNameFor(name: PropertyName): String
object SnakeCase : NameCase() {
override fun computeNameFor(name: PropertyName): String = name.joinToString(separator = "_")
}
object UpperSnakeCase : NameCase() {
override fun computeNameFor(name: PropertyName): String =
name.joinToString(separator = "_", transform = String::toUpperCase)
}
object PascalCase: NameCase() {
override fun computeNameFor(name: PropertyName): String = name.joinToString(separator = "", transform = String::capitalize)
}
object CamelCase: NameCase() {
override fun computeNameFor(name: PropertyName): String = PascalCase.computeNameFor(name).decapitalize()
}
object KebabCase: NameCase() {
override fun computeNameFor(name: PropertyName): String = name.joinToString(separator = "-")
}
/**
* [abc, def] -> abc.def
*/
object InterDotted: NameCase() {
override fun computeNameFor(name: PropertyName): String = name.joinToString(separator = ".")
}
object Raw: NameCase() {
override fun computeNameFor(name: PropertyName): String = name.contentToString()
}
}
| 0
|
Kotlin
|
0
| 0
|
da4bbb1a0248fb134e6be3942ff0527cb99bb016
| 1,233
|
Config4k
|
Apache License 2.0
|
app/src/main/java/com/johnlennonlobo/appilunne/ui/activity/login/AuthActivity.kt
|
john-lobo
| 382,523,866
| false
| null |
package com.johnlennonlobo.appilunne.ui.activity.login
import android.content.Intent
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.johnlennonlobo.appilunne.databinding.AuthActivityBinding
import com.johnlennonlobo.appilunne.model.Usuario
import com.johnlennonlobo.appilunne.ui.activity.AbstractActivity
import com.johnlennonlobo.appilunne.ui.activity.mainHome.MainHomeActivity
class AuthActivity : AbstractActivity() {
private lateinit var viewModel: AuthViewModel
private lateinit var usuario: Usuario
private lateinit var binding: AuthActivityBinding
//TODO implements AbstractActivity
override fun getLayout(): ViewBinding {
binding = AuthActivityBinding.inflate(layoutInflater)
return binding
}
override fun getObject() {
// authentication = ConfigFirebase.getFirebaseAuthentication()
// authentication.signOut() // deslogar usuario
// verifyUsuLog()
supportActionBar?.hide()
actionViews()
viewModel=ViewModelProvider(this, AuthViewModelFactory()).get(
AuthViewModel::class.java
)
with(viewModel){
sucessMessage.observe(this@AuthActivity,{
AlertDialog.Builder(this@AuthActivity)
.setTitle("Sucesso")
.setMessage(it)
.setPositiveButton("OK") { _, _ ->
openMainHome()
}.show()
})
errorMessage.observe(this@AuthActivity, {
showMessage(it)
})
}
}
private fun actionViews() {
with(binding.btnSignOrRegister) {
setOnClickListener {
hideKeyBoard()
hideLogo(false)
val nome = binding.edtNomeLoginID.text.toString()
val email=binding.edtEmailLoginID.text.toString()
val senha=binding.edtSenhalLoginID.text.toString()
val typeAccess= binding.selectTypeAccessID.isChecked
usuario=Usuario()
usuario.nome=nome
usuario.email=email
usuario.senha=senha
with(viewModel) {
getAuthentication(typeAccess, usuario)
hideProgressBar.observe(this@AuthActivity, {
if (it) {
binding.progressBarLoginID.visibility=View.INVISIBLE
}else{
binding.progressBarLoginID.visibility=View.VISIBLE
}
})
}
}
}
with(binding.selectTypeAccessID) {
setOnCheckedChangeListener { _, isChecked ->
hideKeyBoard()
when {
isChecked -> {
binding.btnSignOrRegister.text="CADASTRAR"
binding.edtNomeLoginID.visibility = View.VISIBLE
}
else -> {
binding.btnSignOrRegister.text="ACESSAR"
binding.edtNomeLoginID.visibility = View.GONE
}
}
}
}
with(binding.edtNomeLoginID) {
setOnClickListener {
hideLogo(true)
}
onFocusChangeListener=View.OnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
hideLogo(true)
}
}
}
with(binding.edtEmailLoginID) {
setOnClickListener {
hideLogo(true)
}
onFocusChangeListener=View.OnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
hideLogo(true)
}
}
}
with(binding.edtSenhalLoginID) {
setOnClickListener {
hideLogo(true)
}
onFocusChangeListener=View.OnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
hideLogo(true)
}
}
}
}
//TODO My Functions created in this
private fun openMainHome() {
val intent=Intent(
this@AuthActivity.applicationContext, MainHomeActivity
::class.java
)
this@AuthActivity.startActivity(intent)
finish()
}
// fun verifyUsuLog(){
// val user: FirebaseUser? = authentication.currentUser
// if(user != null){
// openMainHome()
// }
// }
private fun hideLogo(show: Boolean=true) {
if (show) {
binding.imageLogoID.visibility=View.GONE
} else {
binding.imageLogoID.visibility=View.VISIBLE
}
}
// private fun configLayoutParams(modify: Boolean): LinearLayout.LayoutParams {
// var marginTop: Int
// val params: LinearLayout.LayoutParams=LinearLayout.LayoutParams(
// ActionBar.LayoutParams.MATCH_PARENT,
// ActionBar.LayoutParams.WRAP_CONTENT
// )
// when {
// modify -> {
// showLogo()
// marginTop=25
// }
// else -> {
// marginTop=100
// showLogo(false)
// }
// }
//
// params.setMargins(
// MARGIN_RIGHT, marginTop,
// MARGIN_LEFT, MARGIN_BOTTOM
// )
// return params
// }
}
| 0
|
Kotlin
|
0
| 2
|
62b08c90c425eb53f033c60a47bbe697781f35d9
| 5,604
|
AppIlunne
|
MIT License
|
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/targets/native/KotlinNativeCompilation.kt
|
ahsc786
| 173,781,731
| true
|
{"Kotlin": 33489577, "Java": 7553371, "JavaScript": 152998, "HTML": 73561, "Lex": 23082, "IDL": 10847, "ANTLR": 9803, "Shell": 7727, "Groovy": 6893, "Batchfile": 5362, "CSS": 4679, "Scala": 80}
|
/*
* Copyright 2010-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/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch") // Old package for compatibility
package org.jetbrains.kotlin.gradle.plugin.mpp
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Project
import org.gradle.api.file.SourceDirectorySet
import org.gradle.util.ConfigureUtil
import org.jetbrains.kotlin.gradle.dsl.KotlinCommonOptions
import org.jetbrains.kotlin.gradle.dsl.KotlinNativeBinaryContainer
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilationWithResources
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.tasks.KotlinNativeCompile
import org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink
import org.jetbrains.kotlin.gradle.utils.lowerCamelCaseName
import java.io.File
class KotlinNativeCompilation(
override val target: KotlinNativeTarget,
name: String
) : AbstractKotlinCompilation<KotlinCommonOptions>(target, name), KotlinCompilationWithResources<KotlinCommonOptions> {
override val kotlinOptions: KotlinCommonOptions
get() = compileKotlinTask.kotlinOptions
override val compileKotlinTask: KotlinNativeCompile
get() = super.compileKotlinTask as KotlinNativeCompile
private val project: Project
get() = target.project
// A collection containing all source sets used by this compilation
// (taking into account dependencies between source sets). Used by both compilation
// and linking tasks. Unlike kotlinSourceSets, includes dependency source sets.
// TODO: Move into the compilation task when the linking task does klib linking instead of compilation.
internal val allSources: MutableSet<SourceDirectorySet> = mutableSetOf()
// TODO: Move into the compilation task when the linking task does klib linking instead of compilation.
internal val commonSources: MutableSet<SourceDirectorySet> = mutableSetOf()
var isTestCompilation = false
var friendCompilationName: String? = null
internal val friendCompilation: KotlinNativeCompilation?
get() = friendCompilationName?.let {
target.compilations.getByName(it)
}
// Used only to support the old APIs. TODO: Remove when the old APIs are removed.
internal val binaries = mutableMapOf<Pair<NativeOutputKind, NativeBuildType>, NativeBinary>()
// Native-specific DSL.
var extraOpts = mutableListOf<String>()
fun extraOpts(vararg values: Any) = extraOpts(values.toList())
fun extraOpts(values: List<Any>) {
extraOpts.addAll(values.map { it.toString() })
}
var buildTypes = mutableListOf<NativeBuildType>()
var outputKinds = mutableListOf<NativeOutputKind>()
fun outputKind(kind: NativeOutputKind) = outputKinds.add(kind)
fun outputKinds(vararg kinds: NativeOutputKind) {
outputKinds = kinds.toMutableList()
}
fun outputKinds(vararg kinds: String) {
outputKinds = kinds.map { NativeOutputKind.valueOf(it.toUpperCase()) }.toMutableList()
}
fun outputKinds(kinds: List<Any>) {
outputKinds = kinds.map {
when (it) {
is NativeOutputKind -> it
is String -> NativeOutputKind.valueOf(it.toUpperCase())
else -> error("Cannot use $it as an output kind")
}
}.toMutableList()
}
var entryPoint: String? = null
fun entryPoint(value: String) {
entryPoint = value
}
// Interop DSL.
val cinterops = project.container(DefaultCInteropSettings::class.java) { cinteropName ->
DefaultCInteropSettings(project, cinteropName, this)
}
var linkerOpts = mutableListOf<String>()
fun cinterops(action: NamedDomainObjectContainer<DefaultCInteropSettings>.() -> Unit) = cinterops.action()
fun cinterops(action: Closure<Unit>) = cinterops(ConfigureUtil.configureUsing(action))
fun cinterops(action: Action<NamedDomainObjectContainer<DefaultCInteropSettings>>) = action.execute(cinterops)
fun linkerOpts(vararg values: String) = linkerOpts(values.toList())
fun linkerOpts(values: List<String>) {
linkerOpts.addAll(values)
}
// Task accessors.
fun findLinkTask(kind: NativeOutputKind, buildType: NativeBuildType): KotlinNativeLink? = binaries[kind to buildType]?.linkTask
fun getLinkTask(kind: NativeOutputKind, buildType: NativeBuildType): KotlinNativeLink =
findLinkTask(kind, buildType)
?: throw IllegalArgumentException("Cannot find a link task for the binary kind '$kind' and the build type '$buildType'")
fun findLinkTask(kind: String, buildType: String) =
findLinkTask(NativeOutputKind.valueOf(kind.toUpperCase()), NativeBuildType.valueOf(buildType.toUpperCase()))
fun getLinkTask(kind: String, buildType: String) =
getLinkTask(NativeOutputKind.valueOf(kind.toUpperCase()), NativeBuildType.valueOf(buildType.toUpperCase()))
fun findBinary(kind: NativeOutputKind, buildType: NativeBuildType): File? = findLinkTask(kind, buildType)?.outputFile?.get()
fun getBinary(kind: NativeOutputKind, buildType: NativeBuildType): File = getLinkTask(kind, buildType).outputFile.get()
fun findBinary(kind: String, buildType: String) =
findBinary(NativeOutputKind.valueOf(kind.toUpperCase()), NativeBuildType.valueOf(buildType.toUpperCase()))
fun getBinary(kind: String, buildType: String) =
getBinary(NativeOutputKind.valueOf(kind.toUpperCase()), NativeBuildType.valueOf(buildType.toUpperCase()))
// Naming
override val processResourcesTaskName: String
get() = disambiguateName("processResources")
fun linkTaskName(kind: NativeOutputKind, buildType: NativeBuildType): String =
lowerCamelCaseName(
"link",
KotlinNativeBinaryContainer.generateBinaryName(compilationName, buildType, kind.taskNameClassifier),
target.targetName
)
fun linkTaskName(kind: String, buildType: String) =
linkTaskName(NativeOutputKind.valueOf(kind.toUpperCase()), NativeBuildType.valueOf(buildType.toUpperCase()))
override val compileDependencyConfigurationName: String
get() = lowerCamelCaseName(
target.disambiguationClassifier,
compilationName.takeIf { it != KotlinCompilation.MAIN_COMPILATION_NAME }.orEmpty(),
"compileKlibraries"
)
override val compileAllTaskName: String
get() = lowerCamelCaseName(target.disambiguationClassifier, compilationName, "klibrary")
val binariesTaskName: String
get() = lowerCamelCaseName(target.disambiguationClassifier, compilationName, "binaries")
override fun addSourcesToCompileTask(sourceSet: KotlinSourceSet, addAsCommonSources: Boolean) {
allSources.add(sourceSet.kotlin)
if (addAsCommonSources) {
commonSources.add(sourceSet.kotlin)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
14a6f684dc7121182495bd59c94ef658f04d6ae3
| 7,105
|
kotlin
|
Apache License 2.0
|
examples/cactus-example-supply-chain-business-logic-plugin/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/ListShipmentResponse.kt
|
hyperledger
| 216,610,150
| false
| null |
/**
* Hyperledger Cactus Example - Carbon Accounting App
*
* Demonstrates how a business use case can be satisfied with Cactus when multiple distinct ledgers are involved.
*
* The version of the OpenAPI document: 0.2.0
*
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package org.openapitools.client.models
import com.squareup.moshi.Json
/**
*
*
* @param orgName
*/
data class EnrollAdminV1Request (
@Json(name = "orgName")
val orgName: kotlin.String
)
| 488
|
TypeScript
|
230
| 273
|
ea5522ba02a32764674cbc4a3512ba5d406e7891
| 699
|
cacti
|
Apache License 2.0
|
src/main/kotlin/me/melijn/melijnbot/database/role/TempRoleWrapper.kt
|
ToxicMushroom
| 107,187,088
| false
| null |
package me.melijn.melijnbot.database.role
class TempRoleWrapper(private val tempRoleDao: TempRoleDao) {
fun addTempRole(guildId: Long, userId: Long, roleId: Long, duration: Long, added: Boolean) {
val start = System.currentTimeMillis()
tempRoleDao.set(guildId, userId, roleId, start, start + duration, added)
}
fun removeTempRole(userId: Long, roleId: Long) {
tempRoleDao.remove(userId, roleId)
}
suspend fun getObjects(): List<TempRoleInfo> {
return tempRoleDao.getFinishedObjects(System.currentTimeMillis())
}
}
| 5
|
Kotlin
|
22
| 80
|
01107bbaad0e343d770b1e4124a5a9873b1bb5bd
| 573
|
Melijn
|
MIT License
|
lib_base/src/main/kotlin/com/crow/base/tools/extensions/BaseEventExt.kt
|
CrowForKotlin
| 610,636,509
| false
| null |
@file:Suppress("unused")
package com.crow.base.tools.extensions
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import com.crow.base.ui.view.event.BaseEvent
import com.crow.base.ui.view.event.BaseEvent.Companion.BASE_FLAG_TIME_500
import com.crow.base.ui.view.event.click.BaseIEventInterval
import com.crow.base.ui.view.event.click.BaseIEventIntervalExt
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.materialswitch.MaterialSwitch
/************************
* @Machine: RedmiBook Pro 15 Win11
* @Path: lib_base/src/main/java/com/barry/base/extensions
* @Time: 2022/7/10 2:23
* @Author: CrowForKotlin
* @Description: Event Extension
* @formatter:off
**************************/
// View 点击事件间隔 默认1秒
fun View.doOnClickInterval(isGlobal:Boolean = true, flagTime: Long = BASE_FLAG_TIME_500, msg: String? = null, iEven: BaseIEventInterval<View>) {
val baseEvent = if (isGlobal) BaseEvent.getSIngleInstance() else BaseEvent.newInstance(flagTime)
setOnClickListener { iEven.onIntervalOk(baseEvent.getIntervalResult(this, msg, baseEvent) ?: return@setOnClickListener) }
}
// View 扩展 onFailure
fun View.doOnClickInterval(isGlobal:Boolean = true, flagTime: Long = BASE_FLAG_TIME_500, iEven: BaseIEventIntervalExt<View>) {
val baseEvent = if (isGlobal) BaseEvent.getSIngleInstance() else BaseEvent.newInstance(flagTime)
setOnClickListener { baseEvent.doOnIntervalResult(this, baseEvent, iEven) }
}
// MenuItem 点击事件间隔 默认1秒
fun MenuItem.doOnClickInterval(isGlobal:Boolean = true, flagTime: Long = BASE_FLAG_TIME_500, msg: String? = null, iEven: BaseIEventInterval<MenuItem>) {
val baseEvent = if (isGlobal) BaseEvent.getSIngleInstance() else BaseEvent.newInstance(flagTime)
setOnMenuItemClickListener {
iEven.onIntervalOk(baseEvent.getIntervalResult(this, msg, baseEvent) ?: return@setOnMenuItemClickListener true)
true
}
}
// MenuItem 扩展 onFailure
fun MenuItem.doOnClickInterval(isGlobal:Boolean = true, flagTime: Long = BASE_FLAG_TIME_500, iEvent: BaseIEventIntervalExt<MenuItem>) {
val baseEvent = if (isGlobal) BaseEvent.getSIngleInstance() else BaseEvent.newInstance(flagTime)
setOnMenuItemClickListener {
baseEvent.doOnIntervalResult(this, baseEvent, iEvent)
true
}
}
// MaterialToolbar 点击事件间隔 默认1秒
fun MaterialToolbar.navigateIconClickGap(isGlobal: Boolean = true, flagTime: Long = BASE_FLAG_TIME_500, msg: String? = null, iEven: BaseIEventInterval<MaterialToolbar>) {
val baseEvent = if (isGlobal) BaseEvent.getSIngleInstance() else BaseEvent.newInstance(flagTime)
setNavigationOnClickListener {
iEven.onIntervalOk(baseEvent.getIntervalResult(this, msg, baseEvent) ?: return@setNavigationOnClickListener)
}
}
// BaseEvent通用事件回调间隔 默认1秒,需手动创建EventGapTimeExt对象
fun BaseEvent.doOnInterval(msg: String? = null, iEvent: BaseIEventInterval<BaseEvent>) : BaseEvent? {
iEvent.onIntervalOk(getIntervalResult(this, msg, this) ?: return null)
return this
}
// BaseEvent扩展 onFailure
fun BaseEvent.doOnInterval(iEvent: BaseIEventIntervalExt<BaseEvent>) : Boolean {
return doOnIntervalResult(this, this, iEvent)
}
fun BaseEvent.doOnInterval(mHandler: Handler?, runnable: Runnable): BaseEvent {
mHandler?.postDelayed({ runnable.run() }, mCurrentFlagTime)
return this
}
fun BaseEvent.doResetEventFlagTime(flagTime: Long) { mCurrentFlagTime = flagTime }
/*
// BaseEvent扩展 onFailure 使用内联
inline fun SwipeRefreshLayout.setAutoCancelRefreshing(lifecycleOwner: LifecycleOwner, cancelTime: Long = 5_000L, crossinline block: () -> Unit) {
setOnRefreshListener {
block()
lifecycleOwner.lifecycleScope.launch {
delay(cancelTime)
isRefreshing = false
}
}
}
// SwipeRefreshLayout 使用内联扩展刷新事件
inline fun SwipeRefreshLayout.doOnCoroutineRefreshListener(delayMs: Long = 0, lifecycleOwner: LifecycleOwner, crossinline block: suspend CoroutineScope.() -> Unit) {
setOnRefreshListener {
lifecycleOwner.lifecycleScope.launch {
block(this)
if (delayMs != 0L) delay(delayMs)
isRefreshing = false
}
}
}
// SwipeRefreshLayout 使用内联扩展自动刷新
inline fun SwipeRefreshLayout.doOnCoroutineAutoRefresh(delayMs: Long = 0, lifecycleOwner: LifecycleOwner, crossinline block: suspend CoroutineScope.() -> Unit) {
lifecycleOwner.lifecycleScope.launch {
isRefreshing = true
block(this)
if (delayMs != 0L) delay(delayMs)
isRefreshing = false
}
}
*/
// 用于简化对 EditText 组件设置 afterTextChanged 操作的扩展函数。
inline fun EditText.afterTextChanged(crossinline afterTextChanged: (String) -> Unit) {
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) { afterTextChanged.invoke(editable.toString()) }
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})
}
fun MaterialSwitch.setOnCheckedInterval(isGlobal:Boolean = true, flagTime: Long = BASE_FLAG_TIME_500, msg: String? = null, iEven: BaseIEventInterval<MaterialSwitch>) {
val baseEvent = if (isGlobal) BaseEvent.getSIngleInstance() else BaseEvent.newInstance(flagTime)
setOnCheckedChangeListener { buttonView, isChecked -> iEven.onIntervalOk(baseEvent.getIntervalResult(this, msg, baseEvent) ?: return@setOnCheckedChangeListener) }
}
| 4
| null |
6
| 76
|
3b64f3bc7ef0f8014e9311f1c69515ecba83ebfc
| 5,576
|
CopyMangaX
|
Apache License 2.0
|
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-08.kt
|
ferinagy
| 432,170,488
| false
|
{"Kotlin": 787586}
|
package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.IntGrid
import com.github.ferinagy.adventOfCode.get
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import com.github.ferinagy.adventOfCode.toIntGrid
fun main() {
val input = readInputLines(2022, "08-input")
val testInput1 = readInputLines(2022, "08-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val grid = input.map { line -> line.map { it.digitToInt() } }.toIntGrid()
val visible = mutableSetOf<Coord2D>()
fun Coord2D.rotate(times: Int): Coord2D =
if (times == 0) this else Coord2D(y, grid.width - 1 - x).rotate(times - 1)
repeat(4) { dir ->
for (y in 0 until grid.height) {
var max = -1
for (x in 0 until grid.width) {
val coord = Coord2D(x, y).rotate(dir)
if (max < grid[coord]) {
visible += coord
max = grid[coord]
}
}
}
}
return visible.size
}
private fun part2(input: List<String>): Int {
val grid = input.map { line -> line.map { it.digitToInt() } }.toIntGrid()
val scores = IntGrid(grid.width, grid.height) { x, y -> scenicScore(grid, x, y) }
return scores.maxOrNull()!!
}
private fun scenicScore(grid: IntGrid, x: Int, y: Int): Int {
val current = grid[x, y]
val up = visibleTrees(current, isAtEdge = { y - it == 0 }, next = { grid[x, y - it] })
val down = visibleTrees(current, isAtEdge = { y + it == grid.height - 1 }, next = { grid[x, y + it] })
val left = visibleTrees(current, isAtEdge = { x - it == 0 }, next = { grid[x - it, y] })
val right = visibleTrees(current, isAtEdge = { x + it == grid.width - 1 }, next = { grid[x + it, y] })
return up * down * left * right
}
private fun visibleTrees(current: Int, isAtEdge: (Int) -> Boolean, next: (Int) -> Int): Int {
var up = 0
if (!isAtEdge(up)) {
while (true) {
up++
if (isAtEdge(up) || current <= next(up)) break
}
}
return up
}
| 0
|
Kotlin
|
0
| 1
|
f4890c25841c78784b308db0c814d88cf2de384b
| 2,360
|
advent-of-code
|
MIT License
|
app/src/main/java/com/diegobezerra/cinemaisapp/ui/main/home/HomeAdapter.kt
|
dsbezerra
| 212,875,134
| false
| null |
package com.diegobezerra.cinemaisapp.ui.main.home
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener
import com.bumptech.glide.Priority
import com.diegobezerra.cinemaisapp.GlideApp
import com.diegobezerra.cinemaisapp.R
import com.diegobezerra.cinemaisapp.ui.main.home.HomeViewHolder.BannersViewHolder
import com.diegobezerra.cinemaisapp.ui.main.home.HomeViewHolder.HeaderViewHolder
import com.diegobezerra.cinemaisapp.ui.main.home.HomeViewHolder.PlayingMoviesViewHolder
import com.diegobezerra.cinemaisapp.ui.main.home.HomeViewHolder.UpcomingAllViewHolder
import com.diegobezerra.cinemaisapp.ui.main.home.HomeViewHolder.UpcomingMovieViewHolder
import com.diegobezerra.cinemaisapp.util.ImageUtils
import com.diegobezerra.cinemaisapp.util.NetworkUtils
import com.diegobezerra.cinemaisapp.widget.AutoSlideViewPager
import com.diegobezerra.core.cinemais.domain.model.Banner
import com.diegobezerra.core.cinemais.domain.model.Banner.Action.MOVIE
import com.diegobezerra.core.cinemais.domain.model.Cinemas
import com.diegobezerra.core.cinemais.domain.model.Home
import com.diegobezerra.core.cinemais.domain.model.Movie
class HomeAdapter(
private val homeViewModel: HomeViewModel
) : ListAdapter<Any, HomeViewHolder>(HomeDiff) {
companion object {
private const val VIEW_TYPE_PLAYING_HEADER = 0
private const val VIEW_TYPE_UPCOMING_HEADER = 1
private const val VIEW_TYPE_BANNERS = 2
private const val VIEW_TYPE_PLAYING_MOVIES = 3
private const val VIEW_TYPE_UPCOMING_MOVIE = 4
private const val VIEW_TYPE_UPCOMING_ALL = 5
// This is used to save and restore playing movies recycler view horizontal
// scroll position
private const val PLAYING_MOVIES_SCROLL = "playing_movies_scroll"
private const val CURRENT_BANNER_INDEX = "current_banner_index"
}
private val playingMoviesAdapter by lazy {
PlayingMoviesAdapter(homeViewModel)
}
private var isWifiConnection: Boolean = false
private val viewPool = RecyclerView.RecycledViewPool()
var currentBannerIndex = 0
private val bannerPageChangeListener = object : SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
currentBannerIndex = position
}
}
var playingMoviesScroll = 0
var data: Home = Home(
backdrop = "",
banners = emptyList(),
playingMovies = emptyList(),
upcomingMovies = emptyList(),
cinemas = Cinemas()
)
set(value) {
field = value
submitList(buildList())
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): HomeViewHolder {
val context = parent.context
isWifiConnection = NetworkUtils.isWifiConnection(parent.context)
val inflater = LayoutInflater.from(context)
return when (viewType) {
VIEW_TYPE_BANNERS -> BannersViewHolder(
inflater.inflate(R.layout.item_home_banners, parent, false)
)
VIEW_TYPE_PLAYING_HEADER -> HeaderViewHolder(
inflater.inflate(R.layout.item_home_playing_header, parent, false)
)
VIEW_TYPE_PLAYING_MOVIES -> PlayingMoviesViewHolder(
inflater.inflate(R.layout.item_home_playing_movies, parent, false)
)
VIEW_TYPE_UPCOMING_HEADER -> HeaderViewHolder(
inflater.inflate(R.layout.item_home_upcoming_header, parent, false)
)
VIEW_TYPE_UPCOMING_MOVIE -> UpcomingMovieViewHolder(
inflater.inflate(R.layout.item_home_upcoming_movie, parent, false)
)
VIEW_TYPE_UPCOMING_ALL -> UpcomingAllViewHolder(
inflater.inflate(R.layout.item_home_upcoming_all, parent, false)
)
else -> throw IllegalStateException("Unknown viewType $viewType")
}
}
override fun onBindViewHolder(
holder: HomeViewHolder,
position: Int
) {
when (holder) {
is BannersViewHolder -> holder.apply {
val adapter =
BannersAdapter(getItem(position) as List<Banner>)
pager.adapter = adapter
pager.currentItem = currentBannerIndex
pager.removeOnPageChangeListener(bannerPageChangeListener)
pager.addOnPageChangeListener(bannerPageChangeListener)
indicator.viewPager = pager
adapter.setListener {
// NOTE: Movie is currently the only action the app supports.
// Anything else will ask user to choose a browser-like app.
when (it.action) {
MOVIE -> homeViewModel.onMovieClicked(it.resourceId)
else -> {
if (it.htmlUrl.isNotEmpty()) {
itemView.context.startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse(it.htmlUrl)
)
)
}
}
}
}
}
is PlayingMoviesViewHolder -> holder.apply {
recyclerView.run {
adapter = playingMoviesAdapter
setRecycledViewPool(viewPool)
setOnScrollListener(
object : OnScrollListener() {
override fun onScrollStateChanged(
recyclerView: RecyclerView,
newState: Int
) {
if (newState == SCROLL_STATE_IDLE) {
playingMoviesScroll = computeHorizontalScrollOffset()
}
}
}
)
// Make sure our scroll is restored
if (playingMoviesScroll != 0) {
post { scrollBy(playingMoviesScroll, 0) }
}
}
}
is UpcomingMovieViewHolder -> holder.apply {
val movie = getItem(position) as Movie
title.text = movie.title
synopsis.text = movie.synopsis
movie.posters.best(isWifiConnection)?.let {
ImageUtils.loadPoster(it, poster)
// NOTE(diego): isWifiConnection makes sure we load the best image here, but in
// the next time the user starts the app without a network connection he will never
// see the cached large poster.
// To avoid this we will also download the medium poster (temporary).
if (isWifiConnection) {
GlideApp.with(itemView.context)
.load(movie.posters.medium)
.priority(Priority.LOW)
.preload()
}
}
itemView.setOnClickListener {
homeViewModel.onMovieClicked(movie.id)
}
}
is UpcomingAllViewHolder -> holder.apply {
itemView.setOnClickListener {
homeViewModel.onShowAllUpcomingClicked()
}
}
is HeaderViewHolder -> Unit
}
}
override fun onViewRecycled(holder: HomeViewHolder) {
if (holder is BannersViewHolder) {
currentBannerIndex = holder.pager.currentItem
} else if (holder is PlayingMoviesViewHolder) {
playingMoviesScroll = holder.recyclerView.computeHorizontalScrollOffset()
}
}
override fun getItemViewType(position: Int): Int {
return when (val item = getItem(position)) {
is PlayingMoviesHeader -> VIEW_TYPE_PLAYING_HEADER
is UpcomingMoviesHeader -> VIEW_TYPE_UPCOMING_HEADER
is BannersViewHolder -> VIEW_TYPE_BANNERS
is List<*> -> {
return if (item.isNotEmpty() && item[0] is Movie) {
VIEW_TYPE_PLAYING_MOVIES
} else if (item.isNotEmpty() && item[0] is Banner) {
VIEW_TYPE_BANNERS
} else {
throw IllegalStateException("Unknown view type at position $position")
}
}
is Movie -> VIEW_TYPE_UPCOMING_MOVIE
is UpcomingMoviesAll -> VIEW_TYPE_UPCOMING_ALL
else -> throw IllegalStateException("Unknown view type at position $position")
}
}
fun save(outState: Bundle) {
outState.putInt(CURRENT_BANNER_INDEX, currentBannerIndex)
outState.putInt(PLAYING_MOVIES_SCROLL, playingMoviesScroll)
}
fun restore(savedInstanceState: Bundle?) {
savedInstanceState?.let {
currentBannerIndex = it.getInt(CURRENT_BANNER_INDEX)
playingMoviesScroll = it.getInt(PLAYING_MOVIES_SCROLL)
}
}
private fun buildList(): List<Any> {
val result = mutableListOf<Any>()
if (data.banners.isNotEmpty()) {
result.add(data.banners)
}
if (data.playingMovies.isNotEmpty()) {
playingMoviesAdapter.submitList(data.playingMovies)
result.add(PlayingMoviesHeader)
result.add(data.playingMovies)
}
if (data.upcomingMovies.isNotEmpty()) {
result.add(UpcomingMoviesHeader)
result.addAll(data.upcomingMovies)
result.add(UpcomingMoviesAll)
}
return result
}
}
object PlayingMoviesHeader
object UpcomingMoviesHeader
object UpcomingMoviesAll
sealed class HomeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
class HeaderViewHolder(itemView: View) : HomeViewHolder(itemView)
class BannersViewHolder(itemView: View) : HomeViewHolder(itemView) {
val pager: AutoSlideViewPager = itemView.findViewById(R.id.viewpager)
val indicator: BannersIndicatorView = itemView.findViewById(R.id.indicator)
}
class PlayingMoviesViewHolder(itemView: View) : HomeViewHolder(itemView) {
val recyclerView: RecyclerView = itemView.findViewById(R.id.recyclerView)
}
class UpcomingMovieViewHolder(itemView: View) : HomeViewHolder(itemView) {
val title: TextView = itemView.findViewById(R.id.title)
val poster: ImageView = itemView.findViewById(R.id.poster)
val synopsis: TextView = itemView.findViewById(R.id.synopsis)
}
class UpcomingAllViewHolder(itemView: View) : HomeViewHolder(itemView)
}
object HomeDiff : DiffUtil.ItemCallback<Any>() {
override fun areItemsTheSame(
oldItem: Any,
newItem: Any
): Boolean {
return when {
oldItem === PlayingMoviesHeader && newItem === PlayingMoviesHeader -> true
oldItem === UpcomingMoviesHeader && newItem === UpcomingMoviesHeader -> true
oldItem === UpcomingMoviesAll && newItem === UpcomingMoviesAll -> true
oldItem is Movie && newItem is Movie -> oldItem.id == newItem.id
oldItem is List<*> && newItem is List<*> -> oldItem == newItem
else -> false
}
}
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean {
return when {
oldItem is List<*> && newItem is List<*> -> oldItem == newItem
oldItem is Movie && newItem is Movie -> oldItem == newItem
oldItem is Banner && newItem is Banner -> oldItem == newItem
else -> true
}
}
}
| 1
| null |
1
| 1
|
93747bb7148cd46b76e9255f517405db1ae75fdd
| 12,447
|
cinemais-android
|
Apache License 2.0
|
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/behavior/Selectable.kt
|
Xanik
| 282,687,897
| false
| null |
package org.hexworks.zircon.api.behavior
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.zircon.internal.behavior.impl.DefaultSelectable
import kotlin.jvm.JvmStatic
/**
* Represents an object which can be selected.
*/
interface Selectable {
var isSelected: Boolean
val selectedProperty: Property<Boolean>
companion object {
@JvmStatic
fun create(initialSelected: Boolean = false): Selectable = DefaultSelectable(initialSelected)
}
}
| 1
| null |
1
| 2
|
bf435cddeb55f7c3a9da5dd5c29be13af8354d0f
| 506
|
zircon
|
Apache License 2.0
|
app/src/main/java/ru/lapov/forrabitresult/activities/SplashScreen.kt
|
metalink94
| 162,844,359
| false
|
{"Gradle": 3, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "JSON": 1, "Kotlin": 16, "XML": 42, "Java": 1}
|
package ru.lapov.forrabitresult.activities
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import ru.lapov.forrabitresult.R
class SplashScreen: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
checkDatabase()
}
private fun checkDatabase() {
val database = FirebaseDatabase.getInstance()
database.reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
if (p0.value != null) {
val web = p0.child("web").value as Boolean
val url = p0.child("url").value as String?
router(web, url)
}
Log.d("DataBase", "get database ${p0.value}")
}
override fun onCancelled(p0: DatabaseError) {
router()
}
})
}
private fun router(isWeb: Boolean = false, url: String? = null) {
if (isWeb && !url.isNullOrEmpty()) {
showWeb(url)
} else {
showMainScreen()
}
}
private fun showMainScreen() {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
private fun showWeb(url: String?) {
startActivity(WebViewActivity.getInstance(this, url))
finish()
}
}
| 0
|
Kotlin
|
0
| 0
|
a9d318a4b00d992dd6a5899940364a04a9c582c9
| 1,724
|
ForRabitResult
|
Apache License 2.0
|
src/main/kotlin/com/vampmir/features/qol/Drops.kt
|
jeenyuhs
| 749,534,575
| false
|
{"Kotlin": 72421, "Java": 3028}
|
package com.vampmir.features.qol
import com.vampmir.GSM
import com.vampmir.utils.Player
import com.vampmir.utils.TitleRender
import com.vampmir.utils.chat
import gg.essential.universal.ChatColor
import gg.essential.universal.UMatrixStack
import net.minecraft.util.StringUtils
import net.minecraftforge.client.event.ClientChatReceivedEvent
import net.minecraftforge.client.event.RenderGameOverlayEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
object Drops {
private val dropPattern: Regex = Regex("(?<dropType>.*) DROP! (?<dropName>.*) .*\\((?<magicFind>.*)\\).*")
var title: TitleRender? = null
@SubscribeEvent
fun onGameOverlayRender(event: RenderGameOverlayEvent.Text) {
if (title != null) {
title!!.render(UMatrixStack())
}
}
@SubscribeEvent
fun onChatReceived(event: ClientChatReceivedEvent) {
if (!Player.onSkyblock) return
val message = event.message.formattedText ?: return
if (dropPattern.matches(message)) {
if (GSM.config.announceRareDrops) {
val dropType = dropPattern.matchEntire(message)!!.groups["dropType"]!!.value
val dropName = dropPattern.matchEntire(message)!!.groups["dropName"]!!.value
val magicFind = dropPattern.matchEntire(message)!!.groups["magicFind"]!!.value
if (GSM.config.ignoredRareDrops.split(", ").find { it == StringUtils.stripControlCodes(dropName) } != null) {
if (GSM.config.hideIgnoredDropsMessages) event.isCanceled = true
return
}
val titleNoColor = "§l" + StringUtils.stripControlCodes("$dropType DROP!")
title = TitleRender("$dropType DROP!", "$dropName §r§b($magicFind)§r").fadeIn(120f)
.flicker(titleNoColor, 100f)
.flicker(titleNoColor, 100f)
.flicker(titleNoColor, 100f)
.flicker(titleNoColor, 100f)
.fadeOut(200f)
}
if (GSM.config.copyRareDrops) {
GSM.minecraft.thePlayer.chat("${ChatColor.GOLD}[${ChatColor.YELLOW}GSM${ChatColor.GOLD}] ${ChatColor.DARK_GRAY}> ${ChatColor.GOLD}Added drop to clipboard!")
Toolkit.getDefaultToolkit().systemClipboard.setContents(StringSelection(event.message.unformattedText), null)
}
}
}
}
| 7
|
Kotlin
|
0
| 0
|
e62482e3ac9b8b4b5e68d7f6bf33ff72527ed24c
| 2,497
|
GSM
|
The Unlicense
|
src/main/kotlin/com/github/attacktive/troubleshootereditor/model/Identifiable.kt
|
Attacktive
| 517,579,517
| false
| null |
package com.github.attacktive.troubleshootereditor.model
interface Identifiable<T> {
fun getId(): T
}
| 0
|
Kotlin
|
0
| 1
|
01bda97520317ac800b1db32808c9721042cea07
| 104
|
troubleshooter-editor-back-end
|
MIT License
|
app/k9mail/src/main/java/com/fsck/k9/Dependencies.kt
|
pueffl
| 165,477,804
| true
|
{"Java": 4395423, "Kotlin": 540181, "Shell": 3101, "HTML": 292}
|
package com.fsck.k9
import com.fsck.k9.backends.backendsModule
import com.fsck.k9.controller.ControllerExtension
import com.fsck.k9.crypto.EncryptionExtractor
import com.fsck.k9.crypto.openpgp.OpenPgpEncryptionExtractor
import com.fsck.k9.external.BroadcastSenderListener
import com.fsck.k9.external.externalModule
import com.fsck.k9.notification.notificationModule
import com.fsck.k9.preferences.K9StoragePersister
import com.fsck.k9.preferences.StoragePersister
import com.fsck.k9.resources.resourcesModule
import com.fsck.k9.storage.storageModule
import com.fsck.k9.widget.list.MessageListWidgetUpdateListener
import com.fsck.k9.widget.list.messageListWidgetModule
import com.fsck.k9.widget.unread.UnreadWidgetUpdateListener
import com.fsck.k9.widget.unread.unreadWidgetModule
import org.koin.dsl.module.module
private val mainAppModule = module {
single { App.appConfig }
single { MessagingListenerProvider(
listOf(
get<UnreadWidgetUpdateListener>(),
get<MessageListWidgetUpdateListener>(),
get<BroadcastSenderListener>()
))
}
single("controllerExtensions") { emptyList<ControllerExtension>() }
single { OpenPgpEncryptionExtractor.newInstance() as EncryptionExtractor }
single { K9StoragePersister(get()) as StoragePersister }
}
val appModules = listOf(
mainAppModule,
externalModule,
messageListWidgetModule,
unreadWidgetModule,
notificationModule,
resourcesModule,
backendsModule,
storageModule
)
| 0
|
Java
|
0
| 0
|
38be7d2f1a83dce89d43c8c55d0be77b58282704
| 1,578
|
k-9
|
Apache License 2.0
|
app/src/main/kotlin/jp/co/yumemi/android/codecheck/model/GitHubResponse.kt
|
0v0d
| 771,582,978
| false
|
{"Kotlin": 15693}
|
package jp.co.yumemi.android.codecheck.model
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.parcelize.Parcelize
/**
* GitHubのリポジトリ情報を保持するデータクラス
* @param items リポジトリ情報
*/
@Parcelize
data class GitHubResponse(
@Json(name = "items")
val items: List<RepositoryItem>
) : Parcelable
| 3
|
Kotlin
|
0
| 0
|
1edcbf7f97c11594abf480dc98aea91591473c1a
| 317
|
android-engineer-codecheck
|
Apache License 2.0
|
bellatrix.ios/src/main/java/solutions/bellatrix/ios/services/AppService.kt
|
AutomateThePlanet
| 334,964,015
| false
| null |
/*
* Copyright 2021 Automate The Planet Ltd.
* Author: <NAME>
* 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 solutions.bellatrix.ios.services
import solutions.bellatrix.core.utilities.RuntimeInformation
import java.time.Duration
object AppService : MobileService() {
var context: String
get() = wrappedIOSDriver.getContext()
set(name) {
wrappedIOSDriver.context(name)
}
fun backgroundApp(seconds: Int) {
wrappedIOSDriver.runAppInBackground(Duration.ofSeconds(seconds.toLong()))
}
fun closeApp() {
wrappedIOSDriver.closeApp()
}
fun launchApp() {
wrappedIOSDriver.launchApp()
}
fun resetApp() {
wrappedIOSDriver.resetApp()
}
fun installApp(appPath: String) {
var appPath = appPath
if (RuntimeInformation.IS_MAC) {
appPath = appPath.replace('\\', '/')
}
wrappedIOSDriver.installApp(appPath)
}
fun removeApp(appId: String) {
wrappedIOSDriver.removeApp(appId)
}
fun isAppInstalled(bundleId: String): Boolean {
return try {
wrappedIOSDriver.isAppInstalled(bundleId)
} catch (e: Exception) {
false
}
}
}
| 1
|
Kotlin
|
1
| 1
|
5da5e705b47e12c66937d130b3031ac8703b8279
| 1,742
|
BELLATRIX-Kotlin
|
Apache License 2.0
|
src/commonTest/kotlin/com.mfrancza.jwtrevocation/rules/conditions/DateTimeAfterTest.kt
|
mfrancza
| 585,426,278
| false
| null |
package com.mfrancza.jwtrevocation.rules.conditions
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class DateTimeAfterTest {
@Test
fun testAfter() {
val condition = DateTimeAfter(1666928921)
assertFalse(
condition.isMet(condition.value),
"The same value does not meet it")
assertFalse(condition.isMet(
condition.value - 10),
"A lower value does not meet it")
assertTrue(condition.isMet(
condition.value + 10),
"A higher value does meet it")
assertFalse(
condition.isMet(null),
"A null value does not meet the condition")
}
}
| 1
|
Kotlin
|
0
| 0
|
8dd296653b1236cc96df7306ae8202684e0dd843
| 713
|
jwt-revocation-rules
|
Apache License 2.0
|
src/main/kotlin/no/nav/arbeidsforhold/service/outbound/ArbeidsforholdDto.kt
|
navikt
| 175,394,209
| false
|
{"Kotlin": 57979, "Dockerfile": 263}
|
package no.nav.arbeidsforhold.service.outbound
import kotlinx.serialization.Serializable
@Serializable
data class ArbeidsforholdDto(
val navArbeidsforholdId: Long? = null,
val eksternArbeidsforholdId: String? = null,
var type: String? = null,
val sistBekreftet: String? = null,
val arbeidsgiver: ArbeidsgiverDto? = null,
val opplysningspliktigarbeidsgiver: ArbeidsgiverDto? = null,
val ansettelsesperiode: AnsettelsesperiodeDto? = null,
val utenlandsopphold: List<UtenlandsoppholdDto>? = null,
val permisjonPermittering: List<PermisjonPermitteringDto>? = null,
val arbeidsavtaler: List<ArbeidsavtaleDto>? = null,
val ansettelsesform: String? = null,
val antallTimerForTimelonnet: List<AntallTimerForTimeloennetDto>? = null,
val antallTimerPrUke: Double? = null,
var arbeidstidsordning: String? = null,
val sisteStillingsendring: String? = null,
val sisteLoennsendring: String? = null,
val stillingsprosent: Double? = null,
var yrke: String? = null,
var fartsomraade: String? = null,
var skipsregister: String? = null,
var skipstype: String? = null
)
| 2
|
Kotlin
|
0
| 1
|
f54ca6f7870760d64d63b879cbca51777c11044a
| 1,136
|
arbeidsforhold-api
|
MIT License
|
idea/testData/intentions/convertSecondaryConstructorToPrimary/withDelegation.kt
|
JakeWharton
| 99,388,807
| false
| null |
// IS_APPLICABLE: false
class WithDelegation {
constructor()
constructor<caret>(x: Int): this()
}
| 0
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 107
|
kotlin
|
Apache License 2.0
|
code/jvm/src/main/kotlin/aguDataSystem/server/repository/jdbi/mappers/MapperUtils.kt
|
AGU-Data-System
| 765,690,492
| false
|
{"Kotlin": 723386, "TypeScript": 153702, "JavaScript": 1600, "CSS": 925, "Shell": 889, "HTML": 267}
|
package aguDataSystem.server.repository.jdbi.mappers
import aguDataSystem.server.domain.Location
import aguDataSystem.server.domain.company.DNO
import aguDataSystem.server.domain.company.TransportCompany
import aguDataSystem.server.domain.gasLevels.GasLevels
import java.sql.ResultSet
/**
* Utility class for mapping database results to domain objects.
*/
object MapperUtils {
/**
* Maps the result set to a location
*
* @param rs the result set
* @return the location
*/
fun mapToLocation(rs: ResultSet): Location {
return Location(
latitude = rs.getDouble("latitude"),
longitude = rs.getDouble("longitude"),
name = rs.getString("location_name")
)
}
/**
* Maps the result set to a list of AGUs
*
* @param rs the result set
* @return the list of AGUs
*/
fun mapToGasLevels(rs: ResultSet): GasLevels {
return GasLevels(
min = rs.getInt("min_level"),
max = rs.getInt("max_level"),
critical = rs.getInt("critical_level")
)
}
/**
* Maps the result set to a DNO
*
* @param rs the result set
* @return the DNO
*/
fun mapToDNO(rs: ResultSet): DNO {
return DNO(
id = rs.getInt("dno_id"),
name = rs.getString("dno_name"),
region = rs.getString("region")
)
}
/**
* Maps the result set to a transport company
*
* @param rs the result set
* @return the transport company
*/
fun mapToTransportCompany(rs: ResultSet): TransportCompany {
return TransportCompany(
id = rs.getInt("tc_id"),
name = rs.getString("tc_name")
)
}
}
| 0
|
Kotlin
|
0
| 1
|
d41bcf2ff0a21ac97f476a59c83802ddf0269606
| 1,518
|
AGU-Data-System
|
MIT License
|
common/src/test/kotlin/org/amshove/kluent/tests/collections/ShouldContainSingleItemShould.kt
|
MarkusAmshove
| 51,317,191
| false
| null |
package org.amshove.kluent.tests.collections
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldHaveSingleItem
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class ShouldContainSingleItemShould {
@Test
fun notThrowWhenACollectionHasOneItem() {
val collection = listOf(1)
collection.shouldHaveSingleItem()
}
@Test
fun failWhenACollectionIsEmpty() {
val collection = listOf<Int>()
assertFails {
collection.shouldHaveSingleItem()
}
}
@Test
fun failWhenACollectionHasMoreThanOneItem() {
val collection = listOf(1, 2, 3, 4, 5)
assertFails {
collection.shouldHaveSingleItem()
}
}
@Test
fun returnTheItemInsideTheCollection() {
val collection = listOf("Hello")
val item = collection.shouldHaveSingleItem()
assertEquals("Hello", item)
}
@Test
fun notThrowWhenASequenceHasOneItem() {
val sequence = sequenceOf(1)
sequence.shouldHaveSingleItem()
}
@Test
fun failWhenASequenceIsEmpty() {
val sequence = emptySequence<Int>()
assertFails {
sequence.shouldHaveSingleItem()
}
}
@Test
fun failWhenASequenceHasMoreThanOneItem() {
val sequence = sequenceOf(1, 2, 3, 4, 5)
assertFails {
sequence.shouldHaveSingleItem()
}
}
@Test
fun returnTheItemInsideTheSequence() {
val sequence = sequenceOf("Hello")
val item = sequence.shouldHaveSingleItem()
assertEquals("Hello", item)
}
@Test
fun workWithArrays() {
val arr = arrayOf("World")
arr.shouldHaveSingleItem().shouldBeEqualTo("World")
}
@Test
fun workWithPrimitiveArrays() {
val arr = shortArrayOf(5)
arr.shouldHaveSingleItem().shouldBeEqualTo(5)
}
}
| 12
|
Kotlin
|
66
| 843
|
2826b263e5e2b5a74d8eb0394a4354848052e786
| 1,931
|
Kluent
|
MIT License
|
src/main/java/ar/edu/unq/eperdemic/EperdemicApplication.kt
|
Dominikowivan
| 257,255,510
| false
|
{"Gradle Kotlin DSL": 2, "Shell": 1, "Text": 1, "Batchfile": 1, "Markdown": 1, "YAML": 3, "XML": 7, "SQL": 4, "INI": 3, "Kotlin": 22, "Java": 1, "Java Properties": 1}
|
package ar.edu.unq.eperdemic
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class EperdemicApplication
fun main(args: Array<String>) {
runApplication<EperdemicApplication>(*args)
}
| 0
|
Kotlin
|
0
| 0
|
d0b012c8cd6d6aed07fdc054f40573dee6fc08be
| 276
|
EPERdemic_Backend
|
MIT License
|
telegramClient/src/commonMain/kotlin/pw/binom/telegram/dto/SetWebhookRequest.kt
|
caffeine-mgn
| 309,111,702
| false
| null |
package pw.binom.telegram.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
class SetWebhookRequest(
@SerialName("url")
val url: String,
@SerialName("certificate")
val certificate: String? = null,
@SerialName("max_connections")
val maxConnections: Int? = null,
@SerialName("allowed_updates")
val allowedUpdates: List<EventType>? = null
)
| 0
| null |
0
| 2
|
c5d7857070f691965d2097b8a944512bc0283889
| 424
|
telegramClient
|
Apache License 2.0
|
src/lsp/intellij-plugin/src/main/kotlin/Types.kt
|
flock-community
| 506,356,849
| false
| null |
package community.flock.wirespec.lsp.intellij_plugin
import com.intellij.psi.tree.IElementType
interface Types {
class ElementType(debugName: String) : IElementType(debugName, Language.INSTANCE)
companion object {
val COLON = ElementType("COLON")
val COMMA = ElementType("COMMA")
val CUSTOM_VALUE = ElementType("CUSTOM_VALUE")
val CUSTOM_TYPE = ElementType("CUSTOM_TYPE")
val BOOLEAN = ElementType("BOOLEAN")
val INTEGER = ElementType("INTEGER")
val NUMBER = ElementType("NUMBER")
val STRING = ElementType("STRING")
val UNIT = ElementType("UNIT")
val TYPE_DEF = ElementType("TYPE_DEF")
val ENUM_DEF = ElementType("ENUM_DEF")
val REFINED_TYPE_DEF = ElementType("REFINED_TYPE_DEF")
val ENDPOINT_DEF = ElementType("ENDPOINT_DEF")
val CUSTOM_REGEX = ElementType("CUSTOM_REGEX")
val EQUALS = ElementType("EQUALS")
val PIPE = ElementType("PIPE")
val ARROW = ElementType("ARROW")
val METHOD = ElementType("METHOD")
val PATH = ElementType("PATH")
val FORWARD_SLASH = ElementType("FORWARD_SLASH")
val STATUS_CODE = ElementType("STATUS_CODE")
val LEFT_CURLY = ElementType("LEFT_CURLY")
val RIGHT_CURLY = ElementType("RIGHT_CURLY")
val QUESTION_MARK = ElementType("QUESTION_MARK")
val HASH = ElementType("HASH")
val BRACKETS = ElementType("BRACKETS")
val WHITE_SPACE = ElementType("WHITE_SPACE")
val END_OF_PROGRAM = ElementType("END_OF_PROGRAM")
val INVALID = ElementType("INVALID")
}
}
| 9
| null |
2
| 9
|
581cd0ceee63d461c544d34f1cf2cf47813ff90e
| 1,624
|
wirespec
|
Apache License 2.0
|
app/src/main/java/de/thomaskuenneth/benice/IconButtonWithTooltip.kt
|
tkuenneth
| 736,289,151
| false
|
{"Kotlin": 40659}
|
package de.thomaskuenneth.benice
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.PlainTooltipBox
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun IconButtonWithTooltip(
onClick: () -> Unit,
imageVector: ImageVector,
contentDescription: String
) {
PlainTooltipBox(tooltip = {
Text(text = contentDescription)
}) {
IconButton(
onClick = onClick,
modifier = Modifier.tooltipAnchor()
) {
Icon(
imageVector = imageVector,
contentDescription = contentDescription
)
}
}
}
| 1
|
Kotlin
|
0
| 5
|
923fb35a4eb2557f0a2489bb9765c86e81695035
| 963
|
BeNice
|
Apache License 2.0
|
libfunrenderer/src/main/java/io/github/kenneycode/funrenderer/io/FrameBuffer.kt
|
kenneycode
| 186,097,106
| false
| null |
package io.github.kenneycode.funrenderer.io
import android.opengl.GLES30
import io.github.kenneycode.funrenderer.common.FrameBufferCache
import io.github.kenneycode.funrenderer.uitl.GLUtil
/**
*
* Coded by kenney
*
* http://www.github.com/kenneycode
*
**/
open class FrameBuffer(var texture: Int = 0, width : Int = 0, height : Int = 0, private var autoRecycle : Boolean = true) : Output(width, height) {
var frameBuffer = 0
override fun getInput(): IntArray {
return intArrayOf(texture)
}
override fun onBind(width: Int, height: Int) {
bind(width, height)
}
override fun onUnBind() {
unBind()
}
private fun bind(width: Int = 0, height: Int = 0) {
if (width != 0 && height != 0) {
if (frameBuffer == 0) {
frameBuffer = GLUtil.createFrameBuffer()
texture = if (texture == 0) { GLUtil.createTexture() } else { texture }
}
if (width != this.width || height != this.height) {
this.width = width
this.height = height
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, width, height, 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null)
GLUtil.checkError()
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, frameBuffer)
GLUtil.checkError()
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, texture, 0)
GLUtil.checkError()
}
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, frameBuffer)
}
private fun unBind() {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
override fun release() {
GLUtil.deleteTexture(texture)
GLUtil.deleteFrameBuffer(frameBuffer)
}
override fun releaseRef(): Boolean {
var ret = false
if (autoRecycle) {
ret = super.releaseRef()
if (ret) {
FrameBufferCache.releaseFrameBuffer(this)
}
}
return ret
}
}
| 0
|
Kotlin
|
2
| 16
|
d76114e926ecb66c36f11b8251939c4c8143a7e6
| 2,200
|
FunRenderer
|
Apache License 2.0
|
component/src/main/java/cn/nekocode/kotgo/component/ui/stack/RequestData.kt
|
tiagobarreto
| 85,804,001
| true
|
{"Kotlin": 38427, "Python": 9330, "Java": 120}
|
package cn.nekocode.kotgo.component.ui
import android.content.Intent
import android.os.Parcel
import android.os.Parcelable
/**
* Created by nekocode on 16/8/25.
*/
class RequestInfo(var requestCode: Int, var resultCode: Int = 0, var resultData: Intent? = null) : Parcelable {
constructor(source: Parcel) : this(
source.readInt(),
source.readInt(),
source.readParcelable<Intent?>(Intent::class.java.classLoader)
)
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeInt(requestCode)
dest?.writeInt(resultCode)
dest?.writeParcelable(resultData, 0)
}
companion object {
@JvmField final val CREATOR: Parcelable.Creator<RequestInfo> = object : Parcelable.Creator<RequestInfo> {
override fun createFromParcel(source: Parcel): RequestInfo {
return RequestInfo(source)
}
override fun newArray(size: Int): Array<RequestInfo?> {
return arrayOfNulls(size)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
802cef3999515a4d92b1571128fdf64cae8c743d
| 1,121
|
kotgo
|
Apache License 2.0
|
app/src/main/java/mil/nga/msi/ui/map/filter/MapFilterViewModel.kt
|
ngageoint
| 588,211,646
| false
|
{"Kotlin": 1898030}
|
package mil.nga.msi.ui.map.filter
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import mil.nga.msi.datasource.DataSource
import mil.nga.msi.location.LocationPolicy
import mil.nga.msi.repository.preferences.FilterRepository
import javax.inject.Inject
@HiltViewModel
class MapFilterViewModel @Inject constructor(
val locationPolicy: LocationPolicy,
private val filterRepository: FilterRepository
): ViewModel() {
data class DataSourceModel(
val dataSource: DataSource,
val numberOfFilters: Int
)
private val filterableDataSources = listOf(
DataSource.ASAM,
DataSource.MODU,
DataSource.LIGHT,
DataSource.PORT,
DataSource.RADIO_BEACON,
DataSource.DGPS_STATION
)
val dataSources: LiveData<List<DataSourceModel>> = MediatorLiveData<List<DataSourceModel>>().apply {
addSource(filterRepository.filters.asLiveData()) { filters ->
value = filterableDataSources.map { dataSource ->
DataSourceModel(dataSource, filters[dataSource]?.size ?: 0)
}
}
}
}
| 0
|
Kotlin
|
1
| 0
|
d7670ab5f73e2e89b741a56e418b49f2acc810a2
| 1,212
|
marlin-android
|
MIT License
|
app/src/main/kotlin/me/zhiyao/waterever/exts/IntExt.kt
|
WangZhiYao
| 243,558,800
| false
| null |
package me.zhiyao.waterever.exts
import android.content.Context
import android.util.TypedValue
import kotlin.math.roundToInt
/**
*
* @author WangZhiYao
* @date 2020/8/18
*/
fun Int.dp2px(context: Context) =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this.toFloat(), context.resources.displayMetrics
).roundToInt()
fun Int.sp2px(context: Context) =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
this.toFloat(), context.resources.displayMetrics
).roundToInt()
| 0
|
Kotlin
|
0
| 0
|
232f20d623209eb2b9fb889aeb05af6ec3fee535
| 535
|
WaterEver
|
Apache License 2.0
|
library/src/test/kotlin/com/cesarferreira/pluralize/SingularizationTest.kt
|
cesarferreira
| 67,342,759
| false
| null |
package com.cesarferreira.pluralize
import org.junit.Assert.assertEquals
import org.junit.Test
class SingularizationTest {
@Test
fun `Should remove default "s" suffix`() {
assertEquals("word", "words".singularize())
}
@Test
fun `Should handle unCountable words`() {
assertEquals("scissors", "scissors".singularize())
}
@Test
fun `Should handle exception words`() {
assertEquals("person", "people".singularize())
}
@Test
fun `Should handle in case insensitive manner`() {
assertEquals("goy", "Goyim".singularize())
}
}
| 4
|
Kotlin
|
6
| 46
|
e6ed6038c399ce11a8a0268ea0693504ee6497c6
| 605
|
kotlin-pluralizer
|
MIT License
|
cache-core/src/main/kotlin/im/toss/util/cache/CacheValueLoader.kt
|
toss
| 228,551,924
| false
| null |
package im.toss.util.cache
import java.lang.Exception
interface CacheValueLoader<T: Any> {
val version: Long
@Throws(AlreadyLoadedException::class)
suspend fun load(value: T): LoadResult<T>
suspend fun release()
}
class AlreadyLoadedException : Exception()
class ResultGetOrLockForLoad<T: Any>(
val value: T? = null,
val loader: CacheValueLoader<T>? = null
)
data class LoadResult<T>(
val value: T,
val success: Boolean = true,
val isOptimisticLockFailure: Boolean = false
)
| 1
|
Kotlin
|
3
| 7
|
006062a4cc9548d57c09c11cbccdf1811de73589
| 517
|
cache
|
Apache License 2.0
|
Wisdom_Education_Android/edu-logic/src/main/java/com/netease/yunxin/app/wisdom/edu/logic/options/NEEduOptions.kt
|
leeox
| 423,769,135
| true
|
{"Kotlin": 725060, "Objective-C": 715250, "Java": 300037, "TypeScript": 281229, "Swift": 59456, "Less": 38860, "Ruby": 16266, "JavaScript": 8813, "C": 5895, "HTML": 2087}
|
/*
* Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package com.netease.yunxin.app.wisdom.edu.logic.options
import com.netease.yunxin.app.wisdom.edu.logic.foreground.NEEduForegroundServiceConfig
/**
* SDK 全局配置
*
* @property appKey 应用的 AppKey。可以在网易云信控制台中查看。
* @property authorization 调用服务端接口时,请求头中的校验参数。
* @property baseUrl 应用服务器地址。私有化配置时需替换为私有化部署地址
* @property reuseIM 配置是否复用底层NIM-SDK的长连接通道,默认关闭。仅当应用中同时还需独立接入和使用NIM-SDK,才需要开启该配置,其他情况下请忽略该配置。
* @property foregroundServiceConfig 前台服务配置项
*/
class NEEduOptions(
val appKey: String,
val authorization: String,
val baseUrl: String,
val reuseIM: Boolean? = false,
val foregroundServiceConfig: NEEduForegroundServiceConfig? = null,
)
| 0
| null |
0
| 0
|
9b688d0df67721e407cf2c691a94be36551aa0bf
| 815
|
WisdomEducation
|
MIT License
|
shared/src/commonMain/kotlin/com/techbeloved/hymnbook/shared/App.kt
|
techbeloved
| 133,724,406
| false
|
{"Kotlin": 469411, "Java": 8639, "HTML": 4084, "Ruby": 2303, "Swift": 659}
|
package com.techbeloved.hymnbook.shared
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import cafe.adriel.voyager.navigator.Navigator
import com.techbeloved.hymnbook.shared.ui.home.HomeScreen
import com.techbeloved.hymnbook.shared.ui.theme.AppTheme
@Composable
public fun App() {
AppTheme {
Navigator(screen = HomeScreen)
}
}
| 3
|
Kotlin
|
11
| 8
|
00cbad6464a71f89392af48c6089932a2a86d457
| 399
|
hymnbook
|
MIT License
|
app/src/main/java/com/dreamsoftware/fitflextv/ui/screens/settings/SettingsScreen.kt
|
sergio11
| 534,529,261
| false
| null |
package com.dreamsoftware.saborytv.ui.screens.settings
import androidx.compose.runtime.Composable
import androidx.hilt.navigation.compose.hiltViewModel
import com.dreamsoftware.fudge.component.FudgeTvScreen
@Composable
fun SettingsScreen(
viewModel: SettingsViewModel = hiltViewModel(),
onGoToSubscriptions: () -> Unit,
onBackPressed: () -> Unit,
) {
FudgeTvScreen(
viewModel = viewModel,
onBackPressed = onBackPressed,
onSideEffect = {
when(it) {
SettingsSideEffects.OpenSubscriptions -> onGoToSubscriptions()
}
},
onInitialUiState = { SettingsUiState() },
onInit = {
fetchData()
}
) { uiState ->
SettingsScreenContent(
uiState = uiState,
actionListener = viewModel
)
}
}
| 0
| null |
4
| 40
|
98f42de1194e7cbaa6e5507a7cd5feaa6452849e
| 848
|
fitflextv_android
|
MIT License
|
src/main/kotlin/convention/publishing/dsl/MavenPom.kt
|
indramahkota
| 868,423,800
| false
|
{"Kotlin": 65624}
|
package convention.publishing.dsl
import org.gradle.api.publish.maven.MavenPom
import org.gradle.api.publish.maven.MavenPomContributor
import org.gradle.api.publish.maven.MavenPomContributorSpec
import org.gradle.api.publish.maven.MavenPomDeveloper
import org.gradle.api.publish.maven.MavenPomDeveloperSpec
import org.gradle.api.publish.maven.MavenPomLicenseSpec
public fun MavenPomLicenseSpec.mit() {
license {
name.set("MIT License")
url.set("https://opensource.org/licenses/mit-license.php")
}
}
public data class GithubProject(
var owner: String? = null,
var repository: String? = null,
) {
val url: String
get() = "$HTTPS$GITHUB_DOMAIN/$owner/$repository"
val ssh: String
get() = "$SSH$GITHUB_DOMAIN:$owner/$repository.git"
val git: String
get() = "$GIT$GITHUB_DOMAIN/$owner/$repository.git"
private companion object {
const val GIT = "scm:git:git://"
const val SSH = "scm:git:ssh://git@"
const val HTTPS = "https://"
const val GITHUB_DOMAIN = "github.com"
}
}
public fun MavenPom.setGitHubProject(
action: GithubProject.() -> Unit = {},
) {
val githubProject = GithubProject().apply {
action()
}
require(!githubProject.owner.isNullOrEmpty()) {
"GitHub project owner must be set"
}
require(!githubProject.repository.isNullOrEmpty()) {
"GitHub project repository must be set"
}
url.set(githubProject.url)
issueManagement {
url.set("${githubProject.url}/issues")
system.set("GitHub Issues")
}
scm {
url.set(githubProject.url)
connection.set(githubProject.git)
developerConnection.set(githubProject.ssh)
}
}
public fun MavenPomDeveloperSpec.developer(
id: String,
name: String,
email: String,
action: MavenPomDeveloper.() -> Unit = {},
) {
developer {
this.id.set(id)
this.name.set(name)
this.email.set(email)
action()
}
}
public fun MavenPomContributorSpec.contributor(
name: String,
email: String,
action: MavenPomContributor.() -> Unit = {},
) {
contributor {
this.name.set(name)
this.email.set(email)
action()
}
}
| 0
|
Kotlin
|
0
| 0
|
944cb7d03b754ef15b86ed5b7d8f21d7adbe9226
| 2,094
|
build-logic
|
MIT License
|
src/main/kotlin/convention/publishing/dsl/MavenPom.kt
|
indramahkota
| 868,423,800
| false
|
{"Kotlin": 65624}
|
package convention.publishing.dsl
import org.gradle.api.publish.maven.MavenPom
import org.gradle.api.publish.maven.MavenPomContributor
import org.gradle.api.publish.maven.MavenPomContributorSpec
import org.gradle.api.publish.maven.MavenPomDeveloper
import org.gradle.api.publish.maven.MavenPomDeveloperSpec
import org.gradle.api.publish.maven.MavenPomLicenseSpec
public fun MavenPomLicenseSpec.mit() {
license {
name.set("MIT License")
url.set("https://opensource.org/licenses/mit-license.php")
}
}
public data class GithubProject(
var owner: String? = null,
var repository: String? = null,
) {
val url: String
get() = "$HTTPS$GITHUB_DOMAIN/$owner/$repository"
val ssh: String
get() = "$SSH$GITHUB_DOMAIN:$owner/$repository.git"
val git: String
get() = "$GIT$GITHUB_DOMAIN/$owner/$repository.git"
private companion object {
const val GIT = "scm:git:git://"
const val SSH = "scm:git:ssh://git@"
const val HTTPS = "https://"
const val GITHUB_DOMAIN = "github.com"
}
}
public fun MavenPom.setGitHubProject(
action: GithubProject.() -> Unit = {},
) {
val githubProject = GithubProject().apply {
action()
}
require(!githubProject.owner.isNullOrEmpty()) {
"GitHub project owner must be set"
}
require(!githubProject.repository.isNullOrEmpty()) {
"GitHub project repository must be set"
}
url.set(githubProject.url)
issueManagement {
url.set("${githubProject.url}/issues")
system.set("GitHub Issues")
}
scm {
url.set(githubProject.url)
connection.set(githubProject.git)
developerConnection.set(githubProject.ssh)
}
}
public fun MavenPomDeveloperSpec.developer(
id: String,
name: String,
email: String,
action: MavenPomDeveloper.() -> Unit = {},
) {
developer {
this.id.set(id)
this.name.set(name)
this.email.set(email)
action()
}
}
public fun MavenPomContributorSpec.contributor(
name: String,
email: String,
action: MavenPomContributor.() -> Unit = {},
) {
contributor {
this.name.set(name)
this.email.set(email)
action()
}
}
| 0
|
Kotlin
|
0
| 0
|
944cb7d03b754ef15b86ed5b7d8f21d7adbe9226
| 2,094
|
build-logic
|
MIT License
|
whetstone/compiler/src/main/kotlin/com/freeletics/mad/whetstone/parser/Reference.kt
|
freeletics
| 375,363,637
| false
| null |
package com.freeletics.mad.whetstone.parser
import com.squareup.anvil.annotations.ExperimentalAnvilApi
import com.squareup.anvil.compiler.internal.reference.AnnotatedReference
import com.squareup.anvil.compiler.internal.reference.AnnotationReference
import com.squareup.anvil.compiler.internal.reference.AnvilCompilationExceptionAnnotationReference
import com.squareup.anvil.compiler.internal.reference.ClassReference
import com.squareup.anvil.compiler.internal.reference.FunctionReference
import com.squareup.anvil.compiler.internal.reference.MemberFunctionReference
import com.squareup.anvil.compiler.internal.reference.MemberPropertyReference
import com.squareup.anvil.compiler.internal.reference.PropertyReference
import com.squareup.anvil.compiler.internal.reference.TopLevelFunctionReference
import com.squareup.anvil.compiler.internal.reference.argumentAt
import com.squareup.anvil.compiler.internal.reference.asClassName
import com.squareup.kotlinpoet.ClassName
import org.jetbrains.kotlin.descriptors.containingPackage
import org.jetbrains.kotlin.name.FqName
@OptIn(ExperimentalAnvilApi::class)
internal fun AnnotatedReference.findAnnotation(fqName: FqName): AnnotationReference? {
return annotations.find { it.fqName == fqName }
}
@OptIn(ExperimentalAnvilApi::class)
internal fun AnnotationReference.requireClassArgument(name: String, index: Int): ClassName {
return optionalClassArgument(name, index) ?:
throw AnvilCompilationExceptionAnnotationReference(this, "Couldn't find $name for $fqName")
}
@OptIn(ExperimentalAnvilApi::class)
internal fun AnnotationReference.optionalClassArgument(name: String, index: Int): ClassName? {
return argumentAt(name, index)?.value<ClassReference>()?.asClassName()
}
@OptIn(ExperimentalAnvilApi::class)
internal fun AnnotationReference.requireEnumArgument(name: String, index: Int): String {
return argumentAt(name, index)?.value<FqName>()?.shortName()?.asString() ?:
throw AnvilCompilationExceptionAnnotationReference(this, "Couldn't find $name for $fqName")
}
@OptIn(ExperimentalAnvilApi::class)
internal val AnnotatedReference.packageName: String
get() = when (this) {
is ClassReference -> packageName
is TopLevelFunctionReference -> packageName
is MemberPropertyReference -> declaringClass.packageName
is MemberFunctionReference -> declaringClass.packageName
else -> throw UnsupportedOperationException("Can't retrieve packageName for $this")
}
@OptIn(ExperimentalAnvilApi::class)
internal val TopLevelFunctionReference.packageName: String
get() = when (this) {
is TopLevelFunctionReference.Psi -> function.containingKtFile.packageFqName
is TopLevelFunctionReference.Descriptor -> function.containingPackage()!!
}.packageString()
@OptIn(ExperimentalAnvilApi::class)
internal val ClassReference.packageName: String
get() = packageFqName.packageString()
private fun FqName.packageString(): String {
return pathSegments().joinToString(separator = ".")
}
| 9
|
Kotlin
|
7
| 60
|
c6d34481b5bb90e8d720e6c7b018f87c0fe28f9a
| 3,022
|
mad
|
Apache License 2.0
|
z2-kotlin-plugin/src/hu/simplexion/z2/kotlin/adaptive/ir/air/visitors/AirElementVisitorVoid.kt
|
spxbhuhb
| 665,463,766
| false
|
{"Kotlin": 1586446, "CSS": 166528, "Java": 12046, "HTML": 1560, "JavaScript": 975}
|
/*
* Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.z2.kotlin.adaptive.ir.air.visitors
import hu.simplexion.z2.kotlin.adaptive.ir.air.*
interface AirElementVisitorVoid<out R> : AirElementVisitor<R, Nothing?> {
fun visitElement(element: AirElement): R
override fun visitElement(element: AirElement, data: Nothing?) = visitElement(element)
fun visitEntryPoint(airEntryPoint: AirEntryPoint) = visitElement(airEntryPoint)
override fun visitEntryPoint(airEntryPoint: AirEntryPoint, data: Nothing?) = visitEntryPoint(airEntryPoint)
fun visitClass(airClass: AirClass) = visitElement(airClass)
override fun visitClass(airClass: AirClass, data: Nothing?) = visitClass(airClass)
fun visitProperty(property: AirProperty) = visitElement(property)
override fun visitProperty(property: AirProperty, data: Nothing?) = visitProperty(property)
fun visitStateVariable(stateVariable: AirStateVariable) = visitProperty(stateVariable)
override fun visitStateVariable(stateVariable: AirStateVariable, data: Nothing?) = visitStateVariable(stateVariable)
fun visitDirtyMask(dirtyMask: AirDirtyMask) = visitProperty(dirtyMask)
override fun visitDirtyMask(dirtyMask: AirDirtyMask, data: Nothing?) = visitDirtyMask(dirtyMask)
fun visitFunction(function: AirFunction) = visitElement(function)
override fun visitFunction(function: AirFunction, data: Nothing?) = visitFunction(function)
fun visitBuilder(builder: AirBuilder) = visitFunction(builder)
override fun visitBuilder(builder: AirBuilder, data: Nothing?) = visitBuilder(builder)
fun visitBuilderSequence(builder: AirBuilderSequence) = visitBuilder(builder)
override fun visitBuilderSequence(builder: AirBuilderSequence, data: Nothing?) = visitBuilderSequence(builder)
fun visitBuilderCall(builder: AirBuilderCall) = visitBuilder(builder)
override fun visitBuilderCall(builder: AirBuilderCall, data: Nothing?) = visitBuilderCall(builder)
fun visitBuilderForLoop(builder: AirBuilderForLoop) = visitBuilder(builder)
override fun visitBuilderForLoop(builder: AirBuilderForLoop, data: Nothing?) = visitBuilderForLoop(builder)
fun visitBuilderWhen(builder: AirBuilderWhen) = visitBuilder(builder)
override fun visitBuilderWhen(builder: AirBuilderWhen, data: Nothing?) = visitBuilderWhen(builder)
fun visitExternalPatch(externalPatch: AirExternalPatch) = visitFunction(externalPatch)
override fun visitExternalPatch(externalPatch: AirExternalPatch, data: Nothing?) = visitExternalPatch(externalPatch)
fun visitExternalPatchSequence(externalPatch: AirExternalPatchSequence) = visitExternalPatch(externalPatch)
override fun visitExternalPatchSequence(externalPatch: AirExternalPatchSequence, data: Nothing?) = visitExternalPatchSequence(externalPatch)
fun visitExternalPatchCall(externalPatch: AirExternalPatchCall) = visitExternalPatch(externalPatch)
override fun visitExternalPatchCall(externalPatch: AirExternalPatchCall, data: Nothing?) = visitExternalPatchCall(externalPatch)
fun visitExternalPatchForLoop(externalPatch: AirExternalPatchForLoop) = visitExternalPatch(externalPatch)
override fun visitExternalPatchForLoop(externalPatch: AirExternalPatchForLoop, data: Nothing?) = visitExternalPatchForLoop(externalPatch)
fun visitExternalPatchWhen(externalPatch: AirExternalPatchWhen) = visitExternalPatch(externalPatch)
override fun visitExternalPatchWhen(externalPatch: AirExternalPatchWhen, data: Nothing?) = visitExternalPatchWhen(externalPatch)
fun visitFragmentFactory(fragmentFactory: AirFragmentFactory) = visitFunction(fragmentFactory)
override fun visitFragmentFactory(fragmentFactory: AirFragmentFactory, data: Nothing?) = visitFragmentFactory(fragmentFactory)
}
| 5
|
Kotlin
|
0
| 1
|
a7213ad95437796bc87674dd9530a95e1528901e
| 3,852
|
z2
|
Apache License 2.0
|
verik-compiler/src/main/kotlin/io/verik/compiler/check/mid/ValueParameterCheckerStage.kt
|
frwang96
| 269,980,078
| false
| null |
/*
* SPDX-License-Identifier: Apache-2.0
*/
package io.verik.compiler.check.mid
import io.verik.compiler.ast.element.declaration.kt.EKtAbstractFunction
import io.verik.compiler.ast.element.declaration.kt.EKtValueParameter
import io.verik.compiler.common.TreeVisitor
import io.verik.compiler.core.common.Core
import io.verik.compiler.main.ProjectContext
import io.verik.compiler.main.ProjectStage
import io.verik.compiler.message.Messages
/**
* Stage that checks for value parameters with types that should not ever be passed as a value argument.
*/
object ValueParameterCheckerStage : ProjectStage() {
override fun process(projectContext: ProjectContext) {
projectContext.project.accept(ValueParameterCheckerVisitor)
}
private object ValueParameterCheckerVisitor : TreeVisitor() {
override fun visitKtAbstractFunction(abstractFunction: EKtAbstractFunction) {
super.visitKtAbstractFunction(abstractFunction)
abstractFunction.valueParameters.forEach { checkValueParameter(it) }
}
private fun checkValueParameter(valueParameter: EKtValueParameter) {
if (valueParameter.type.isSubtype(Core.Vk.C_Module)) {
Messages.ILLEGAL_VALUE_PARAMETER_TYPE.on(valueParameter, valueParameter.type)
}
}
}
}
| 0
|
Kotlin
|
1
| 33
|
ee22969235460fd144294bcbcbab0338c638eb92
| 1,319
|
verik
|
Apache License 2.0
|
openai/api/src/main/kotlin/io/bluetape4k/openai/api/models/embedding/EmbeddingResult.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.openai.api.models.embedding
import com.fasterxml.jackson.annotation.JsonProperty
import io.bluetape4k.openai.api.models.ObjectId
import io.bluetape4k.openai.api.models.Usage
import io.bluetape4k.openai.api.models.model.ModelId
import java.io.Serializable
/**
* Embeddings response
*
* @property embeddings An embedding results.
* @property usage Emdedding usage data.
*/
data class EmbeddingResult(
@get:JsonProperty("object")
val objectId: ObjectId? = null,
val data: List<Embedding>,
val model: ModelId,
val usage: Usage,
): Serializable
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 589
|
bluetape4k
|
MIT License
|
app/src/main/java/it/unibs/mp/horace/backend/DateTimeFormatter.kt
|
H3isenb3rg
| 604,173,455
| false
| null |
package it.unibs.mp.horace.backend
import android.content.Context
import it.unibs.mp.horace.R
import java.time.LocalDate
import java.time.LocalTime
import java.time.format.DateTimeFormatter
class DateTimeFormatter(val context: Context) {
fun formatDate(date: LocalDate): String {
return when (date) {
LocalDate.now() -> {
context.getString(R.string.today)
}
LocalDate.now().minusDays(1) -> {
context.getString(R.string.yesterday)
}
else -> date.format(DateTimeFormatter.ofPattern("E, d MMM yyyy"))
}
}
fun formatTime(time: LocalTime): String = time.format(DateTimeFormatter.ofPattern("HH:mm"))
fun formatDuration(duration: Int): String {
val hours = duration / 3600
val minutes = (duration % 3600) / 60
val minutesString = context.resources.getQuantityString(R.plurals.minutes, minutes, minutes)
val hoursString = context.resources.getQuantityString(R.plurals.hours, hours, hours)
return if (hours == 0) {
minutesString
} else if (minutes == 0) {
hoursString
} else {
"$hoursString $minutesString"
}
}
}
| 9
|
Kotlin
|
0
| 0
|
807d5f55d3cdfc9e45b9a2db6cf736335e8e9d19
| 1,239
|
MobileProgramming2023
|
MIT License
|
baselibs/src/main/java/com/cxz/kotlin/baselibs/mvp/IView.kt
|
iceCola7
| 157,877,897
| false
| null |
package com.cxz.kotlin.baselibs.mvp
/**
* @author chenxz
* @date 2018/11/18
* @desc IView
*/
interface IView {
/**
* 显示加载
*/
fun showLoading()
/**
* 隐藏加载
*/
fun hideLoading()
/**
* 使用默认的样式显示信息: CustomToast
*/
fun showDefaultMsg(msg: String)
/**
* 显示信息
*/
fun showMsg(msg: String)
/**
* 显示错误信息
*/
fun showError(errorMsg: String)
}
| 1
|
Kotlin
|
40
| 160
|
1a57b38ab15c718f4fce77fc70486cc71a3d507a
| 430
|
KotlinMVPSamples
|
Apache License 2.0
|
serialization-djvm/src/main/kotlin/net/corda/serialization/djvm/serializers/SandboxZonedDateTimeSerializer.kt
|
corda
| 70,137,417
| false
| null |
package net.corda.serialization.djvm.serializers
import net.corda.djvm.rewiring.SandboxClassLoader
import net.corda.serialization.djvm.deserializers.ZonedDateTimeDeserializer
import net.corda.serialization.djvm.toSandboxAnyClass
import net.corda.serialization.internal.amqp.CustomSerializer
import net.corda.serialization.internal.amqp.SerializerFactory
import net.corda.serialization.internal.amqp.custom.ZonedDateTimeSerializer.ZonedDateTimeProxy
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.util.function.Function
class SandboxZonedDateTimeSerializer(
classLoader: SandboxClassLoader,
taskFactory: Function<Class<out Function<*, *>>, out Function<in Any?, out Any?>>,
factory: SerializerFactory
) : CustomSerializer.Proxy<Any, Any>(
clazz = classLoader.toSandboxAnyClass(ZonedDateTime::class.java),
proxyClass = classLoader.toSandboxAnyClass(ZonedDateTimeProxy::class.java),
factory = factory
) {
private val task = taskFactory.apply(ZonedDateTimeDeserializer::class.java)
private val creator: Function<in Any?, out Any?>
init {
val createTask = clazz.getMethod(
"createDJVM",
classLoader.toSandboxClass(LocalDateTime::class.java),
classLoader.toSandboxClass(ZoneOffset::class.java),
classLoader.toSandboxClass(ZoneId::class.java)
)
creator = task.andThen { input ->
@Suppress("unchecked_cast", "SpreadOperator")
createTask(null, *(input as Array<out Any?>))!!
}
}
override val deserializationAliases = aliasFor(ZonedDateTime::class.java)
override fun toProxy(obj: Any): Any = abortReadOnly()
override fun fromProxy(proxy: Any): Any {
return creator.apply(proxy)!!
}
}
| 57
| null |
1090
| 3,952
|
1eb3b3b42b2b916b7f81354238ccd3ce685b0bd3
| 1,827
|
corda
|
Apache License 2.0
|
android/src/main/java/com/facebook/flipper/plugins/uidebugger/descriptors/FragmentFrameworkDescriptor.kt
|
facebook
| 129,283,183
| false
| null |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.flipper.plugins.uidebugger.descriptors
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.facebook.flipper.plugins.uidebugger.model.Bounds
import com.facebook.flipper.plugins.uidebugger.model.Inspectable
import com.facebook.flipper.plugins.uidebugger.model.InspectableObject
import com.facebook.flipper.plugins.uidebugger.model.InspectableValue
import com.facebook.flipper.plugins.uidebugger.model.MetadataId
class FragmentFrameworkDescriptor(val register: DescriptorRegister) :
ChainedDescriptor<android.app.Fragment>() {
private val NAMESPACE = "Fragment"
private var SectionId =
MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, NAMESPACE)
override fun onGetName(node: android.app.Fragment): String {
return node.javaClass.simpleName
}
override fun onGetBounds(node: android.app.Fragment): Bounds? = Bounds(0, 0, 0, 0)
override fun onGetChildren(node: android.app.Fragment): List<Any> =
node.view?.let { view -> listOf(view) } ?: listOf()
override fun onGetAttributes(
node: android.app.Fragment,
attributeSections: MutableMap<MetadataId, InspectableObject>
) {
val args: Bundle = node.arguments
val props = mutableMapOf<Int, Inspectable>()
for (key in args.keySet()) {
val metadata = MetadataRegister.get(NAMESPACE, key)
val identifier =
metadata?.id ?: MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, key)
when (val value = args[key]) {
is Number -> props[identifier] = InspectableValue.Number(value)
is Boolean -> props[identifier] = InspectableValue.Boolean(value)
is String -> props[identifier] = InspectableValue.Text(value)
}
}
attributeSections[SectionId] = InspectableObject(props.toMap())
}
}
| 500
| null |
953
| 13,340
|
533f0886100aebb3f1207465a7a2165247f5efc1
| 2,022
|
flipper
|
MIT License
|
app/src/main/java/pl/sienczykm/templbn/utils/EmptyStringTypeAdapter.kt
|
mat-sienczyk
| 193,071,707
| false
| null |
package pl.sienczykm.templbn.utils
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import java.lang.reflect.Type
class EmptyStringTypeAdapter<T>
private constructor() : JsonDeserializer<T> {
@Throws(JsonParseException::class)
override fun deserialize(jsonElement: JsonElement, type: Type, context: JsonDeserializationContext): T? {
if (jsonElement.isJsonPrimitive) {
val jsonPrimitive = jsonElement.asJsonPrimitive
if (jsonPrimitive.isString && jsonPrimitive.asString.isEmpty()) {
return null
}
}
return context.deserialize<T>(jsonElement, type)
}
}
| 0
|
Kotlin
|
1
| 2
|
9c87e40d685d62a4e523708428c2f8ec44494948
| 761
|
LubelskieStacjePogodowe
|
Apache License 2.0
|
features/letterboxd/api/src/main/kotlin/com/letterboxd/authentication/AccessTokenFetcher.kt
|
mr-archano
| 146,216,727
| false
| null |
package com.letterboxd.authentication
import io.reactivex.Single
interface AccessTokenFetcher {
fun createAccessToken(username: String, password: String): Single<AccessToken>
fun refreshAccessToken(refreshToken: RefreshToken): Single<AccessToken>
}
| 0
|
Kotlin
|
0
| 2
|
ce0878d93549121beb5b79dda7bd2cd6c4ae8783
| 260
|
playground
|
Apache License 2.0
|
src/main/kotlin/com/papsign/ktor/openapigen/annotations/type/string/length/MinLength.kt
|
papsign
| 186,148,881
| false
| null |
package com.papsign.ktor.openapigen.annotations.type.string.length
import com.papsign.ktor.openapigen.schema.processor.SchemaProcessorAnnotation
import com.papsign.ktor.openapigen.validation.ValidatorAnnotation
@Target(AnnotationTarget.TYPE, AnnotationTarget.PROPERTY)
@SchemaProcessorAnnotation(MinLengthProcessor::class)
@ValidatorAnnotation(MinLengthProcessor::class)
annotation class MinLength(val value: Int, val errorMessage: String = "")
| 24
| null |
35
| 172
|
8362dafa8a8b701983ad7d0119a15a12b863953f
| 446
|
Ktor-OpenAPI-Generator
|
Apache License 2.0
|
sdkpushexpress/src/main/java/com/pushexpress/sdk/repository/ApiRepositoryImpl.kt
|
pushexpress
| 600,907,986
| false
| null |
package com.pushexpress.sdk.repository
import android.content.Context
import android.telephony.TelephonyManager
import android.util.Log
import com.google.android.gms.ads.identifier.AdvertisingIdClient.getAdvertisingIdInfo
import com.pushexpress.sdk.local_settings.SdkSettingsRepository
import com.pushexpress.sdk.retrofit.RetrofitBuilder
import com.pushexpress.sdk.utils.retryHttpIO
import kotlinx.coroutines.*
import java.util.*
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.ktx.messaging
import com.pushexpress.sdk.models.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
internal class ApiRepositoryImpl(
private val context: Context,
private val settingsRepository: SdkSettingsRepository
) : ApiRepository {
private val builder = RetrofitBuilder(SDK_PUSHEXPRESS_COMMON_URL)
private val sdkService = builder.sdkService
private var devicesJob: Job = Job()
private var heartBeatsJob: Job = Job()
private var commonJob: Job = SupervisorJob()
private val handler = CoroutineExceptionHandler { _, exception ->
println("SdkPushExpress: CoroutineExceptionHandler got $exception")
}
private val scope = CoroutineScope(Dispatchers.IO + commonJob + handler)
override suspend fun doApiLoop() =
withContext(scope.coroutineContext) {
Log.d(TAG, "doApiLoop")
devicesJob.cancel()
heartBeatsJob.cancel()
try {
val res =
retryHttpIO(times = 10) { sdkService.sendDeviceConfig(createDevicesRequest()) }
repeatRequestDevices(res.device_intvl)
repeatRequestHeartBeat(res.hbeat_intvl)
} catch (e: Exception) {
Log.d(TAG, "doApiLoop: unhandled error: $e")
// repeat loop now
repeatRequestDevices(1)
}
}
// send only once after appId or ExtId changes
override suspend fun sendDeviceConfig() =
withContext(scope.coroutineContext) {
Log.d(TAG, "sendDeviceConfig")
sdkService.sendDeviceConfig(createDevicesRequest())
}
override suspend fun sendLifecycleEvent(event: EventsLifecycle) {
scope.launch {
val settings = settingsRepository.getSdkSettings()
Log.d(TAG, "sendLifecycleEvent ${event.event}")
sdkService.sendLifecycleEvent(
EventsLifecycleRequest(
app_id = settings.appId,
ic_token = settings.instanceToken,
event = event.event
)
)
}
}
override fun sendNotificationEvent(messageId: String, event: NotificationEvent) {
scope.launch {
Log.d(TAG, "sendNotificationEvent")
val sdkSettings = settingsRepository.getSdkSettings()
sdkService.sendNotificationEvent(
NotificationEventRequest(
app_id = sdkSettings.appId,
ic_token = sdkSettings.instanceToken,
event = event.event,
msg_id = messageId
)
)
}
}
private fun repeatRequestDevices(timeSec: Long) {
devicesJob = scope.launch {
Log.d(TAG, "repeatRequestDevices")
timeSec.let {
delay(it * 1000)
ensureActive()
doApiLoop()
}
}
}
private fun repeatRequestHeartBeat(timeSec: Long) {
heartBeatsJob = scope.launch {
Log.d(TAG, "repeatRequestHeartBeat")
timeSec.let {
while (isActive) {
delay(it * 1000)
ensureActive()
sendLifecycleEvent(EventsLifecycle.HBEAT)
}
}
}
}
private suspend fun createDevicesRequest(): DeviceConfigRequest {
val advId = try {
getAdvertisingIdInfo(context).id.orEmpty()
} catch (e: Exception) {
null
}
val sdkSettings = settingsRepository.getSdkSettings()
val dc = DeviceConfigRequest(
app_id = sdkSettings.appId,
ic_token = sdkSettings.instanceToken,
ext_id = sdkSettings.extId,
lang = Locale.getDefault().language,
country_net = getCountryCode(),
country_sim = getCountrySim().uppercase(),
timezone = TimeZone.getDefault().rawOffset / 1000,
install_ts = sdkSettings.installTs,
fcm_token = sdkSettings.firebaseToken ?: getFirebaseToken(),
ad_id = advId.orEmpty(),
onscreen_cnt = sdkSettings.onscreenCnt,
onscreen_sec = sdkSettings.onscreenSec
)
Log.d(TAG, "deviceConfig: $dc")
return dc
}
private suspend fun getFirebaseToken(): String {
return suspendCoroutine { continuation ->
Firebase.messaging.token.addOnCompleteListener {
if (it.isSuccessful) {
Log.d(TAG, "Fetched FCM registration: token=${it.result}")
settingsRepository.saveFirebaseToken(it.result)
continuation.resume(it.result)
} else {
continuation.resume("")
}
}
}
}
private fun getCountrySim(): String {
val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
return tm.simCountryIso
}
private fun getCountryCode(): String {
val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
return tm.networkCountryIso.uppercase()
}
companion object {
private const val SDK_PUSHEXPRESS_COMMON_URL = "https://sdk.push.express/r/v1/"
private const val TAG = "SdkPushExpress"
}
}
| 0
|
Kotlin
|
0
| 2
|
d4d3a824b5633a161ae6c87d846f6e922cd4b56b
| 5,906
|
pushexpress-android-sdk
|
Apache License 2.0
|
app/src/main/java/com/spindox/composetemplate/api/BaseRepo.kt
|
michele-marconi
| 712,552,242
| false
|
{"Kotlin": 53719}
|
package com.spindox.composetemplate.api
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import retrofit2.Response
import timber.log.Timber
import java.io.IOException
abstract class BaseRepo {
// This is a generic function to handle all API calls
suspend fun <T> safeApiCall(apiToBeCalled: suspend () -> Response<T>): Resource<T> {
return withContext(Dispatchers.IO) {
try {
val response: Response<T> = apiToBeCalled()
if (response.isSuccessful)
Resource.Success(data = response.body())
else
Resource.Error(key = response.errorBody()?.toString() ?: "Something went wrong")
} catch (e: HttpException) {
Resource.Error<T>(key = e.message ?: "Something went wrong")
.also { Timber.e(e.message) }
} catch (e: IOException) {
Resource.Error("Please check your network connection")
} catch (e: Exception) {
Resource.Error<T>(key = e.message ?: "Something went wrong")
.also { Timber.e(e.message) }
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c7c471b04207b8943a073a4f119cad32bd1764f4
| 1,222
|
compose-template
|
MIT License
|
noteServer/note/src/main/kotlin/com/rabbitcat/note/aop/LogAspect.kt
|
bcc829
| 155,066,475
| false
| null |
package com.rabbitcat.note.aop
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.*
@Component
@Aspect
class LogAspect {
val logger = LoggerFactory.getLogger(javaClass)
@Before("execution(* com.rabbitcat.note.controller.*.*.*(..))")
fun controllerLogging(pjp: JoinPoint){
logger.info("-------------------------------------")
/* 전달되는 모든 파라미터들을 Object의 배열로 가져온다. */
logger.info("1 파라미터:" + Arrays.toString(pjp.args))
/* 해당 Advice의 타입을 알아낸다. */
logger.info("2 Advice의 타입:" + pjp.kind)
/* 실행하는 대상 객체의 메소드에 대한 정보를 알아낼 때 사용 */
logger.info("3 객체의 메소드 이름:" + pjp.signature.name)
/* target 객체를 알아낼 때 사용 */
logger.info("4 target 객체:" + pjp.target.toString())
/* Advice를 행하는 객체를 알아낼 때 사용 */
//logger.info("5 Advice를 행하는 객체:" +pjp.`this`.toString())
logger.info("-------------------------------------")
}
@Around("execution(* com.rabbitcat.note.controller.*.*.*(..))")
fun controllerTimeLog(pjp: ProceedingJoinPoint): Any {
val startTime = System.currentTimeMillis()
//실제 타겟을 실행하는 부분이다. 이 부분이 없으면 advice가 적용된 메소드가 동작을 안할것 같다.
val result = pjp.proceed() //proceed는 Exception 보다 상위 Throwable을 처리해야 한다.
logger.info("==============================")
val endTime = System.currentTimeMillis()
logger.info(pjp.signature.name + " 실행시간 : " + (endTime - startTime) + "ms") //target 메소드의 동작 시간을 출력한다.
logger.info("==============================")
//Around를 사용할 경우 반드시 Object를 리턴해야 한다.
return result
}
@Around("execution(* com.rabbitcat.note.service.fileStorage.FileStorageService.downloadFile(..))")
fun fileDownloadLog(pjp: ProceedingJoinPoint): Any{
val startTime = System.currentTimeMillis()
val result = pjp.proceed()
logger.info("==============================")
val endTime = System.currentTimeMillis()
logger.info(pjp.signature.name)
logger.info("파라미터: " + Arrays.toString(pjp.args))
logger.info("파일 다운로드 완료")
logger.info("파일 다운로드 시간 : " + (endTime - startTime) + "ms") //target 메소드의 동작 시간을 출력한다.
logger.info("==============================")
return result
}
@Around("execution(* com.rabbitcat.note.service.fileStorage.FileStorageService.uploadFile(..))")
fun fileUploadLog(pjp: ProceedingJoinPoint): Any{
val startTime = System.currentTimeMillis()
val result = pjp.proceed()
logger.info("==============================")
val endTime = System.currentTimeMillis()
logger.info(pjp.signature.name)
logger.info("파라미터: " + Arrays.toString(pjp.args))
logger.info("파일 업로드 완료")
logger.info("업로드 시간 : " + (endTime - startTime) + "ms") //target 메소드의 동작 시간을 출력한다.
logger.info("==============================")
return result
}
@Around("execution(* com.rabbitcat.note.service.fileStorage.FileStorageService.deleteFile(..))")
fun fileDeleteLog(pjp: ProceedingJoinPoint): Any{
val startTime = System.currentTimeMillis()
val result = pjp.proceed()
logger.info("==============================")
val endTime = System.currentTimeMillis()
logger.info(pjp.signature.name)
logger.info("파라미터: " + Arrays.toString(pjp.args))
logger.info("파일 삭제 완료")
logger.info("삭제 시간 : " + (endTime - startTime) + "ms") //target 메소드의 동작 시간을 출력한다.
logger.info("==============================")
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
86de7b7de8acea55072bf7cc083d3cb85e7f82bb
| 3,801
|
noteServer
|
Apache License 2.0
|
app/src/main/java/cn/lelight/iot/blemesh/demo/CommonDeviceActivity.kt
|
LeMeshIoT
| 462,249,715
| false
|
{"Kotlin": 60213, "Java": 1411}
|
package cn.lelight.iot.blemesh.demo
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.InputType
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.lelight.iot.blemesh.demo.databinding.ActivityCommonDeviceBinding
import cn.lelight.leiot.data.bean.DeviceBean
import cn.lelight.leiot.data.bean.base.DpBean
import cn.lelight.leiot.data.leenum.DeviceType
import cn.lelight.leiot.data.leenum.devsubtype.CommercialDevSubType
import cn.lelight.leiot.data.leenum.devsubtype.SensorDevSubType
import cn.lelight.leiot.data.leenum.dps.*
import cn.lelight.leiot.data.leenum.dps.commercial.CardElectriDp
import cn.lelight.leiot.data.leenum.dps.commercial.TempControllerDp
import cn.lelight.leiot.data.leenum.dps.sub.RadarSensorDp
import cn.lelight.leiot.sdk.LeHomeSdk
import cn.lelight.leiot.sdk.adapter.CommonAdapter
import cn.lelight.leiot.sdk.adapter.ViewHolder
import cn.lelight.leiot.sdk.api.callback.IControlCallback
import cn.lelight.leiot.sdk.api.callback.data.IDevDataListener
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.input.input
import com.afollestad.materialdialogs.list.listItems
class CommonDeviceActivity : AppCompatActivity(), IDevDataListener {
private var dps: ArrayList<DpPackageBean> = ArrayList()
private var targetBean: DeviceBean? = null
private var dpAdapter: DpAdapter? = null
private lateinit var binding: ActivityCommonDeviceBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCommonDeviceBinding.inflate(layoutInflater)
setContentView(binding.root)
//
//
val dataManger = LeHomeSdk.getDataManger()
if (dataManger == null) {
finish()
return
}
val id = intent.getStringExtra("ID")
targetBean = dataManger.getDeviceBean(id)
if (targetBean == null) {
finish()
return
}
//
if (supportActionBar != null) {
supportActionBar!!.title = targetBean!!.mac
supportActionBar!!.setDisplayShowHomeEnabled(true)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
//
binding.btnSendHeartbeat.setOnClickListener {
targetBean?.heartBeat()
}
//
initData()
LeHomeSdk.getInstance().registerDevDataChangeListener(this)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
private fun initData() {
if (targetBean!!.getType() == DeviceType.Light.type) {
for (value in LightDp.values()) {
// 添加灯具的功能列表
val dpPackageBean = DpPackageBean()
dpPackageBean.id = value.dpId
dpPackageBean.type = value.type
dpPackageBean.name = value.getName()
dpPackageBean.obj = value.desc
//
dps.add(dpPackageBean)
}
} else if (targetBean!!.getType() == DeviceType.Curtain.type) {
for (value in CurtainDp.values()) {
// 添加灯具的功能列表
val dpPackageBean = DpPackageBean()
dpPackageBean.id = value.dpId
dpPackageBean.type = value.type
dpPackageBean.name = value.getName()
dpPackageBean.obj = value.desc
//
dps.add(dpPackageBean)
}
} else if (targetBean!!.getType() == DeviceType.Switch.type) {
for (value in SwitchDp.values()) {
// 添加灯具的功能列表
val dpPackageBean = DpPackageBean()
dpPackageBean.id = value.dpId
dpPackageBean.type = value.type
dpPackageBean.name = value.getName()
//
dps.add(dpPackageBean)
}
} else if (targetBean!!.getType() == DeviceType.Sensor.type) {
if (targetBean!!.getDevSubType() == SensorDevSubType.RADAR_A3.type) {
for (value in RadarSensorDp.values()) {
val dpPackageBean = DpPackageBean()
dpPackageBean.id = value.dpId
dpPackageBean.type = value.type
dpPackageBean.name = value.getName()
dpPackageBean.mode = value.mode
dpPackageBean.obj = value.desc
//
dps.add(dpPackageBean)
}
} else {
for (value in SensorDp.values()) {
val dpPackageBean = DpPackageBean()
dpPackageBean.id = value.dpId
dpPackageBean.type = value.type
dpPackageBean.name = value.getName()
dpPackageBean.mode = value.mode
//
dps.add(dpPackageBean)
}
}
} else if (targetBean!!.getType() == DeviceType.Commercial.type) {
if (targetBean!!.getDevSubType() == CommercialDevSubType.CardElectri.type) {
for (value in CardElectriDp.values()) {
val dpPackageBean = DpPackageBean()
dpPackageBean.id = value.dpId
dpPackageBean.type = value.type
dpPackageBean.name = value.getName()
dpPackageBean.mode = value.mode
//
dps.add(dpPackageBean)
}
} else if (targetBean!!.getDevSubType() == CommercialDevSubType.TempController.type) {
for (value in TempControllerDp.values()) {
val dpPackageBean = DpPackageBean()
dpPackageBean.id = value.dpId
dpPackageBean.type = value.type
dpPackageBean.name = value.getName()
dpPackageBean.mode = value.mode
dpPackageBean.obj = value.desc
//
dps.add(dpPackageBean)
}
}
}
//
for (dp in dps) {
//==//LelogUtil.e("-----" + dp.toString());
}
dpAdapter = DpAdapter(this, dps)
binding.lvDps.setAdapter(dpAdapter)
}
inner class DpAdapter(context: Context?, datas: List<DpPackageBean>) :
CommonAdapter<DpPackageBean>(context, datas, R.layout.item_common_dp) {
override fun convert(holder: ViewHolder, dpPackageBean: DpPackageBean) {
holder.getTextView(R.id.tv_dp_id).text = dpPackageBean.id.toString() + ""
holder.getTextView(R.id.tv_dp_type).text = dpPackageBean.type.toString() + ""
for (value in DpType.values()) {
if (value.type == dpPackageBean.type) {
holder.getTextView(R.id.tv_dp_type).text = value.getName()
break
}
}
//
if (targetBean!!.getDps().containsKey(dpPackageBean.id)) {
holder.getTextView(R.id.tv_dp_value)
.setText(targetBean!!.getDps().get(dpPackageBean.id).toString() + "")
} else {
holder.getTextView(R.id.tv_dp_value).text = "无"
}
//
//
if (dpPackageBean.mode == "rw") {
holder.getTextView(R.id.tv_dp_mode).text = "可下发可上报"
} else if (dpPackageBean.mode == "ro") {
holder.getTextView(R.id.tv_dp_mode).text = "仅上报"
} else if (dpPackageBean.mode == "wr") {
holder.getTextView(R.id.tv_dp_mode).text = "仅下发"
}
//
holder.getTextView(R.id.tv_dp_name).text = dpPackageBean.name
//
holder.getmConverView().setOnClickListener {
if (dpPackageBean.mode == "ro") {
} else {
if (dpPackageBean.type == DpType.BOOL.type) {
showBoolDialog(dpPackageBean)
} else if (dpPackageBean.type == DpType.VALUE.type) {
showInputValueDialog(dpPackageBean)
} else if (dpPackageBean.type == DpType.STR.type) {
showInputStrDialog(dpPackageBean)
} else if (dpPackageBean.type == DpType.ENUM.type) {
if (dpPackageBean.obj is Array<*>) {
showSelectEnumDialog(dpPackageBean)
}
}
}
}
}
}
@SuppressLint("CheckResult")
private fun showInputValueDialog(dpPackageBean: DpPackageBean) {
//
MaterialDialog(this)
.show {
title(text = dpPackageBean.name!!)
message(text = "请根据具体范围输入数值\n本弹窗不做范围限制,仅作调试测试用")
input(
hint = "输入数值",
allowEmpty = false,
inputType = InputType.TYPE_CLASS_NUMBER
) { dialog, input ->
try {
val value = input.toString().toInt()
//
targetBean!!.sendDp(
DpBean(dpPackageBean.id, dpPackageBean.type, value),
object : IControlCallback {
override fun onSuccess() {
Toast.makeText(
this@CommonDeviceActivity,
"发送成功",
Toast.LENGTH_SHORT
).show()
}
override fun onFail(code: Int, msg: String) {
Toast.makeText(
this@CommonDeviceActivity,
"发送失败:$msg",
Toast.LENGTH_SHORT
)
.show()
}
})
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
@SuppressLint("CheckResult")
private fun showSelectEnumDialog(dpPackageBean: DpPackageBean) {
//
MaterialDialog(this)
.show {
title(text = dpPackageBean.name)
listItems(items = (dpPackageBean.obj as Array<String>).toList()) { dialog, index, text ->
targetBean!!.sendDp(DpBean(
dpPackageBean.id,
dpPackageBean.type,
text.toString()
),
object : IControlCallback {
override fun onSuccess() {
Toast.makeText(
this@CommonDeviceActivity,
"发送成功",
Toast.LENGTH_SHORT
).show()
}
override fun onFail(code: Int, msg: String) {
Toast.makeText(
this@CommonDeviceActivity,
"发送失败:$msg",
Toast.LENGTH_SHORT
).show()
}
})
}
}
}
@SuppressLint("CheckResult")
private fun showInputStrDialog(dpPackageBean: DpPackageBean) {
MaterialDialog(this)
.show {
title(text = dpPackageBean.name!!)
message(text = "请根据具体范围输入数值\n本弹窗不做范围限制,仅作调试测试用")
input(
hint = "输入内容",
allowEmpty = false
) { dialog, input ->
try {
val value = input.toString()
// todo
targetBean!!.sendDp(
DpBean(dpPackageBean.id, dpPackageBean.type, value),
object : IControlCallback {
override fun onSuccess() {
Toast.makeText(
this@CommonDeviceActivity,
"发送成功",
Toast.LENGTH_SHORT
).show()
}
override fun onFail(code: Int, msg: String) {
Toast.makeText(
this@CommonDeviceActivity,
"发送失败:$msg",
Toast.LENGTH_SHORT
)
.show()
}
})
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
@SuppressLint("CheckResult")
private fun showBoolDialog(dpPackageBean: DpPackageBean) {
val myItems = listOf("打开", "关闭")
MaterialDialog(this).show {
title(text = dpPackageBean.name)
listItems(items = myItems) { dialog, index, text ->
targetBean!!.sendDp(
DpBean(dpPackageBean.id, dpPackageBean.type, index == 0),
object : IControlCallback {
override fun onSuccess() {}
override fun onFail(code: Int, msg: String) {
Toast.makeText(
this@CommonDeviceActivity,
"fail:$msg",
Toast.LENGTH_SHORT
)
.show()
}
})
}
}
}
inner class DpPackageBean {
var id = 0
var type = 0
var mode: String? = null
var name: String? = null
var obj: Any? = null
override fun toString(): String {
return "DpPackageBean{" +
"id=" + id +
", type=" + type +
", name='" + name + '\'' +
'}'
}
}
override fun onDeviceAdd(p0: String?) {
}
override fun onStatusChanged(p0: String?, p1: Boolean) {
}
override fun onDpUpdate(p0: String?, p1: Int, p2: Int, p3: Any?) {
}
override fun onDevInfoUpdate(p0: String?) {
if (dpAdapter != null) {
dpAdapter!!.notifyDataSetChanged()
}
}
override fun onRemoved(p0: String?) {
}
override fun onDestroy() {
LeHomeSdk.getInstance().unRegisterDevDataChangeListener(this)
super.onDestroy()
}
}
| 1
|
Kotlin
|
0
| 0
|
80837f5dad923cab33b761c1323066d764dbf730
| 15,420
|
LeMesh-blemesh-android-sdk-sample-kotlin
|
MIT License
|
src/test/kotlin/days/Day12Test.kt
|
butnotstupid
| 571,247,661
| false
| null |
package days
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.Is.`is`
import org.junit.jupiter.api.Test
class Day12Test {
private val dayTwelve = Day12()
@Test
fun testPartOne() {
val partOne = dayTwelve.partOne()
println("\nPART ONE: $partOne")
assertThat(partOne, `is`(361))
}
@Test
fun testPartTwo() {
val partTwo = dayTwelve.partTwo()
println("PART TWO: $partTwo\n")
assertThat(partTwo, `is`(354))
}
}
| 0
|
Kotlin
|
0
| 0
|
4760289e11d322b341141c1cde34cfbc7d0ed59b
| 508
|
aoc-2022
|
Creative Commons Zero v1.0 Universal
|
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/photos/GetAllExtendedResponse.kt
|
alatushkin
| 156,866,851
| false
| null |
package name.alatushkin.api.vk.generated.photos
open class GetAllExtendedResponse(
val count: Long? = null,
val items: Array<PhotoFullXtrRealOffset>? = null,
val more: Boolean? = null
)
| 2
|
Kotlin
|
3
| 10
|
123bd61b24be70f9bbf044328b98a3901523cb1b
| 199
|
kotlin-vk-api
|
MIT License
|
src/test/kotlin/dev/olog/flow/test/observer/FlowTestCollectorImplErrorMessagesTest.kt
|
ologe
| 235,895,634
| false
| null |
package dev.olog.flow.test.observer
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.AfterClass
import org.junit.Assert.assertEquals
import org.junit.BeforeClass
import org.junit.Test
class FlowTestCollectorImplErrorMessagesTest {
data class TestModel(
val id: Long,
val firstName: String,
val lastName: String,
) {
companion object {
val item1 = TestModel(1, "firstName1", "lastName1")
val item2 = TestModel(2, "firstName2", "lastName2")
val item3 = TestModel(3, "firstName3", "lastName3")
}
}
companion object {
private var messages: MutableList<String>? = null
@BeforeClass
@JvmStatic
fun setup() {
messages = mutableListOf()
}
@AfterClass
@JvmStatic
fun teardown() {
// sort then print all the messages to have an overview on how consistent are message
for (s in messages?.sorted().orEmpty()) {
println(s)
}
messages = null
}
}
@Test
fun `test valueAt, case no values`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf<TestModel>()
flow.test(this) {
try {
valueAt(0)
} catch (ex: Throwable) {
ex.printAndAssert("No values (values = 0, has error = false, completed = true)")
}
}
}
@Test
fun `test valueAt, case out of bound lower`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
valueAt(-1)
} catch (ex: Throwable) {
ex.printAndAssert("Index -1 is out of range [0, 1) (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test valueAt, case out of bound upper`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
valueAt(2)
} catch (ex: Throwable) {
ex.printAndAssert("Index 2 is out of range [0, 1) (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test assertComplete message`() = runTest(UnconfinedTestDispatcher()) {
val flow = MutableStateFlow(Unit)
flow.test(this) {
try {
assertComplete()
} catch (ex: Throwable) {
ex.printAndAssert("Not completed! (values = 1, has error = false, completed = false)")
}
}
}
@Test
fun `test assertNotComplete message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
assertNotComplete()
} catch (ex: Throwable) {
ex.printAndAssert("Completed! (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test assertNoErrors message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flow<Unit> {
throw RuntimeException("message")
}
flow.test(this) {
try {
assertNoErrors()
} catch (ex: Throwable) {
ex.printAndAssert("Error present: java.lang.RuntimeException: message (values = 0, has error = true, completed = true)")
}
}
}
@Test
fun `test assertError message, case no errors`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
assertError { it is RuntimeException }
} catch (ex: Throwable) {
ex.printAndAssert("No errors (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test assertError message, case wrong error`() = runTest(UnconfinedTestDispatcher()) {
val flow = flow<Unit> {
throw IllegalArgumentException("message")
}
flow.test(this) {
try {
assertError { it is IndexOutOfBoundsException }
} catch (ex: Throwable) {
ex.printAndAssert("Predicate doesn't match, got: java.lang.IllegalArgumentException: message (values = 0, has error = true, completed = true)")
}
}
}
@Test
fun `test assertError java class message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flow<Unit> {
throw java.lang.IllegalArgumentException("message")
}
flow.test(this) {
try {
assertError(IndexOutOfBoundsException::class.java)
} catch (ex: Throwable) {
ex.printAndAssert("Predicate doesn't match, got: java.lang.IllegalArgumentException: message (values = 0, has error = true, completed = true)")
}
}
}
@Test
fun `test assertError kotlin class message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flow<Unit> {
throw IllegalArgumentException("message")
}
flow.test(this) {
try {
assertError(IndexOutOfBoundsException::class)
} catch (ex: Throwable) {
ex.printAndAssert("Predicate doesn't match, got: java.lang.IllegalArgumentException: message (values = 0, has error = true, completed = true)")
}
}
}
@Test
fun `test assertErrorMessage message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flow<Unit> {
throw IllegalArgumentException("message")
}
flow.test(this) {
try {
assertErrorMessage("expected message")
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected: expected message\ngot: message (values = 0, has error = true, completed = true)")
}
}
}
@Test
fun `test assertValue message, case value + empty list`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf<TestModel>()
flow.test(this) {
try {
assertValue(value = TestModel.item1)
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected: TestModel(id=1, firstName=firstName1, lastName=lastName1) (class: TestModel)\ngot: [] (values = 0, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValue message, case value + 2 items list`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1, TestModel.item2, TestModel.item3)
flow.test(this) {
try {
assertValue(value = TestModel.item1)
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected: TestModel(id=1, firstName=firstName1, lastName=lastName1) (class: TestModel)\ngot: [TestModel(id=1, firstName=firstName1, lastName=lastName1), TestModel(id=2, firstName=firstName2, lastName=lastName2), TestModel(id=3, firstName=firstName3, lastName=lastName3)] (values = 3, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValue message, case predicate + empty list`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf<TestModel>()
flow.test(this) {
try {
assertValue { it == TestModel.item1 }
} catch (ex: Throwable) {
ex.printAndAssert("No values (values = 0, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValue message, case predicate + 2 items list`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1, TestModel.item2, TestModel.item3)
flow.test(this) {
try {
assertValue { it == TestModel.item1 }
} catch (ex: Throwable) {
ex.printAndAssert("The first value passed the predicate but this consumer received more than one value (values = 3, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValue message, case predicate doesn't match`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1, TestModel.item2, TestModel.item3)
flow.test(this) {
try {
assertValue(value = TestModel.item2)
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected: TestModel(id=2, firstName=firstName2, lastName=lastName2) (class: TestModel)\ngot: [TestModel(id=1, firstName=firstName1, lastName=lastName1), TestModel(id=2, firstName=firstName2, lastName=lastName2), TestModel(id=3, firstName=firstName3, lastName=lastName3)] (values = 3, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValueIsNull message, case predicate + empty list`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf<TestModel>()
flow.test(this) {
try {
assertValueIsNull()
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected exactly one item\ngot :0; Value count differs (values = 0, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValueIsNull message, case predicate + 2 items list`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1, TestModel.item2)
flow.test(this) {
try {
assertValueIsNull()
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected exactly one item\ngot :2; Value count differs (values = 2, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValueAt message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
assertValueAt(0, TestModel.item2)
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected: TestModel(id=2, firstName=firstName2, lastName=lastName2) (class: TestModel)\ngot: TestModel(id=1, firstName=firstName1, lastName=lastName1) (class: TestModel); Value at position 0 differ (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValueAt predicate message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
assertValueAt(0) { it == TestModel.item2 }
} catch (ex: Throwable) {
ex.printAndAssert("Value TestModel(id=1, firstName=firstName1, lastName=lastName1) (class: TestModel) at position 0 did not pass the predicate (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test vararg assertValues message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
assertValues(TestModel.item2)
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected: TestModel(id=2, firstName=firstName2, lastName=lastName2) (class: TestModel)\ngot: TestModel(id=1, firstName=firstName1, lastName=lastName1) (class: TestModel); Value at position 0 differ (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test iterable assertValues message, less values`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1, TestModel.item2)
flow.test(this) {
try {
assertValues(listOf(TestModel.item1))
} catch (ex: Throwable) {
ex.printAndAssert("More values received than expected (1) (values = 2, has error = false, completed = true)")
}
}
}
@Test
fun `test iterable assertValues message, more values`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
assertValues(listOf(TestModel.item1, TestModel.item2))
} catch (ex: Throwable) {
ex.printAndAssert("Fewer values received than expected (1) (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test sequence assertValues message, less values`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1, TestModel.item2)
flow.test(this) {
try {
assertValues(sequenceOf(TestModel.item1))
} catch (ex: Throwable) {
ex.printAndAssert("More values received than expected (1) (values = 2, has error = false, completed = true)")
}
}
}
@Test
fun `test sequence assertValues message, more values`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
assertValues(sequenceOf(TestModel.item1, TestModel.item2))
} catch (ex: Throwable) {
ex.printAndAssert("Fewer values received than expected (1) (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test assertNoValues message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1)
flow.test(this) {
try {
assertNoValues()
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected: 0\ngot: 1; Value counts differ (values = 1, has error = false, completed = true)")
}
}
}
@Test
fun `test assertValueCount message`() = runTest(UnconfinedTestDispatcher()) {
val flow = flowOf(TestModel.item1, TestModel.item2, TestModel.item3)
flow.test(this) {
try {
assertValueCount(2)
} catch (ex: Throwable) {
ex.printAndAssert("\nexpected: 2\ngot: 3; Value counts differ (values = 3, has error = false, completed = true)")
}
}
}
private fun Throwable.printAndAssert(expectedMessage: String) {
messages?.add(expectedMessage)
assertEquals(expectedMessage, message)
}
}
| 0
|
Kotlin
|
0
| 40
|
315ec4a863ca38d9820f9858f3ea6fe49533af3d
| 14,598
|
flow-test-observer
|
MIT License
|
app/src/main/java/com/project/neardoc/utils/service/StepCountForegroundServiceManager.kt
|
HashemDeveloper
| 207,633,364
| false
| null |
package com.project.neardoc.utils.service
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import android.util.Log
import com.project.neardoc.BuildConfig
import com.project.neardoc.services.StepCountForegroundService
import com.project.neardoc.utils.Constants
import javax.inject.Inject
class StepCountForegroundServiceManager @Inject constructor(): IStepCountForegroundServiceManager {
companion object {
private val TAG: String = StepCountForegroundServiceManager::class.java.canonicalName!!
}
@Inject
lateinit var context: Context
private var stepCountForegroundService: StepCountForegroundService?= null
private var mBound: Boolean = false
private var isActivityStopped: Boolean = false
private fun bindService() {
try {
if (!this.mBound) {
bindOperator()
}
} catch (ex: Exception) {
if (BuildConfig.DEBUG) {
if (ex.localizedMessage != null) {
Log.i(TAG, ex.localizedMessage!!)
}
}
}
}
override fun startForegroundService() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this.context.startForegroundService(Intent(this.context, StepCountForegroundService::class.java))
bindService()
} else {
this.context.startService(Intent(this.context, StepCountForegroundService::class.java))
bindService()
}
}
override fun stopStepCountService() {
val intent = Intent(this.context, StepCountForegroundService::class.java)
intent.putExtra(Constants.SIGN_OUT, true)
this.context.stopService(intent)
}
override fun unBindOnActivityStart(isForegroundServiceAvailable: Boolean) {
if (isForegroundServiceAvailable) {
if (this.isActivityStopped && !this.mBound) {
try {
bindOperator()
} catch (ex: Exception) {
if (BuildConfig.DEBUG) {
if (ex.localizedMessage != null) {
Log.i(TAG, ex.localizedMessage!!)
}
}
}
}
}
}
override fun bindOnActivityStop(isForegroundServiceAvailable: Boolean) {
if (isForegroundServiceAvailable) {
if (this.mBound) {
try {
unBindOperator()
this.mBound = false
this.isActivityStopped = true
} catch (ex: Exception) {
if (BuildConfig.DEBUG) {
if (ex.localizedMessage != null) {
Log.i(TAG, ex.localizedMessage!!)
}
}
startForegroundService()
}
}
}
}
override fun stopBindService(isForegroundServiceAvailable: Boolean) {
if (isForegroundServiceAvailable) {
if (isServiceRunning()) {
try {
unBindOperator()
} catch (ex: Exception) {
if (BuildConfig.DEBUG) {
if (ex.localizedMessage != null) {
Log.i(TAG, ex.localizedMessage!!)
}
}
}
}
}
}
private fun bindOperator() {
this.context.bindService(Intent(this.context, StepCountForegroundService::class.java), this.serviceConnection, Context.BIND_AUTO_CREATE)
}
private fun unBindOperator() {
this.context.unbindService(this.serviceConnection)
}
private fun isServiceRunning(): Boolean {
val manager: ActivityManager =
this.context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service: ActivityManager.RunningServiceInfo in manager.getRunningServices(
Int.MAX_VALUE
)) {
if (StepCountForegroundService::class.java.name == service.service.className) {
return true
}
}
return false
}
private val serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
val localBinder: StepCountForegroundService.LocalBinder = iBinder as StepCountForegroundService.LocalBinder
stepCountForegroundService = localBinder.service
mBound = true
}
override fun onServiceDisconnected(componentName: ComponentName) {
stepCountForegroundService = null
mBound = false
}
}
}
| 0
|
Kotlin
|
0
| 1
|
38bbb6b46017f0da78d0c5bfda187a864830db4c
| 4,903
|
NearDoc
|
Apache License 2.0
|
kgl-glfw/src/jvmMain/kotlin/com/kgl/glfw/Cursor.kt
|
Dominaezzz
| 164,507,082
| false
| null |
/**
* Copyright [2019] [<NAME>]
*
* 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.kgl.glfw
import io.ktor.utils.io.core.*
import org.lwjgl.glfw.*
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.system.*
actual class Cursor : Closeable {
val ptr: Long
actual constructor(image: Image, xhot: Int, yhot: Int) {
ptr = MemoryStack.stackPush().use { stack ->
val imagePtr = GLFWImage.callocStack(stack)
imagePtr.width(image.width)
imagePtr.height(image.height)
imagePtr.pixels(image.pixels.buffer)
glfwCreateCursor(imagePtr, xhot, yhot)
}
}
actual constructor(shape: Standard) {
ptr = glfwCreateStandardCursor(shape.value)
}
override fun close() {
glfwDestroyCursor(ptr)
}
actual enum class Standard(internal val value: Int) {
Arrow(GLFW_ARROW_CURSOR),
IBeam(GLFW_IBEAM_CURSOR),
CrossHair(GLFW_CROSSHAIR_CURSOR),
Hand(GLFW_HAND_CURSOR),
HResize(GLFW_HRESIZE_CURSOR),
VResize(GLFW_VRESIZE_CURSOR);
}
}
| 13
| null |
11
| 96
|
41155a8200602535697b872232e41cfe6f5eb20e
| 1,464
|
kgl
|
Apache License 2.0
|
data-layer/src/main/kotlin/org/deafsapps/android/favquotes/datalayer/domain/OnDataMapper.kt
|
pablodeafsapps
| 354,134,895
| false
| null |
package org.deafsapps.android.favquotes.datalayer.domain
import org.deafsapps.android.favquotes.domainlayer.domain.FailureBo
import org.deafsapps.android.favquotes.domainlayer.domain.QuoteBo
import org.deafsapps.android.favquotes.domainlayer.domain.QuoteListWrapperBo
private const val DEFAULT_STRING_VALUE = ""
private const val DEFAULT_BOOLEAN_VALUE = false
private const val DEFAULT_INTEGER_VALUE = -1
/**
*
*/
fun QuoteListWrapperDto.toListWrapperBo() = QuoteListWrapperBo(
page = page ?: DEFAULT_INTEGER_VALUE,
isLastPage = isLastPage ?: DEFAULT_BOOLEAN_VALUE,
quoteList = quoteList?.toBoList() ?: emptyList()
)
/**
*
*/
fun QotdDto.toQuoteBo(): QuoteBo = with(quote) {
QuoteBo(
author = this?.author ?: DEFAULT_STRING_VALUE,
authorPermalink = this?.authorPermalink ?: DEFAULT_STRING_VALUE,
body = this?.body ?: DEFAULT_STRING_VALUE,
dialogue = this?.dialogue ?: DEFAULT_BOOLEAN_VALUE,
downvotesCount = this?.downvotesCount ?: DEFAULT_INTEGER_VALUE,
favoritesCount = this?.favoritesCount ?: DEFAULT_INTEGER_VALUE,
id = this?.id ?: DEFAULT_INTEGER_VALUE,
isPrivate = this?.isPrivate ?: DEFAULT_BOOLEAN_VALUE,
tags = this?.tags ?: emptyList(),
upvotesCount = this?.upvotesCount ?: DEFAULT_INTEGER_VALUE,
url = this?.url ?: DEFAULT_STRING_VALUE
)
}
/**
*
*/
fun List<QuoteDto>.toBoList(): List<QuoteBo> = map { it.toBo() }
/**
*
*/
fun QuoteDto.toBo() = QuoteBo(
author = author ?: DEFAULT_STRING_VALUE,
authorPermalink = authorPermalink ?: DEFAULT_STRING_VALUE,
body = body ?: DEFAULT_STRING_VALUE,
dialogue = dialogue ?: DEFAULT_BOOLEAN_VALUE,
downvotesCount = downvotesCount ?: DEFAULT_INTEGER_VALUE,
favoritesCount = favoritesCount ?: DEFAULT_INTEGER_VALUE,
id = id ?: DEFAULT_INTEGER_VALUE,
isPrivate = isPrivate ?: DEFAULT_BOOLEAN_VALUE,
tags = tags ?: emptyList(),
upvotesCount = upvotesCount ?: DEFAULT_INTEGER_VALUE,
url = url ?: DEFAULT_STRING_VALUE
)
/**
* Maps a [FailureDto] into a [FailureBo]
*/
fun FailureDto.dtoToBoFailure(): FailureBo = when (this) {
FailureDto.NoConnection -> FailureBo.NoConnection
is FailureDto.RequestError -> FailureBo.RequestError(msg = msg ?: DEFAULT_STRING_VALUE)
FailureDto.LoginError -> FailureBo.ServerError(msg = msg ?: DEFAULT_STRING_VALUE)
is FailureDto.RegisterError -> FailureBo.ServerError(msg = msg ?: DEFAULT_STRING_VALUE)
FailureDto.NoData -> FailureBo.NoData
is FailureDto.Error -> FailureBo.ServerError(msg = msg ?: DEFAULT_STRING_VALUE)
FailureDto.Unknown -> FailureBo.Unknown
}
| 0
|
Kotlin
|
1
| 0
|
7aee42ace3c06830262a3bc5e407186e4da93850
| 2,636
|
fav-quotes
|
MIT License
|
shared/src/commonMain/kotlin/data/classSchedule/GetVerifyCodeFormWest2.kt
|
west2-online
| 840,273,230
| false
|
{"Kotlin": 742964, "Swift": 592, "Shell": 228}
|
package data.classSchedule
import kotlinx.serialization.Serializable
@Serializable data class GetVerifyCodeFormWest2(val message: String)
| 6
|
Kotlin
|
2
| 0
|
484b699b372e6ff5c43ae725372b28c6de4eaa73
| 140
|
fzuhelper-KMP
|
Apache License 2.0
|
server/src/main/kotlin/jetbrains/rsynk/io/BasicReadingIO.kt
|
richardy2012
| 96,218,024
| true
|
{"Kotlin": 167498, "Python": 3069, "FreeMarker": 566}
|
/**
* Copyright 2016 - 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 jetbrains.rsynk.io
import java.io.IOException
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.atomic.AtomicLong
class BasicReadingIO(private val input: InputStream) : ReadingIO {
private val readBytes = AtomicLong(0)
override fun readBytes(len: Int): ByteArray {
val buf = ByteArray(len)
val read = input.read(buf)
if (read == -1) {
throw IOException("Cannot read $len byte(s): EOF received")
}
if (read != len) {
throw IOException("Cannot read requested amount of data: only $read bytes of $len were read")
}
readBytes.addAndGet(read.toLong())
return buf
}
override fun readInt(): Int {
return ByteBuffer.wrap(readBytes(4)).order(ByteOrder.LITTLE_ENDIAN).int
}
override fun readChar(): Char {
return ByteBuffer.wrap(readBytes(2)).order(ByteOrder.LITTLE_ENDIAN).char
}
override fun bytesRead(): Long = readBytes.get()
}
| 0
|
Kotlin
|
0
| 0
|
75dfd34ec9b90a3f4ab0eddbd2d4961ae8496491
| 1,639
|
rsynk
|
Apache License 2.0
|
cache/src/main/java/com/playone/mobile/cache/db/Db.kt
|
lekaha
| 121,380,867
| false
| null |
package com.playone.mobile.cache.db
/**
* This class defines the tables found within the application Database. All table
* definitions should contain column names and a sequence for creating the table.
*/
object Db {
object PlayoneTable {
const val TABLE_NAME = "playone"
const val PLAYONE_ID = "playone_id"
const val NAME = "name"
const val TITLE = "title"
const val AVATAR = "avatar"
const val CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
PLAYONE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
NAME + " TEXT NOT NULL," +
TITLE + " TEXT," +
AVATAR + " TEXT" +
"); "
}
}
| 5
|
Kotlin
|
0
| 1
|
15ca77cbe9189554723b9b5cd4302946fd4675a8
| 715
|
playone-android
|
MIT License
|
backend/src/main/java/radar/stats/repositories/api/StatsRepository.kt
|
community-graph
| 107,399,783
| false
|
{"JavaScript": 26063, "Kotlin": 19083, "HTML": 9320, "SCSS": 6334, "CSS": 444}
|
package radar.stats.repositories.api
interface StatsRepository {
data class Monthly(val month: String, val count: Int)
fun tweetsPerMonth(): List<Monthly>
}
| 4
|
JavaScript
|
2
| 2
|
356eb3188cff3f1090f427f65557c8b0e1c3518d
| 168
|
community-radar
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/SendMoneySmartphone.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.SendMoneySmartphone: ImageVector
get() {
if (_sendMoneySmartphone != null) {
return _sendMoneySmartphone!!
}
_sendMoneySmartphone = Builder(name = "SendMoneySmartphone", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(6.0f, 16.0f)
lineTo(0.0f, 16.0f)
lineTo(0.0f, 0.0f)
horizontalLineToRelative(16.0f)
verticalLineToRelative(4.0f)
lineTo(6.0f, 4.0f)
verticalLineToRelative(12.0f)
close()
moveTo(0.0f, 18.0f)
horizontalLineToRelative(16.0f)
verticalLineToRelative(3.0f)
curveToRelative(0.0f, 1.657f, -1.343f, 3.0f, -3.0f, 3.0f)
lineTo(3.0f, 24.0f)
curveToRelative(-1.657f, 0.0f, -3.0f, -1.343f, -3.0f, -3.0f)
verticalLineToRelative(-3.0f)
close()
moveTo(7.0f, 22.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(2.0f)
close()
moveTo(24.0f, 6.0f)
verticalLineToRelative(10.0f)
lineTo(8.0f, 16.0f)
lineTo(8.0f, 6.0f)
horizontalLineToRelative(16.0f)
close()
moveTo(12.0f, 13.5f)
curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
close()
moveTo(12.0f, 8.5f)
curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
close()
moveTo(19.0f, 11.0f)
curveToRelative(0.0f, -1.657f, -1.343f, -3.0f, -3.0f, -3.0f)
reflectiveCurveToRelative(-3.0f, 1.343f, -3.0f, 3.0f)
reflectiveCurveToRelative(1.343f, 3.0f, 3.0f, 3.0f)
reflectiveCurveToRelative(3.0f, -1.343f, 3.0f, -3.0f)
close()
moveTo(23.0f, 13.5f)
curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
close()
moveTo(23.0f, 8.5f)
curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
close()
}
}
.build()
return _sendMoneySmartphone!!
}
private var _sendMoneySmartphone: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,183
|
icons
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.