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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/cookbook/MaxPerKeyExamples.kt
|
axbaretto
| 68,967,334
| false
| null |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.examples.kotlin.cookbook
import com.google.api.services.bigquery.model.TableFieldSchema
import com.google.api.services.bigquery.model.TableRow
import com.google.api.services.bigquery.model.TableSchema
import org.apache.beam.examples.kotlin.cookbook.MaxPerKeyExamples.FormatMaxesFn
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO
import org.apache.beam.sdk.io.gcp.bigquery.WriteResult
import org.apache.beam.sdk.options.*
import org.apache.beam.sdk.transforms.DoFn
import org.apache.beam.sdk.transforms.Max
import org.apache.beam.sdk.transforms.PTransform
import org.apache.beam.sdk.transforms.ParDo
import org.apache.beam.sdk.values.KV
import org.apache.beam.sdk.values.PCollection
import java.util.ArrayList
/**
* An example that reads the public samples of weather data from BigQuery, and finds the maximum
* temperature ('mean_temp') for each month.
*
*
* Concepts: The 'Max' statistical combination function, and how to find the max per key group.
*
*
* Note: Before running this example, you must create a BigQuery dataset to contain your output
* table.
*
*
* To execute this pipeline locally, specify the BigQuery table for the output with the form:
*
* <pre>`--output=YOUR_PROJECT_ID:DATASET_ID.TABLE_ID
`</pre> *
*
*
* To change the runner, specify:
*
* <pre>`--runner=YOUR_SELECTED_RUNNER
`</pre> *
*
* See examples/java/README.md for instructions about how to configure different runners.
*
*
* The BigQuery input table defaults to `clouddataflow-readonly:samples.weather_stations `
* and can be overridden with `--input`.
*/
object MaxPerKeyExamples {
// Default to using a 1000 row subset of the public weather station table publicdata:samples.gsod.
private const val WEATHER_SAMPLES_TABLE = "clouddataflow-readonly:samples.weather_stations"
/**
* Examines each row (weather reading) in the input table. Output the month of the reading, and
* the mean_temp.
*/
internal class ExtractTempFn : DoFn<TableRow, KV<Int, Double>>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val row = c.element()
val month = Integer.parseInt(row["month"] as String)
val meanTemp = java.lang.Double.parseDouble(row["mean_temp"].toString())
c.output(KV.of(month, meanTemp))
}
}
/** Format the results to a TableRow, to save to BigQuery. */
internal class FormatMaxesFn : DoFn<KV<Int, Double>, TableRow>() {
@ProcessElement
fun processElement(c: ProcessContext) {
val row = TableRow()
.set("month", c.element().key)
.set("max_mean_temp", c.element().value)
c.output(row)
}
}
/**
* Reads rows from a weather data table, and finds the max mean_temp for each month via the 'Max'
* statistical combination function.
*/
internal class MaxMeanTemp : PTransform<PCollection<TableRow>, PCollection<TableRow>>() {
override fun expand(rows: PCollection<TableRow>): PCollection<TableRow> {
// row... => <month, mean_temp> ...
val temps = rows.apply(ParDo.of(ExtractTempFn()))
// month, mean_temp... => <month, max mean temp>...
val tempMaxes = temps.apply(Max.doublesPerKey())
// <month, max>... => row...
return tempMaxes.apply(ParDo.of(FormatMaxesFn()))
}
}
/**
* Options supported by [MaxPerKeyExamples].
*
*
* Inherits standard configuration options.
*/
interface Options : PipelineOptions {
@get:Description("Table to read from, specified as <project_id>:<dataset_id>.<table_id>")
@get:Default.String(WEATHER_SAMPLES_TABLE)
var input: String
@get:Description("Table to write to, specified as <project_id>:<dataset_id>.<table_id>")
@get:Validation.Required
var output: String
}
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
val options = PipelineOptionsFactory.fromArgs(*args).withValidation() as Options
val p = Pipeline.create(options)
// Build the table schema for the output table.
val fields = arrayListOf<TableFieldSchema>(
TableFieldSchema().setName("month").setType("INTEGER"),
TableFieldSchema().setName("max_mean_temp").setType("FLOAT"))
val schema = TableSchema().setFields(fields)
p.apply(BigQueryIO.readTableRows().from(options.input))
.apply(MaxMeanTemp())
.apply<WriteResult>(
BigQueryIO.writeTableRows()
.to(options.output)
.withSchema(schema)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE))
p.run().waitUntilFinish()
}
}
| 74
| null |
4009
| 9
|
c20455fe0a97c885a8ef11d60d3381020c9f1bdc
| 5,870
|
beam
|
Apache License 2.0
|
ktu-ais-api/src/main/java/lt/welovedotnot/ktu_ais_api/handlers/DataHandler.kt
|
we-love-dot-not
| 102,258,182
| false
| null |
package lt.welovedotnot.ktu_ais_api.handlers
import org.jsoup.Connection
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import lt.welovedotnot.ktu_ais_api.models.MarkModel
import lt.welovedotnot.ktu_ais_api.models.ModuleModel
import lt.welovedotnot.ktu_ais_api.models.YearModel
/**
* Created by simonas on 9/3/17.
*/
class DataHandler {
fun getGrades(studCookie: String, planYear: YearModel)
= getGrades(studCookie, planYear.year, planYear.id)
fun getGrades(studCookie: String, planYear: String, studId: String): List<MarkModel> {
val markList = mutableListOf<MarkModel>()
val moduleList = getModules(studCookie, planYear, studId)
moduleList.forEach { moduleModel ->
val moduleMarkList = getModuleMarkList(moduleModel, studCookie)
markList.addAll(moduleMarkList)
}
return markList
}
fun getModules(studCookie: String, planYear: String, studId: String): List<ModuleModel> {
val url = "https://uais.cr.ktu.lt/ktuis/STUD_SS2.planas_busenos?" +
"plano_metai=$planYear&" +
"p_stud_id=$studId"
val request = Jsoup.connect(url)
.cookie("STUDCOOKIE", studCookie)
.method(Connection.Method.GET)
.execute()
request.charset("windows-1257")
val parse = request.parse()
val moduleList = mutableListOf<ModuleModel>()
val moduleTable = parse.select(".table.table-hover > tbody > tr")
if (moduleTable.size > 0) {
moduleTable.forEach { moduleElement ->
val model = ModuleModel(moduleElement)
moduleList.add(model)
}
}
return moduleList
}
private fun getModuleMarkList(moduleModel: ModuleModel, studCookie: String): List<MarkModel> {
val markList = mutableListOf<MarkModel>()
val url = "https://uais.cr.ktu.lt/ktuis/STUD_SS2.infivert"
val request = Jsoup.connect(url)
.cookie("STUDCOOKIE", studCookie)
.method(Connection.Method.POST)
.data(mapOf(
"p1" to moduleModel.p1,
"p2" to moduleModel.p2
))
.execute()
request.charset("windows-1257")
val parse = request.parse()
val markTable = parse.select(".d_grd2[style=\"border-collapse:collapse; empty-cells:hide;\"]").firstOrNull()
val markInfoTable = parse.select(".d_grd2[style=\"border-collapse:collapse; table-layout:fixed; width:450px;\"]").firstOrNull()
val headerInfo = parse.select("blockquote").select("p")
if (markTable != null && markInfoTable != null) {
val markTypeIdList: List<String> = getMarkTypeIdList(markTable)
val infoTypeRowList: Map<String, String> = getMarkTypeMap(markInfoTable)
val markWeekList: List<String> = getMarkWeekList(markTable)
val markDataList: Map<Int, List<String>> = getMarkDataMap(markTable)
val profestorText = headerInfo[2].text()
(0 until markWeekList.size-1).forEach { index ->
if (markTypeIdList[index] != " ") {
val markModel = MarkModel(
name = moduleModel.module_name,
id = moduleModel.module_code,
semester = moduleModel.semester,
module_code = moduleModel.module_code,
module_name = moduleModel.module_name,
semester_number = moduleModel.semester_number,
credits = moduleModel.credits,
language = moduleModel.language,
profestor = profestorText,
typeId = markTypeIdList[index],
type = infoTypeRowList[markTypeIdList[index]]!!,
week = markWeekList[index],
mark = markDataList[index] ?: listOf()
)
markList.add(markModel)
}
}
}
return markList
}
private fun getMarkTypeMap(element: Element): Map<String, String> {
return mutableMapOf<String, String>().apply {
element.select("tr.dtr").forEach { typeElement ->
val key = typeElement.children()[0].text()
val value = typeElement.children()[1].text()
put(key, value)
}
}
}
private fun getMarkWeekList(element: Element): MutableList<String> {
val rowList = element.select("tr")
return mutableListOf<String>().apply {
val headerWeekRow = rowList[0].children()
.subList(4, rowList[0].children().size - 2)
headerWeekRow.forEach { cell ->
add(cell.text())
}
}
}
private fun getMarkTypeIdList(element: Element): MutableList<String> {
val rowList = element.select("tr")
return mutableListOf<String>().apply {
val headerTypeRow = rowList[1].children()
.subList(1, rowList[1].children().size - 3)
headerTypeRow.forEach { cell ->
add(cell.text())
}
}
}
private fun getMarkDataMap(element: Element): Map<Int, List<String>> {
val rowList = element.select("tr")
return mutableMapOf<Int, MutableList<String>>().apply {
(2 until rowList.size).forEach { rowIndex ->
var headerDataRow = rowList[rowIndex].children().toList()
if (rowIndex == 2) {
headerDataRow = headerDataRow.subList(4, rowList[rowIndex].children().size - 4)
} else {
headerDataRow = headerDataRow.subList(1, rowList[rowIndex].children().size - 1)
}
headerDataRow.forEachIndexed { index, cell ->
val text = cell.text()
if (text != " ") {
if (containsKey(index)) {
put(index, get(index)!!.apply { add(text) })
} else {
put(index, mutableListOf(text))
}
}
}
}
}
}
}
| 0
|
Kotlin
|
2
| 3
|
28af4aa5c64856b303713c28d978b04f03946b47
| 6,421
|
ktu-ais-api-android
|
MIT License
|
app/src/main/java/com/example/shinelon/lianqin/view/RegiOrUpdaView.kt
|
HB-pencil
| 112,829,724
| false
| null |
package com.example.shinelon.lianqin.view
import android.app.Dialog
import com.example.shinelon.lianqin.view.BaseView
/**
* Created by Shinelon on 2018/2/17.
*/
interface RegiOrUpdaView:BaseView{
override fun init() {
}
fun showSuccessDialog()
fun showFailureDialog(msg: String)
fun showProgress()
fun dismissProgress()
}
| 0
|
Kotlin
|
0
| 0
|
d7876605647920c59a6bea2bfb6581b60091823e
| 350
|
lianqin
|
Apache License 2.0
|
app/src/main/java/com/example/shinelon/lianqin/view/RegiOrUpdaView.kt
|
HB-pencil
| 112,829,724
| false
| null |
package com.example.shinelon.lianqin.view
import android.app.Dialog
import com.example.shinelon.lianqin.view.BaseView
/**
* Created by Shinelon on 2018/2/17.
*/
interface RegiOrUpdaView:BaseView{
override fun init() {
}
fun showSuccessDialog()
fun showFailureDialog(msg: String)
fun showProgress()
fun dismissProgress()
}
| 0
|
Kotlin
|
0
| 0
|
d7876605647920c59a6bea2bfb6581b60091823e
| 350
|
lianqin
|
Apache License 2.0
|
app/src/main/java/com/example/galleryapp_compose/ui/galleryscreen/GalleryScreenUiState.kt
|
PauloSzT
| 642,027,877
| false
| null |
package com.example.galleryapp_compose.ui.galleryscreen
import com.example.galleryapp_compose.models.Photo
import kotlinx.coroutines.flow.StateFlow
data class GalleryScreenUiState (
val photoList: StateFlow<List<Photo>>
)
| 0
|
Kotlin
|
0
| 0
|
ff0020fd13ce6382ebeae42afefb475c4fde4e23
| 228
|
GalleryApp_compose_navigation
|
MIT License
|
skellig-test-step-processing-db/src/main/kotlin/org/skellig/teststep/processor/db/DatabaseRequestExecutorFactory.kt
|
skellig-framework
| 263,021,995
| false
|
{"Kotlin": 793363, "CSS": 525608, "Java": 185441, "HTML": 11313, "FreeMarker": 9740, "ANTLR": 2041}
|
package org.skellig.teststep.processor.db
import org.skellig.teststep.processing.exception.TestStepProcessingException
import org.skellig.teststep.processor.db.model.DatabaseRequest
open class DatabaseRequestExecutorFactory(select: DatabaseRequestExecutor,
insert: DatabaseRequestExecutor,
update: DatabaseRequestExecutor) {
private var databaseRequestExecutors =
mutableMapOf(
Pair("select", select),
Pair("insert", insert),
Pair("update", update)
)
operator fun get(databaseRequest: DatabaseRequest): DatabaseRequestExecutor? {
var command = databaseRequest.command
if (isQueryOnlyProvided(databaseRequest, command)) {
val query: String = databaseRequest.query!!
command = databaseRequestExecutors.keys.firstOrNull { item: String -> query.lowercase().trim { it <= ' ' }.startsWith(item) }
}
return if (databaseRequestExecutors.containsKey(command)) {
databaseRequestExecutors[command]
} else {
if (isQueryOnlyProvided(databaseRequest, command)) {
throw TestStepProcessingException(java.lang.String.format("No database query executors found for query: '%s'." +
" Supported types of queries: %s", databaseRequest.query, databaseRequestExecutors.keys))
} else {
throw TestStepProcessingException(String.format("No database query executors found for command: '%s'." +
" Supported commands: %s", command, databaseRequestExecutors.keys))
}
}
}
private fun isQueryOnlyProvided(databaseRequest: DatabaseRequest, command: String?): Boolean {
return command == null && databaseRequest.query != null
}
}
| 5
|
Kotlin
|
0
| 2
|
d11be068a414e3dfea0300bc9ef52c0180091d90
| 1,895
|
skellig-core
|
Apache License 2.0
|
src/main/kotlin/no/nav/syfo/sykmelding/aivenmigrering/SykmeldingV2KafkaMessage.kt
|
navikt
| 526,559,029
| false
| null |
package no.nav.syfo.sykmelding.aivenmigrering
import no.nav.syfo.model.sykmelding.arbeidsgiver.ArbeidsgiverSykmelding
import no.nav.syfo.model.sykmeldingstatus.KafkaMetadataDTO
import no.nav.syfo.model.sykmeldingstatus.SykmeldingStatusKafkaEventDTO
data class SykmeldingV2KafkaMessage(
val sykmelding: ArbeidsgiverSykmelding,
val kafkaMetadata: KafkaMetadataDTO,
val event: SykmeldingStatusKafkaEventDTO?
)
| 1
|
Kotlin
|
1
| 0
|
715d7812d509fe5ec1ed7b075807fb42e0df16f4
| 421
|
syfoservice-data-syfosmregister
|
MIT License
|
src/main/kotlin/org/jetbrains/plugins/template/services/MyApplicationService.kt
|
bshadmehr98
| 491,152,980
| false
|
{"Kotlin": 7010}
|
package org.jetbrains.plugins.template.services
import org.jetbrains.plugins.template.MyBundle
class MyApplicationService {
init {
System.setProperty("-Dproject.tree.structure.show.url", "false");
System.setProperty("project.tree.structure.show.url", "false");
println(MyBundle.message("applicationService"))
}
}
| 0
|
Kotlin
|
0
| 0
|
e81bff4984f26e54f2fde44cf801f4544aa4e52c
| 348
|
jetbrain-path-hide
|
Apache License 2.0
|
kmock/src/commonMain/kotlin/tech/antibytes/kmock/proxy/SpyGuard.kt
|
bitPogo
| 455,829,905
| false
|
{"Kotlin": 3553507}
|
/* ktlint-disable filename */
/*
* Copyright (c) 2022 Matthias Geisler (bitPogo) / All rights reserved.
*
* Use of this source code is governed by Apache v2.0
*/
package tech.antibytes.kmock.proxy
internal fun <ReturnValue, SideEffect : Function<ReturnValue>> Any?.guardSpy(spyOn: SideEffect): SideEffect? {
return if (this != null) {
spyOn
} else {
null
}
}
| 2
|
Kotlin
|
2
| 54
|
61a11f511db12b1944449d0edd5b48e9ba3beb46
| 393
|
kmock
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/UsdCircle.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.UsdCircle: ImageVector
get() {
if (_usdCircle != null) {
return _usdCircle!!
}
_usdCircle = Builder(name = "UsdCircle", defaultWidth = 512.0.dp, defaultHeight = 512.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) {
moveTo(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(10.644f, 10.76f)
lineToRelative(3.041f, 0.507f)
curveToRelative(1.342f, 0.223f, 2.315f, 1.373f, 2.315f, 2.733f)
curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-2.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, -1.346f, -3.0f, -3.0f)
horizontalLineToRelative(2.0f)
curveToRelative(0.0f, 0.552f, 0.448f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(2.0f)
curveToRelative(0.552f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f)
curveToRelative(0.0f, -0.378f, -0.271f, -0.698f, -0.644f, -0.76f)
lineToRelative(-3.041f, -0.507f)
curveToRelative(-1.342f, -0.223f, -2.315f, -1.373f, -2.315f, -2.733f)
curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f)
horizontalLineToRelative(-2.0f)
curveToRelative(0.0f, -0.551f, -0.448f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-2.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, 0.449f, -1.0f, 1.0f)
curveToRelative(0.0f, 0.378f, 0.271f, 0.698f, 0.644f, 0.76f)
close()
}
}
.build()
return _usdCircle!!
}
private var _usdCircle: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,096
|
icons
|
MIT License
|
server/src/test/java/de/zalando/zally/rule/zally/CaseCheckerRuleTest.kt
|
natrem
| 184,784,603
| true
|
{"Kotlin": 559448, "JavaScript": 110833, "Go": 73479, "HTML": 6081, "Shell": 3643, "CSS": 2805, "Dockerfile": 844}
|
package de.zalando.zally.rule.zally
import de.zalando.zally.getOpenApiContextFromContent
import de.zalando.zally.getSwaggerContextFromContent
import de.zalando.zally.rule.ZallyAssertions
import de.zalando.zally.testConfig
import org.intellij.lang.annotations.Language
import org.junit.Test
@Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction", "TooManyFunctions", "StringLiteralDuplication")
class CaseCheckerRuleTest {
private val cut = CaseCheckerRule(testConfig)
@Test
fun `checkPropertyNames returns violations`() {
@Language("YAML")
val context = getSwaggerContextFromContent(
"""
swagger: '2.0'
definitions:
Defined:
properties:
InVaLiD!:
type: boolean
""".trimIndent()
)
val violations = cut.checkPropertyNames(context)
ZallyAssertions
.assertThat(violations)
.pointersEqualTo("/definitions/Defined/properties/InVaLiD!")
.descriptionsAllMatch("Property 'InVaLiD!' does not match .*".toRegex())
}
@Test
fun `checkPathParameterNames with InVaLiD! returns violations`() {
@Language("YAML")
val context = getSwaggerContextFromContent(
"""
swagger: '2.0'
paths:
/things:
post:
parameters:
- in: path
name: InVaLiD!
""".trimIndent()
)
val violations = cut.checkPathParameterNames(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Path parameter 'InVaLiD!' does not match .*".toRegex())
.pointersEqualTo("/paths/~1things/post/parameters/0")
}
@Test
fun `checkPathParameterNames with kebab-case returns no violations`() {
@Language("YAML")
val context = getSwaggerContextFromContent(
"""
swagger: '2.0'
paths:
/things:
post:
parameters:
- in: path
name: kebab-case
""".trimIndent()
)
val violations = cut.checkPathParameterNames(context)
ZallyAssertions
.assertThat(violations)
.isEmpty()
}
@Test
fun `checkPathParameterNames with snake_case returns no violations`() {
@Language("YAML")
val context = getSwaggerContextFromContent(
"""
swagger: '2.0'
paths:
/things:
post:
parameters:
- in: path
name: snake_case
""".trimIndent()
)
val violations = cut.checkPathParameterNames(context)
ZallyAssertions
.assertThat(violations)
.isEmpty()
}
@Test
fun `checkQueryParameterNames returns violations`() {
@Language("YAML")
val context = getSwaggerContextFromContent(
"""
swagger: '2.0'
paths:
/things:
post:
parameters:
- in: query
name: InVaLiD!
""".trimIndent()
)
val violations = cut.checkQueryParameterNames(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Query parameter 'InVaLiD!' does not match .*".toRegex())
.pointersEqualTo("/paths/~1things/post/parameters/0")
}
@Test
fun `checkHeaderNames returns violations`() {
@Language("YAML")
val context = getSwaggerContextFromContent(
"""
swagger: '2.0'
paths:
/things:
post:
parameters:
- in: header
name: InVaLiD!
""".trimIndent()
)
val violations = cut.checkHeaderNames(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Header 'InVaLiD!' does not match .*".toRegex())
.pointersEqualTo("/paths/~1things/post/parameters/0")
}
@Test
fun `checkPathSegments returns violations`() {
@Language("YAML")
val context = getSwaggerContextFromContent(
"""
swagger: '2.0'
paths:
/things/{param}//InVaLiD:
post:
""".trimIndent()
)
val violations = cut.checkPathSegments(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Path segment 'InVaLiD' does not match .*".toRegex())
.pointersEqualTo("/paths/~1things~1{param}~1~1InVaLiD")
}
@Test
fun `checkDiscriminatorValues with invalid mapping returns violations`() {
@Language("YAML")
val context = getOpenApiContextFromContent(
"""
openapi: '3.0.0'
components:
schemas:
Pet:
type: object
required:
- pet_type
properties:
pet_type:
type: string
discriminator:
propertyName: pet_type
mapping:
InVaLiD: Cat
""".trimIndent()
)
val violations = cut.checkDiscriminatorValues(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Discriminator value 'InVaLiD' does not match .*".toRegex())
.pointersEqualTo("/components/schemas/Pet/discriminator")
}
@Test
fun `checkDiscriminatorValues with invalid enum returns violations`() {
@Language("YAML")
val context = getOpenApiContextFromContent(
"""
openapi: '3.0.0'
components:
schemas:
Pet:
type: object
required:
- pet_type
properties:
pet_type:
type: string
enum: [ InVaLiD ]
discriminator:
propertyName: pet_type
""".trimIndent()
)
val violations = cut.checkDiscriminatorValues(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Discriminator property enum value 'InVaLiD' does not match .*".toRegex())
.pointersEqualTo("/components/schemas/Pet/properties/pet_type")
}
@Test
fun `checkDiscriminatorValues with invalid swagger enum returns violations`() {
@Language("YAML")
val context = getSwaggerContextFromContent(
"""
swagger: '2.0'
definitions:
Pet:
type: object
discriminator: petType
properties:
name:
type: string
petType:
type: string
enum: [InVaLiD]
required:
- name
- petType
""".trimIndent()
)
val violations = cut.checkDiscriminatorValues(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Discriminator property enum value 'InVaLiD' does not match .*".toRegex())
.pointersEqualTo("/definitions/Pet/properties/petType")
}
@Test
fun `checkEnumValues with invalid discriminator returns no violations`() {
@Language("YAML")
val context = getOpenApiContextFromContent(
"""
openapi: '3.0.0'
components:
schemas:
Pet:
type: object
required:
- pet_type
properties:
pet_type:
type: string
enum: [ InVaLiD ]
discriminator:
propertyName: pet_type
""".trimIndent()
)
val violations = cut.checkEnumValues(context)
ZallyAssertions
.assertThat(violations)
.isEmpty()
}
@Test
fun `checkEnumValues with invalid enum returns violations`() {
@Language("YAML")
val context = getOpenApiContextFromContent(
"""
openapi: '3.0.0'
components:
schemas:
Pet:
type: object
properties:
huntingSkill:
type: string
enum:
- InVaLiD
""".trimIndent()
)
val violations = cut.checkEnumValues(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Enum value 'InVaLiD' does not match .*".toRegex())
.pointersEqualTo("/components/schemas/Pet/properties/huntingSkill")
}
@Test
fun `checkEnumValues with invalid parameter enum returns violations`() {
@Language("YAML")
val context = getOpenApiContextFromContent(
"""
openapi: '3.0.0'
components:
parameters:
huntingSkill:
name: huntingSkill
in: query
schema:
type: string
enum:
- InVaLiD
""".trimIndent()
)
val violations = cut.checkEnumValues(context)
ZallyAssertions
.assertThat(violations)
.descriptionsAllMatch("Enum value 'InVaLiD' does not match .*".toRegex())
.pointersEqualTo("/components/parameters/huntingSkill/schema")
}
}
| 0
|
Kotlin
|
0
| 0
|
8e8a4bfcb13fbda0f16ff1dbf29453a861bc78c7
| 9,997
|
zally
|
MIT License
|
leitnerbox/dagger/components/LocalDataSourceComponent.kt
|
morync
| 198,999,267
| false
| null |
package com.kecsot.leitnerbox.dagger.components
import com.kecsot.leitnerbox.dagger.modules.LocalDataSourceModule
import com.kecsot.leitnerbox.repository.CardRepository
import com.kecsot.leitnerbox.repository.DeckRepository
import com.kecsot.leitnerbox.repository.ImageRepository
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = [LocalDataSourceModule::class])
interface LocalDataSourceComponent {
fun inject(repository: DeckRepository)
fun inject(repository: CardRepository)
fun inject(imageRepository: ImageRepository)
}
| 0
|
Kotlin
|
0
| 0
|
7a05fb782936ec6d4832add38c6026b43762c373
| 577
|
Leitner-Box-Flashcard
|
MIT License
|
common/src/main/kotlin/com/turikhay/mc/pwam/mc/Session.kt
|
turikhay
| 786,989,595
| false
|
{"Kotlin": 74167, "Java": 16135}
|
package com.turikhay.mc.pwam.mc
import com.turikhay.mc.pwam.common.*
import com.turikhay.mc.pwam.common.text.*
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.concurrent.Executor
class Session(
client: IClient,
private val info: SessionInfo,
private val db: Database,
executor: Executor,
commandNodeAccessor: ICommandNodeAccessor<ICommandSource>,
askServerSuggestion: IAskServerSuggestion,
pattern: PasswordPattern,
) : PasswordChangeCallback, Invalidatable, Disposable {
private val registerPwdProvider = CacheableTextProvider(
provideText("register", executor) {
generatePassword(12)
}
)
private val registerPwdPatternProvider = CacheableTextProvider(
pattern.providePwdPattern(registerPwdProvider)
)
private val loginPwdProvider = CacheableTextProvider(
PatternAwarePasswordGenerator(
provideText("login", executor) {
transaction(db) {
getPassword(info.username, info.server)
}
},
pattern,
registerPwdPatternProvider,
maxAttempts = 2,
)
)
private val loginPwdPatternProvider = CacheableTextProvider(
pattern.providePwdPattern(loginPwdProvider)
)
val pwdPatternCache = TextProvidersCache(
listOf(
loginPwdPatternProvider,
registerPwdPatternProvider,
)
)
private val pairs = Pairs(
login = PasswordPairProvider(
loginPwdProvider,
loginPwdPatternProvider,
),
register = PasswordPairProvider(
registerPwdProvider,
registerPwdPatternProvider,
),
)
private val notificator = Notificator(
client,
pattern
)
val commandRewriter = PatternCommandRewriter(
pairs.asList(),
notificator,
pattern,
)
val commandDispatcherHandler = CommandDispatcherHandler(
KnownCommandHandler(
client,
commandRewriter,
pairs,
this,
notificator,
pattern,
),
pairs,
commandNodeAccessor,
askServerSuggestion,
ManagementCmd(
db,
pattern,
info,
client,
this,
client.version,
),
client,
executor,
)
override fun changePassword(newPassword: String) {
transaction(db) {
setPassword(
info.username,
info.server,
newPassword,
)
}
invalidate()
notificator.passwordChangeNotification(newPassword)
}
override fun invalidate() {
invalidateAll(
loginPwdProvider,
loginPwdPatternProvider,
registerPwdProvider,
registerPwdPatternProvider,
pwdPatternCache,
)
}
override fun cleanUp() {
invalidate()
}
companion object {
var session: Session? = null
}
}
| 3
|
Kotlin
|
0
| 0
|
dab6357393e3135a6c1ac4916c5a9878843bf7de
| 3,167
|
passwordmanager-for-authme
|
MIT License
|
app/src/main/java/com/egorhoot/chomba/repo/OnLineGameRepository.kt
|
HootEgor
| 676,993,231
| false
|
{"Kotlin": 274712}
|
package com.egorhoot.chomba.repo
import androidx.compose.runtime.MutableState
import com.egorhoot.chomba.pages.onlinegame.OnLineGameUiState
import com.egorhoot.chomba.pages.user.ProfileScreenUiState
interface OnLineGameRepository {
suspend fun createRoom(onLineGameUiState: MutableState<OnLineGameUiState>,
profileUi: MutableState<ProfileScreenUiState>,
onResult: () -> Unit)
suspend fun joinRoom(code: String,
onLineGameUiState: MutableState<OnLineGameUiState>,
profileUi: MutableState<ProfileScreenUiState>,
onResult: () -> Unit)
suspend fun getAvailableRooms(onLineGameUiState: MutableState<OnLineGameUiState>,
profileUi: MutableState<ProfileScreenUiState>,
onResult: () -> Unit)
}
| 0
|
Kotlin
|
0
| 0
|
a7e96673c7df504b49fbc9dd4eba6e69ae319164
| 872
|
Chomba
|
MIT License
|
src/main/kotlin/com/github/vatbub/openthesaurus/apiclient/CachedDataProvider.kt
|
vatbub
| 343,217,797
| false
| null |
/*-
* #%L
* Open Thesaurus Java View
* %%
* Copyright (C) 2016 - 2021 <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.
* #L%
*/
package com.github.vatbub.openthesaurus.apiclient
import com.github.vatbub.openthesaurus.util.Either
import com.github.vatbub.openthesaurus.util.left
import java.util.*
fun DataProvider.cacheResults(cacheSize: Int = 50): DataProvider = object : DataProvider {
override val screenName: String
get() = this@cacheResults.screenName
override val supportedLocales: List<Locale>
get() = this@cacheResults.supportedLocales
private var cache: MutableMap<CacheKey, CacheEntry> = mutableMapOf()
override suspend fun requestTerm(term: String, searchLocale: Locale): Either<Response, ApiError> {
cache[CacheKey(term, searchLocale)]?.let { return it.result.left() }
val result = this@cacheResults.requestTerm(term, searchLocale)
if (result is Either.Left<Response>)
addToCache(CacheKey(term, searchLocale), result.value)
return result
}
private fun addToCache(request: CacheKey, result: Response) {
cache[request] = CacheEntry(System.currentTimeMillis(), result)
if (cache.size > cacheSize) {
val sortedList = cache.toList().sortedBy { it.second.timestamp }.toMutableList()
while (sortedList.size > cacheSize)
sortedList.removeFirst()
cache = sortedList.toMap().toMutableMap()
}
}
}
private data class CacheKey(val term: String, val searchLocale: Locale)
private data class CacheEntry(val timestamp: Long, val result: Response)
| 0
|
Kotlin
|
0
| 0
|
a976aa86d7930509ff363e62061eaf4a2ea2f445
| 2,141
|
open-thesaurus-java-view
|
Apache License 2.0
|
app/src/androidTest/kotlin/jp/co/yumemi/android/code_check/TestExtension.kt
|
MarcoDzuong
| 406,395,463
| false
| null |
package jp.co.yumemi.android.code_check
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
fun <T> LiveData<T>.getOrAwaitData(): T{
var data: T?=null
val latch = CountDownLatch(1)
val observer = object : Observer<T>{
override fun onChanged(t: T) {
data = t
this@getOrAwaitData.removeObserver(this)
latch.countDown()
}
}
GlobalScope.launch(Dispatchers.Main) {
// your code here...
this@getOrAwaitData.observeForever(observer)
}
try {
if (!latch.await(5,TimeUnit.SECONDS)){
throw TimeoutException("Live data never git it")
}
} finally {
GlobalScope.launch(Dispatchers.Main) {
// your code here...
this@getOrAwaitData.removeObserver(observer)
}
}
return data as T
}
| 0
|
Kotlin
|
0
| 2
|
703e158b758aa7ddc05ab75a670b183d7c8d092f
| 1,098
|
yumemi-android-engineer-codecheck
|
Apache License 2.0
|
game/src/main/kotlin/gg/rsmod/game/message/impl/EventKeyboardMessage.kt
|
2011Scape
| 578,880,245
| false
|
{"Kotlin": 8359518, "Dockerfile": 1354}
|
package org.alter.game.message.impl
import org.alter.game.message.Message
/**
* @author Tom <<EMAIL>>
*/
data class EventKeyboardMessage(val events: List<KeyEvent>) : Message {
data class KeyEvent(val key: Int, val lastKeyPress: Int)
}
| 8
|
Kotlin
|
33
| 32
|
da66bb6d68ebae531ee325b909a6536e798b1144
| 244
|
game
|
Apache License 2.0
|
app/src/main/java/com/fruitable/Fruitable/app/presentation/view/setting/LeaveAppScreen.kt
|
ApptiveDev
| 535,231,127
| false
|
{"Kotlin": 234453}
|
package com.fruitable.Fruitable.app.presentation.view.setting
import android.content.Context
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fruitable.Fruitable.app.presentation.component.FruitableButton
import com.fruitable.Fruitable.app.presentation.component.FruitableDivider
import com.fruitable.Fruitable.app.presentation.component.FruitableTitle
import com.fruitable.Fruitable.app.presentation.component._feature.FruitablePopUp
import com.fruitable.Fruitable.app.presentation.component._feature.TextFieldBox
import com.fruitable.Fruitable.app.presentation.component._view.DialogBoxLoading
import com.fruitable.Fruitable.app.presentation.component._view.FruitableCheckBox
import com.fruitable.Fruitable.app.presentation.event.LeaveAppEvent
import com.fruitable.Fruitable.app.presentation.navigation.Screen
import com.fruitable.Fruitable.app.presentation.viewmodel.user.LeaveAppViewModel
import com.fruitable.Fruitable.ui.theme.MainGreen1
import com.fruitable.Fruitable.ui.theme.MainGreen1_1
import com.fruitable.Fruitable.ui.theme.TextStyles
import kotlinx.coroutines.flow.collectLatest
@Composable
fun LeaveAppScreen(
navController: NavController,
viewModel: LeaveAppViewModel = hiltViewModel()
){
val passwordState = viewModel.password.value
val password2State = viewModel.password2.value
val focusRequester = remember { FocusRequester() }
var isChecked by remember { mutableStateOf(false) }
var isDialogOpen by remember { mutableStateOf(false) }
val isLeavable = viewModel.isLeavable() && isChecked
val Token = LocalContext.current.getSharedPreferences("token", Context.MODE_PRIVATE)
val scaffoldState = rememberScaffoldState()
LaunchedEffect(key1 = true) {
viewModel.eventFlow.collectLatest { event ->
when (event) {
is LeaveAppViewModel.UiEvent.LeaveApp -> {
Token.edit().putString("token", "").apply()
navController.navigate(Screen.LogInScreen.route){ popUpTo(0) }
}
is LeaveAppViewModel.UiEvent.LeaveAppError -> {
scaffoldState.snackbarHostState.showSnackbar(
message = "🌱 ${event.message}"
)
}
}
}
}
if (viewModel.isLoading.value) DialogBoxLoading()
FruitablePopUp(
text = "탈퇴 시 본인 계정의 모든 기록이 삭제되며 복구할 수 없습니다.\n정말 탈퇴하시겠습니까?",
cancelText = "취소",
confirmText = "탈퇴하기",
cancel = { isDialogOpen = false},
confirm = { viewModel.onEvent(LeaveAppEvent.LeaveApp) },
isOpen = isDialogOpen
)
Scaffold(
scaffoldState = scaffoldState,
bottomBar = {
Column(
modifier = Modifier.background(Color.White).fillMaxWidth()
) {
FruitableDivider()
FruitableButton(
text = "탈퇴하기",
enabled = isLeavable,
disableColor = MainGreen1_1,
modifier = Modifier.padding(30.dp, 14.dp, 30.dp, 30.dp),
onClick = {
viewModel.passwordErrorCheck()
if (isChecked && isLeavable) isDialogOpen = true
}
)
}
}
) {
FruitableTitle(
title = "회원 탈퇴",
subtitle = "푸릇에이블을 떠나신다니 아쉽습니다."
) {
Text(
text = "회원 탈퇴 안내",
style = TextStyles.TextBold6
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "지금까지 푸릇에이블을 이용해주셔서 감사합니다.\n" +
"회원을 탈퇴하시면 푸릇에이블 서비스 내 프로필 " +
"정보가 삭제되며 복구할 수 없습니다.",
style = TextStyles.TextSmall2,
)
FruitableCheckBox(
modifier = Modifier.padding(top = 30.dp, bottom = 40.dp),
isChecked = isChecked,
borderColor = MainGreen1,
backgroundColor = MainGreen1,
onClick = { isChecked = !isChecked }
)
TextFieldBox(
state = passwordState,
modifier = Modifier.focusRequester(focusRequester),
visualTransformation = PasswordVisualTransformation(),
onValueChange = { viewModel.onEvent(LeaveAppEvent.EnteredPassword(it)) },
onFocusChange = { viewModel.onEvent(LeaveAppEvent.ChangePasswordFocus(it)) },
)
Spacer(modifier = Modifier.height(28.dp))
TextFieldBox(
state = password2State,
modifier = Modifier.focusRequester(focusRequester),
visualTransformation = PasswordVisualTransformation(),
onValueChange = { viewModel.onEvent(LeaveAppEvent.EnteredPassword2(it)) },
onFocusChange = { viewModel.onEvent(LeaveAppEvent.ChangePassword2Focus(it)) },
)
Spacer(modifier = Modifier.height(100.dp))
}
}
}
| 0
|
Kotlin
|
3
| 3
|
70217aa3ebcf0a278fe2cb9fa9791e2621fd8f4f
| 5,731
|
apptive-17th-fruitable-frontend
|
MIT License
|
desktop/views/src/main/kotlin/com/soyle/stories/layout/config/dynamic/BaseStoryStructureConfig.kt
|
Soyle-Productions
| 239,407,827
| false
| null |
package com.soyle.stories.layout.config.dynamic
import com.soyle.stories.characterarc.baseStoryStructure.BaseStoryStructureScope
import com.soyle.stories.domain.character.Character
import com.soyle.stories.domain.theme.Theme
import com.soyle.stories.layout.config.ToolConfig
import com.soyle.stories.layout.config.ToolTabConfig
import com.soyle.stories.layout.repositories.OpenToolContext
import com.soyle.stories.layout.tools.DynamicTool
import com.soyle.stories.layout.tools.FixedTool
import com.soyle.stories.project.ProjectScope
import com.soyle.stories.project.layout.ToolViewModel
import com.soyle.stories.project.layout.config.ToolViewModelConfig
import com.soyle.stories.usecase.character.CharacterDoesNotExist
import com.soyle.stories.usecase.theme.ThemeDoesNotExist
import javafx.scene.control.Tab
import javafx.scene.control.TabPane
import tornadofx.find
import tornadofx.onChange
import tornadofx.tab
import java.util.*
import kotlin.reflect.KClass
object BaseStoryStructureConfig : ToolConfig<BaseStoryStructure> {
override fun getRegistration(): Pair<KClass<BaseStoryStructure>, ToolConfig<BaseStoryStructure>> {
return BaseStoryStructure::class to this
}
override fun getFixedType(): FixedTool? = null
override fun getViewModelConfig(type: BaseStoryStructure): ToolViewModelConfig {
return object : ToolViewModelConfig {
override fun toolName(): String = "Base Story Structure: ${type.themeId}"
}
}
override fun getTabConfig(tool: ToolViewModel, type: BaseStoryStructure): ToolTabConfig {
return object : ToolTabConfig {
override fun getTab(tabPane: TabPane, projectScope: ProjectScope): Tab {
val scope = BaseStoryStructureScope(projectScope, tool.toolId, type)
val structure = find<com.soyle.stories.characterarc.baseStoryStructure.BaseStoryStructure>(scope = scope)
val tab = tabPane.tab(structure)
tab.tabPaneProperty().onChange {
if (it == null) {
scope.close()
}
}
return tab
}
}
}
}
data class BaseStoryStructure(val characterId: UUID, val themeId: UUID) : DynamicTool() {
override val isTemporary: Boolean
get() = false
override suspend fun validate(context: OpenToolContext) {
context.characterRepository.getCharacterById(Character.Id(characterId))
?: throw CharacterDoesNotExist(characterId)
context.themeRepository.getThemeById(Theme.Id(themeId))
?: throw ThemeDoesNotExist(themeId)
}
override fun identifiedWithId(id: UUID): Boolean =
id == characterId || id == themeId
}
| 45
|
Kotlin
|
0
| 9
|
1a110536865250dcd8d29270d003315062f2b032
| 2,495
|
soyle-stories
|
Apache License 2.0
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/pm/conversationslist/ConversationsListPresenter.kt
|
esqr
| 107,263,447
| true
|
{"Kotlin": 283399}
|
package io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversationslist
import io.github.feelfreelinux.wykopmobilny.api.pm.PMApi
import io.github.feelfreelinux.wykopmobilny.base.BasePresenter
import io.github.feelfreelinux.wykopmobilny.utils.rx.SubscriptionHelperApi
class ConversationsListPresenter(private val subscriptionHelperApi: SubscriptionHelperApi, val pmApi: PMApi) : BasePresenter<ConversationsListView>() {
var page = 1
fun loadConversations(shouldRefresh : Boolean) {
if (shouldRefresh) page = 1
subscriptionHelperApi.subscribe(pmApi.getConversations(page), {
if (it.isNotEmpty()) {
page ++
view?.showConversations(it, shouldRefresh)
} else view?.disableLoading()
}, { view?.showErrorDialog(it) }, this)
}
override fun unsubscribe() {
super.unsubscribe()
subscriptionHelperApi.dispose(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
39e5a49b2b9770d0c6c8a18d48670f53e96f32ff
| 932
|
WykopMobilny
|
MIT License
|
app/src/main/java/com/example/hobbyfi/adapters/chatroom/BaseChatroomListAdapter.kt
|
GGLozanov
| 310,078,278
| false
| null |
package com.example.hobbyfi.adapters.chatroom
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.Button
import android.widget.GridView
import androidx.appcompat.widget.AppCompatImageButton
import androidx.core.content.ContextCompat
import androidx.paging.ExperimentalPagingApi
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.signature.ObjectKey
import com.example.hobbyfi.MainApplication
import com.example.hobbyfi.R
import com.example.hobbyfi.adapters.base.ImageLoaderViewHolder
import com.example.hobbyfi.models.data.Chatroom
import com.example.hobbyfi.models.data.Tag
import com.example.hobbyfi.shared.Constants
import com.example.hobbyfi.shared.PrefConfig
import com.example.hobbyfi.utils.GlideUtils
import com.google.android.material.button.MaterialButton
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.kodein
import org.kodein.di.generic.instance
abstract class BaseChatroomListAdapter<VH : RecyclerView.ViewHolder>(
protected inline val onJoinChatroomButton: ((view: View, chatroom: Chatroom) -> Unit)? = null,
protected inline val onTagsViewButton: ((view: View, chatroom: Chatroom) -> Unit)
) : PagingDataAdapter<Chatroom, VH>(DIFF_CALLBACK), KodeinAware {
@ExperimentalPagingApi
override val kodein: Kodein by kodein(MainApplication.applicationContext)
protected val prefConfig: PrefConfig by instance(tag = "prefConfig")
abstract class BaseChatroomViewHolder(
itemView: View,
prefConfig: PrefConfig,
private inline val onJoinChatroomButton: ((view: View, chatroom: Chatroom) -> Unit)?,
private inline val onTagsViewButton: (view: View, chatroom: Chatroom) -> Unit
) : ImageLoaderViewHolder<Chatroom>(itemView, prefConfig) {
override fun bind(model: Chatroom?, position: Int) {
bindImage(model, position)
initChatroomButtonListener(model, chatroomJoinButton) {
onJoinChatroomButton?.invoke(
tagsViewButton,
model!!
)
}
initChatroomButtonListener(model, tagsViewButton) {
onTagsViewButton.invoke(
tagsViewButton,
model!!
)
}
}
private fun initChatroomButtonListener(
chatroom: Chatroom?,
button: View,
callback: () -> Unit
) {
button.setOnClickListener {
if (chatroom != null) {
callback()
}
}
}
override val signatureGenerator: (position: Int) -> ObjectKey = { position ->
GlideUtils.getPagingObjectKey(
prefConfig,
position,
R.string.pref_last_chatrooms_fetch_time,
Constants.chatroomPageSize
)
}
override val defaultPicDrawable: Drawable by lazy {
ContextCompat.getDrawable(itemView.context, R.drawable.chatroom_default_pic)!!
}
abstract val tagsViewButton: AppCompatImageButton
abstract val chatroomJoinButton: MaterialButton
}
companion object {
private val DIFF_CALLBACK = object :
DiffUtil.ItemCallback<Chatroom>() {
// Chatroom details may have changed if reloaded from the database,
// but ID is fixed.
override fun areItemsTheSame(oldChatroom: Chatroom,
newChatroom: Chatroom
) = oldChatroom.id == newChatroom.id
override fun areContentsTheSame(oldChatroom: Chatroom,
newChatroom: Chatroom
) = oldChatroom == newChatroom
}
}
}
| 0
|
Kotlin
|
3
| 1
|
afb30f72a4213c924fdf8e3cb5eefd76d6a0d320
| 3,912
|
Hobbyfi
|
Apache License 2.0
|
src/main/kotlin/Main.kt
|
TheCloudkill
| 853,557,598
| false
|
{"Kotlin": 945}
|
package com.example
import com.jessecorbett.diskord.bot.bot
import com.jessecorbett.diskord.bot.classicCommands
/*
* This can be replaced with any method to load the bot token. This specific method is provided only for convenience
* and as a way to prevent accidental disclosure of bot tokens.
*
* Alternative methods might include reading from the environment, using a system property, or reading from the CLI.
*/
private val BOT_TOKEN = try {
ClassLoader.getSystemResource("bot-token.txt").readText().trim()
} catch (error: Exception) {
throw RuntimeException("Failed to load bot token. Make sure to create a file named bot-token.txt in" +
" src/main/resources and paste the bot token into that file.", error)
}
suspend fun main(args: Array<String>) {
bot(BOT_TOKEN) {
classicCommands {
command("ping") { message ->
message.respond("Pong!")
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
35d108507225fbd3a5149fa6ffa29ea29e4be4c8
| 945
|
MayaDiscordBot
|
The Unlicense
|
app/src/main/java/com/precopia/david/lists/view/reauthentication/phone/buildlogic/PhoneReAuthComponent.kt
|
DavidPrecopia
| 150,194,957
| false
| null |
package com.precopia.david.lists.view.reauthentication.phone.buildlogic
import android.app.Application
import androidx.fragment.app.Fragment
import com.precopia.david.lists.common.buildlogic.ViewCommonModule
import com.precopia.david.lists.common.buildlogic.ViewScope
import com.precopia.david.lists.view.reauthentication.phone.PhoneReAuthView
import dagger.BindsInstance
import dagger.Component
@ViewScope
@Component(modules = [
PhoneReAuthModule::class,
ViewCommonModule::class
])
interface PhoneReAuthComponent {
fun inject(phoneReAuthView: PhoneReAuthView)
@Component.Builder
interface Builder {
fun build(): PhoneReAuthComponent
@BindsInstance
fun application(application: Application): Builder
@BindsInstance
fun view(view: Fragment): Builder
}
}
| 1
|
Kotlin
|
2
| 4
|
1f20908547972ac55036d1f804f5e93906aeb509
| 821
|
Lists
|
Apache License 2.0
|
fd-applet-server/src/main/kotlin/io/github/haruhisa_enomoto/server/routes/StorageRoutes.kt
|
haruhisa-enomoto
| 628,298,470
| false
| null |
package io.github.haruhisa_enomoto.server.routes
import io.github.haruhisa_enomoto.server.storage.SessionStorage
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Route.storageRoutes() {
post("/kill") {
val clientId = call.request.queryParameters["client_id"]
if (clientId != null) {
SessionStorage.delete(clientId)
}
}
get("/active-ids") {
call.respond(SessionStorage.getIdList())
}
}
| 0
|
Kotlin
|
0
| 0
|
8ec1afe14e9f0d6330d02652c1cd782a68fca5db
| 503
|
fd-applet
|
MIT License
|
generators/app/templates/clean-architecture/data/src/main/kotlin/com/nelosan/clean/data/rest/NsConnector.kt
|
nelosan
| 95,792,492
| false
| null |
package <%= appPackage %>.data.rest
import android.app.Application
import <%= appPackage %>.data.parser.Serializer
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* Created by nelo on 16/2/17.
*/
class NsConnector {
var ENDPOINT = Host.getHost()
val CONNECTION_TIMEOUT: Long = 10
val application: Application
val serializer: Serializer
lateinit var adapter: Retrofit
constructor(application: Application) {
this.application = application
createApi()
serializer = Serializer()
}
fun createApi() {
var client: OkHttpClient = OkHttpClient
.Builder()
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.addInterceptor(NsInterceptor(application))
.build()
adapter = Retrofit
.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build()
}
}
| 0
|
Kotlin
|
0
| 0
|
cff887582146c38ebda542640fb4e351a890f02e
| 1,250
|
yeoman-kotlin-clean
|
Apache License 2.0
|
app/src/main/java/au/com/tilbrook/android/rxkotlin/fragments/RotationPersist2Fragment.kt
|
beblank
| 95,780,281
| true
|
{"Kotlin": 90878, "Java": 363}
|
package au.com.tilbrook.android.rxkotlin.fragments
import android.os.Bundle
import android.os.Handler
import android.os.Looper.getMainLooper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import au.com.tilbrook.android.rxkotlin.R
import au.com.tilbrook.android.rxkotlin.writing.LogAdapter
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.ctx
import rx.Observable
import rx.Observer
import rx.subscriptions.CompositeSubscription
import timber.log.Timber
import java.util.*
class RotationPersist2Fragment : BaseFragment(), RotationPersist2WorkerFragment.IAmYourMaster {
private lateinit var _logList: ListView
private lateinit var _adapter: LogAdapter
private lateinit var _logs: MutableList<String>
private var _subscriptions = CompositeSubscription()
// -----------------------------------------------------------------------------------
// @OnClick(R.id.btn_rotate_persist)
val startOperationFromWorkerFrag = { v:View? ->
_logs = ArrayList<String>()
_adapter.clear()
val fm = activity.supportFragmentManager
var frag: RotationPersist2WorkerFragment? =
fm.findFragmentByTag(FRAG_TAG) as? RotationPersist2WorkerFragment
if (frag == null) {
frag = RotationPersist2WorkerFragment()
fm.beginTransaction().add(frag, FRAG_TAG).commit()
} else {
Timber.d("Worker frag already spawned")
}
Unit
}
override fun setStream(intStream: Observable<Int>) {
_subscriptions.add(//
intStream
.doOnSubscribe { _log("Subscribing to intsObservable") }
.subscribe(object : Observer<Int> {
override fun onCompleted() {
_log("Observable is complete")
}
override fun onError(e: Throwable) {
Timber.e(e, "Error in worker demo frag observable")
_log("Dang! something went wrong.")
}
override fun onNext(integer: Int?) {
_log("Worker frag spits out - %d".format(integer))
}
})
)
}
// -----------------------------------------------------------------------------------
// Boilerplate
// -----------------------------------------------------------------------------------
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
_setupLogger()
}
override fun onCreateView(inflater: LayoutInflater?,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val layout = with(ctx) {
verticalLayout {
textView(R.string.msg_demo_rotation_persist) {
lparams(width = matchParent)
this.gravity = Gravity.CENTER
padding = dip(10)
}
button("Start operation") {
lparams(width = matchParent)
onClick(startOperationFromWorkerFrag)
}
_logList = listView {
lparams(width = matchParent, height = matchParent)
}
}
}
return layout
}
override fun onPause() {
super.onPause()
_subscriptions.clear()
}
private fun _setupLogger() {
_logs = ArrayList<String>()
_adapter = LogAdapter(activity, ArrayList<String>())
_logList.adapter = _adapter
}
private fun _log(logMsg: String) {
_logs.add(0, logMsg)
// You can only do below stuff on main thread.
Handler(getMainLooper()).post({
_adapter.clear()
_adapter.addAll(_logs)
})
}
companion object {
val FRAG_TAG = RotationPersist2WorkerFragment::class.java.name
}
}
| 0
|
Kotlin
|
0
| 0
|
6222cd92baa85d9159393861d4d5af9bb96b259a
| 4,101
|
RxKotlin-Android-Samples
|
Apache License 2.0
|
app/src/main/java/com/github/arburk/vscp/app/activity/RoundSettings.kt
|
arburk
| 640,248,515
| false
| null |
package com.github.arburk.vscp.app.activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ListView
import androidx.fragment.app.Fragment
import com.github.arburk.vscp.app.MainActivity
import com.github.arburk.vscp.app.R
import com.github.arburk.vscp.app.databinding.FragmentRoundSettingsBinding
import com.github.arburk.vscp.app.model.Blind
import com.github.arburk.vscp.app.service.TimerService
class RoundSettings : Fragment() {
private var _binding: FragmentRoundSettingsBinding? = null
private val binding get() = _binding!!
private lateinit var timerService: TimerService
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentRoundSettingsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
timerService = (activity as MainActivity).timerService
initLayout()
}
private fun initLayout() {
requireActivity().findViewById<ListView?>(R.id.rounds_row_list_view).adapter =
RoundSettingsListViewAdapter(requireContext(), timerService.getRoundsAsPokerTimerModel())
requireActivity().findViewById<ImageButton>(R.id.add_blind_button)?.setOnClickListener { addBlind() }
requireActivity().findViewById<ImageButton>(R.id.remove_last_blind_button)?.setOnClickListener { removeBlind() }
}
private fun addBlind() {
var newRound = Blind(1)
timerService.getRounds().also {
if (it.isNotEmpty()) {
val lastRound = it[it.size - 1]
newRound = Blind(lastRound.getBig())
}
timerService.setRounds(it.plus(newRound))
}
initLayout()
}
private fun removeBlind() {
timerService.getRounds().also {
if (it.isNotEmpty()) {
timerService.setRounds(it.dropLast(1).toTypedArray())
initLayout()
}
}
}
}
| 9
|
Kotlin
|
0
| 0
|
a0c1411d4683f20c6317fde2220f0f7b173840be
| 2,013
|
vscp
|
Apache License 2.0
|
library/common/src/main/kotlin/com/fphoenixcorneae/ximalaya/common/router/mine/MineRouterHelper.kt
|
wenmagi
| 407,388,827
| true
|
{"Kotlin": 62539}
|
package com.fphoenixcorneae.ximalaya.common.router.mine
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.fphoenixcorneae.ximalaya.common.constant.Router
import com.fphoenixcorneae.ximalaya.thirdpart.ext.defaultARouter
/**
* @desc:MineRouterHelper
* @date:2021/08/03 10:18
*/
object MineRouterHelper {
@Autowired(name = Router.Service.MINE)
lateinit var mMineService: MineRouterService
init {
defaultARouter.inject(this)
}
fun navigation(): Fragment {
return mMineService.navigation()
}
}
| 0
| null |
0
| 0
|
be3c4b43bebd68638a29c868a63eb46508591f3b
| 598
|
Ximalaya
|
Apache License 2.0
|
android/src/main/java/io/github/tonnyl/moka/widget/MainSearchBarComposable.kt
|
ETSEmpiricalStudyKotlinAndroidApps
| 496,360,843
| false
|
{"Kotlin": 1391177, "Swift": 100384, "CSS": 30407, "JavaScript": 13933, "Shell": 2990}
|
package io.github.tonnyl.moka.widget
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material.icons.outlined.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.github.tonnyl.moka.R
import io.github.tonnyl.moka.ui.Screen
import io.github.tonnyl.moka.ui.theme.*
@Composable
fun MainSearchBar(
openDrawer: (() -> Unit)?,
modifier: Modifier = Modifier
) {
val currentAccount = LocalAccountInstance.current ?: return
val navController = LocalNavController.current
MainSearchBarContent(
modifier = modifier,
avatarUrl = currentAccount.signedInAccount.account.avatarUrl,
onMenuClicked = openDrawer,
onTextClicked = {
Screen.Search.navigate(navController = navController)
},
onAvatarClicked = {
navController.navigate(route = Screen.AccountDialog.route)
}
)
}
@Composable
private fun MainSearchBarContent(
modifier: Modifier,
avatarUrl: String?,
onMenuClicked: (() -> Unit)?,
onTextClicked: () -> Unit,
onAvatarClicked: () -> Unit
) {
val displayMenuIcon = onMenuClicked != null
Box(
modifier = modifier
.background(color = Color.Transparent)
.height(height = 64.dp)
.fillMaxWidth()
.padding(
vertical = ContentPaddingMediumSize,
horizontal = ContentPaddingLargeSize
)
) {
Card(
elevation = 3.dp,
shape = MaterialTheme.shapes.small
) {
Box(
modifier = Modifier
.fillMaxSize()
.clickable(onClick = onTextClicked)
.padding(
start = DefaultIconButtonSizeModifier,
end = ContentPaddingSmallSize + ContentPaddingSmallSize + IconSize
)
) {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = stringResource(id = R.string.search_input_hint),
maxLines = 1,
style = MaterialTheme.typography.body1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.align(alignment = Alignment.CenterStart)
)
}
}
IconButton(
enabled = displayMenuIcon,
onClick = {
onMenuClicked?.invoke()
}
) {
Icon(
contentDescription = stringResource(
id = if (displayMenuIcon) {
R.string.navigation_drawer_open
} else {
R.string.search_input_hint
}
),
imageVector = if (displayMenuIcon) {
Icons.Outlined.Menu
} else {
Icons.Outlined.Search
}
)
}
Row(modifier = Modifier.align(alignment = Alignment.CenterEnd)) {
AvatarImage(
url = avatarUrl,
modifier = Modifier
.size(size = IconSize)
.clip(shape = CircleShape)
.clickable(onClick = onAvatarClicked)
.padding(all = ContentPaddingSmallSize)
.clip(shape = CircleShape)
)
Spacer(modifier = Modifier.width(width = ContentPaddingSmallSize))
}
}
}
}
@Preview(
showBackground = true,
name = "MainSearchBarPreview",
backgroundColor = 0xFFFFFF
)
@Composable
private fun MainSearchBarPreview() {
MainSearchBarContent(
modifier = Modifier,
avatarUrl = null,
onMenuClicked = {},
onTextClicked = {},
onAvatarClicked = {}
)
}
| 0
| null |
0
| 0
|
34db6153b274028158de1ee08f080b1a8f985325
| 4,721
|
Moka
|
MIT License
|
Olebo/src/jvmMain/kotlin/model/tools/Assign.kt
|
TristanBoulesteix
| 158,809,102
| false
| null |
package jdr.exia.model.tools
import kotlin.reflect.KMutableProperty0
/**
* Assign a value to a mutable property if the value is different from the previous one
*/
fun <T> KMutableProperty0<T>.assignIfDifferent(value: T) {
if (get() != value)
set(value)
}
| 0
|
Kotlin
|
0
| 1
|
263438ba7218f604c75369cdf29edf8232948cde
| 270
|
Olebo
|
Apache License 2.0
|
app/src/main/java/com/test/pocketaces/di/SearchComponent.kt
|
stAyushJain
| 342,903,412
| false
| null |
package com.test.pocketaces.di
import com.test.pocketaces.ui.SearchActivity
import com.test.pocketaces.di.base.BaseComponent
import dagger.Component
@FeatureScope
@Component(modules = [SearchModule::class, ViewModelModule::class], dependencies = [BaseComponent::class])
interface SearchComponent {
fun inject(searchActivity: SearchActivity)
}
| 0
|
Kotlin
|
0
| 0
|
010a95a97cd75d665d41144abb6780d32075a7a4
| 348
|
MovieApp
|
Apache License 2.0
|
technocracy.foundation/src/main/kotlin/net/cydhra/technocracy/foundation/content/blocks/OreBlock.kt
|
tth05
| 198,904,996
| true
|
{"Kotlin": 1367573, "GLSL": 13066}
|
package net.cydhra.technocracy.foundation.content.blocks
import net.cydhra.technocracy.foundation.TCFoundation
import net.cydhra.technocracy.foundation.model.blocks.api.AbstractBaseBlock
import net.cydhra.technocracy.foundation.model.blocks.color.ConstantBlockColor
import net.minecraft.block.material.Material
import net.minecraft.util.BlockRenderLayer
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
/**
* Class for all ore type blocks of this modification
*/
class OreBlock(unlocalizedName: String, oreType: String, colorMultiplier: Int)
: AbstractBaseBlock("$oreType.$unlocalizedName",
colorMultiplier = ConstantBlockColor(colorMultiplier),
material = Material.ROCK,
oreDictionaryName = "ore${unlocalizedName.capitalize()}") {
override val modelLocation: String = "${TCFoundation.MODID}:$oreType"
init {
this.blockResistance = 3.5f
this.blockHardness = 3f
}
@SideOnly(Side.CLIENT)
override fun getBlockLayer(): BlockRenderLayer {
return BlockRenderLayer.CUTOUT
}
}
| 0
|
Kotlin
|
0
| 1
|
057d12813fbcb73a11b202caae0631020b2fa303
| 1,100
|
Technocracy
|
MIT License
|
Foodtruck/app/src/main/java/com/example/foodtruck/ui/foodie/fragments/FoodTruckDetailsDialog.kt
|
Build-Week-FoodTruck-TrackR
| 215,889,839
| false
| null |
package com.example.foodtruck.ui.foodie.fragments
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.example.foodtruck.R
import com.example.foodtruck.data.source.local.model.SaveableFoodtruck
import com.example.foodtruck.ui.vendor.fragments.MenuCreationScreen
import com.example.foodtruck.util.createAlert
class FoodTruckDetailsDialog: DialogFragment() {
private lateinit var alertDialogView: View
private lateinit var saveableFoodtruck: SaveableFoodtruck
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val a = AlertDialog.Builder(context)
.setCancelable(true)
.setPositiveButton("OK"){d, i->}
return a.create()
}
override fun show(manager: FragmentManager, tag: String?) {
alertDialogView = LayoutInflater.from(context).inflate(R.layout.search_results_layout, null)
val bundle = arguments
if(bundle != null){
saveableFoodtruck = bundle.get("foodTruckMarker") as SaveableFoodtruck
alertDialogView.findViewById<TextView>(R.id.tv_foodtruck_name).text = saveableFoodtruck.name
alertDialogView.findViewById<Button>(R.id.rating_bar).text = "${saveableFoodtruck.averageReviewScore}\\t\\t\\t\\t ${saveableFoodtruck.allReviews.size}"
TODO("NEED TO DETERMINE WHETHER THE OPERATIONAL HOURS FOR TODAY MEANS ITS CURRENTLY OPEN")
}
alertDialogView.findViewById<Button>(R.id.button).setOnClickListener {
//reveal operating hours
val alertDialogView = LayoutInflater.from(context).inflate(R.layout.operational_hours_layout, null)
val a = AlertDialog.Builder(context)
.setCancelable(true)
.setView(alertDialogView)
.setOnCancelListener {
this.show(fragmentManager!!, "OK")
}
.setPositiveButton("OK"){ d, i->
this.show(fragmentManager!!, "OK")
}
}
alertDialogView.findViewById<Button>(R.id.rating_bar).setOnClickListener {
//bring us to review page
val reviewDialog = ReviewDialog()
val bundle = Bundle()
bundle.putSerializable("foodTruck", saveableFoodtruck)
reviewDialog.arguments = bundle
reviewDialog.show(fragmentManager!!, "review")
}
alertDialogView.findViewById<Button>(R.id.btn_view_menu).setOnClickListener {
val m = MenuCreationScreen()
val bundle = Bundle()
bundle.putSerializable("uneditableMenu", saveableFoodtruck.menu)
m.arguments = bundle
m.show(fragmentManager!!, "uneditableMenuView")
}
fragmentManager!!.executePendingTransactions()
(dialog as AlertDialog).setView(alertDialogView)
super.show(manager, tag)
}
}
| 0
|
Kotlin
|
1
| 0
|
76b215d943e9f9d0331cfd221bc5cc5800663554
| 3,155
|
AND
|
MIT License
|
src/main/kotlin/shop/itbug/fluttercheckversionx/tools/ExtensionsUtil.kt
|
mdddj
| 390,183,676
| false
|
{"Kotlin": 505710, "HTML": 1106}
|
package shop.itbug.fluttercheckversionx.tools
import javax.swing.BorderFactory
import javax.swing.border.Border
fun emptyBorder(): Border = BorderFactory.createEmptyBorder(0, 0, 0, 0)
| 4
|
Kotlin
|
4
| 37
|
92551e634b5d6c3ef37e10cba3fc05b9021bd577
| 186
|
dd_flutter_idea_plugin
|
MIT License
|
src/main/kotlin/shop/itbug/fluttercheckversionx/tools/ExtensionsUtil.kt
|
mdddj
| 390,183,676
| false
|
{"Kotlin": 505710, "HTML": 1106}
|
package shop.itbug.fluttercheckversionx.tools
import javax.swing.BorderFactory
import javax.swing.border.Border
fun emptyBorder(): Border = BorderFactory.createEmptyBorder(0, 0, 0, 0)
| 4
|
Kotlin
|
4
| 37
|
92551e634b5d6c3ef37e10cba3fc05b9021bd577
| 186
|
dd_flutter_idea_plugin
|
MIT License
|
src/main/kotlin/no/nav/jantra/river/bridge/EventRiver.kt
|
jantra-io
| 657,993,647
| false
|
{"Kotlin": 283127, "HTML": 466}
|
package no.nav.jantra.river.bridge
import kotlin.concurrent.thread
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.MessageContext
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.River
import no.nav.jantra.river.model.Event
import no.nav.jantra.river.IEventListener
import no.nav.jantra.river.InternalBehov
import no.nav.jantra.river.publish
import java.util.*
class EventRiver(val rapidsConnection: RapidsConnection, val eventListener: IEventListener, private val riverValidation:River.PacketValidation) : River.PacketListener{
var nonBlocking:Boolean = true
fun start() {
configure(
River(rapidsConnection).apply {
validate(riverValidation)
}
).register(this)
}
private fun configure(river: River): River {
return river.validate {
Event.packetValidator.validate(it)
}
}
override fun onPacket(packet: JsonMessage, context: MessageContext) {
val event = Event.create(packet)
val uuid = UUID.randomUUID().toString()
event.riverId = uuid
val createRiver = event.createBehov(InternalBehov("create-river"), mapOf())
println("Creating river")
rapidsConnection.publish(createRiver)
if (nonBlocking) {
thread {
eventListener.onEvent(event)
}
}
else {
eventListener.onEvent(event)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
9ed6336c790b6b8fb6da39e687168580fc9dde35
| 1,498
|
jantra-river-pond
|
MIT License
|
core/src/main/java/com/aidventory/core/barcode/generator/BarcodeGeneratorImpl.kt
|
yuriikonovalov
| 615,443,609
| false
| null |
package com.aidventory.core.barcode.generator
import com.aidventory.core.domain.interfaces.BarcodeGenerator
import java.util.UUID
import javax.inject.Inject
internal class BarcodeGeneratorImpl @Inject constructor() : BarcodeGenerator {
override fun generate(): String {
val uuid = UUID.randomUUID()
return System.nanoTime().toString() + uuid.toString()
}
}
| 0
|
Kotlin
|
0
| 0
|
9753d24aca8bb645cef085498124e58e9cda451a
| 382
|
aidventory
|
MIT License
|
view/src/androidMain/kotlin/tech/skot/view/live/SKLiveData.kt
|
MathieuScotet
| 235,318,194
| false
| null |
package tech.skot.view.live
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
actual open class SKLiveData<D> actual constructor(initialValue: D) : SKLiveDataCommon<D>(initialValue) {
fun observe(lifecycleOwner: LifecycleOwner, onChanged: (d: D) -> Unit) {
observers.add(LifecycleOwnerObserver(lifecycleOwner, onChanged))
}
fun setObserver(lifecycleOwner: LifecycleOwner, onChanged: (d: D) -> Unit) {
val currentObservers = observers.toSet()
currentObservers.forEach {
(it as? LifecycleOwnerObserver)?.apply {
onDestroy()
lifecycleOwner.lifecycle.removeObserver(lifecycleOwnerObserver)
}
}
observers.add(LifecycleOwnerObserver(lifecycleOwner, onChanged))
}
inner class LifecycleOwnerObserver(
val lifecycleOwner: LifecycleOwner,
onChanged: (d: D) -> Unit
) : Observer(onChanged) {
init {
if (shouldBeActive()) {
onBecomeActive()
}
}
val lifecycleOwnerObserver = object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onAny() {
val newState = lifecycleOwner.lifecycle.currentState
when {
newState == Lifecycle.State.DESTROYED -> {
onDestroy()
lifecycleOwner.lifecycle.removeObserver(this)
}
newState.isAtLeast(Lifecycle.State.STARTED) -> onBecomeActive()
else -> onBecomeInactive()
}
}
}
init {
lifecycleOwner.lifecycle.addObserver(lifecycleOwnerObserver)
}
override fun shouldBeActive(): Boolean {
return lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
}
}
}
| 0
|
Kotlin
|
2
| 1
|
2a15509308fd2c9797c18a9ce0d97cc9454275b0
| 2,130
|
skot
|
Apache License 2.0
|
app/src/main/java/ly/david/mbjc/ui/collections/releases/ReleasesByCollectionViewModel.kt
|
lydavid
| 458,021,427
| false
| null |
package ly.david.mbjc.ui.collections.releases
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingSource
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import ly.david.data.domain.ReleaseListItemModel
import ly.david.data.domain.toReleaseListItemModel
import ly.david.data.network.MusicBrainzResource
import ly.david.data.network.api.MusicBrainzApiService
import ly.david.data.persistence.artist.release.ArtistRelease
import ly.david.data.persistence.artist.release.ArtistReleaseDao
import ly.david.data.persistence.relation.BrowseResourceCount
import ly.david.data.persistence.relation.RelationDao
import ly.david.data.persistence.release.ReleaseDao
import ly.david.data.persistence.release.ReleaseForListItem
import ly.david.data.persistence.release.toRoomModel
import ly.david.mbjc.ui.common.paging.BrowseResourceUseCase
import ly.david.mbjc.ui.common.paging.IPagedList
import ly.david.mbjc.ui.common.paging.PagedList
// TODO: we will need something similar to ReleasesByArtistViewModel if we sync with MB's collection
// consider how we can integrate local collections with mb's collections before committing too much
// - users can create collections in our app without making a mb account
// - after auth, they can choose to sync their collections to mb
// - collections without a mb id will be pushed to mb, then the newly created mbid will be saved
// - collections from mb will be pulled into our db
// - refreshing a collection will pull data from mb -> but how do we sync? what if user adds on our app, refreshing shouldn't delete it
// TODO: research ANKI syncing
@HiltViewModel
internal class ReleasesByCollectionViewModel @Inject constructor(
private val pagedList: PagedList<ReleaseForListItem, ReleaseListItemModel>,
private val musicBrainzApiService: MusicBrainzApiService,
private val relationDao: RelationDao,
private val artistReleaseDao: ArtistReleaseDao,
private val releaseDao: ReleaseDao,
) : ViewModel(),
IPagedList<ReleaseListItemModel> by pagedList,
BrowseResourceUseCase<ReleaseForListItem, ReleaseListItemModel> {
init {
pagedList.scope = viewModelScope
pagedList.useCase = this
}
override suspend fun browseLinkedResourcesAndStore(resourceId: String, nextOffset: Int): Int {
val response = musicBrainzApiService.browseReleasesByArtist(
artistId = resourceId,
offset = nextOffset
)
if (response.offset == 0) {
relationDao.insertBrowseResourceCount(
browseResourceCount = BrowseResourceCount(
resourceId = resourceId,
browseResource = MusicBrainzResource.RELEASE,
localCount = response.releases.size,
remoteCount = response.count
)
)
} else {
relationDao.incrementLocalCountForResource(resourceId, MusicBrainzResource.RELEASE, response.releases.size)
}
val releaseMusicBrainzModels = response.releases
releaseDao.insertAll(releaseMusicBrainzModels.map { it.toRoomModel() })
artistReleaseDao.insertAll(
releaseMusicBrainzModels.map { release ->
ArtistRelease(
artistId = resourceId,
releaseId = release.id
)
}
)
return releaseMusicBrainzModels.size
}
override suspend fun getRemoteLinkedResourcesCountByResource(resourceId: String): Int? =
relationDao.getBrowseResourceCount(resourceId, MusicBrainzResource.RELEASE)?.remoteCount
override suspend fun getLocalLinkedResourcesCountByResource(resourceId: String) =
relationDao.getBrowseResourceCount(resourceId, MusicBrainzResource.RELEASE)?.localCount ?: 0
override suspend fun deleteLinkedResourcesByResource(resourceId: String) {
artistReleaseDao.withTransaction {
artistReleaseDao.deleteReleasesByArtist(resourceId)
artistReleaseDao.deleteArtistReleaseLinks(resourceId)
relationDao.deleteBrowseResourceCountByResource(resourceId, MusicBrainzResource.RELEASE)
}
}
override fun getLinkedResourcesPagingSource(
resourceId: String,
query: String
): PagingSource<Int, ReleaseForListItem> = when {
query.isEmpty() -> {
artistReleaseDao.getReleasesByArtist(resourceId)
}
else -> {
artistReleaseDao.getReleasesByArtistFiltered(
artistId = resourceId,
query = "%$query%"
)
}
}
override fun transformRoomToListItemModel(roomModel: ReleaseForListItem): ReleaseListItemModel {
return roomModel.toReleaseListItemModel()
}
override fun postFilter(listItemModel: ReleaseListItemModel): Boolean {
return true
}
}
| 12
|
Kotlin
|
0
| 0
|
fed58c870f84e30299acfe2205b737e767459328
| 4,930
|
MusicSearch
|
Apache License 2.0
|
lib/src/main/kotlin/com/lemonappdev/konsist/core/provider/KoIsGenericTypeProviderCore.kt
|
LemonAppDev
| 621,181,534
| false
|
{"Kotlin": 5054558, "Python": 46133}
|
package com.lemonappdev.konsist.core.provider
import com.lemonappdev.konsist.api.declaration.type.KoTypeDeclaration
import com.lemonappdev.konsist.api.provider.KoIsGenericTypeProvider
internal interface KoIsGenericTypeProviderCore :
KoIsGenericTypeProvider,
KoSourceAndAliasTypeProviderCore,
KoBaseProviderCore {
override val isGenericType: Boolean
get() {
val regex = "\\w+<[^<>]+>".toRegex()
val type =
if ((this as? KoTypeDeclaration)?.isTypeAlias == true) {
bareSourceType
} else {
sourceType
}
return regex.matches(type)
}
}
| 6
|
Kotlin
|
27
| 1,141
|
696b67799655e2154447ab45f748e983d8bcc1b5
| 690
|
konsist
|
Apache License 2.0
|
src/main/kotlin/io/saagie/astonparking/domain/Spot.kt
|
saagie
| 98,111,756
| false
| null |
package io.saagie.astonparking.domain
import com.fasterxml.jackson.annotation.JsonIgnore
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
@Document
data class Spot(
@JsonIgnore @Id val id: String?,
val number: Int,
var state: State,
var userId: String?
)
| 1
|
Kotlin
|
1
| 0
|
d5cb3c6d16f146e78716e458f09e35927d4c113b
| 347
|
aston-parking
|
MIT License
|
framework/starter-logging/src/main/kotlin/top/bettercode/logging/websocket/WebsocketConfiguration.kt
|
top-bettercode
| 387,652,015
| false
| null |
package top.bettercode.logging.websocket
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.socket.server.standard.ServerEndpointExporter
/**
* 自动增加请求日志过滤器
*
* @author <NAME>
* @since 0.1.5
*/
@ConditionalOnWebApplication
@ConditionalOnClass(org.springframework.web.socket.server.standard.ServerEndpointExporter::class)
@ConditionalOnProperty(prefix = "summer.logging.websocket", name = ["enabled"], havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
class WebsocketConfiguration {
private val log: Logger = LoggerFactory.getLogger(WebsocketConfiguration::class.java)
@Bean
fun serverEndpointExporter(applicationContext: ApplicationContext): ServerEndpointExporter {
WebSocketController.applicationContext = applicationContext
return ServerEndpointExporter()
}
@Bean
fun webSocketController(): WebSocketController {
return WebSocketController()
}
}
| 0
|
Kotlin
|
0
| 1
|
06bc1af2c336a85338f944c969e3be8d55efc387
| 1,384
|
summer
|
Apache License 2.0
|
app/src/main/java/com/satyajit/myshop/ui/searchscreen/SearchBar.kt
|
satyajitdas95
| 669,541,557
| false
| null |
@file:OptIn(ExperimentalMaterial3Api::class)
package com.satyajit.myshop.ui.searchscreen
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.AppBarDefaults
import androidx.compose.material.ContentAlpha
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.flow.MutableStateFlow
@Composable
fun SearchBar(
modifier: Modifier,
placeholderText: String, onSearchTextChanged: (String) -> Unit
) {
var query by rememberSaveable { mutableStateOf("") }
Surface(
modifier,
tonalElevation = AppBarDefaults.TopAppBarElevation,
color = MaterialTheme.colorScheme.background, shape = RoundedCornerShape(percent = 10)
) {
val focusRequester = remember { FocusRequester() }
TextField(modifier = Modifier
.wrapContentHeight()
.focusRequester(focusRequester),
value = query,
onValueChange = {
query = it
onSearchTextChanged(it)
},
placeholder = {
Text(
modifier = Modifier
.alpha(ContentAlpha.disabled),
text = placeholderText,
color = Color.Black,
fontSize = 12.sp
)
},
textStyle = TextStyle(
fontSize = MaterialTheme.typography.bodyMedium.fontSize,
color = Color.Black
),
singleLine = true,
leadingIcon = {
IconButton(
modifier = Modifier
.alpha(ContentAlpha.medium),
onClick = {}
) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = "Search Icon",
tint = Color.Black
)
}
},
trailingIcon = {
if (query.isNotEmpty()) {
IconButton(
onClick = {
if (query.isNotEmpty()) {
query = ""
onSearchTextChanged("")
}
}
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Close Icon",
tint = Color.Black
)
}
}
},
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done, keyboardType = KeyboardType.Text
),
keyboardActions = KeyboardActions(
onSearch = {
focusRequester.freeFocus()
}
),
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.background,
cursorColor = Color.Black.copy(alpha = ContentAlpha.medium)
))
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4241eb2917d22212a01bc35cf2d83aae20686037
| 4,577
|
MyShop
|
MIT License
|
src/main/kotlin/br/com/zup/edu/pix/carrega/CarregaChavePixResponseConverter.kt
|
MirianLuz
| 346,391,954
| true
|
{"Kotlin": 52537}
|
package br.com.zup.edu.pix.carrega
import br.com.zup.edu.CarregaChavePixResponse
import br.com.zup.edu.TipoChave
import br.com.zup.edu.TipoConta
import br.com.zup.edu.pix.ChavePixInfo
import com.google.protobuf.Timestamp
import java.time.ZoneId
class CarregaChavePixResponseConverter {
fun convert(chaveInfo: ChavePixInfo): CarregaChavePixResponse {
return CarregaChavePixResponse.newBuilder()
.setClienteId(chaveInfo.clienteId?.toString() ?: "") // Protobuf usa "" como default value para String
.setPixId(chaveInfo.pixId?.toString() ?: "") // Protobuf usa "" como default value para String
.setChave(CarregaChavePixResponse.ChavePix // 1
.newBuilder()
.setTipoChave(TipoChave.valueOf(chaveInfo.tipo.name)) // 2
.setChave(chaveInfo.chave)
.setConta(
CarregaChavePixResponse.ChavePix.ContaInfo.newBuilder() // 1
.setTipoConta(TipoConta.valueOf(chaveInfo.tipoDeConta.name)) // 2
.setInstituicao(chaveInfo.conta.instituicao) // 1 (Conta)
.setNomeDoTitular(chaveInfo.conta.nomeDoTitular)
.setCpfDoTitular(chaveInfo.conta.cpfDoTitular)
.setAgencia(chaveInfo.conta.agencia)
.setNumeroDaConta(chaveInfo.conta.numeroDaConta)
.build()
)
.setCriadaEm(chaveInfo.registradaEm.let {
val createdAt = it.atZone(ZoneId.of("UTC")).toInstant()
Timestamp.newBuilder()
.setSeconds(createdAt.epochSecond)
.setNanos(createdAt.nano)
.build()
})
)
.build()
}
}
| 0
|
Kotlin
|
0
| 0
|
f9ce7f193ef6772c3dc97aeed0817f65f8638d0c
| 1,831
|
orange-talents-01-template-pix-keymanager-grpc
|
Apache License 2.0
|
app/src/main/java/com/ctrlaccess/moviebuff/ResourceCompare.kt
|
galemu2
| 415,395,349
| false
|
{"Kotlin": 67065}
|
package com.ctrlaccess.moviebuff
import android.content.Context
class ResourceCompare {
fun isEqual(
context: Context,
resId: Int,
string: String
): Boolean {
return context.getString(resId) == string
}
}
| 0
|
Kotlin
|
0
| 0
|
287fa00f50eb97c7da2ef43231fbc59e4ccc6156
| 251
|
Movie-Buff
|
MIT License
|
app/src/main/java/com/jaseem/apod/presentation/ui/theme/Color.kt
|
Jaseemakhtar
| 570,799,517
| false
| null |
package com.jaseem.apod.presentation.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val EbonyClay500 = Color(0xFF22323E)
val RiverBed500 = Color(0xFF4B5861)
| 0
|
Kotlin
|
0
| 0
|
c040ce5d7b32ca15088e0cd3bcdf64cb9d2dd894
| 366
|
AssignmentApod
|
Apache License 2.0
|
lib-client/src/main/java/com/baptistecarlier/kotlin/datagouvfr/client/model/Schema.kt
|
BapNesS
| 393,147,318
| false
| null |
package com.baptistecarlier.kotlin.datagouvfr.client.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* @property id The schema identifier
* @property label The schema display name
* @property versions The available versions of the schema
*/
@Serializable
data class Schema(
@SerialName("id")
var id: String? = null,
@SerialName("label")
var label: String? = null,
@SerialName("versions")
var versions: List<String>? = null
)
| 3
|
Kotlin
|
0
| 2
|
f4b849f1b4377c781423bc0b4afbe37fd69ed3e7
| 499
|
kotlin-datagouvfr-client
|
Apache License 2.0
|
services/csm.cloud.project.news/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/event/model/LiveUpdateEvent.kt
|
boschglobal
| 805,348,245
| false
|
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
package com.bosch.pt.csm.cloud.projectmanagement.event.model
import com.bosch.pt.csm.cloud.projectmanagement.news.model.ObjectIdentifier
import com.fasterxml.jackson.annotation.JsonProperty
class LiveUpdateEvent(
val root: ObjectIdentifier,
@JsonProperty("object") val objectIdentifier: ObjectIdentifierWithVersion,
val event: String
)
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 350
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
app/src/main/java/xyz/teamgravity/channel/MainActivity.kt
|
raheemadamboev
| 330,661,855
| false
| null |
package xyz.teamgravity.channel
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.flow.collect
import xyz.teamgravity.channel.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
// collect events
lifecycleScope.launchWhenStarted {
viewModel.eventFlow.collect { event ->
when (event) {
is MainViewModel.MainEvent.ErrorEvent ->
Snackbar.make(parentLayout, event.message, Snackbar.LENGTH_LONG).show()
}
}
}
// show button
showB.setOnClickListener {
viewModel.triggerEvent(resources)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b62717be76f831fc3c4a08e27f2ccb4d39f71e8c
| 1,255
|
channel-app
|
Apache License 2.0
|
app/src/main/java/com/example/hwangtube/ui/home/VideoListAdapter.kt
|
tutorhwang
| 737,711,501
| false
|
{"Kotlin": 25571}
|
package com.example.hwangtube.ui.home
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.hwangtube.R
import com.example.hwangtube.data.model.youtube.ListItem
import com.example.hwangtube.databinding.ItemLayout2Binding
import com.example.hwangtube.databinding.ItemLayoutBinding
class VideoListAdapter(
private val onClick: (ListItem) -> Unit,
private val onFavoriteClick: (ListItem.VideoItem) -> Unit
) :
ListAdapter<ListItem, RecyclerView.ViewHolder>(object : DiffUtil.ItemCallback<ListItem>() {
override fun areItemsTheSame(oldItem: ListItem, newItem: ListItem): Boolean {
return when {
oldItem is ListItem.HeaderItem && newItem is ListItem.HeaderItem ->
oldItem.thumbnail == newItem.thumbnail
oldItem is ListItem.VideoItem && newItem is ListItem.VideoItem ->
oldItem.title == newItem.title
else -> false
}
}
override fun areContentsTheSame(oldItem: ListItem, newItem: ListItem): Boolean {
return oldItem == newItem
}
}) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
TYPE_HEADER -> {
val binding =
ItemLayout2Binding.inflate(LayoutInflater.from(parent.context), parent, false)
HeaderItemHolder(binding)
}
else -> {
val binding =
ItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
VideoItemHolder(binding)
}
}
}
override fun onBindViewHolder(itemHolder: RecyclerView.ViewHolder, position: Int) {
runCatching {
when (val item = getItem(position)) {
is ListItem.HeaderItem -> {
(itemHolder as HeaderItemHolder).bind(item)
}
is ListItem.VideoItem -> {
(itemHolder as VideoItemHolder).bind(item)
}
}
}.onFailure { exception ->
Log.e("VideoListAdapter", "Exception! ${exception.message}")
}
}
override fun getItemViewType(position: Int): Int {
return when (getItem(position)) {
is ListItem.HeaderItem -> TYPE_HEADER
is ListItem.VideoItem -> TYPE_CONTENT
}
}
companion object {
private const val TYPE_HEADER = 0
private const val TYPE_CONTENT = 1
}
inner class VideoItemHolder(binding: ItemLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
private val channelLogoView = binding.logo
private val channelNameView = binding.channelName
private val titleView = binding.title
private val thumbnailView = binding.mainImage
private val favoriteButton = binding.ivHeart
fun bind(video: ListItem.VideoItem) {
with(video) {
Glide.with(itemView).load(thumbnail).into(thumbnailView)
thumbnailView.setOnClickListener { onClick(this) }
titleView.text = title
channelNameView.text = channelTitle
channelLogoView.setImageResource(R.drawable.haelin)
favoriteButton.setFavorite(isFavorite)
favoriteButton.setOnClickListener {
isFavorite = !isFavorite
(it as ImageView).setFavorite(isFavorite)
it.startFavoriteAnimation(isFavorite)
onFavoriteClick(this)
}
}
}
private fun ImageView.setFavorite(isFavorite: Boolean) {
val favoriteRes = if (isFavorite) R.color.favorite_on else R.color.favorite_off
val favoriteColor = ContextCompat.getColor(context, favoriteRes)
DrawableCompat.setTint(drawable, favoriteColor)
}
private fun ImageView.startFavoriteAnimation(favorite: Boolean) {
val startColor = if (favorite) R.color.favorite_off else R.color.favorite_on
val endColor = if (favorite) R.color.favorite_on else R.color.favorite_off
val colorAnimation = ValueAnimator.ofObject(
ArgbEvaluator(),
ContextCompat.getColor(context, startColor),
ContextCompat.getColor(context, endColor)
)
colorAnimation.duration = 500L
colorAnimation.addUpdateListener { animator ->
val animatedColor = animator.animatedValue as Int
val wrappedDrawable = DrawableCompat.wrap(drawable).mutate()
DrawableCompat.setTint(wrappedDrawable, animatedColor)
setImageDrawable(wrappedDrawable)
}
colorAnimation.start()
}
}
inner class HeaderItemHolder(binding: ItemLayout2Binding) :
RecyclerView.ViewHolder(binding.root) {
private val thumbnailView = binding.mainImage
fun bind(item: ListItem.HeaderItem) {
with(item) {
Glide.with(itemView).load(thumbnail).into(thumbnailView)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c354210fa230ffabfbb8e21dd2fdb89beae91b11
| 5,640
|
HwangTube
|
MIT License
|
src/main/kotlin/com/jalgoarena/domain/UserSubmissionsEvent.kt
|
jalgoarena
| 77,244,989
| false
| null |
package com.jalgoarena.domain
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
@JsonIgnoreProperties(ignoreUnknown = true)
data class UserSubmissionsEvent(
val type: String = "refreshUserSubmissions",
val userId: String,
val problemId: String,
val submissionId: String
)
| 2
|
Kotlin
|
22
| 3
|
f319b36b1b4a56e92f8277acc7ce33040a7e6363
| 316
|
JAlgoArena-Submissions
|
Apache License 2.0
|
app/src/main/java/com/thk/sevendays/ui/theme/SevenDaysTheme.kt
|
taehee28
| 453,343,657
| false
|
{"Kotlin": 81020}
|
package com.thk.sevendays.ui.theme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
object SevenDaysTheme {
val colors: SevenDaysColors
@Composable
@ReadOnlyComposable
get() = LocalSevenDaysColors.current
}
| 0
|
Kotlin
|
1
| 0
|
6d0dfcf4439b7608c941054dfad65e6c305c79bf
| 281
|
SevenDays
|
MIT License
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/serenitea_pot/fish_farming/HomeScenePointFishFarmingInfo.kt
|
Anime-Game-Servers
| 642,871,918
| false
|
{"Kotlin": 1651536}
|
package org.anime_game_servers.multi_proto.gi.data.serenitea_pot.fish_farming
import org.anime_game_servers.core.base.Version.GI_3_2_0
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.ProtoModel
@AddedIn(GI_3_2_0)
@ProtoModel
internal interface HomeScenePointFishFarmingInfo {
var fishIdList: List<Int>
var localEntityId: Int
var sceneId: Int
}
| 0
|
Kotlin
|
2
| 6
|
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
| 428
|
anime-game-multi-proto
|
MIT License
|
inappmessaging/src/test/java/com/rakuten/tech/mobile/inappmessaging/runtime/data/repositories/ReadyForDisplayMessageRepositorySpec.kt
|
donnie-jp
| 358,824,345
| true
|
{"Kotlin": 483530}
|
package com.rakuten.tech.mobile.inappmessaging.runtime.data.repositories
import com.rakuten.tech.mobile.inappmessaging.runtime.BaseTest
import com.rakuten.tech.mobile.inappmessaging.runtime.data.models.messages.Message
import com.rakuten.tech.mobile.inappmessaging.runtime.data.models.messages.ValidTestMessage
import com.rakuten.tech.mobile.inappmessaging.runtime.utils.InAppMessagingConstants
import org.amshove.kluent.shouldBeEmpty
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldHaveSize
import org.junit.Assert
import org.junit.Before
import org.junit.Test
/**
* Test class for ReadyForDisplayMessageRepository.
*/
class ReadyForDisplayMessageRepositorySpec : BaseTest() {
private val messageList = ArrayList<Message>()
private val message0 = ValidTestMessage()
private val message1 = ValidTestMessage("1234")
@Before
fun setup() {
ReadyForDisplayMessageRepository.instance().clearMessages()
PingResponseMessageRepository.instance().clearMessages()
message0.timesClosed = 0
message1.timesClosed = 0
messageList.add(message0)
messageList.add(message1)
PingResponseMessageRepository.instance().replaceAllMessages(messageList)
}
@Test
fun `should throw exception when list is null`() {
try {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(null)
Assert.fail()
} catch (e: IllegalArgumentException) {
e.localizedMessage shouldBeEqualTo InAppMessagingConstants.ARGUMENT_IS_NULL_EXCEPTION
}
}
@Test
fun `should be empty after clearing`() {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(2)
ReadyForDisplayMessageRepository.instance().clearMessages()
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(0)
}
@Test
fun `should contain correct messages after clearing then adding`() {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(2)
ReadyForDisplayMessageRepository.instance().clearMessages()
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(0)
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(2)
}
@Test
fun `should remove matching message and increment times closed`() {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().removeMessage(message0.getCampaignId(), true)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(1)
for (msg in PingResponseMessageRepository.instance().getAllMessagesCopy()) {
if (msg.getCampaignId() == message0.getCampaignId()) {
msg.getNumberOfTimesClosed() shouldBeEqualTo 1
} else {
msg.getNumberOfTimesClosed() shouldBeEqualTo 0
}
}
}
@Test
fun `should remove matching message but not increment`() {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().removeMessage(message0.getCampaignId(), false)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(1)
for (msg in PingResponseMessageRepository.instance().getAllMessagesCopy()) {
msg.getNumberOfTimesClosed() shouldBeEqualTo 0
}
}
@Test
fun `should not remove and not increment when no match`() {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().removeMessage("4321", false)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(2)
for (msg in PingResponseMessageRepository.instance().getAllMessagesCopy()) {
msg.getNumberOfTimesClosed() shouldBeEqualTo 0
}
}
@Test
fun `should not remove and not increment when no match and flag true`() {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().removeMessage("4321", true)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldHaveSize(2)
for (msg in PingResponseMessageRepository.instance().getAllMessagesCopy()) {
msg.getNumberOfTimesClosed() shouldBeEqualTo 0
}
}
@Test
fun `should clear messages and increment times closed`() {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().clearMessages(true)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldBeEmpty()
for (msg in PingResponseMessageRepository.instance().getAllMessagesCopy()) {
msg.getNumberOfTimesClosed() shouldBeEqualTo 1
}
}
@Test
fun `should clear messages but not increment times closed`() {
ReadyForDisplayMessageRepository.instance().replaceAllMessages(messageList)
ReadyForDisplayMessageRepository.instance().clearMessages(false)
ReadyForDisplayMessageRepository.instance().getAllMessagesCopy().shouldBeEmpty()
for (msg in PingResponseMessageRepository.instance().getAllMessagesCopy()) {
msg.getNumberOfTimesClosed() shouldBeEqualTo 0
}
}
}
| 0
| null |
0
| 0
|
ee0ae9ba299dd769d7b2553d97abd22c68e3e3a8
| 5,742
|
android-inappmessaging
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/ui/home/ThemeCard.kt
|
onlyloveyd
| 347,247,313
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.home
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.data.PlantTheme
import com.example.androiddevchallenge.data.PlantThemes
import com.example.androiddevchallenge.ui.theme.BloomTheme
@Composable
fun ThemeCard(plantTheme: PlantTheme) {
Card(
shape = BloomTheme.shapes.small,
elevation = BloomTheme.elevations.card,
modifier = Modifier
.wrapContentSize()
.padding(bottom = 8.dp),
backgroundColor = MaterialTheme.colors.background
) {
Column(modifier = Modifier.wrapContentSize()) {
Image(
painter = painterResource(id = plantTheme.cover),
contentDescription = plantTheme.name,
contentScale = ContentScale.Crop,
modifier = Modifier
.width(136.dp)
.height(96.dp)
)
Text(
text = plantTheme.name,
style = MaterialTheme.typography.h2,
textAlign = TextAlign.Start,
color = BloomTheme.colors.onPrimary,
modifier = Modifier
.paddingFromBaseline(
top = 24.dp,
bottom = 16.dp,
)
.padding(start = 16.dp)
)
}
}
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun LightPreviewThemeCard() {
BloomTheme(darkTheme = false) {
ThemeCard(PlantThemes[0])
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun DarkPreviewThemeCard() {
BloomTheme(darkTheme = false) {
ThemeCard(PlantThemes[0])
}
}
| 0
|
Kotlin
|
0
| 1
|
4d54f6b663bd06a771003d20932534949d161def
| 3,113
|
Jetpack-Compose-SpeedRound
|
Apache License 2.0
|
JobScheduler/app/src/main/java/com/thakur/android/jobscheduler/BootCompletedReceiver.kt
|
ankitthakur
| 149,578,562
| false
| null |
package com.thakur.android.jobscheduler
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
class BootCompletedReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("1", "onReceive");
// context?.let { connectivityCheckJobSchedule(it) }
}
}
| 0
|
Kotlin
|
0
| 0
|
d9c77a51b81e8ba1ae1bc8b8a9f921944c7190ca
| 385
|
JobScheduler
|
MIT License
|
app/src/main/java/com/bngel/bcy/dao/CosControllerDao/CosControllerDao.kt
|
Bngel
| 389,700,084
| false
| null |
package com.bngel.bcy.dao.CosControllerDao
import com.bngel.bcy.bean.CosController.deleteAcgCos.DeleteAcgCos
import com.bngel.bcy.bean.CosController.deleteAcgLikeCosComment.DeleteAcgLikeCosComment
import com.bngel.bcy.bean.CosController.deleteEsAllSearchHistory.DeleteEsAllSearchHistory
import com.bngel.bcy.bean.CosController.deleteEsSearchHistory.DeleteEsSearchHistory
import com.bngel.bcy.bean.CosController.getAcgCos.GetAcgCos
import com.bngel.bcy.bean.CosController.getAcgCosComment.GetAcgCosComment
import com.bngel.bcy.bean.CosController.getAcgCosCommentComment.GetAcgCosCommentComment
import com.bngel.bcy.bean.CosController.getAcgCosCommentCountsList.GetAcgCosCommentCountsList
import com.bngel.bcy.bean.CosController.getAcgCosCountsList.GetAcgCosCountsList
import com.bngel.bcy.bean.CosController.getAcgFollowCos.GetAcgFollowCos
import com.bngel.bcy.bean.CosController.getAcgFollowNoRead.GetAcgFollowNoRead
import com.bngel.bcy.bean.CosController.getAcgRecommendList.GetAcgRecommendList
import com.bngel.bcy.bean.CosController.getEsLabelCos.GetEsLabelCos
import com.bngel.bcy.bean.CosController.getEsRecommendCos.GetEsRecommendCos
import com.bngel.bcy.bean.CosController.getEsSearchHistory.GetEsSearchHistory
import com.bngel.bcy.bean.CosController.postAcgCos.PostAcgCos
import com.bngel.bcy.bean.CosController.postAcgCosComment.PostAcgCosComment
import com.bngel.bcy.bean.CosController.postAcgCosPhotoUpload.PostAcgCosPhotoUpload
import com.bngel.bcy.bean.CosController.postAcgLikeCosComment.PostAcgLikeCosComment
import com.bngel.bcy.bean.CosController.postEsSearchCos.PostEsSearchCos
import com.bngel.bcy.web.SSLSocketClient
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.*
import java.util.concurrent.TimeUnit
interface CosControllerDao {
/**
* 获取cos页面上半部分内容(获取底下评论在另外一个接口)
*/
@GET("/acg/cos")
fun getAcgCos(
@Query("id") id: String?,
@Query("number") number: String,
@Query("token") token: String?
): Call<GetAcgCos>
/**
* 发布cos
*/
@POST("/acg/cos")
fun postAcgCos(
@Query("id") id: String,
@Query("description") description: String,
@Query("label") label: List<String>,
@Query("permission") permission: Int,
@Query("photo") photo: List<String>,
@Query("token") token: String
): Call<PostAcgCos>
/**
* 批量删除Cos(管理员用,如果违反规定就删除)(只有一个也扔这个接口~)
*/
@DELETE("/acg/cos")
fun deleteAcgCos(
@Query("numbers") numbers: List<String>
): Call<DeleteAcgCos>
/**
* 修改cos内容(没改的参数不要带,或者可以带空,图片要注意下带空就是没图)
*/
@PUT("/acg/cos")
fun putAcgCos(
@Query("id") id: String,
@Query("number") number: String,
@Query("description") description: String?,
@Query("permission") permission: String?,
@Query("cosPhoto") cosPhoto: List<String>?,
@Query("token") token: String
)//: Call<PutAcgCos>
/**
* 获取cos页面下面的评论内容
*/
@GET("/acg/cosComment")
fun getAcgCosComment(
@Query("id") id: String?,
@Query("number") number: String,
@Query("cnt") cnt: Int,
@Query("page") page: Int,
@Query("type") type: Int,
@Query("token") token: String?
): Call<GetAcgCosComment>
/**
* 发表cos下面的评论
*/
@POST("/acg/cosComment")
fun postAcgCosComment(
@Query("id") id: String,
@Query("cosNumber") cosNumber: String,
@Query("description") description: String,
@Query("fatherNumber") fatherNumber: String?,
@Query("reply") reply: String?,
@Query("replyNumber") replyNumber: String?,
@Query("toId") toId: String?,
@Query("token") token: String
): Call<PostAcgCosComment>
/**
* 获取cos下面评论的评论列表(在cos页面也用这个接口获取下面的回复数据,cnt请填3 page请填1 type请填1)
*/
@GET("/acg/cosCommentComment")
fun getAcgCosCommentComment(
@Query("id") id: String?,
@Query("cnt") cnt: Int,
@Query("number") number: String,
@Query("page") page: Int,
@Query("type") type: Int,
@Query("token") token: String?
): Call<GetAcgCosCommentComment>
/**
* 获取cos下面评论的点赞数和评论数
*/
@GET("/acg/cosCommentCountsList")
fun getAcgCosCommentCountsList(
@Query("id") id: String?,
@Query("number") number: String,
@Query("token") token: String?
): Call<GetAcgCosCommentCountsList>
/**
* 获取cos的 点赞 评论 收藏数
*/
@GET("/acg/cosCountsList")
fun getAcgCosCountsList(
@Query("id") id: String?,
@Query("number") number: String,
@Query("token") token: String?
): Call<GetAcgCosCountsList>
/**
* cos图片上传
*/
@Multipart
@POST("/acg/cosPhotoUpload")
fun postAcgCosPhotoUpload(
@Part photo: MultipartBody.Part,
@Part("token") token: String
): Call<PostAcgCosPhotoUpload>
/**
* 获取关注用户的cos列表
*/
@GET("/acg/followCos")
fun getAcgFollowCos(
@Query("id") id: String,
@Query("cnt") cnt: Int,
@Query("page") page: Int,
@Query("token") token: String
): Call<GetAcgFollowCos>
/**
* 获取关注的未读数(获取关注的cos的关注列表后会清空)
*/
@GET("/acg/followNoRead")
fun getAcgFollowNoRead(
@Query("id") id: String,
@Query("token") token: String
): Call<GetAcgFollowNoRead>
/**
* 获取日榜热门cos列表
*/
@GET("/acg/hotDayCos")
fun getAcgHotDayCos(
@Query("time") time: String,
@Query("type") type: Int
)//: Call<GetAcgHotDayCos>
/**
* 获取周榜热门cos列表
*/
@GET("/acg/hotWeekCos")
fun getAcgHotWeekCos(
@Query("time") time: String
)//: Call<GetAcgHotWeekCos>
/**
* 点赞cos下的评论
*/
@POST("/acg/likeCosComment")
fun postAcgLikeCosComment(
@Query("id") id: String,
@Query("number") number: String,
@Query("token") token: String
): Call<PostAcgLikeCosComment>
/**
* 取消点赞cos下的评论
*/
@DELETE("/acg/likeCosComment")
fun deleteAcgLikeCosComment(
@Query("id") id: String,
@Query("number") number: String,
@Query("token") token: String
): Call<DeleteAcgLikeCosComment>
/**
* 获取推荐cos标签
*/
@GET("/acg/recommendList")
fun getAcgRecommendList(
): Call<GetAcgRecommendList>
/**
* 清空所有(搜索)历史记录
*/
@DELETE("/es/allSearchHistory")
fun deleteEsAllSearchHistory(
@Query("id") id: String,
@Query("token") token: String
): Call<DeleteEsAllSearchHistory>
/**
* 获取标题(绘画 cos 写作)下的cos内容(也是推荐制的,随机)
*/
@GET("/es/labelCos")
fun getEsLabelCos(
@Query("cnt") cnt: Int,
@Query("id") id: String,
@Query("keyword") keyword: String,
@Query("page") page: Int,
@Query("token") token: String
): Call<GetEsLabelCos>
/**
* 发现(推荐cos,在不同的获取是会有重复推荐的)
*/
@GET("/es/recommendCos")
fun getEsRecommendCos(
@Query("cnt") cnt: Int,
@Query("id") id: String,
@Query("token") token: String?
): Call<GetEsRecommendCos>
/**
* cos搜索(会匹配标签内容和描述 拼音分词(搜拼音也能搜到) + ik细粒度分词)
*/
@POST("/es/searchCos")
fun postEsSearchCos(
@Query("cnt") cnt: Int,
@Query("id") id: String,
@Query("keyword") keyword: String,
@Query("page") page: Int,
@Query("token") token: String?
): Call<PostEsSearchCos>
/**
* 获取搜索历史
*/
@GET("/es/searchHistory")
fun getEsSearchHistory(
@Query("id") id: String,
@Query("token") token: String
): Call<GetEsSearchHistory>
/**
* 删除历史搜索
*/
@DELETE("/es/searchHistory")
fun deleteEsSearchHistory(
@Query("id") id: String,
@Query("token") token: String
): Call<DeleteEsSearchHistory>
companion object {
fun create(): CosControllerDao {
val baseUrl = "https://www.rat403.cn/"
val gson = GsonBuilder()
.setLenient()
.create()
val mHttpClient = OkHttpClient().newBuilder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.sslSocketFactory(SSLSocketClient.SSLSocketFactory)//配置
.hostnameVerifier(SSLSocketClient.hostnameVerifier)//配置
.build()
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(mHttpClient)
.build()
return retrofit.create(CosControllerDao::class.java)
}
fun create(gson: Gson): CosControllerDao {
val baseUrl = "https://www.rat403.cn/"
val mHttpClient = OkHttpClient().newBuilder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.sslSocketFactory(SSLSocketClient.SSLSocketFactory)//配置
.hostnameVerifier(SSLSocketClient.hostnameVerifier)//配置
.build();
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(mHttpClient)
.build()
return retrofit.create(CosControllerDao::class.java)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f8091bdbb9d4b7720587def7411b72a9c2d6fe35
| 9,688
|
bcy
|
Apache License 2.0
|
src/main/kotlin/me/bristermitten/plumber/dsl/TaskLengthConfiguration.kt
|
knightzmc
| 205,340,852
| false
| null |
package me.bristermitten.plumber.dsl
import me.bristermitten.plumber.dsl.implementation.DefaultTaskLengthConfiguration
import me.bristermitten.plumber.scheduling.timings.TimeUnitPicker
/**
* Interface for deciding how long a task should take
* @param B the child interface for later configuration
*/
interface TaskLengthConfiguration<B : ActionBuilder<*>> {
/**
* Do the task forever
*/
fun forever()
/**
* Do the task until certain conditions are met, at which point it will be cancelled/undone depending on the task
* @return the child interface to configure the conditions
*/
fun until(): B
/**
* Undo the task (if applicable) after a certain length of time
* @param time the length of time in arbitrary units
* @return a [TimeUnitPicker] to configure the length of time
*/
fun undoAfter(time: Long): TimeUnitPicker<B>
companion object {
var impl: Class<out TaskLengthConfiguration<*>> = DefaultTaskLengthConfiguration::class.java
}
}
| 0
|
Kotlin
|
1
| 5
|
94086cda311397d42e7b603daaffbeb877f14177
| 1,032
|
plumber
|
MIT License
|
src/main/kotlin/com/github/jntakpe/releasemonitor/model/client/FolderChildren.kt
|
jntakpe
| 106,203,948
| false
| null |
package com.github.jntakpe.releasemonitor.model.client
data class FolderChildren(val uri: String)
| 0
|
Kotlin
|
0
| 0
|
8dbbac5839efaf1b4a314a5746885cc2bd5bee72
| 98
|
release-monitor
|
MIT License
|
backend/src/main/java/backend/mwvb/service/UserChangePasswordService.kt
|
ShorterThanDijkstra
| 475,805,906
| false
|
{"Kotlin": 3601851, "Java": 135590, "Vue": 64832, "Shell": 574}
|
package backend.mwvb.service
import backend.mwvb.entity.ResetPasswordInfo
interface UserChangePasswordService {
companion object {
const val CHANGE_PASSWORD_INFO_EXPIRE = 10 * 60 * 1000L
const val CHANGE_PASSWORD_JWT_SUBJECT = "USER-CHANGE-PASSWORD"
const val CHANGE_PASSWORD_JWT_CLAIMS_KEY = "USER-EMAIL"
}
fun request(email: String)
fun complete(resetPasswordInfo: ResetPasswordInfo)
}
| 0
|
Kotlin
|
0
| 0
|
ee59db5d24c8817285a3f8f22fa3d0c983a5a451
| 430
|
silver-apples
|
MIT License
|
src/main/kotlin/com/kalikov/game/GameField.kt
|
kalikov
| 696,277,791
| false
|
{"Kotlin": 422636}
|
package com.kalikov.game
class GameField(
private val eventRouter: EventRouter,
private val imageManager: ImageManager,
private val entityFactory: EntityFactory,
private val spriteContainer: SpriteContainer,
x: Int = Globals.UNIT_SIZE,
y: Int = Globals.UNIT_SIZE
) {
private companion object {
private const val SIZE = 13 * Globals.UNIT_SIZE
}
val bounds = Rect(x, y, SIZE, SIZE)
fun load(map: StageMapConfig, playersCount: Int) {
val cleanRects = mutableSetOf(
Rect(map.base, 2, 2).multiply(Globals.TILE_SIZE).translate(bounds.x, bounds.y)
)
map.playerSpawnPoints.asSequence()
.take(playersCount)
.map {
Rect(it, 2, 2).multiply(Globals.TILE_SIZE).translate(bounds.x, bounds.y)
}.forEach {
cleanRects.add(it)
}
map.enemySpawnPoints.forEach {
cleanRects.add(Rect(it, 2, 2).multiply(Globals.TILE_SIZE).translate(bounds.x, bounds.y))
}
for (mapObject in map.objects) {
val sprite = entityFactory.create(
mapObject.type,
bounds.x + mapObject.x * Globals.TILE_SIZE,
bounds.y + mapObject.y * Globals.TILE_SIZE
)
if (cleanRects.none { it.intersects(sprite.bounds) }) {
spriteContainer.addSprite(sprite)
} else {
sprite.dispose()
}
}
spriteContainer.addSprite(
Base(
eventRouter,
imageManager,
bounds.x + map.base.x * Globals.TILE_SIZE,
bounds.y + map.base.y * Globals.TILE_SIZE
)
)
}
fun update() {
val sprites = spriteContainer.sprites
sprites.forEach { it.update() }
}
fun draw(surface: ScreenSurface) {
surface.fillRect(bounds.x, bounds.y, bounds.width, bounds.height, ARGB.BLACK)
spriteContainer.sprites.forEach {
if (!it.isDestroyed) {
it.draw(surface)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8430011ec8cf4957d6a4401752ea0dec8a099e65
| 2,116
|
battle-city
|
MIT License
|
app/src/main/java/br/com/iwatasoftware/basickotlinapp/activity/addcountry/AddCountryView.kt
|
BrendonIwata
| 248,399,355
| false
| null |
package br.com.iwatasoftware.basickotlinapp.activity.addcountry
interface AddCountryView {
fun showToast (texto : String)
}
| 0
|
Kotlin
|
0
| 0
|
02460528ba3beba47f223fc19c3e45dcf37ced00
| 128
|
CountryListKotlinApp
|
The Unlicense
|
dataforge-meta/src/commonMain/kotlin/space/kscience/dataforge/meta/MetaDelegate.kt
|
SciProgCentre
| 148,831,678
| false
|
{"Kotlin": 393889}
|
package space.kscience.dataforge.meta
import space.kscience.dataforge.meta.descriptors.MetaDescriptor
import space.kscience.dataforge.misc.DFExperimental
import space.kscience.dataforge.names.Name
import space.kscience.dataforge.names.asName
import kotlin.properties.ReadOnlyProperty
/* Meta delegates */
public fun MetaProvider.node(key: Name? = null): ReadOnlyProperty<Any?, Meta?> = ReadOnlyProperty { _, property ->
get(key ?: property.name.asName())
}
/**
* Use [metaSpec] to read the Meta node
*/
public fun <T> MetaProvider.spec(
metaSpec: MetaSpec<T>,
key: Name? = null,
): ReadOnlyProperty<Any?, T?> = ReadOnlyProperty { _, property ->
get(key ?: property.name.asName())?.let { metaSpec.read(it) }
}
/**
* Use object serializer to transform it to Meta and back
*/
@DFExperimental
public inline fun <reified T> MetaProvider.serializable(
descriptor: MetaDescriptor? = null,
key: Name? = null,
): ReadOnlyProperty<Any?, T?> = spec(MetaConverter.serializable(descriptor), key)
@Deprecated("Use convertable", ReplaceWith("convertable(converter, key)"))
public fun <T> MetaProvider.node(
key: Name? = null,
converter: MetaSpec<T>,
): ReadOnlyProperty<Any?, T?> = spec(converter, key)
/**
* Use [converter] to convert a list of same name siblings meta to object
*/
public fun <T> Meta.listOfSpec(
converter: MetaSpec<T>,
key: Name? = null,
): ReadOnlyProperty<Any?, List<T>> = ReadOnlyProperty{_, property ->
val name = key ?: property.name.asName()
getIndexed(name).values.map { converter.read(it) }
}
@DFExperimental
public inline fun <reified T> Meta.listOfSerializable(
descriptor: MetaDescriptor? = null,
key: Name? = null,
): ReadOnlyProperty<Any?, List<T>> = listOfSpec(MetaConverter.serializable(descriptor), key)
/**
* A property delegate that uses custom key
*/
public fun MetaProvider.value(key: Name? = null): ReadOnlyProperty<Any?, Value?> = ReadOnlyProperty { _, property ->
get(key ?: property.name.asName())?.value
}
public fun <R> MetaProvider.value(
key: Name? = null,
reader: (Value?) -> R,
): ReadOnlyProperty<Any?, R> = ReadOnlyProperty { _, property ->
reader(get(key ?: property.name.asName())?.value)
}
//TODO add caching for sealed nodes
/* Read-only delegates for [Meta] */
public fun MetaProvider.string(key: Name? = null): ReadOnlyProperty<Any?, String?> = value(key) { it?.string }
public fun MetaProvider.boolean(key: Name? = null): ReadOnlyProperty<Any?, Boolean?> = value(key) { it?.boolean }
public fun MetaProvider.number(key: Name? = null): ReadOnlyProperty<Any?, Number?> = value(key) { it?.numberOrNull }
public fun MetaProvider.double(key: Name? = null): ReadOnlyProperty<Any?, Double?> = value(key) { it?.double }
public fun MetaProvider.float(key: Name? = null): ReadOnlyProperty<Any?, Float?> = value(key) { it?.float }
public fun MetaProvider.int(key: Name? = null): ReadOnlyProperty<Any?, Int?> = value(key) { it?.int }
public fun MetaProvider.long(key: Name? = null): ReadOnlyProperty<Any?, Long?> = value(key) { it?.long }
public fun MetaProvider.string(default: String, key: Name? = null): ReadOnlyProperty<Any?, String> =
value(key) { it?.string ?: default }
public fun MetaProvider.boolean(default: Boolean, key: Name? = null): ReadOnlyProperty<Any?, Boolean> =
value(key) { it?.boolean ?: default }
public fun MetaProvider.number(default: Number, key: Name? = null): ReadOnlyProperty<Any?, Number> =
value(key) { it?.numberOrNull ?: default }
public fun MetaProvider.double(default: Double, key: Name? = null): ReadOnlyProperty<Any?, Double> =
value(key) { it?.double ?: default }
public fun MetaProvider.float(default: Float, key: Name? = null): ReadOnlyProperty<Any?, Float> =
value(key) { it?.float ?: default }
public fun MetaProvider.int(default: Int, key: Name? = null): ReadOnlyProperty<Any?, Int> =
value(key) { it?.int ?: default }
public fun MetaProvider.long(default: Long, key: Name? = null): ReadOnlyProperty<Any?, Long> =
value(key) { it?.long ?: default }
public inline fun <reified E : Enum<E>> MetaProvider.enum(default: E, key: Name? = null): ReadOnlyProperty<Any?, E> =
value<E>(key) { it?.enum<E>() ?: default }
public fun MetaProvider.string(key: Name? = null, default: () -> String): ReadOnlyProperty<Any?, String> =
value(key) { it?.string ?: default() }
public fun MetaProvider.boolean(key: Name? = null, default: () -> Boolean): ReadOnlyProperty<Any?, Boolean> =
value(key) { it?.boolean ?: default() }
public fun MetaProvider.number(key: Name? = null, default: () -> Number): ReadOnlyProperty<Any?, Number> =
value(key) { it?.numberOrNull ?: default() }
| 14
|
Kotlin
|
3
| 24
|
8116489e8bd07e677a4fb78a4dd20d41172783d4
| 4,686
|
dataforge-core
|
Apache License 2.0
|
src/test/kotlin/dev/arli/openapi/model/TagTest.kt
|
alipovatyi
| 487,519,792
| false
|
{"Kotlin": 451322}
|
package dev.arli.openapi.model
import com.google.common.truth.Truth.assertThat
import io.ktor.http.Url
import org.junit.jupiter.api.Test
internal class TagTest {
@Test
fun `Should create tag`() {
val expectedTag = Tag(
name = "Tag",
description = "Description",
externalDocs = ExternalDocumentation(
url = Url("http://localhost/external-docs")
)
)
val actualTag = Tag.Builder(name = "Tag").apply {
description = "Description"
externalDocs(url = Url("http://localhost/external-docs"))
}.build()
assertThat(actualTag).isEqualTo(expectedTag)
}
@Test
fun `Should create tag with default values`() {
val expectedTag = Tag(
name = "Tag",
description = null,
externalDocs = null
)
val actualTag = Tag.Builder(name = "Tag").build()
assertThat(actualTag).isEqualTo(expectedTag)
}
}
| 0
|
Kotlin
|
1
| 1
|
3637b43dc2e255f263b559a5a80ebf80f3e78d96
| 1,001
|
ktor-openapi
|
Apache License 2.0
|
meistercharts-canvas/src/commonMain/kotlin/com/meistercharts/font/FontVariant.kt
|
Neckar-IT
| 599,079,962
| false
| null |
/**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.font
/**
* Selects a normal, or small-caps face from a font family
*
* [CSS font-variant](https://developer.mozilla.org/de/docs/Web/CSS/font-variant)
*
* Attention! small-caps may lead to unforeseen problems! Use with care.
*/
enum class FontVariant {
/**
* A normal font variant
*/
Normal,
/**
* Attention! This may lead to unforeseen problems. Use with care
*/
SmallCaps
}
| 3
| null |
3
| 5
|
ed849503e845b9d603598e8d379f6525a7a92ee2
| 1,047
|
meistercharts
|
Apache License 2.0
|
src/main/kotlin/com/bloock/sdk/proof/entity/Proof.kt
|
bloock
| 305,086,190
| false
| null |
package com.bloock.sdk.proof.entity
import com.bloock.sdk.shared.Utils
import kotlin.math.floor
class Proof(
val leaves: List<String>,
val nodes: List<String>,
val depth: String,
val bitmap: String
) {
companion object {
fun isValid(proof: Any): Boolean {
if (proof is Proof) {
try {
if (proof.leaves.any { !Utils.isHex(it) || it.length != 64 }) {
return false
}
if (proof.nodes.any { !Utils.isHex(it) || it.length != 64 }) {
return false
}
if (
proof.depth.length != (proof.leaves.size + proof.nodes.size) * 4 &&
Utils.isHex(proof.depth)
) {
return false
}
val nElements = proof.leaves.size + proof.nodes.size
if (proof.depth.length != nElements * 4) {
return false
}
if (
floor(proof.bitmap.length.toDouble() / 2) < floor((nElements.toDouble() + 8 - (nElements % 8)) / 8)
) {
return false
}
return true
} catch (t: Throwable) {
return false
}
}
return false
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8ab2fa2de53e1ba94781e110456c13428300c65c
| 1,488
|
bloock-sdk-kotlin
|
MIT License
|
shared/src/commonMain/kotlin/ru/akella/cryptocoin/data/response/latestlisting/Data.kt
|
akella266
| 651,284,444
| false
| null |
package ru.akella.cryptocoin.data.response.latestlisting
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class LatestListingData(
@SerialName("circulating_supply")
val circulatingSupply: Double,
@SerialName("cmc_rank")
val cmcRank: Double,
@SerialName("date_added")
val dateAdded: String,
val id: Int,
@SerialName("last_updated")
val lastUpdated: String,
@SerialName("max_supply")
val maxSupply: Double?,
val name: String,
@SerialName("num_market_pairs")
val numMarketPairs: Double,
// val platform: String?,
val quote: Map<String, CurrencyDetails>,
val slug: String,
val symbol: String,
val tags: List<String>,
@SerialName("total_supply")
val totalSupply: Double
)
| 0
|
Kotlin
|
0
| 0
|
964e22544c5bab7b6b67224e84a3c41dd960a0a0
| 804
|
CryptoCoin
|
Apache License 2.0
|
src/test/kotlin/com/jacobhyphentated/day20/Day20Test.kt
|
jacobhyphenated
| 572,119,677
| false
| null |
package com.jacobhyphentated.day20
import com.jacobhyphenated.day20.Day20
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class Day20Test {
@Test
fun testPart1_simple() {
val input =
"""
A
A
#######.#########
#######.........#
#######.#######.#
#######.#######.#
#######.#######.#
##### B ###.#
BC...## C ###.#
##.## ###.#
##...DE F ###.#
##### G ###.#
#########.#####.#
DE..#######...###.#
#.#########.###.#
FG..#########.....#
###########.#####
Z
Z
""".trimIndent()
val day20 = Day20()
assertEquals(23, day20.part1(input))
}
@Test
fun testPart1_long() {
val input =
"""
A
A
#################.#############
#.#...#...................#.#.#
#.#.#.###.###.###.#########.#.#
#.#.#.......#...#.....#.#.#...#
#.#########.###.#####.#.#.###.#
#.............#.#.....#.......#
###.###########.###.#####.#.#.#
#.....# A C #.#.#.#
####### S P #####.#
#.#...# #......VT
#.#.#.# #.#####
#...#.# YN....#.#
#.###.# #####.#
DI....#.# #.....#
#####.# #.###.#
ZZ......# QG....#..AS
###.### #######
JO..#.#.# #.....#
#.#.#.# ###.#.#
#...#..DI BU....#..LF
#####.# #.#####
YN......# VT..#....QG
#.###.# #.###.#
#.#...# #.....#
###.### J L J #.#.###
#.....# O F P #.#...#
#.###.#####.#.#####.#####.###.#
#...#.#.#...#.....#.....#.#...#
#.#####.###.###.#.#.#########.#
#...#.#.....#...#.#.#.#.....#.#
#.###.#####.###.###.#.#.#######
#.#.........#...#.............#
#########.###.###.#############
B J C
U P P
""".trimIndent()
val day20 = Day20()
assertEquals(58, day20.part1(input))
}
@Test
fun testPart2_simple() {
val input =
"""
A
A
#######.#########
#######.........#
#######.#######.#
#######.#######.#
#######.#######.#
##### B ###.#
BC...## C ###.#
##.## ###.#
##...DE F ###.#
##### G ###.#
#########.#####.#
DE..#######...###.#
#.#########.###.#
FG..#########.....#
###########.#####
Z
Z
""".trimIndent()
val day20 = Day20()
assertEquals(26, day20.part2(input))
}
@Test
fun testPart2_complex() {
val input =
"""
Z L X W C
Z P Q B K
###########.#.#.#.#######.###############
#...#.......#.#.......#.#.......#.#.#...#
###.#.#.#.#.#.#.#.###.#.#.#######.#.#.###
#.#...#.#.#...#.#.#...#...#...#.#.......#
#.###.#######.###.###.#.###.###.#.#######
#...#.......#.#...#...#.............#...#
#.#########.#######.#.#######.#######.###
#...#.# F R I Z #.#.#.#
#.###.# D E C H #.#.#.#
#.#...# #...#.#
#.###.# #.###.#
#.#....OA WB..#.#..ZH
#.###.# #.#.#.#
CJ......# #.....#
####### #######
#.#....CK #......IC
#.###.# #.###.#
#.....# #...#.#
###.### #.#.#.#
XF....#.# RF..#.#.#
#####.# #######
#......CJ NM..#...#
###.#.# #.###.#
RE....#.# #......RF
###.### X X L #.#.#.#
#.....# F Q P #.#.#.#
###.###########.###.#######.#########.###
#.....#...#.....#.......#...#.....#.#...#
#####.#.###.#######.#######.###.###.#.#.#
#.......#.......#.#.#.#.#...#...#...#.#.#
#####.###.#####.#.#.#.#.###.###.#.###.###
#.......#.....#.#...#...............#...#
#############.#.#.###.###################
A O F N
A A D M
""".trimIndent()
val day20 = Day20()
assertEquals(396, day20.part2(input))
}
}
| 0
|
Kotlin
|
0
| 0
|
1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4
| 6,564
|
advent2019
|
The Unlicense
|
src/main/kotlin/no/nav/syfo/ws/OidcToken.kt
|
navikt
| 523,302,442
| false
|
{"Kotlin": 21818, "Dockerfile": 276}
|
package no.nav.syfo.ws
data class OidcToken(val access_token: String, val token_type: String, val expires_in: Long)
| 1
|
Kotlin
|
1
| 0
|
83e25c4c1587e00c766c7b55d364c47e4e487a3e
| 117
|
smgcp-proxy
|
MIT License
|
src/main/java/utils/MainScheduler.kt
|
ExpensiveBelly
| 104,675,798
| false
| null |
package utils
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.concurrent.Executor
val mainScheduler = Schedulers.from(Executor(Runnable::run))
| 0
|
Kotlin
|
11
| 19
|
e07a3aea09f9235077d6d0dd553af2cfe782b393
| 164
|
RxKata
|
MIT License
|
app/src/main/java/com/nedaluof/qurany/ui/screens/suras/SuraItem.kt
|
nedaluof
| 808,717,545
| false
|
{"Kotlin": 94094}
|
package com.nedaluof.qurany.ui.screens.suras
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.nedaluof.data.model.SuraModel
import com.nedaluof.qurany.R
import com.nedaluof.qurany.ui.theme.AppGreen
import com.nedaluof.qurany.ui.theme.QuranyComposeTheme
/**
* Created By NedaluOf - 6/4/2024.
*/
@Composable
fun SuraItem(
sura: SuraModel,
onPlayClicked: () -> Unit = {},
onDownloadClicked: () -> Unit = {}
) {
Card(
onClick = onPlayClicked,
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.background),
shape = RoundedCornerShape(8.dp),
border = BorderStroke(1.dp, AppGreen),
modifier = Modifier
.padding(horizontal = 8.dp)
.height(90.dp)
.padding(bottom = 8.dp)
) {
Row(Modifier.fillMaxWidth()) {
Image(
painter = painterResource(id = R.drawable.ic_opened_quran),
contentDescription = "opened quran",
modifier = Modifier
.width(70.dp)
.padding(start = 8.dp, end = 8.dp)
.align(Alignment.CenterVertically)
)
Spacer(
modifier = Modifier
.padding(horizontal = 4.dp)
.width(2.dp)
)
Column(
Modifier
.weight(1f)
.align(Alignment.CenterVertically)
) {
Text(
text = sura.name,
maxLines = 1,
style = MaterialTheme.typography.titleMedium,
color = AppGreen
)
Text(
text = "${stringResource(id = R.string.rewaya_label)} ${sura.rewaya}",
style = MaterialTheme.typography.bodySmall,
color = AppGreen
)
Text(
text = stringResource(id = R.string.sura_number_label, sura.id),
style = MaterialTheme.typography.bodySmall,
color = AppGreen
)
}
Column(
Modifier
.background(MaterialTheme.colorScheme.primary)
.fillMaxHeight()
) {
IconButton(
modifier = Modifier
.weight(1f)
.padding(6.dp), onClick = onPlayClicked
) {
Icon(
painter = painterResource(id = R.drawable.ic_play),
contentDescription = "run sura in media player",
tint = Color.White
)
}
IconButton(
modifier = Modifier
.padding(6.dp)
.weight(1f),
onClick = onDownloadClicked,
) {
Icon(
painter = painterResource(id = R.drawable.ic_download),
contentDescription = "download sura to your local storage",
tint = Color.White
)
}
}
}
}
}
@Preview
@Composable
fun SuraItemPreview(modifier: Modifier = Modifier) {
QuranyComposeTheme {
SuraItem(sura = SuraModel().apply {
id = 1
name = "Al Fatiha"
rewaya = "Hafs An Assem"
reciterName = "Maher Al Mueqle"
playerTitle = "Al Fatiha | Maher Al Mueqle"
})
}
}
| 0
|
Kotlin
|
0
| 0
|
d36ea9df3b56e05dcdfefce9a6793c95977550be
| 4,110
|
Qurany-Compose
|
Apache License 2.0
|
worldwind/src/commonMain/kotlin/earth/worldwind/geom/Ellipsoid.kt
|
WorldWindEarth
| 488,505,165
| false
|
{"Kotlin": 2798182, "JavaScript": 459619, "HTML": 108987, "CSS": 8778}
|
package earth.worldwind.geom
import kotlin.jvm.JvmStatic
/**
* Oblate ellipsoid with semi-major axis and inverse flattening.
*/
data class Ellipsoid(
/**
* One half of the ellipsoid's major axis length in meters, which runs through the center to opposite points on the
* equator.
*/
val semiMajorAxis: Double,
/**
* Measure of the ellipsoid's compression. Indicates how much the ellipsoid's semi-minor axis is compressed relative
* to the semi-major axis. Expressed as `1/f`, where `f = (a - b) / a`, given the semi-major axis `a` and the semi-minor axis `b`.
*/
val inverseFlattening: Double
) {
/**
* Computes this ellipsoid's semi-minor length axis in meters. The semi-minor axis is one half of the ellipsoid's
* minor axis, which runs through the center to opposite points on the poles.
*/
val semiMinorAxis: Double get() {
val f = 1 / inverseFlattening
return semiMajorAxis * (1 - f)
}
/**
* Computes this ellipsoid's eccentricity squared. The returned value is equivalent to `2*f - f*f`,
* where `f` is this ellipsoid's flattening.
*/
val eccentricitySquared: Double get() {
val f = 1 / inverseFlattening
return 2 * f - f * f
}
companion object {
/**
* WGS 84 reference ellipsoid for Earth. The ellipsoid's semi-major axis and inverse flattening factor are
* configured according to the WGS 84 reference system (aka WGS 1984, EPSG:4326). WGS 84 reference values taken from
* [here](http://earth-info.nga.mil/GandG/publications/NGA_STND_0036_1_0_0_WGS84/NGA.STND.0036_1.0.0_WGS84.pdf).
*/
@JvmStatic val WGS84 = Ellipsoid(6378137.0, 298.257223563)
/**
* Krasovsky 1940 reference ellipsoid for Earth.
*/
@JvmStatic val Krasovsky = Ellipsoid(6378245.0, 298.3)
}
}
| 22
|
Kotlin
|
12
| 98
|
b5ee69cdd30f6c6a90bf3bec638a3bc5bdb0fbc2
| 1,897
|
WorldWindKotlin
|
Apache License 2.0
|
repository/src/main/kotlin/com/coach/flame/jpa/repository/configs/CustomerTypeRepository.kt
|
FlameNutrition
| 333,186,829
| false
| null |
package com.coach.flame.jpa.repository.configs
import com.coach.flame.jpa.entity.ClientType
import com.coach.flame.jpa.repository.cache.CacheLoaderRepository
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
@Repository
interface CustomerTypeRepository : JpaRepository<ClientType, Long>, CacheLoaderRepository<ClientType> {
@Query("select ct from ClientType ct " +
"where ct.type = :key")
override fun findByKey(@Param("key") key: String): ClientType?
@Query("select ct from ClientType ct")
override fun findAll(): List<ClientType>
}
| 20
|
Kotlin
|
0
| 0
|
7c1c498be8afbb39848a2f6eb27e97099ebda58f
| 734
|
flame-coach-service
|
MIT License
|
kotlin/src/main/kotlin/com/simiacryptus/skyenet/heart/KotlinInterpreter.kt
|
SimiaCryptus
| 619,329,127
| false
|
{"Kotlin": 170461, "JavaScript": 17844, "CSS": 11163, "Java": 5935, "Scala": 5261, "HTML": 2533}
|
@file:Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
package com.simiacryptus.skyenet.heart
import com.simiacryptus.skyenet.Heart
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineFactoryBase
import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes
import org.jetbrains.kotlin.cli.common.setupCommonArguments
import org.jetbrains.kotlin.cli.common.setupLanguageVersionSettings
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler
import org.jetbrains.kotlin.cli.jvm.setupJvmSpecificArguments
import org.jetbrains.kotlin.codegen.CompilationException
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.LanguageVersion
import org.slf4j.LoggerFactory
import java.io.File
import java.lang.ref.WeakReference
import java.lang.reflect.Proxy
import java.util.*
import java.util.Map
import javax.script.Bindings
import javax.script.ScriptContext
import kotlin.script.experimental.api.dependencies
import kotlin.script.experimental.api.with
import kotlin.script.experimental.host.ScriptDefinition
import kotlin.script.experimental.jsr223.KOTLIN_JSR223_RESOLVE_FROM_CLASSLOADER_PROPERTY
import kotlin.script.experimental.jsr223.KotlinJsr223DefaultScript
import kotlin.script.experimental.jvm.JvmDependencyFromClassLoader
import kotlin.script.experimental.jvm.JvmScriptCompilationConfigurationBuilder
import kotlin.script.experimental.jvm.jvm
import kotlin.script.experimental.jvm.updateClasspath
import kotlin.script.experimental.jvm.util.scriptCompilationClasspathFromContext
import kotlin.script.experimental.jvmhost.createJvmScriptDefinitionFromTemplate
import kotlin.script.experimental.jvmhost.jsr223.KotlinJsr223ScriptEngineImpl
open class KotlinInterpreter(
private val defs: Map<String, Object> = HashMap<String, Object>() as Map<String, Object>
) : Heart {
override fun validate(code: String): Throwable? {
val messageCollector = MessageCollectorImpl(code)
val environment: KotlinCoreEnvironment by lazy {
KotlinCoreEnvironment.createForProduction(
{},
CompilerConfiguration().apply {
val arguments = jvmCompilerArguments(code)
arguments.configureAnalysisFlags(messageCollector, LanguageVersion.KOTLIN_2_1)
arguments.configureLanguageFeatures(messageCollector)
put(
CommonConfigurationKeys.MODULE_NAME,
arguments.moduleName!!
)
put(
CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY,
messageCollector
)
this.setupJvmSpecificArguments(arguments)
this.setupCommonArguments(arguments)
this.setupLanguageVersionSettings(arguments)
},
EnvironmentConfigFiles.JVM_CONFIG_FILES
)
}
return try {
val compileBunchOfSources: GenerationState? =
KotlinToJVMBytecodeCompiler.analyzeAndGenerate(environment)
//val compileBunchOfSources1 = KotlinToJVMBytecodeCompiler.compileBunchOfSources(environment)
if (null == compileBunchOfSources) {
Exception("Compilation failed")
} else {
if (messageCollector.errors.isEmpty()) {
null
} else RuntimeException(
"""
|${messageCollector.errors.joinToString("\n") { "Error: $it" }}
|${messageCollector.warnings.joinToString("\n") { "Warning: $it" }}
""".trimMargin()
)
}
} catch (e: CompilationException) {
RuntimeException(
"""
|${e.message}
|${messageCollector.errors.joinToString("\n") { "Error: " + it }}
|${messageCollector.warnings.joinToString("\n") { "Warning: " + it }}
""".trimMargin(), e
)
} catch (e: Exception) {
e
}
}
private class MessageCollectorImpl(
val code: String,
val errors: ArrayList<String> = ArrayList(),
val warnings: ArrayList<String> = ArrayList(),
) : MessageCollector {
override fun clear() {}
override fun hasErrors() = errors.isNotEmpty()
override fun report(
severity: CompilerMessageSeverity,
message: String,
location: CompilerMessageSourceLocation?
) {
val msg = errorMessage(code, location?.line ?: 1, location?.column ?: 1, message)
log.info(msg)
when {
severity.isError -> errors.add(msg)
severity.isWarning -> warnings.add(msg)
}
}
}
protected open fun jvmCompilerArguments(code: String): K2JVMCompilerArguments {
val arguments = K2JVMCompilerArguments()
//arguments.fragmentSources = arrayOf(tempFile.absolutePath)
// arguments.allowNoSourceFiles = false
arguments.expression = code
arguments.classpath = System.getProperty("java.class.path")
// arguments.compileJava = true
// arguments.allowAnyScriptsInSourceRoots = true
// arguments.allowUnstableDependencies = false
// arguments.checkPhaseConditions = true
arguments.enableDebugMode = true
// arguments.enableSignatureClashChecks = true
arguments.extendedCompilerChecks = true
// arguments.linkViaSignatures = true
arguments.reportOutputFiles = true
arguments.moduleName = "KotlinInterpreter"
arguments.noOptimize = true
// arguments.noReflect = true
arguments.script = true
arguments.validateIr = true
arguments.validateBytecode = true
arguments.verbose = true
// arguments.javaParameters = true
arguments.useTypeTable = true
// arguments.useJavac = true
// arguments.useFirExtendedCheckers = true
// arguments.destination = "kotlinBuild"
// File(arguments.destination).mkdirs()
return arguments
}
private val scriptDefinition: ScriptDefinition = createJvmScriptDefinitionFromTemplate<KotlinJsr223DefaultScript>()
private var lastClassLoader: ClassLoader? = null
private var lastClassPath: List<File>? = null
@Synchronized
private fun JvmScriptCompilationConfigurationBuilder.dependenciesFromCurrentContext() {
val currentClassLoader = Thread.currentThread().contextClassLoader
val classPath = if (lastClassLoader == null || lastClassLoader != currentClassLoader) {
scriptCompilationClasspathFromContext(
classLoader = currentClassLoader,
wholeClasspath = true,
unpackJarCollections = true
).also {
lastClassLoader = currentClassLoader
lastClassPath = it
}
} else lastClassPath!!
updateClasspath(classPath)
}
protected open val scriptEngineFactory by lazy { KotlinScriptEngineFactory() }
inner class KotlinScriptEngineFactory : KotlinJsr223JvmScriptEngineFactoryBase() {
override fun getScriptEngine() = KotlinJsr223ScriptEngineImpl(
this,
scriptDefinition.compilationConfiguration.with {
jvm {
if (System.getProperty(KOTLIN_JSR223_RESOLVE_FROM_CLASSLOADER_PROPERTY) == "true") {
dependencies(JvmDependencyFromClassLoader { Thread.currentThread().contextClassLoader })
} else {
dependenciesFromCurrentContext()
}
}
},
scriptDefinition.evaluationConfiguration
) {
ScriptArgsWithTypes(
arrayOf(it.getBindings(ScriptContext.ENGINE_SCOPE).orEmpty()),
arrayOf(Bindings::class)
)
}
}
override fun run(code: String): Any? {
val wrappedCode = wrapCode(code)
log.info(
"""
|Running:
| ${wrappedCode.trimIndent().replace("\n", "\n\t")}
|""".trimMargin().trim()
)
try {
return scriptEngineFactory.scriptEngine.eval(wrappedCode)
} catch (ex: javax.script.ScriptException) {
var lineNumber = ex.lineNumber
var column = ex.columnNumber
if (lineNumber == -1 && column == -1) {
val match = Regex("\\(.*:(\\d+):(\\d+)\\)").find(ex.message ?: "")
if (match != null) {
lineNumber = match.groupValues[1].toInt()
column = match.groupValues[2].toInt()
}
}
throw RuntimeException(
errorMessage(code, lineNumber, column, ex.message ?: ""), ex
)
}
}
override fun wrapCode(code: String): String {
val out = ArrayList<String>()
val (imports, otherCode) = code.split("\n").partition { it.trim().startsWith("import ") }
out.addAll(imports)
defs.entrySet().forEach { (key, value) ->
val uuid = storageMap.getOrPut(value) { UUID.randomUUID() }
retrievalIndex.put(uuid, WeakReference(value))
val fqClassName = KotlinInterpreter::class.java.name.replace("$", ".")
val typeStr = typeOf(value)
out.add("val $key : $typeStr = $fqClassName.retrievalIndex.get(java.util.UUID.fromString(\"$uuid\"))?.get()!! as $typeStr\n")
}
out.addAll(otherCode)
return out.joinToString("\n")
}
open fun typeOf(value: Any?): String {
if (value is Proxy) {
return value.javaClass.interfaces[0].name.replace("$", ".") + "?"
}
val replace = value?.javaClass?.name?.replace("$", ".")
return if (replace != null) ("$replace") else "null"
}
companion object {
val log = LoggerFactory.getLogger(KotlinInterpreter::class.java)
val storageMap = WeakHashMap<Object, UUID>()
val retrievalIndex = HashMap<UUID, WeakReference<Object>>()
fun errorMessage(
code: String,
line: Int,
column: Int,
message: String
) = """
|$message at line ${line} column ${column}
| ${code.split("\n")[line - 1]}
| ${" ".repeat(column - 1) + "^"}
""".trimMargin().trim()
}
override fun getLanguage(): String {
return "Kotlin"
}
}
| 1
|
Kotlin
|
0
| 1
|
0558081bc584b387b6f95b0fc51d29549559b937
| 11,275
|
SkyeNet
|
Apache License 2.0
|
android/src/main/java/co/touchlab/droidcon/android/viewModel/sessions/SessionDetailViewModel.kt
|
touchlab
| 140,843,272
| false
|
{"Kotlin": 414936, "Swift": 72972, "HTML": 7463, "Python": 3635, "Ruby": 1869}
|
package co.touchlab.droidcon.android.viewModel.sessions
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import co.touchlab.droidcon.R
import co.touchlab.droidcon.android.service.DateTimeFormatterViewService
import co.touchlab.droidcon.android.viewModel.feedback.FeedbackViewModel
import co.touchlab.droidcon.application.gateway.SettingsGateway
import co.touchlab.droidcon.domain.composite.ScheduleItem
import co.touchlab.droidcon.domain.entity.Session
import co.touchlab.droidcon.domain.gateway.SessionGateway
import co.touchlab.droidcon.domain.service.DateTimeService
import co.touchlab.droidcon.domain.service.FeedbackService
import co.touchlab.droidcon.dto.WebLink
import co.touchlab.droidcon.service.ParseUrlViewService
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
@OptIn(ExperimentalCoroutinesApi::class)
class SessionDetailViewModel : ViewModel(), KoinComponent {
private val sessionGateway by inject<SessionGateway>()
private val dateTimeFormatter by inject<DateTimeFormatterViewService>()
private val dateTimeService by inject<DateTimeService>()
private val parseUrlViewService by inject<ParseUrlViewService>()
private val feedbackService: FeedbackService by inject()
private val settingsGateway: SettingsGateway by inject()
private val observeScheduleItem = MutableSharedFlow<ScheduleItem?>(replay = 1)
private var scheduleItem: ScheduleItem? = null
set(value) {
field = value
observeScheduleItem.tryEmit(value)
}
var id = MutableStateFlow<Session.Id?>(null)
val title: Flow<String> = observeScheduleItem.map { it?.session?.title ?: "" }
val description: Flow<Pair<String, List<WebLink>>> = observeScheduleItem.map { scheduleItem ->
scheduleItem?.session?.description?.let { it to parseUrlViewService.parse(it) } ?: "" to emptyList()
}
val locationInfo: Flow<String> = observeScheduleItem.map {
listOfNotNull(
it?.room?.name,
it?.let { item ->
dateTimeFormatter.timeRange(
item.session.startsAt,
item.session.endsAt,
)
},
).joinToString()
}
val hasEnded: Flow<Boolean> = observeScheduleItem.flatMapLatest { scheduleItem ->
flow {
while (currentCoroutineContext().isActive) {
val hasEnded = scheduleItem?.session?.endsAt?.let { dateTimeService.now() > it } ?: false
emit(hasEnded)
delay(1_000)
}
}
}
val isAttending: Flow<Boolean> = observeScheduleItem.map { it?.session?.rsvp?.isAttending ?: false }
val statusRes: Flow<Int> = observeScheduleItem.mapNotNull {
if (it == null) {
return@mapNotNull R.string.schedule_session_detail_status_future
}
dateTimeService.now().let { now ->
when {
it.session.endsAt < now -> R.string.schedule_session_detail_status_past
it.session.startsAt <= now && now <= it.session.endsAt -> R.string.schedule_session_detail_status_in_progress
it.isInConflict -> R.string.schedule_session_detail_status_conflict
it.session.startsAt > now -> R.string.schedule_session_detail_status_future
else -> null
}
}
}
val speakers: Flow<List<ProfileViewModel>> = observeScheduleItem.map { it?.speakers?.map(::ProfileViewModel) ?: emptyList() }
val showFeedbackOption: StateFlow<Boolean> = settingsGateway.settings()
.map { it.isFeedbackEnabled }
.combine(hasEnded) { feedbackEnabled, hasEnded ->
feedbackEnabled && hasEnded
}
.stateIn(viewModelScope, SharingStarted.Lazily, false)
val showFeedbackTitleRes: StateFlow<Int> = observeScheduleItem.map {
if (it?.session?.feedback != null) {
R.string.feedback_change_title
} else {
R.string.feedback_add_title
}
}.stateIn(viewModelScope, SharingStarted.Lazily, initialValue = R.string.feedback_add_title)
val showFeedback: MutableStateFlow<FeedbackViewModel?> = MutableStateFlow(null)
init {
viewModelScope.launch {
id.flatMapLatest {
it?.let { sessionGateway.observeScheduleItem(it) } ?: flowOf(null)
}.collect {
scheduleItem = it
}
}
}
fun toggleIsAttending(value: Boolean) {
scheduleItem?.session?.let { session ->
viewModelScope.launch {
sessionGateway.setAttending(session, value)
}
}
}
fun writeFeedbackTapped() {
val session = scheduleItem?.session ?: return
showFeedback.value = FeedbackViewModel(
MutableStateFlow(session),
submitFeedback = { currentSession, feedback ->
feedbackService.submit(currentSession, feedback)
showFeedback.value = null
},
closeAndDisableFeedback = null,
skipFeedback = {
feedbackService.skip(it)
showFeedback.value = null
},
)
}
}
| 11
|
Kotlin
|
77
| 931
|
100f83d3c6ad66c23321cfdceef84139cbba89fd
| 5,974
|
DroidconKotlin
|
Apache License 2.0
|
Formulary/app/src/main/java/com/bcha/formulary/view/main/MainInteractor.kt
|
BCHA-Formulary
| 197,990,810
| true
|
{"Kotlin": 21500}
|
package com.bcha.formulary.view.main
/**
* Created by <NAME> on 2018-11-04.
*/
class MainInteractor : MainActivityMVP.Interactor {
override fun unsubscribe() {
}
override fun onDestroy() {
}
}
| 0
|
Kotlin
|
0
| 0
|
be08eba07aeeeea1948e1348196f4432def529e6
| 212
|
Formulary-Android-v3
|
MIT License
|
browser-kotlin/src/jsMain/kotlin/web/html/Loading.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6149909}
|
// Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.html
// language=JavaScript
@JsName("""(/*union*/{eager: 'eager', lazy: 'lazy'}/*union*/)""")
sealed external interface Loading {
companion object {
val eager: Loading
val lazy: Loading
}
}
| 0
|
Kotlin
|
6
| 26
|
3fcfd2c61da8774151cf121596e656cc123b37db
| 368
|
types-kotlin
|
Apache License 2.0
|
sdk/src/main/java/com/moyasar/android/sdk/stcpay/presentation/model/validator/STCPayOTPValidator.kt
|
moyasar
| 389,428,787
| false
|
{"Kotlin": 136585}
|
package com.moyasar.android.sdk.stcpay.presentation.model.validator
/**
* Created by <NAME> on 22,September,2024
*/
internal object STCPayOTPValidator {
fun isValidOtp(otp: String): Boolean {
return otp.length in 4..10
}
}
| 0
|
Kotlin
|
4
| 0
|
22f9f5e0c4e6cdebbdd16a5031bd3189d5ec974c
| 241
|
moyasar-android-sdk
|
MIT License
|
examples/ongoing/src/main/java/me/digi/examples/ongoing/model/GenreInsight.kt
|
digime
| 198,619,583
| false
|
{"Kotlin": 198719}
|
package me.digi.examples.ongoing.model
data class GenreInsight(val title: String, val playCount: Int, val sampleSize: Int)
| 0
|
Kotlin
|
3
| 1
|
dd0b82f0c991547c220d09408b63996b758a4c0d
| 123
|
digime-sdk-android
|
Apache License 2.0
|
app/src/main/java/com/omralcorut/githubsearcher/ui/search/SearchFragment.kt
|
omralcrt
| 327,512,466
| false
| null |
package com.omralcorut.githubsearcher.ui.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.omralcorut.githubsearcher.databinding.FragmentSearchBinding
import com.omralcorut.githubsearcher.models.Repository
import com.omralcorut.githubsearcher.models.User
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SearchFragment : Fragment() {
private val searchViewModel: SearchViewModel by viewModels()
private var _binding: FragmentSearchBinding? = null
private val binding get() = _binding!!
private lateinit var searchEpoxyController: SearchEpoxyController
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSearchBinding.inflate(inflater, container, false)
setAdapter()
initSearchView()
viewModelObserver()
return binding.root
}
private fun setAdapter() {
searchEpoxyController =
SearchEpoxyController(object : SearchEpoxyController.SearchEpoxyAdapterCallbacks {
override fun userClick(user: User) {
TODO("Not yet implemented")
}
override fun repositoryClick(repository: Repository) {
TODO("Not yet implemented")
}
})
searchEpoxyController.isDebugLoggingEnabled = true
binding.recyclerViewSearch.layoutManager = LinearLayoutManager(context)
binding.recyclerViewSearch.adapter = searchEpoxyController.adapter
}
private fun initSearchView() {
binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
if (newText.isEmpty()) {
searchViewModel.clearResults()
} else {
searchViewModel.getUsers(newText)
searchViewModel.getRepositories(newText)
}
return false
}
})
}
private fun viewModelObserver() {
searchViewModel.users.observe(viewLifecycleOwner, {
searchEpoxyController.setData(
searchViewModel.users.value,
searchViewModel.repositories.value
)
binding.recyclerViewSearch.layoutManager?.scrollToPosition(0)
})
searchViewModel.repositories.observe(viewLifecycleOwner, {
searchEpoxyController.setData(
searchViewModel.users.value,
searchViewModel.repositories.value
)
})
searchViewModel.isResultEmpty.observe(viewLifecycleOwner, {
binding.textViewNoResult.visibility = if (it) View.VISIBLE else View.GONE
})
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
5178b79c6d5667fe80d8825b39a87bbcf03cc2ab
| 3,299
|
GithubSearcher
|
The Unlicense
|
app/src/androidTest/java/br/com/fioalpha/heromarvel/ApplicationCustomTest.kt
|
fioalpha
| 264,306,059
| false
| null |
package br.com.fioalpha.heromarvel
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import org.koin.core.context.loadKoinModules
import org.koin.core.context.unloadKoinModules
import org.koin.core.module.Module
class ApplicationCustomTest : CustomApplication() {
internal fun loadModules(module: Module, block: () -> Unit) {
loadKoinModules(module)
block()
unloadKoinModules(module)
}
}
class MyRunnerTest : AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, ApplicationCustomTest::class.java.name, context)
}
}
| 0
|
Kotlin
|
0
| 3
|
7b0ee22d4431c2330e147de651b92022d61aea5a
| 759
|
Hero-Marvel
|
The Unlicense
|
app/src/main/java/com/cesarwillymc/culqui/data/sources/preferences/PreferencesDaoImpl.kt
|
cesarwillymc
| 702,712,147
| false
|
{"Kotlin": 100901}
|
package com.cesarwillymc.culqui.data.sources.preferences
import android.content.SharedPreferences
import androidx.core.content.edit
import com.cesarwillymc.culqui.util.constants.EMPTY_STRING
import com.cesarwillymc.culqui.util.state.Result
import javax.inject.Inject
class PreferencesDaoImpl @Inject constructor(
private val sharedPreferences: SharedPreferences
) : PreferencesDao {
private companion object {
const val USER_SESSION = "user_information"
}
override val getToken: Result<String>
get() = try {
val session = sharedPreferences.getString(USER_SESSION, EMPTY_STRING)
Result.Success(data = session.orEmpty())
} catch (e: Exception) {
Result.Error(e)
}
override fun saveToken(value: String): Result<Unit> {
sharedPreferences.edit {
this.putString(USER_SESSION, value)
}
return Result.Success(Unit)
}
override val isLogged: Result<Boolean>
get() = try {
val session = sharedPreferences.getString(USER_SESSION, EMPTY_STRING)
Result.Success(data = !session.isNullOrBlank())
} catch (e: Exception) {
Result.Error(e)
}
override fun cleanPreferences(): Result<Unit> {
sharedPreferences.edit {
remove(USER_SESSION)
}
return Result.Success(Unit)
}
}
| 0
|
Kotlin
|
0
| 0
|
4c78a8c8855369baf783579f178429076eb6b573
| 1,395
|
Culqui
|
Apache License 2.0
|
cutilslibrary/src/main/java/com/utils/library/ui/adapter/SingleTypeListAdapter.kt
|
EasonHolmes
| 390,691,373
| false
|
{"Java": 270865, "Kotlin": 185892}
|
package com.utils.library.ui.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.widget.library.refresh.recyclerview.DDRecyclerViewLayout
import com.utils.library.ui.AbstractBaseAdapter
/**
* Created by cuiyang
* 单类型item adapter
* 不需要上拉下拉时refreshLayout可传null
* 这里只是控制在数据过于少和数据量恢复后停止和恢复上拉下拉加载
*/
abstract class SingleTypeListAdapter<T, B : ViewBinding>(ddRecyclerViewLayout: DDRecyclerViewLayout) : AbstractBaseAdapter<T>(ddRecyclerViewLayout) {
private lateinit var _binding:B
protected val binding get() = _binding
override fun onBindViewHolder(holder1: RecyclerView.ViewHolder, position: Int) {
val holder = holder1 as BindingViewHolder<*>
val item = getItem(position)
@Suppress("UNCHECKED_CAST")
val binding = holder.binding as B
onItemBinding(binding, item, position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
// binding = DataBindingUtil.inflate(LayoutInflater.from(parent.context),
// setItemLayoutResource(), parent, false)
_binding = bindingLyoaut(parent)
return BindingViewHolder(binding)
}
protected abstract fun bindingLyoaut(parent: ViewGroup): B
abstract fun onItemBinding(binding: B, item: T, position: Int)
}
| 1
| null |
1
| 1
|
e551ff7e3f3bb7345483e09cbef8dcc547ef19e6
| 1,384
|
CBaseLibrary
|
Apache License 2.0
|
compiler/testData/diagnostics/testsWithStdLib/smartcasts/letStable.kt
|
JakeWharton
| 99,388,807
| true
| null |
// KT-9051: Allow smart cast for captured variables if they are not modified
fun foo(y: String?) {
var x: String? = ""
if (x != null) {
y?.let { x != y }
// x is not changed, smart cast is possible
<!DEBUG_INFO_SMARTCAST!>x<!>.length
}
}
| 181
|
Kotlin
|
5748
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 275
|
kotlin
|
Apache License 2.0
|
app/src/main/java/knf/kuma/explorer/FragmentBase.kt
|
jordyamc
| 119,774,950
| false
|
{"Kotlin": 2043989, "Java": 285074, "AIDL": 8794, "Ruby": 815}
|
package knf.kuma.explorer
import androidx.fragment.app.Fragment
abstract class FragmentBase : Fragment() {
abstract fun onBackPressed(): Boolean
}
| 24
|
Kotlin
|
39
| 159
|
99d8108ca5a9c32b89952aeb217319693df57688
| 154
|
UKIKU
|
MIT License
|
app/src/test/java/com/kiwiandroiddev/sc2buildassistant/feature/translate/domain/impl/CheckTranslationPossibleUseCaseImplTest.kt
|
kiwiandroiddev
| 93,439,255
| false
|
{"Java": 312136, "Kotlin": 187776}
|
package com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.impl
import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.CheckTranslationPossibleUseCase
import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.LanguageCode
import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.datainterface.SupportedLanguagesAgent
import com.kiwiandroiddev.sc2buildassistant.subscribeTestObserver
import io.reactivex.Observable
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
/**
* Created by matthome on 31/07/17.
*/
class CheckTranslationPossibleUseCaseImplTest {
@Mock lateinit var mockSupportedLanguagesAgent: SupportedLanguagesAgent
lateinit var checkTranslationPossibleUseCase: CheckTranslationPossibleUseCase
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
checkTranslationPossibleUseCase =
CheckTranslationPossibleUseCaseImpl(mockSupportedLanguagesAgent)
}
private fun givenSupportedLanguagesAgentThrowsError(error: RuntimeException) {
`when`(mockSupportedLanguagesAgent.supportedLanguages())
.thenReturn(Observable.error(error))
}
private fun givenSupportedLanguageCodes(vararg languageCodes: LanguageCode) {
`when`(mockSupportedLanguagesAgent.supportedLanguages())
.thenReturn(Observable.fromArray(*languageCodes))
}
private fun givenNoLanguageCodesAreSupported() {
`when`(mockSupportedLanguagesAgent.supportedLanguages())
.thenReturn(Observable.empty())
}
@Test
fun fromDeToEn_getSupportedLanguagesAgentThrowsError_returnsFalse() {
val error = RuntimeException("No network connection!")
givenSupportedLanguagesAgentThrowsError(error)
checkTranslationPossibleUseCase
.canTranslateFromLanguage(fromLanguageCode = "de", toLanguageCode = "en")
.subscribeTestObserver()
.assertResult(false)
}
@Test
fun fromDeToEn_getSupportedLanguagesAgentReturnsEmptyList_returnsFalse() {
givenNoLanguageCodesAreSupported()
checkTranslationPossibleUseCase
.canTranslateFromLanguage(fromLanguageCode = "de", toLanguageCode = "en")
.subscribeTestObserver()
.assertResult(false)
}
@Test
fun fromDeToEn_getSupportedLanguagesAgentReturnsEnAndDe_returnsTrue() {
givenSupportedLanguageCodes("de", "en")
checkTranslationPossibleUseCase
.canTranslateFromLanguage(fromLanguageCode = "de", toLanguageCode = "en")
.subscribeTestObserver()
.assertResult(true)
}
@Test
fun fromEsToRu_getSupportedLanguagesAgentReturnsEnAndDe_returnsFalse() {
givenSupportedLanguageCodes("de", "en")
checkTranslationPossibleUseCase
.canTranslateFromLanguage(fromLanguageCode = "es", toLanguageCode = "ru")
.subscribeTestObserver()
.assertResult(false)
}
@Test
fun fromEsToRu_getSupportedLanguagesAgentReturnsEnDeEsRu_returnsTrue() {
givenSupportedLanguageCodes("en", "de", "es", "ru")
checkTranslationPossibleUseCase
.canTranslateFromLanguage(fromLanguageCode = "es", toLanguageCode = "ru")
.subscribeTestObserver()
.assertResult(true)
}
}
| 1
| null |
1
| 1
|
83c7b27afae29a81689be2b5fbc74b84c4934ddb
| 3,494
|
starcraft-2-build-player
|
MIT License
|
app/src/main/java/com/droid47/petpot/home/presentation/di/ViewModelBindingModule.kt
|
AndroidKiran
| 247,345,176
| false
| null |
package com.droid47.petpot.home.presentation.di
import androidx.lifecycle.ViewModel
import com.droid47.petpot.aboutUs.presentation.viewmodel.AboutUsViewModel
import com.droid47.petpot.app.di.scopes.ViewModelKey
import com.droid47.petpot.home.presentation.viewmodels.HomeViewModel
import com.droid47.petpot.home.presentation.viewmodels.NavigationViewModel
import com.droid47.petpot.organization.presentation.viewmodel.OrganizationViewModel
import com.droid47.petpot.petDetails.presentation.viewmodels.PetDetailsViewModel
import com.droid47.petpot.search.presentation.viewmodel.*
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
@Module
interface ViewModelBindingModule {
@Binds
@IntoMap
@ViewModelKey(HomeViewModel::class)
fun bindHomeViewModel(homeViewModel: HomeViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(NavigationViewModel::class)
fun bindNavigationViewModel(navigationViewModel: NavigationViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(AboutUsViewModel::class)
fun bindAboutUsViewModel(aboutUsViewModel: AboutUsViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(BookmarkViewModel::class)
fun bindBookmarkViewModel(bookmarkViewModel: BookmarkViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(PetDetailsViewModel::class)
fun bindPetDetailsViewModel(petDetailsViewModel: PetDetailsViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(SearchViewModel::class)
fun bindSearchViewModel(searchViewModel: SearchViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(PetSpinnerAndLocationViewModel::class)
fun bindPetSpinnerViewModel(petSpinnerAndLocationViewModel: PetSpinnerAndLocationViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(FilterViewModel::class)
fun bindFilterViewModel(filterViewModel: FilterViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(OrganizationViewModel::class)
fun bindOrganisationViewModel(organizationViewModel: OrganizationViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(SettingsViewModel::class)
fun bindSettingsViewModel(settingsViewModel: SettingsViewModel): ViewModel
}
| 1
| null |
1
| 2
|
07d9c0c4f0d5bef32d9705f6bb49f938ecc456e3
| 2,218
|
PetPot
|
Apache License 2.0
|
sample/src/main/java/indi/yume/tools/sample/PLazyList.kt
|
Yumenokanata
| 58,027,726
| false
|
{"Java": 213171, "Kotlin": 23848}
|
package indi.yume.tools.sample
/**
* Created by yume on 16-5-16.
*/
class PLazyList<T> private constructor(val list: () -> Pair<T, Any>?) {
constructor(): this({ null })
fun cons(head: T): PLazyList<T> = PLazyList({ Pair(head, list)})
fun head(): T? = list()?.first
fun tail(): PLazyList<T> {
val data = list()
return if(data == null) {
PLazyList()
}else {
PLazyList(data.second as () -> Pair<T, Any>?)
}
}
fun isEmpty(): Boolean = list() == null
fun <K> fold(n: Int, acc: K, f: (K, T) -> K): K =
if(n == 0 || isEmpty()) {
acc
} else {
tail().fold(n - 1, f(acc, head()!!), f)
}
fun <K> foldAll(acc: K, f: (K, T) -> K): K =
if(isEmpty()) {
acc
} else {
tail().foldAll(f(acc, head()!!), f)
}
fun take(n: Int): List<T> =
fold(n, emptyList<T>()) { list, item -> list + item }
fun takeAll(): List<T> =
foldAll(emptyList()) { list, item -> list + item }
fun toList(): List<T> = takeAll()
}
| 1
| null |
1
| 1
|
8550a359843c94dde7f48f49545763459e51897b
| 1,136
|
Avocado
|
Apache License 2.0
|
app/src/main/java/com/tawk/framework/mvvm/di/module/DatabaseModule.kt
|
evankhan1234
| 423,089,159
| false
|
{"Gradle": 3, "Java Properties": 4, "Shell": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Ignore List": 2, "JSON": 1, "Kotlin": 59, "XML": 194, "Java": 5, "INI": 3}
|
package com.tawk.framework.mvvm.di.module
import android.content.Context
import androidx.room.Room
import com.tawk.framework.mvvm.data.database.Dao.ScheduleDao
import com.tawk.framework.mvvm.data.database.SchedulerDatabase
import com.tawk.framework.mvvm.data.database.repository.ScheduleRepository
import com.tawk.framework.mvvm.data.database.repository.impl.ScheduleRepositoryImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
object DatabaseModule {
@Provides
@Singleton
fun providesDatabase(@ApplicationContext app: Context): SchedulerDatabase {
return Room.databaseBuilder(app,
SchedulerDatabase::class.java, SchedulerDatabase.DB_NAME)
.allowMainThreadQueries()
// .fallbackToDestructiveMigration()
.build()
}
@Provides
@Singleton
fun providesSchedulerDao(db: SchedulerDatabase): ScheduleDao {
return db.getScheduleDao()
}
@Singleton
@Provides
fun providesSchedulerRepository(dao: ScheduleDao): ScheduleRepository {
return ScheduleRepositoryImpl(dao)
}
}
| 0
|
Kotlin
|
0
| 0
|
26608cfb6d1cbce0f90540de6595082ba824ae43
| 1,292
|
Tawk
|
Apache License 2.0
|
app/src/main/java/priv/lzy/andtestsuite/utils/IThreadHandler.kt
|
s549520798
| 249,212,214
| false
|
{"Java": 534335, "Kotlin": 48208}
|
package priv.lzy.andtestsuite.utils
import android.os.Handler
import android.os.Looper
interface IThreadHandler {
fun post(runnable: Runnable): Boolean
fun postDelayed(runnable: Runnable, millis: Long): Boolean
fun removeCallbacks(runnable: Runnable)
}
class ATSMainHandler : IThreadHandler {
private val mHandler = Handler(Looper.getMainLooper())
override fun post(runnable: Runnable): Boolean {
return mHandler.post(runnable)
}
override fun postDelayed(runnable: Runnable, millis: Long): Boolean {
return mHandler.postDelayed(runnable, millis)
}
override fun removeCallbacks(runnable: Runnable) {
mHandler.removeCallbacks(runnable)
}
}
| 1
|
Java
|
1
| 1
|
8d2c1ef31ab2ce57d34d260f95a4dcbc9758cb5e
| 712
|
AndoridTestSuite
|
Apache License 2.0
|
compiler/testData/integration/ant/jvm/version/hello.kt
|
JakeWharton
| 99,388,807
| false
| null |
package hello
fun main(args : Array<String>) {
println("Yo!")
}
| 0
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 69
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/danhdueexoictif/androidgenericadapter/ui/base/BaseMainTabFragment.kt
|
DanhDue
| 251,030,651
| false
| null |
package com.danhdueexoictif.androidgenericadapter.ui.base
import android.os.Bundle
import android.widget.Toast
import androidx.activity.addCallback
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import com.danhdueexoictif.androidgenericadapter.NavGlobalDirections
import com.danhdueexoictif.androidgenericadapter.R
import com.danhdueexoictif.androidgenericadapter.utils.Constants
import kotlin.math.absoluteValue
abstract class BaseMainTabFragment<ViewBinding : ViewDataBinding, ViewModel : BaseViewModel> :
BaseFragment<ViewBinding, ViewModel>() {
private var doubleBackToExitPressedOnce: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (hasOptionMenu()) {
setHasOptionsMenu(true)
}
}
open fun hasOptionMenu(): Boolean = true
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
sharedViewModel.mainTabOnBackPressSecondTime.value = System.currentTimeMillis()
}
}
override fun observeField() {
if (sharedViewModel.shouldNavigateToRoot && navController.graph.id == R.id.nav_home) {
sharedViewModel.shouldNavigateToRoot = false
navController.navigate(NavGlobalDirections.navigateToRoot())
}
sharedViewModel.apply {
mainTabOnBackPressSecondTime.observe(viewLifecycleOwner, Observer {
if (it - sharedViewModel.mainTabOnBackPressFirstTime < Constants.CLOSE_APP_DELAY_TIME) {
requireActivity().moveTaskToBack(true)
} else {
Toast.makeText(
requireContext(),
getText(R.string.msg_press_back_again_to_exit),
Toast.LENGTH_SHORT
).show()
}
sharedViewModel.mainTabOnBackPressFirstTime = it.absoluteValue
})
}
}
}
| 0
| null |
5
| 7
|
02e0d14f09140531c8911ff6af46ee5d8eda4941
| 2,113
|
AndroidGenericAdapter
|
Apache License 2.0
|
app/src/main/java/com/rstit/connector/di/login/LoginModule.kt
|
rstgroup
| 113,022,246
| false
|
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 100, "XML": 31, "Java": 3}
|
package com.rstit.connector.di.login
import com.rstit.connector.di.base.scope.FragmentScope
import com.rstit.connector.ui.login.CustomLoginViewAccess
import com.rstit.connector.ui.login.LoginFragment
import com.rstit.ui.auth.login.LoginViewAccess
import dagger.Module
import dagger.Provides
/**
* @author Tomasz Trybala
* @since 2017-07-17
*/
@Module
class LoginModule(private val fragment: LoginFragment) {
@Provides
@FragmentScope
fun provideLoginFragment(): LoginFragment = fragment
@Provides
@FragmentScope
fun provideCustomLoginViewAccess(fragment: LoginFragment): CustomLoginViewAccess = fragment
@Provides
@FragmentScope
fun provideLoginViewAccess(fragment: LoginFragment): LoginViewAccess = fragment
}
| 0
|
Kotlin
|
0
| 0
|
4385ffd936f56a53aa1db9a83da4c9f3c3488fc9
| 752
|
rst-connector
|
Apache License 2.0
|
src/nl/rubensten/texifyidea/inspections/latex/LatexCollapseCiteInspection.kt
|
Tom-Evers
| 159,332,620
| false
|
{"Gradle": 2, "Markdown": 5, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Kotlin": 248, "Java": 137, "Java Properties": 1, "JFlex": 2, "CODEOWNERS": 1, "SVG": 2, "XML": 3, "HTML": 61, "Python": 1}
|
package nl.rubensten.texifyidea.inspections.latex
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import nl.rubensten.texifyidea.index.LatexCommandsIndex
import nl.rubensten.texifyidea.insight.InsightGroup
import nl.rubensten.texifyidea.inspections.TexifyInspectionBase
import nl.rubensten.texifyidea.psi.LatexCommands
import nl.rubensten.texifyidea.psi.LatexContent
import nl.rubensten.texifyidea.psi.LatexNormalText
import nl.rubensten.texifyidea.util.*
/**
* @author Ruben Schellekens
*/
open class LatexCollapseCiteInspection : TexifyInspectionBase() {
override fun getInspectionGroup() = InsightGroup.LATEX
override fun getInspectionId() = "CollapseCite"
override fun getDisplayName() = "Collapce cite commands"
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): MutableList<ProblemDescriptor> {
val descriptors = descriptorList()
val commands = LatexCommandsIndex.getItems(file)
for (cmd in commands) {
if (cmd.name !in Magic.Command.bibliographyReference) {
continue
}
val bundle = cmd.findCiteBundle()
if (bundle.size <= 1) {
continue
}
descriptors.add(manager.createProblemDescriptor(
cmd,
"Citations can be collapsed",
InspectionFix(bundle),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOntheFly
))
}
return descriptors
}
private fun LatexCommands.findCiteBundle(): List<LatexCommands> {
val bundle: MutableList<LatexCommands> = ArrayList()
// Lookbefore
var foundBefore: LatexCommands? = previousCite()
while (foundBefore != null) {
bundle.add(foundBefore)
foundBefore = foundBefore.previousCite()
}
// Current
bundle.add(this)
// Lookahead
var foundAfter: LatexCommands? = nextCite()
while (foundAfter != null) {
bundle.add(foundAfter)
foundAfter = foundAfter.nextCite()
}
return bundle
}
private fun LatexCommands.nextCite() = searchCite { it.nextSiblingIgnoreWhitespace() as? LatexContent }
private fun LatexCommands.previousCite() = searchCite { it.previousSiblingIgnoreWhitespace() as? LatexContent }
private inline fun LatexCommands.searchCite(nextThing: (LatexContent) -> LatexContent?): LatexCommands? {
val content = grandparent(2) as? LatexContent ?: return null
val nextContent = nextThing(content) ?: return null
var cite = nextContent.firstChildOfType(LatexCommands::class)
if (cite == null) {
if (!nextContent.isCorrect()) {
return null
}
val secondNextContent = nextThing(nextContent) ?: return null
cite = secondNextContent.firstChildOfType(LatexCommands::class) ?: return null
}
val name = cite.name ?: return null
val nextCommandIsACitation = name in Magic.Command.bibliographyReference
val previousCommandIsOfTheSameType = this.name == name
val equalStars = hasStar() == cite.hasStar()
return if (nextCommandIsACitation && previousCommandIsOfTheSameType && equalStars) cite else null
}
private fun LatexContent.isCorrect(): Boolean {
val normalText = firstChildOfType(LatexNormalText::class) ?: return false
return normalText.text.length == 1
}
/**
* @author <NAME>
*/
private inner class InspectionFix(val citeBundle: List<LatexCommands>) : LocalQuickFix {
override fun getFamilyName(): String {
return "Collapse citations"
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val file = descriptor.psiElement.containingFile ?: return
val document = file.document() ?: return
val sortedBundle = citeBundle.sortedBy { it.textOffset }
val offsetRange = sortedBundle.first().textOffset until sortedBundle.last().endOffset()
val bundle = sortedBundle
.flatMap { it.requiredParameters }
.joinToString(",")
val first = citeBundle.first()
val star = if (first.hasStar()) "*" else ""
document.replaceString(offsetRange.toTextRange(), "${first.name}$star{$bundle}")
}
}
}
| 1
| null |
1
| 1
|
e77533d731fe0ec201180a682f9e9fbec12683ec
| 4,740
|
TeXiFy-IDEA
|
MIT License
|
feature-staking-impl/src/main/java/jp/co/soramitsu/staking/impl/presentation/staking/controller/confirm/ConfirmSetControllerFragment.kt
|
soramitsu
| 278,060,397
| false
| null |
package jp.co.soramitsu.staking.impl.presentation.staking.controller.confirm
import android.os.Bundle
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import dev.chrisbanes.insetter.applyInsetter
import jp.co.soramitsu.common.base.BaseFragment
import jp.co.soramitsu.common.mixin.impl.observeValidations
import jp.co.soramitsu.common.view.viewBinding
import jp.co.soramitsu.account.api.presentation.actions.setupExternalActions
import jp.co.soramitsu.feature_staking_impl.R
import jp.co.soramitsu.feature_staking_impl.databinding.FragmentConfirmSetControllerBinding
const val PAYLOAD_KEY = "PAYLOAD_KEY"
@AndroidEntryPoint
class ConfirmSetControllerFragment : BaseFragment<ConfirmSetControllerViewModel>(R.layout.fragment_confirm_set_controller) {
companion object {
fun getBundle(payload: ConfirmSetControllerPayload) = Bundle().apply {
putParcelable(PAYLOAD_KEY, payload)
}
}
override val viewModel: ConfirmSetControllerViewModel by viewModels()
private val binding by viewBinding(FragmentConfirmSetControllerBinding::bind)
override fun initViews() {
with(binding) {
confirmSetControllerToolbar.applyInsetter {
type(statusBars = true) {
padding()
}
}
confirmSetControllerToolbar.setHomeButtonListener { viewModel.back() }
confirmSetControllerConfirm.setOnClickListener { viewModel.confirmClicked() }
confirmSetControllerStashAccount.setWholeClickListener { viewModel.openStashExternalActions() }
confirmSetControllerDestinationAccount.setWholeClickListener { viewModel.openControllerExternalActions() }
}
}
override fun subscribe(viewModel: ConfirmSetControllerViewModel) {
observeValidations(viewModel)
setupExternalActions(viewModel)
viewModel.feeStatusLiveData.observe(binding.confirmSetControllerFee::setFeeStatus)
viewModel.stashAddressLiveData.observe {
binding.confirmSetControllerStashAccount.setTextIcon(it.image)
binding.confirmSetControllerStashAccount.setMessage(it.nameOrAddress)
}
viewModel.controllerAddressLiveData.observe {
binding.confirmSetControllerDestinationAccount.setTextIcon(it.image)
binding.confirmSetControllerDestinationAccount.setMessage(it.nameOrAddress)
}
}
}
| 15
| null |
30
| 89
|
1de6dfa7c77d4960eca2d215df2bdcf71a2ef5f2
| 2,447
|
fearless-Android
|
Apache License 2.0
|
log/src/main/java/android/log/UncaughtExceptionHandler.kt
|
eastar-dev
| 241,168,541
| false
|
{"Gradle": 3, "Java Properties": 2, "YAML": 2, "Shell": 17, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 13, "INI": 1, "Gradle Kotlin DSL": 3, "Kotlin": 25, "XML": 12, "Java": 2}
|
@file:Suppress("unused")
package android.log
import android.app.Activity
import android.app.Application
import android.content.Context
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.webkit.WebView
import androidx.core.view.children
import androidx.core.view.drawToBitmap
import java.io.File
import java.lang.ref.WeakReference
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class UncaughtExceptionHandler(
context: Context,
actor: ((File) -> Unit)? = { it.deleteRecursively() },
) {
var timeFormatter: String = "yyyyMMdd-HHmmss"
var versionTag: String = "v"
var logDir = File(context.externalCacheDir, "temp")
init {
lastActivityWeakReference(context)
uncaughtExceptionHandler {
val uncaughtExceptionFilename = uncaughtExceptionFilename
uncaughtScreen(uncaughtExceptionFilename)
uncaughtStackTraceText(uncaughtExceptionFilename, it)
}
actor?.invoke(logDir)
}
private var mLastActivityWeakReference: WeakReference<Activity>? = null
private fun lastActivityWeakReference(context: Context) {
(context.applicationContext as Application).registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {
mLastActivityWeakReference = WeakReference(activity)
}
})
}
private fun uncaughtExceptionHandler(block: (stackTraceText: String) -> Unit) {
val def = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
block(throwable.stackTraceToString())
def?.uncaughtException(thread, throwable)
}
}
private val now get() = SimpleDateFormat(timeFormatter, Locale.getDefault()).format(Date(System.currentTimeMillis()))
private val uncaughtExceptionFilename: String get() = mLastActivityWeakReference?.get()?.let { uncaughtExceptionFilename(it) } ?: now
private fun uncaughtExceptionFilename(activity: Activity): String {
var name = now + ":" + activity.javaClass.simpleName
(activity.window.decorView as ViewGroup).findViewByChild(WebView::class.java)?.let {
name += ":" + it.url?.substringAfterLast("/")?.substringBeforeLast(".")
name += ":" + it.title
}
return name
}
private fun uncaughtStackTraceText(filename: String, stackTraceText: String) {
File(logDir, "$filename.txt")
.apply { parentFile?.mkdirs() }
.writeText("$versionTag\n$filename\n$stackTraceText")
}
private fun uncaughtScreen(filename: String) {
mLastActivityWeakReference?.get()?.findViewById<View>(Window.ID_ANDROID_CONTENT)?.drawToBitmap(Bitmap.Config.RGB_565)
?.let { bitmap ->
File(logDir, "/$filename.jpeg")
.apply { parentFile?.mkdirs() }
.outputStream().use {
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)
}
}
}
////////////////////////////////////////////////////////////////////////////////
@Suppress("UNCHECKED_CAST")
private fun <T : View> ViewGroup.findViewByChild(clz: Class<T>): T? {
val result = children.firstOrNull { clz.isInstance(it) }
?: children.filter { it is ViewGroup }
.map { (it as ViewGroup).findViewByChild(clz) }
.firstOrNull { clz.isInstance(it) }
return result as? T
}
}
| 3
|
Kotlin
|
1
| 7
|
fdd5aef622fdcb581b366c92b0443936dfb7b241
| 4,142
|
EastarLog2
|
Apache License 2.0
|
MoTrack/test-unit/src/androidTest/java/com/motrack/sdk/TestAttributionHandler.kt
|
motrackorg
| 542,491,377
| false
| null |
package com.motrack.sdk
import android.content.Context
import android.net.Uri
import android.os.SystemClock
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import com.motrack.sdk.test.UnitTestActivity
import org.json.JSONException
import org.json.JSONObject
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* @author yaya (@yahyalmh)
* @since 20th November 2021
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class TestAttributionHandler {
lateinit var mockLogger: MockLogger
lateinit var mockActivityHandler: MockActivityHandler
lateinit var mockHttpsURLConnection: MockHttpsURLConnection
lateinit var assertUtil: AssertUtil
private var activity: UnitTestActivity? = null
private var context: Context? = null
private var attributionPackage: ActivityPackage? = null
private var firstSessionPackage: ActivityPackage? = null
private var sdkClickPackage: ActivityPackage? = null
@Rule
public val mActivityRule: ActivityScenarioRule<UnitTestActivity> =
ActivityScenarioRule(UnitTestActivity::class.java)
@Before
fun setUp() {
context = InstrumentationRegistry.getInstrumentation().targetContext
mockLogger = MockLogger()
mockActivityHandler = MockActivityHandler(mockLogger)
mockHttpsURLConnection = MockHttpsURLConnection(null, mockLogger)
assertUtil = AssertUtil(mockLogger)
MotrackFactory.setLogger(mockLogger)
MotrackFactory.setActivityHandler(mockActivityHandler)
MotrackFactory.httpsURLConnectionProvider = mockHttpsURLConnection
savePackages()
mockLogger.reset()
}
private fun savePackages() {
val mockAttributionHandler = MockAttributionHandler(mockLogger)
val mockPackageHandler = MockPackageHandler(mockLogger)
val mockSdkClickHandler = MockSdkClickHandler(mockLogger)
MotrackFactory.setAttributionHandler(mockAttributionHandler)
MotrackFactory.setPackageHandler(mockPackageHandler)
MotrackFactory.setSdkClickHandler(mockSdkClickHandler)
// deleting the activity state file to simulate a first session
val activityStateDeleted = ActivityHandler.deleteActivityState(context!!)
val attributionDeleted = ActivityHandler.deleteAttribution(context!!)
// create the config to start the session
val config = MotrackConfig(context, "123456789012", MotrackConfig.ENVIRONMENT_SANDBOX)
// start activity handler with config
val activityHandler = ActivityHandler.getInstance(config)!!
activityHandler.onResume()
val attributions =
Uri.parse("Tests://example.com/path/inApp?adjust_tracker=trackerValue&other=stuff&adjust_campaign=campaignValue&adjust_adgroup=adgroupValue&adjust_creative=creativeValue")
val now = System.currentTimeMillis()
activityHandler.readOpenUrl(attributions, now)
SystemClock.sleep(3000)
val attributionPackage: ActivityPackage = activityHandler.getAttribution()
val attributionPackageTest = TestActivityPackage(attributionPackage)
attributionPackageTest.testAttributionPackage()
firstSessionPackage = mockPackageHandler.queue[0]
sdkClickPackage = mockSdkClickHandler.queue[0]
this.attributionPackage = attributionPackage
MotrackFactory.setAttributionHandler(null)
MotrackFactory.setPackageHandler(null)
MotrackFactory.setSdkClickHandler(null)
}
@After
fun tearDown() {
MotrackFactory.httpsURLConnectionProvider = null
MotrackFactory.setActivityHandler(null)
MotrackFactory.setLogger(null)
activity = null
context = null
}
@Test
fun testGetAttribution() {
// assert test name to read better in logcat
mockLogger.assert("TestAttributionHandler testGetAttribution")
val attributionHandler = AttributionHandler(
mockActivityHandler,
true, attributionPackage
)
// test null client
nullClientTest(attributionHandler)
// test client exception
clientExceptionTest(attributionHandler)
// test wrong json response
wrongJsonTest(attributionHandler)
// test empty response
emptyJsonResponseTest(attributionHandler)
// test server error
serverErrorTest(attributionHandler)
// test ok response with message
okMessageTest(attributionHandler)
}
@Test
fun testCheckSessionResponse() {
// assert test name to read better in logcat
mockLogger.assert("TestAttributionHandler testCheckSessionResponse")
val attributionHandler = AttributionHandler(
mockActivityHandler,true,
attributionPackage
)
// new attribution
var attributionJson: JSONObject? = null
try {
attributionJson = JSONObject(
"{ " +
"\"tracker_token\" : \"ttValue\" , " +
"\"tracker_name\" : \"tnValue\" , " +
"\"network\" : \"nValue\" , " +
"\"campaign\" : \"cpValue\" , " +
"\"adgroup\" : \"aValue\" , " +
"\"creative\" : \"ctValue\" , " +
"\"click_label\" : \"clValue\" }"
)
} catch (e: JSONException) {
assertUtil.fail(e.message!!)
}
val sessionResponseData =
ResponseData.buildResponseData(firstSessionPackage!!, null) as SessionResponseData
sessionResponseData.jsonResponse = attributionJson
attributionHandler.checkSessionResponse(sessionResponseData)
SystemClock.sleep(1000)
// updated set askingAttribution to false
assertUtil.test("ActivityHandler setAskingAttribution, false")
// it did not update to true
assertUtil.notInTest("ActivityHandler setAskingAttribution, true")
// and waiting for query
assertUtil.notInDebug("Waiting to query attribution")
// check attribution was called without ask_in
assertUtil.test("ActivityHandler launchSessionResponseTasks, message:null timestamp:null json:{\"tracker_token\":\"ttValue\",\"tracker_name\":\"tnValue\",\"network\":\"nValue\",\"campaign\":\"cpValue\",\"adgroup\":\"aValue\",\"creative\":\"ctValue\",\"click_label\":\"clValue\"}")
}
@Test
fun testCheckSdkClickResponse() {
// assert test name to read better in logcat
mockLogger.assert("TestAttributionHandler testCheckSdkClickResponse")
val attributionHandler = AttributionHandler(
mockActivityHandler,
true,
attributionPackage,
)
// new attribution
var attributionJson: JSONObject? = null
try {
attributionJson = JSONObject(
"{ " +
"\"tracker_token\" : \"ttValue\" , " +
"\"tracker_name\" : \"tnValue\" , " +
"\"network\" : \"nValue\" , " +
"\"campaign\" : \"cpValue\" , " +
"\"adgroup\" : \"aValue\" , " +
"\"creative\" : \"ctValue\" , " +
"\"click_label\" : \"clValue\" }"
)
} catch (e: JSONException) {
assertUtil.fail(e.message!!)
}
val sdkClickResponseData =
ResponseData.buildResponseData(sdkClickPackage!!, null) as SdkClickResponseData
sdkClickResponseData.jsonResponse = attributionJson
attributionHandler.checkSdkClickResponse(sdkClickResponseData)
SystemClock.sleep(1000)
// updated set askingAttribution to false
assertUtil.test("ActivityHandler setAskingAttribution, false")
// it did not update to true
assertUtil.notInTest("ActivityHandler setAskingAttribution, true")
// and waiting for query
assertUtil.notInDebug("Waiting to query attribution")
// check attribution was called without ask_in
assertUtil.test("ActivityHandler launchSdkClickResponseTasks, message:null timestamp:null json:{\"tracker_token\":\"ttValue\",\"tracker_name\":\"tnValue\",\"network\":\"nValue\",\"campaign\":\"cpValue\",\"adgroup\":\"aValue\",\"creative\":\"ctValue\",\"click_label\":\"clValue\"}")
}
@Test
fun testAskIn() {
// assert test name to read better in logcat
mockLogger.assert("TestAttributionHandler testAskIn")
val attributionHandler = AttributionHandler(
mockActivityHandler,
true,
attributionPackage
)
val response = "Response: { \"ask_in\" : 4000 }"
var askIn4sJson: JSONObject? = null
try {
askIn4sJson = JSONObject("{ \"ask_in\" : 4000 }")
} catch (e: JSONException) {
assertUtil.fail(e.message!!)
}
mockHttpsURLConnection.responseType = ResponseType.MESSAGE
val sessionResponseData =
ResponseData.buildResponseData(firstSessionPackage!!, null) as SessionResponseData
sessionResponseData.jsonResponse = askIn4sJson
attributionHandler.checkSessionResponse(sessionResponseData)
// sleep enough not to trigger the timer
SystemClock.sleep(1000)
// change the response to avoid a cycle;
mockHttpsURLConnection.responseType = ResponseType.MESSAGE
// check attribution was called with ask_in
assertUtil.notInTest("ActivityHandler updateAttribution")
// it did update to true
assertUtil.test("ActivityHandler setAskingAttribution, true")
// and waited to for query
assertUtil.debug("Waiting to query attribution in 4.0 seconds")
SystemClock.sleep(2000)
var askIn5sJson: JSONObject? = null
try {
askIn5sJson = JSONObject("{ \"ask_in\" : 5000 }")
} catch (e: JSONException) {
assertUtil.fail(e.message!!)
}
sessionResponseData.jsonResponse = askIn5sJson
attributionHandler.checkSessionResponse(sessionResponseData)
// sleep enough not to trigger the old timer
SystemClock.sleep(3000)
// it did update to true
assertUtil.test("ActivityHandler setAskingAttribution, true")
// and waited to for query
assertUtil.debug("Waiting to query attribution in 5.0 seconds")
// it was been waiting for 1000 + 2000 + 3000 = 6 seconds
// check that the mock http client was not called because the original clock was reseted
assertUtil.notInTest("HttpClient execute")
// check that it was finally called after 6 seconds after the second ask_in
SystemClock.sleep(4000)
okMessageTestLogs(attributionHandler)
//requestTest(mockHttpClient.lastRequest);
}
@Test
fun testPause() {
// assert test name to read better in logcat
mockLogger.assert("TestAttributionHandler testPause")
val attributionHandler = AttributionHandler(
mockActivityHandler,
false,
attributionPackage
)
mockHttpsURLConnection.responseType = ResponseType.MESSAGE
attributionHandler.getAttribution()
SystemClock.sleep(1000)
// check that the activity handler is paused
assertUtil.debug("Attribution handler is paused")
// and it did not call the http client
//assertUtil.isNull(mockHttpClient.lastRequest);
assertUtil.notInTest("MockHttpsURLConnection getInputStream")
}
@Test
fun testDeeplink() {
// assert test name to read better in logcat
mockLogger.assert("TestAttributionHandler testDeeplink")
val attributionHandler = AttributionHandler(
mockActivityHandler,
true,
attributionPackage,
)
val responseJson = JSONObject()
val sessionResponseDeeplink =
ResponseData.buildResponseData(firstSessionPackage!!, null) as SessionResponseData
try {
val internalAttributionJson = JSONObject()
internalAttributionJson.put("deeplink", "testDeeplinkAttribution://")
responseJson.put("deeplink", "testDeeplinkRoot://")
responseJson.put("attribution", internalAttributionJson)
//sessionResponseDeeplink.jsonResponse = new JSONObject("{ " +
// "\"deeplink\" : \"testDeeplinkRoot://\" }");
} catch (e: JSONException) {
assertUtil.fail(e.message!!)
}
sessionResponseDeeplink.jsonResponse = responseJson
attributionHandler.checkSessionResponse(sessionResponseDeeplink)
SystemClock.sleep(2000)
assertUtil.test("ActivityHandler setAskingAttribution, false")
assertUtil.test(
"ActivityHandler launchSessionResponseTasks, message:null timestamp:null " +
"json:{\"deeplink\":\"testDeeplinkRoot:\\/\\/\",\"attribution\":{\"deeplink\":\"testDeeplinkAttribution:\\/\\/\"}}"
)
val attributionResponseDeeplink =
ResponseData.buildResponseData(attributionPackage!!, null) as AttributionResponseData
attributionResponseDeeplink.jsonResponse = responseJson
attributionHandler.checkAttributionResponse(attributionResponseDeeplink)
SystemClock.sleep(2000)
assertUtil.test("ActivityHandler setAskingAttribution, false")
assertUtil.test(
"ActivityHandler launchAttributionResponseTasks, message:null timestamp:null " +
"json:{\"deeplink\":\"testDeeplinkRoot:\\/\\/\",\"attribution\":{\"deeplink\":\"testDeeplinkAttribution:\\/\\/\"}}"
)
assertUtil.isEqual(
attributionResponseDeeplink.deeplink,
Uri.parse("testDeeplinkAttribution://")
)
}
private fun nullClientTest(attributionHandler: AttributionHandler) {
startGetAttributionTest(attributionHandler, null)
// check response was not logged
assertUtil.notInVerbose("Response")
}
private fun clientExceptionTest(attributionHandler: AttributionHandler) {
startGetAttributionTest(attributionHandler, ResponseType.CLIENT_PROTOCOL_EXCEPTION)
// check the client error
assertUtil.error("Failed to get attribution (testResponseError)")
}
private fun wrongJsonTest(attributionHandler: AttributionHandler) {
startGetAttributionTest(attributionHandler, ResponseType.WRONG_JSON)
// check that the mock http client was called
assertUtil.test("MockHttpsURLConnection getInputStream")
assertUtil.verbose("Response: not a json response")
assertUtil.error("Failed to parse json response. (Value not of type java.lang.String cannot be converted to JSONObject)")
}
private fun emptyJsonResponseTest(attributionHandler: AttributionHandler) {
startGetAttributionTest(attributionHandler, ResponseType.EMPTY_JSON)
// check that the mock http client was called
assertUtil.test("MockHttpsURLConnection getInputStream")
assertUtil.verbose("Response: { }")
assertUtil.info("No message found")
// check attribution was called without ask_in
assertUtil.test("ActivityHandler setAskingAttribution, false")
assertUtil.test("ActivityHandler launchAttributionResponseTasks, message:null timestamp:null json:{}")
}
private fun serverErrorTest(attributionHandler: AttributionHandler) {
startGetAttributionTest(attributionHandler, ResponseType.INTERNAL_SERVER_ERROR)
// check that the mock http client was called
assertUtil.test("MockHttpsURLConnection getErrorStream")
// the response logged
assertUtil.verbose("Response: { \"message\": \"testResponseError\"}")
// the message in the response
assertUtil.error("testResponseError")
// check attribution was called without ask_in
assertUtil.test("ActivityHandler setAskingAttribution, false")
assertUtil.test("ActivityHandler launchAttributionResponseTasks, message:testResponseError timestamp:null json:{\"message\":\"testResponseError\"}")
}
private fun okMessageTest(attributionHandler: AttributionHandler) {
startGetAttributionTest(attributionHandler, ResponseType.MESSAGE)
okMessageTestLogs(attributionHandler)
}
private fun okMessageTestLogs(attributionHandler: AttributionHandler) {
/*
TestActivityPackage.testQueryStringRequest(attributionHandler.lastUrlUsed.getQuery(), null);
// check that the mock http client was called
assertUtil.test("MockHttpsURLConnection getInputStream");
// the response logged
assertUtil.verbose("Response: { \"message\" : \"response OK\"}");
// the message in the response
assertUtil.info("response OK");
assertUtil.test("ActivityHandler setAskingAttribution, false");
// check attribution was called without ask_in
assertUtil.test("ActivityHandler launchAttributionResponseTasks, message:response OK timestamp:null json:{\"message\":\"response OK\"}");
*/
}
private fun startGetAttributionTest(
attributionHandler: AttributionHandler,
responseType: ResponseType?
) {
mockHttpsURLConnection.responseType = responseType
attributionHandler.getAttribution()
SystemClock.sleep(1000)
}
}
| 0
|
Kotlin
|
0
| 0
|
c17229901ac6b1d10fc016297f6daefe8506b6c2
| 17,804
|
AndroidSDK
|
MIT License
|
app/src/main/kotlin/com/base/BaseActivity.kt
|
rooest
| 95,102,872
| true
|
{"Kotlin": 12054}
|
package com.base
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.base.di.component.AppComponent
import com.base.mvp.BaseView
/**
* Created by <NAME> on 20.05.2017.
* <EMAIL>
* https://github.com/burakeregar
*/
abstract class BaseActivity: AppCompatActivity(), BaseView {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onActivityInject()
}
protected abstract fun onActivityInject()
fun getAppcomponent(): AppComponent = App.appComponent
}
| 0
|
Kotlin
|
0
| 0
|
393e44d73e16a0411138e460dfe93d1ce38e1011
| 557
|
KotlinMvpArchitecture
|
MIT License
|
wisefy/networkinfo/src/main/kotlin/com/isupatches/android/wisefy/networkinfo/entities/NetworkConnectionStatusData.kt
|
isuPatches
| 57,158,628
| false
|
{"Kotlin": 1057623, "Shell": 4398}
|
/*
* Copyright 2022 <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.isupatches.android.wisefy.networkinfo.entities
/**
* A data representation of the current network connection status from Android OS level returns.
*
* @property isConnected If the device is connected to a mobile or wifi network
* @property isConnectedToMobileNetwork If the device is connected to a mobile network
* @property isConnectedToWifiNetwork If the device is connected to a wifi network
* @property isRoaming If the device is roaming
* @property ssidOfNetworkConnectedTo The current SSID that the device is connected to, or null
* @property bssidOfNetworkConnectedTo The current BSSID that the device is connected to, or null
* @property ip The IP address of the device from it's current network, or null
*
* @author <NAME>
* @since 12/2022, version 5.0.0
*/
data class NetworkConnectionStatusData(
val isConnected: Boolean,
val isConnectedToMobileNetwork: Boolean,
val isConnectedToWifiNetwork: Boolean,
val isRoaming: Boolean,
val ssidOfNetworkConnectedTo: String?,
val bssidOfNetworkConnectedTo: String?,
val ip: String?
)
| 19
|
Kotlin
|
38
| 312
|
2d87a8f560c82b6e2447c20304793f3f00087fc3
| 1,675
|
android-wisefy
|
Apache License 2.0
|
data/src/main/java/com/mikhaellopez/data/net/NetworkChecker.kt
|
lopspower
| 522,617,808
| false
|
{"Kotlin": 168656, "Java": 749}
|
package com.mikhaellopez.data.net
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import org.koin.core.annotation.Single
/**
* Copyright (C) 2022 <NAME>
* Licensed under the Apache License Version 2.0
*/
@Single
class NetworkChecker(private val context: Context) {
@Suppress("DEPRECATION")
val isConnected: Boolean
@SuppressLint("MissingPermission")
get() = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager)?.run {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getNetworkCapabilities(activeNetwork)?.run {
when {
hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} ?: false
} else {
activeNetworkInfo?.run {
when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
else -> false
}
} ?: false
}
} ?: false
}
| 0
|
Kotlin
|
6
| 111
|
ce41ce693cdb09facc455224b8af8fedcff74ad1
| 1,436
|
PokeCardCompose
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.