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
buildSrc/src/main/kotlin/io/embrace/gradle/InternalEmbracePlugin.kt
embrace-io
704,537,857
false
{"Kotlin": 3102378, "C": 189946, "Java": 179815, "C++": 13140, "CMake": 4188}
package io.embrace.gradle import com.android.build.api.dsl.LibraryExtension import io.gitlab.arturbosch.detekt.Detekt import io.gitlab.arturbosch.detekt.DetektCreateBaselineTask import io.gitlab.arturbosch.detekt.extensions.DetektExtension import kotlinx.validation.ApiValidationExtension import org.gradle.api.JavaVersion import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.quality.Checkstyle import org.gradle.api.plugins.quality.CheckstyleExtension import org.gradle.api.tasks.compile.JavaCompile import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.dependencies import org.jetbrains.kotlin.gradle.tasks.KotlinCompile @Suppress("UnstableApiUsage") // because most of AGP is unstable :| class InternalEmbracePlugin : Plugin<Project> { override fun apply(project: Project) { configureBuildPlugins(project) // TODO: (future) - these scripts should be integrated into this class. project.apply(from = project.file("../scripts/release.gradle")) project.pluginManager.withPlugin("com.android.library") { val android = project.extensions.getByType(LibraryExtension::class.java) configureAndroidExtension(project, android) configureJavaOptions(project) configureKotlinOptions(project) } val embrace = project.extensions.create("embraceOptions", EmbracePluginExtension::class.java) configureModuleDependencies(project) configureDetekt(project) configureCheckstyle(project) configureApiValidation(project, embrace) } /** * Configures behavior of Checkstyle plugin. */ private fun configureCheckstyle(project: Project) { val checkstyle = project.extensions.getByType(CheckstyleExtension::class.java) checkstyle.run { toolVersion = "10.3.2" } val checkstyleTaskProvider = project.tasks.register("checkstyle", Checkstyle::class.java) checkstyleTaskProvider.configure { configFile = project.rootProject.file("config/checkstyle/google_checks.xml") ignoreFailures = false isShowViolations = true source("src") include("**/*.java") classpath = project.files() maxWarnings = 0 } } /** * Configures behavior of API binary compatibility check plugin. */ private fun configureApiValidation( project: Project, embrace: EmbracePluginExtension ) { project.afterEvaluate { project.configure<ApiValidationExtension> { validationDisabled = !embrace.apiBinaryCompatChecks.get() nonPublicMarkers += mutableSetOf() } } } /** * Configures behavior of Detekt plugin. */ private fun configureDetekt(project: Project) { val detekt = project.extensions.getByType(DetektExtension::class.java) detekt.run { buildUponDefaultConfig = true autoCorrect = true config.from(project.files("${project.rootDir}/config/detekt/detekt.yml")) // overwrite default behaviour here baseline = project.file("${project.projectDir}/config/detekt/baseline.xml") // suppress pre-existing issues } project.tasks.withType(Detekt::class.java).configureEach { jvmTarget = "1.8" reports { html.required.set(true) xml.required.set(false) txt.required.set(true) sarif.required.set(false) md.required.set(false) } } project.tasks.withType(DetektCreateBaselineTask::class.java).configureEach { jvmTarget = "1.8" } } /** * Configures the Android extension. */ private fun configureAndroidExtension(project: Project, android: LibraryExtension) { android.run { compileSdk = Versions.compileSdk defaultConfig { minSdk = Versions.minSdk testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" aarMetadata { minCompileSdk = Versions.minSdk } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } lint { abortOnError = true warningsAsErrors = true checkAllWarnings = true checkReleaseBuilds = false // run on CI instead, speeds up release builds baseline = project.file("lint-baseline.xml") disable.addAll(mutableSetOf("GradleDependency", "NewerVersionAvailable")) } testOptions { // Calling Android logging methods will throw exceptions if this is false // see: http://tools.android.com/tech-docs/unit-testing-support#TOC-Method-...-not-mocked.- unitTests.isReturnDefaultValues = true unitTests.isIncludeAndroidResources = true unitTests { all { test -> test.testLogging { this.exceptionFormat = TestExceptionFormat.FULL } } } } buildTypes { named("release") { isMinifyEnabled = false } } testOptions { unitTests { all { test -> test.maxParallelForks = (Runtime.getRuntime().availableProcessors() / 3) + 1 } } } } } private fun configureKotlinOptions(project: Project) { project.tasks.withType(KotlinCompile::class.java).configureEach { kotlinOptions { apiVersion = "1.4" languageVersion = "1.4" jvmTarget = JavaVersion.VERSION_1_8.toString() freeCompilerArgs = freeCompilerArgs + "-Xexplicit-api=strict" // FIXME: targeting Kotlin 1.4 emits a warning that I can't find a way to suppress. // Disabling this check for now. allWarningsAsErrors = false } } } private fun configureJavaOptions(project: Project) { project.tasks.withType(JavaCompile::class.java).configureEach { val args = listOf("-Xlint:unchecked", "-Xlint:deprecation") options.compilerArgs.addAll(args) } } /** * Adds common plugins to the project. */ private fun configureBuildPlugins(project: Project) { val plugins = listOf( "com.android.library", "kotlin-android", "io.gitlab.arturbosch.detekt", "checkstyle", "binary-compatibility-validator" ) plugins.forEach { project.plugins.apply(it) } } /** * Adds build-time dependencies to the project. */ private fun configureModuleDependencies(project: Project) { project.dependencies { add("testImplementation", "junit:junit:${Versions.junit}") add("implementation", "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlinExposed}") add("detektPlugins", "io.gitlab.arturbosch.detekt:detekt-formatting:${Versions.detekt}") add("lintChecks", project.project(":embrace-lint")) } } }
15
Kotlin
7
130
e3ab4c793ce7fceae98cf82ff68d1ee6cd33a2c1
7,737
embrace-android-sdk
Apache License 2.0
releases-hub-gradle-plugin/src/test/java/com/releaseshub/gradle/plugin/dependencies/BasicDependenciesExtractorTest.kt
dipien
196,064,299
false
{"Kotlin": 111095, "Shell": 2559, "HTML": 1750, "Java": 15}
package com.releaseshub.gradle.plugin.dependencies import com.google.common.truth.Truth import com.releaseshub.gradle.plugin.artifacts.ArtifactUpgrade import com.releaseshub.gradle.plugin.common.ResourceUtils import org.junit.Assert import org.junit.Test import java.io.File class BasicDependenciesExtractorTest { @Test fun extractFromEmptyTest() { val dependenciesParserResult = extractArtifacts("empty_dependencies_file") Assert.assertTrue(dependenciesParserResult.getAllArtifacts().isEmpty()) Assert.assertTrue(dependenciesParserResult.excludedArtifacts.isEmpty()) } @Test fun extractFromDeprecatedTest() { val dependenciesParserResult = extractArtifacts("deprecated_file") Truth.assertThat(dependenciesParserResult.getAllArtifacts()).isEmpty() Truth.assertThat(dependenciesParserResult.excludedArtifacts).isEmpty() } @Test fun extractFromCommentTest() { val dependenciesParserResult = extractArtifacts("comments_file") Assert.assertTrue("Found these artifacts: ${dependenciesParserResult.getAllArtifacts()}", dependenciesParserResult.getAllArtifacts().isEmpty()) Assert.assertTrue(dependenciesParserResult.excludedArtifacts.isEmpty()) } @Test fun extractWithVersionTest() { val dependenciesParserResult = extractArtifacts("dependencies_versions_file") Assert.assertEquals(2, dependenciesParserResult.getAllArtifacts().size) val firstArtifact = dependenciesParserResult.getAllArtifacts()[0] Assert.assertEquals("com.dipien", firstArtifact.groupId) Assert.assertEquals("sample", firstArtifact.artifactId) Assert.assertEquals("3.0.0", firstArtifact.fromVersion) val secondArtifact = dependenciesParserResult.getAllArtifacts()[1] Assert.assertEquals("junit", secondArtifact.groupId) Assert.assertEquals("junit", secondArtifact.artifactId) Assert.assertEquals("4.13", secondArtifact.fromVersion) Assert.assertTrue(dependenciesParserResult.excludedArtifacts.isEmpty()) } @Test fun extractGradleArtifactTest() { val dependenciesParserResult = extractGradleArtifacts() Assert.assertEquals(1, dependenciesParserResult.getAllArtifacts().size) val firstArtifact = dependenciesParserResult.getAllArtifacts()[0] Assert.assertEquals(ArtifactUpgrade.GRADLE_ID, firstArtifact.id) Assert.assertEquals("6.0.1", firstArtifact.fromVersion) Assert.assertTrue(dependenciesParserResult.excludedArtifacts.isEmpty()) } private fun extractArtifacts(basePath: String): DependenciesExtractorResult { val extractor = BasicDependenciesExtractor(listOf("$basePath/Libs.kt")) return extractor.extractArtifacts(File(ResourceUtils.getRequiredResourcePath("root"))) } private fun extractGradleArtifacts(): DependenciesExtractorResult { val extractor = BasicDependenciesExtractor(listOf("gradle" + File.separator + "wrapper" + File.separator + "gradle-wrapper.properties")) return extractor.extractArtifacts(File(ResourceUtils.getRequiredResourcePath("root_gradle"))) } }
27
Kotlin
7
151
92e5d7af431c81f5f3c6c7fa5fc0857b0f18a0e6
3,170
releases-hub-gradle-plugin
Apache License 2.0
app/src/main/java/com/dede/nativetools/netspeed/utils/NetFormatter.kt
hushenghao
242,718,110
false
null
package com.dede.nativetools.netspeed.utils import java.text.DecimalFormat /** * 字节数格式化工具 * * Created by hsh on 2017/5/15 015 下午 05:14. */ object NetFormatter { /** * 精确等宽格式 * * 888 * 88.8 * 8.88 */ const val ACCURACY_EQUAL_WIDTH_EXACT = 1 /** * 精确格式 * * 88.88 */ const val ACCURACY_EXACT = 2 /** * 低精度格式 * * 88.8 */ const val ACCURACY_SHORTER = 4 /** * 等宽格式 * * 88 * 8.8 */ const val ACCURACY_EQUAL_WIDTH = 3 /** * 单位B字符的标志位 * * Pair(8.8, B), Pair(8.8, KB) */ const val FLAG_BYTE = 1 /** * /s字符的标志位 * * Pair(8.8, /s) */ const val FLAG_INFIX_SECOND = 1 shl 1 /** * 全量字符标志位 * * Pair(8.8, KB/s) */ const val FLAG_FULL = FLAG_BYTE or FLAG_INFIX_SECOND /** * 无拼接字符标志位 * * Pair(8.8, B), Pair(8.8, K) */ const val FLAG_NULL = 0 private const val CHAR_BYTE = 'B' private const val CHARS_INFIX_SECOND = "/s" private val UNIT_CHARS = charArrayOf('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'B', 'N', 'D') // android.text.format.Formatter.formatFileSize(android.content.Context, long) // 8.0以后使用的单位是1000,非1024 private const val UNIT_SIZE = 1024 private const val THRESHOLD = 900 fun format(bytes: Long, flags: Int, accuracy: Int): Pair<String, String> { fun hasFlag(flag: Int): Boolean = (flags and flag) > 0 var speed = bytes.toDouble() var unit: Char = CHAR_BYTE for (char in UNIT_CHARS) { if (speed > THRESHOLD) { speed /= UNIT_SIZE unit = char } else { break } } val format = formatNumberInternal(speed, accuracy)// 速度 val sb = StringBuilder() .append(unit)// 单位 if (hasFlag(FLAG_BYTE) && unit != CHAR_BYTE) { sb.append(CHAR_BYTE)// 拼接B } if (hasFlag(FLAG_INFIX_SECOND)) { sb.append(CHARS_INFIX_SECOND)// 拼接/s } return format to sb.toString() } private fun formatNumberInternal(num: Double, accuracy: Int): String { val pattern = when (accuracy) { ACCURACY_EQUAL_WIDTH_EXACT -> when { num >= 100 -> "0" // 100.2 -> 100 num >= 10 -> "0.#" // 10.22 -> 10.2 else -> "0.##" // 0.223 -> 0.22 } ACCURACY_EQUAL_WIDTH -> when { num >= 10 -> "0" // 10.2 -> 10 else -> "0.#" // 1.22 -> 1.2 } ACCURACY_EXACT -> "0.##" // 0.223 -> 0.22 ACCURACY_SHORTER -> "0.#" else -> "0.##" } return DecimalFormat(pattern).format(num) } }
1
Kotlin
2
5
f7550e37d20efe555914c0c2428a048b131a89aa
2,819
NativeTools
Apache License 2.0
app/src/main/java/com/example/universitysystem/adapters/LectureSelectionAdapter.kt
SabirHalil
707,783,946
false
{"Kotlin": 99226}
package com.example.universitysystem.adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.example.universitysystem.R import com.example.universitysystem.data.models.Lecture import com.example.universitysystem.databinding.OneLectureLayoutBinding class LectureSelectionAdapter(private val list :ArrayList<Lecture>, val onAddOrDeleteClicked: OnAddOrDeleteClicked,val isAdd:Boolean): RecyclerView.Adapter<LectureSelectionAdapter.ViewHolder>() { interface OnAddOrDeleteClicked{ fun onAddOrDeleteClicked(id:Int, isAdd:Boolean) } inner class ViewHolder(private val binding: OneLectureLayoutBinding):RecyclerView.ViewHolder(binding.root) { @SuppressLint("ResourceAsColor") fun bind(lecture: Lecture){ binding.tvCode.text = lecture.lectureCode binding.tvName.text = lecture.lectureName binding.tvKredi.text = lecture.lectureCredit.toString() if (isAdd){ val greenColor = ContextCompat.getColor(binding.root.context, R.color.green) binding.view1.setBackgroundColor(greenColor) binding.ivAdd.setImageResource(R.drawable.ic_add) } binding.ivAdd.setOnClickListener { onAddOrDeleteClicked.onAddOrDeleteClicked(adapterPosition,isAdd) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(OneLectureLayoutBinding.inflate(LayoutInflater.from(parent.context),parent,false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(list[position]) } override fun getItemCount(): Int { return list.size } }
0
Kotlin
0
1
53a236db8ff589a5dc2824526ba2b98a90f2971d
1,872
University-System-Mobile-Kotlin
MIT License
android/companionapp/src/main/java/com/benoitletondor/pixelminimalwatchfacecompanion/view/donation/DonationViewModel.kt
benoitletondor
236,035,670
false
null
/* * 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.benoitletondor.pixelminimalwatchfacecompanion.view.donation import android.app.Activity import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.billingclient.api.ProductDetails import com.benoitletondor.pixelminimalwatchfacecompanion.billing.Billing import com.benoitletondor.pixelminimalwatchfacecompanion.helper.MutableLiveFlow import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class DonationViewModel @Inject constructor( private val billing: Billing, ) : ViewModel() { private val errorPayingEventMutableFlow = MutableLiveFlow<Throwable>() val errorPayingEventFlow: Flow<Throwable> = errorPayingEventMutableFlow private val donationSuccessEventMutableFlow = MutableLiveFlow<String>() val donationSuccessEventFlow: Flow<String> = donationSuccessEventMutableFlow private val stateMutableFlow = MutableStateFlow<State>(State.Loading) val stateFlow: Flow<State> = stateMutableFlow val state: State get() = stateMutableFlow.value init { loadSKUs() } private fun loadSKUs() { viewModelScope.launch { withContext(Dispatchers.IO) { stateMutableFlow.value = State.Loading try { val productDetails = billing.getDonationsProductDetails() stateMutableFlow.value = State.Loaded( items = productDetails.map { productDetail -> DonationItem( sku = productDetail.productId, title = productDetail.name, description = productDetail.description, price = productDetail.oneTimePurchaseOfferDetails?.formattedPrice ?: "?", ) }, productDetails = productDetails, ) } catch (error: Throwable) { Log.e("DonationViewModel", "Error while loading SKUs", error) stateMutableFlow.value = State.ErrorLoading(error) } } } } fun onRetryLoadSKUsButtonClicked() { loadSKUs() } fun onDonateButtonClicked(productId: String, activity: Activity) { val loadedState = state as? State.Loaded ?: return val productDetails = loadedState.productDetails.firstOrNull { it.productId == productId } ?: return viewModelScope.launch { withContext(Dispatchers.IO) { try { val purchaseStatus = billing.launchDonationPurchaseFlow(activity, productDetails) if( purchaseStatus ) { donationSuccessEventMutableFlow.emit(productDetails.oneTimePurchaseOfferDetails?.formattedPrice ?: "?") } } catch (error: Throwable) { Log.e("DonationViewModel", "Error while donation for SKU: $productId", error) errorPayingEventMutableFlow.emit(error) } } } } sealed class State { object Loading : State() class ErrorLoading(val error: Throwable) : State() class Loaded(val items: List<DonationItem>, val productDetails: List<ProductDetails>) : State() } data class DonationItem( val sku: String, val title: String, val description: String, val price: String, ) }
13
Kotlin
35
161
b52591c3f9f416864935664942f633d8ca71bac8
4,364
PixelMinimalWatchFace
Apache License 2.0
survey/src/main/java/com.quickbirdstudios.surveykit/backend/views/questions/IntegerQuestionView.kt
QuickBirdEng
208,727,886
false
{"Kotlin": 246845, "Shell": 8542}
package com.quickbirdstudios.surveykit.backend.views.questions import android.content.Context import android.view.Gravity import androidx.annotation.StringRes import com.quickbirdstudios.surveykit.AnswerFormat import com.quickbirdstudios.surveykit.R import com.quickbirdstudios.surveykit.StepIdentifier import com.quickbirdstudios.surveykit.backend.helpers.extensions.afterTextChanged import com.quickbirdstudios.surveykit.backend.views.question_parts.IntegerTextFieldPart import com.quickbirdstudios.surveykit.backend.views.step.QuestionView import com.quickbirdstudios.surveykit.extensions.getNonNullText import com.quickbirdstudios.surveykit.result.QuestionResult import com.quickbirdstudios.surveykit.result.question_results.IntegerQuestionResult internal class IntegerQuestionView( context: Context, id: StepIdentifier, isOptional: Boolean, title: String?, text: String?, nextButtonText: String, skipButtonText: String, @StringRes private val hintText: Int = R.string.empty, private val answerFormat: AnswerFormat.IntegerAnswerFormat, private val preselected: Int? = null ) : QuestionView(context, id, isOptional, title, text, nextButtonText, skipButtonText) { //region Members private lateinit var questionAnswerView: IntegerTextFieldPart private var isValueChanged = false //endregion //region Overrides override fun createResults(): QuestionResult = IntegerQuestionResult( id = id, startDate = startDate, answer = questionAnswerView.field.text.toString().parseToIntOrNull(), stringIdentifier = questionAnswerView.field.text.toString() ) override fun isValidInput(): Boolean = isOptional || ((questionAnswerView.field.getNonNullText().isNotBlank()) && answerFormat.isValid(questionAnswerView.field.getNonNullText().toInt())) override fun setupViews() { super.setupViews() questionAnswerView = content.add(IntegerTextFieldPart.withHint(context, hintText)) questionAnswerView.field.gravity = Gravity.CENTER questionAnswerView.field.hint = answerFormat.hint questionAnswerView.field.afterTextChanged { val isValidInput = isValidInput() footer.canContinue = isValidInput if (isValidInput || !isValueChanged) { questionAnswerView.fieldInfo.error = null } else { questionAnswerView.fieldInfo.error = answerFormat.errorText } isValueChanged = true } val alreadyEntered = preselected?.toString() ?: answerFormat.defaultValue?.toString() questionAnswerView.field.setText(alreadyEntered ?: "") } //endregion //region Private Helpers private fun String.parseToIntOrNull(): Int? = runCatching { this.toInt() }.getOrNull() //endregion }
19
Kotlin
71
384
83cd95cc79db67fb96e642e84b815a4c8b5fb5ab
2,915
SurveyKit
MIT License
app/server/src/main/jooq/io/github/novemdecillion/adapter/jooq/tables/FlywaySchemaHistoryTable.kt
novemdecillion
332,666,905
false
null
/* * This file is generated by jOOQ. */ package io.github.novemdecillion.adapter.jooq.tables import io.github.novemdecillion.adapter.jooq.DefaultSchema import io.github.novemdecillion.adapter.jooq.indexes.FLYWAY_SCHEMA_HISTORY_S_IDX import io.github.novemdecillion.adapter.jooq.keys.FLYWAY_SCHEMA_HISTORY_PK import io.github.novemdecillion.adapter.jooq.tables.records.FlywaySchemaHistoryRecord import java.time.LocalDateTime import kotlin.collections.List import org.jooq.Field import org.jooq.ForeignKey import org.jooq.Index import org.jooq.Name import org.jooq.Record import org.jooq.Row10 import org.jooq.Schema import org.jooq.Table import org.jooq.TableField import org.jooq.TableOptions import org.jooq.UniqueKey import org.jooq.impl.DSL import org.jooq.impl.Internal import org.jooq.impl.SQLDataType import org.jooq.impl.TableImpl /** * This class is generated by jOOQ. */ @Suppress("UNCHECKED_CAST") open class FlywaySchemaHistoryTable( alias: Name, child: Table<out Record>?, path: ForeignKey<out Record, FlywaySchemaHistoryRecord>?, aliased: Table<FlywaySchemaHistoryRecord>?, parameters: Array<Field<*>?>? ): TableImpl<FlywaySchemaHistoryRecord>( alias, DefaultSchema.DEFAULT_SCHEMA, child, path, aliased, parameters, DSL.comment(""), TableOptions.table() ) { companion object { /** * The reference instance of <code>flyway_schema_history</code> */ val FLYWAY_SCHEMA_HISTORY = FlywaySchemaHistoryTable() } /** * The class holding records for this type */ override fun getRecordType(): Class<FlywaySchemaHistoryRecord> = FlywaySchemaHistoryRecord::class.java /** * The column <code>flyway_schema_history.installed_rank</code>. */ val INSTALLED_RANK: TableField<FlywaySchemaHistoryRecord, Int?> = createField(DSL.name("installed_rank"), SQLDataType.INTEGER.nullable(false), this, "") /** * The column <code>flyway_schema_history.version</code>. */ val VERSION: TableField<FlywaySchemaHistoryRecord, String?> = createField(DSL.name("version"), SQLDataType.VARCHAR(50), this, "") /** * The column <code>flyway_schema_history.description</code>. */ val DESCRIPTION: TableField<FlywaySchemaHistoryRecord, String?> = createField(DSL.name("description"), SQLDataType.VARCHAR(200).nullable(false), this, "") /** * The column <code>flyway_schema_history.type</code>. */ val TYPE: TableField<FlywaySchemaHistoryRecord, String?> = createField(DSL.name("type"), SQLDataType.VARCHAR(20).nullable(false), this, "") /** * The column <code>flyway_schema_history.script</code>. */ val SCRIPT: TableField<FlywaySchemaHistoryRecord, String?> = createField(DSL.name("script"), SQLDataType.VARCHAR(1000).nullable(false), this, "") /** * The column <code>flyway_schema_history.checksum</code>. */ val CHECKSUM: TableField<FlywaySchemaHistoryRecord, Int?> = createField(DSL.name("checksum"), SQLDataType.INTEGER, this, "") /** * The column <code>flyway_schema_history.installed_by</code>. */ val INSTALLED_BY: TableField<FlywaySchemaHistoryRecord, String?> = createField(DSL.name("installed_by"), SQLDataType.VARCHAR(100).nullable(false), this, "") /** * The column <code>flyway_schema_history.installed_on</code>. */ val INSTALLED_ON: TableField<FlywaySchemaHistoryRecord, LocalDateTime?> = createField(DSL.name("installed_on"), SQLDataType.LOCALDATETIME(6).nullable(false).defaultValue(DSL.field("now()", SQLDataType.LOCALDATETIME)), this, "") /** * The column <code>flyway_schema_history.execution_time</code>. */ val EXECUTION_TIME: TableField<FlywaySchemaHistoryRecord, Int?> = createField(DSL.name("execution_time"), SQLDataType.INTEGER.nullable(false), this, "") /** * The column <code>flyway_schema_history.success</code>. */ val SUCCESS: TableField<FlywaySchemaHistoryRecord, Boolean?> = createField(DSL.name("success"), SQLDataType.BOOLEAN.nullable(false), this, "") private constructor(alias: Name, aliased: Table<FlywaySchemaHistoryRecord>?): this(alias, null, null, aliased, null) private constructor(alias: Name, aliased: Table<FlywaySchemaHistoryRecord>?, parameters: Array<Field<*>?>?): this(alias, null, null, aliased, parameters) /** * Create an aliased <code>flyway_schema_history</code> table reference */ constructor(alias: String): this(DSL.name(alias)) /** * Create an aliased <code>flyway_schema_history</code> table reference */ constructor(alias: Name): this(alias, null) /** * Create a <code>flyway_schema_history</code> table reference */ constructor(): this(DSL.name("flyway_schema_history"), null) constructor(child: Table<out Record>, key: ForeignKey<out Record, FlywaySchemaHistoryRecord>): this(Internal.createPathAlias(child, key), child, key, FLYWAY_SCHEMA_HISTORY, null) override fun getSchema(): Schema = DefaultSchema.DEFAULT_SCHEMA override fun getIndexes(): List<Index> = listOf(FLYWAY_SCHEMA_HISTORY_S_IDX) override fun getPrimaryKey(): UniqueKey<FlywaySchemaHistoryRecord> = FLYWAY_SCHEMA_HISTORY_PK override fun getKeys(): List<UniqueKey<FlywaySchemaHistoryRecord>> = listOf(FLYWAY_SCHEMA_HISTORY_PK) override fun `as`(alias: String): FlywaySchemaHistoryTable = FlywaySchemaHistoryTable(DSL.name(alias), this) override fun `as`(alias: Name): FlywaySchemaHistoryTable = FlywaySchemaHistoryTable(alias, this) /** * Rename this table */ override fun rename(name: String): FlywaySchemaHistoryTable = FlywaySchemaHistoryTable(DSL.name(name), null) /** * Rename this table */ override fun rename(name: Name): FlywaySchemaHistoryTable = FlywaySchemaHistoryTable(name, null) // ------------------------------------------------------------------------- // Row10 type methods // ------------------------------------------------------------------------- override fun fieldsRow(): Row10<Int?, String?, String?, String?, String?, Int?, String?, LocalDateTime?, Int?, Boolean?> = super.fieldsRow() as Row10<Int?, String?, String?, String?, String?, Int?, String?, LocalDateTime?, Int?, Boolean?> }
10
Kotlin
0
0
ea259afd23a28ccf03aa7c5c6f35b932d2c22182
6,280
magic-lantern
Apache License 2.0
android/src/main/kotlin/qiuxiang/android_window/WindowService.kt
qiuxiang
412,021,747
false
null
package qiuxiang.android_window import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Intent import android.content.res.Configuration import android.os.Build import android.os.IBinder import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.dart.DartExecutor class WindowService : android.app.Service() { private lateinit var engine: FlutterEngine private lateinit var androidWindow: AndroidWindow private var running = false private val channelId = "foreground" override fun onBind(intent: Intent): IBinder? { return null } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) androidWindow.updateLayout() } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { if (!running) { engine = FlutterEngine(application) val entry = intent.getStringExtra("entry") ?: "androidWindow" val entryPoint = DartExecutor.DartEntrypoint(findAppBundlePath(), entry) engine.dartExecutor.executeDartEntrypoint(entryPoint) val focusable = intent.getBooleanExtra("focusable", false) val width = intent.getIntExtra("width", 400) val height = intent.getIntExtra("height", 600) val x = intent.getIntExtra("x", 0) val y = intent.getIntExtra("y", 0) androidWindow = AndroidWindow(this, focusable, width, height, x, y, engine) androidWindow.open() startForeground(1, getNotification()) running = true androidWindow.app?.androidWindowMessenger = engine.dartExecutor.binaryMessenger androidWindow.app?.running = true } return super.onStartCommand(intent, flags, startId) } private fun getNotification(): Notification { return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) { val channel = NotificationChannel(channelId, "Window Service", NotificationManager.IMPORTANCE_DEFAULT) val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) Notification.Builder(this, channel.id) } else { @Suppress("Deprecation") Notification.Builder(this) }.build() } override fun onDestroy() { androidWindow.close() try { engine.destroy() } catch (_: Exception) { } androidWindow.app?.running = false } }
10
Kotlin
15
42
c30187c88ede6fffe76b51482876170ddc6457c2
2,451
flutter-android-window
MIT License
sample-kotlin-koin/src/main/java/com/infullmobile/android/infullmvp/sample/mvpCardActivity/MvpCardActivity.kt
inFullMobile
75,730,560
false
null
package com.infullmobile.android.infullmvp.sample.mvpCardActivity import com.infullmobile.android.infullmvp.InFullMvpActivity import org.koin.android.ext.android.inject import org.koin.core.parameter.parametersOf class MvpCardActivity : InFullMvpActivity<MvpCardView, MvpCardPresenter>() { override val presenter: MvpCardPresenter by inject { parametersOf(this) } override val presentedView: MvpCardView by inject { parametersOf(this) } }
7
Kotlin
5
11
2b25b5b957fff0c6bec89a5c6875b1870a152e3e
448
InfullMvpAndroid
MIT License
src/main/kotlin/com/networkedassets/gherkin/runner/util/GherkinLoader.kt
NetworkedAssets
120,890,153
false
null
package com.networkedassets.gherkin.runner.util import com.networkedassets.gherkin.runner.exception.InvalidTagsExpressionException import com.networkedassets.gherkin.runner.gherkin.GherkinFeature import com.networkedassets.gherkin.runner.gherkin.GherkinScenario import gherkin.AstBuilder import gherkin.Parser import gherkin.ast.GherkinDocument import mu.KotlinLogging import org.reflections.Reflections import org.reflections.scanners.ResourcesScanner import java.util.regex.Pattern import javax.script.ScriptEngineManager import javax.script.ScriptException object GherkinLoader { val log = KotlinLogging.logger { } @JvmStatic @JvmOverloads fun loadFeatures(packagePrefix: String = "", featureFilter: String? = null, scenarioFilter: String? = null): List<GherkinFeature> { log.info { "Loading feature specifications from package: '$packagePrefix' with feature filter: '$featureFilter' and scenario filter: '$scenarioFilter'" } val reflections = Reflections(packagePrefix, ResourcesScanner()) val fileNames = reflections.getResources(Pattern.compile(".*\\.feature")) return fileNames.map({ readFeatureFromFile(it) }).filter(featureFilter, scenarioFilter) } private fun readFeatureFromFile(path: String): GherkinFeature { log.info { "Reading feature file: '$path'" } val parser = Parser<GherkinDocument>(AstBuilder()) val featureFileContent = this.javaClass.classLoader.getResource(path).readText() val gherkinDocument = parser.parse(featureFileContent) val feature = gherkinDocument.feature return GherkinConverter.convertFeature(feature) } private fun List<GherkinFeature>.filter(featureFilter: String? = null, scenarioFilter: String? = null): List<GherkinFeature> { val tagsExpression = System.getProperty("gherkinTags") if(!tagsExpression.isNullOrBlank()) log.info { "Filtering features and scenarios using expression: '$tagsExpression'" } return this.filter { filterFeature(it, featureFilter) }.map { val gherkinFeature = it.copy() gherkinFeature.scenarios.addAll(it.scenarios.filter { filterScenario(it, scenarioFilter, tagsExpression) }) gherkinFeature }.filter { it.scenarios.size > 0 } } private fun filterFeature(feature: GherkinFeature, featureFilter: String?) = (featureFilter == null || feature.name == featureFilter) private fun filterScenario(scenario: GherkinScenario, scenarioFilter: String?, tagsExpression: String?) = (scenarioFilter == null || scenario.name == scenarioFilter || scenario.outline?.name == scenarioFilter) && matchToTagsExpression(tagsExpression, scenario.tags) private fun matchToTagsExpression(expression: String?, tags: List<String>): Boolean { return if (!expression.isNullOrEmpty()) { val replacedInput = expression!!.replace(" AND ", " && ").replace(" OR ", " || ").replace(" NOT ", " !").replace(" NOT(", " !(") val withTagsInput = replacedInput.replace("@[^\\s)]+".toRegex()) { tags.contains(it.value).toString() } try { ScriptEngineManager().getEngineByName("javascript").eval(withTagsInput) as Boolean } catch (e: Exception) { throw InvalidTagsExpressionException("Tags expression '$expression' is invalid and can not be parsed!", e) } } else true } }
3
null
4
7
b57d6f90acd5183511aa988040d4f33ddcba5bdb
3,547
gherkin-runner
Apache License 2.0
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/routes/HealthRoutes.kt
navikt
487,246,438
false
{"Kotlin": 1044388, "Shell": 1318, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.vedtak.routes import io.ktor.server.response.respondText import io.ktor.server.routing.Route import io.ktor.server.routing.get /** Disse skal være helt åpne. */ fun Route.healthRoutes() { get("/isalive") { call.respondText("ALIVE") } get("/isready") { call.respondText("READY") } }
2
Kotlin
0
1
e5295a1543d080919ecbada5e796e59baa089fa7
346
tiltakspenger-vedtak
MIT License
local/local/src/main/java/com/nimbusframework/nimbuslocal/deployment/webserver/LocalHttpServer.kt
thomasjallerton
163,180,980
false
null
package com.nimbusframework.nimbuslocal.deployment.webserver import org.eclipse.jetty.server.Connector import org.eclipse.jetty.server.Server import org.eclipse.jetty.server.ServerConnector class LocalHttpServer(val port: Int, handler: WebServerHandler) { val handler = CorsPassThroughHandler(handler) var server: Server? = null fun startServer() { val localServer = Server(port) val connector: Connector = ServerConnector(localServer) localServer.addConnector(connector) server = localServer localServer.handler = handler localServer.start() localServer.join() } fun startServerWithoutJoin() { val localServer = Server(port) server = localServer localServer.handler = handler localServer.start() } fun stopServer() { server?.stop() server = null } }
3
Kotlin
5
38
789a9599d2388bde323feabc5896edc72d405198
901
nimbus-framework
MIT License
app/src/main/java/com/julianczaja/esp_monitoring_app/presentation/device/DeviceScreen.kt
julianczaja
575,978,649
false
{"Kotlin": 566150}
package com.julianczaja.esp_monitoring_app.presentation.device import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.zIndex import com.julianczaja.esp_monitoring_app.R import com.julianczaja.esp_monitoring_app.domain.model.Photo import com.julianczaja.esp_monitoring_app.presentation.deviceinfo.DeviceInfoScreen import com.julianczaja.esp_monitoring_app.presentation.devicephotos.DevicePhotosScreen import com.julianczaja.esp_monitoring_app.presentation.devicetimelapses.DeviceTimelapsesScreen import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.launch @Composable fun DeviceScreen( onSetAppBarTitle: (Int) -> Unit, snackbarHostState: SnackbarHostState, navigateToPhotoPreview: (Int) -> Unit, navigateToRemovePhotosDialog: (List<Photo>) -> Unit, navigateToSavePhotosDialog: (List<Photo>) -> Unit, navigateToTimelapseCreatorScreen: () -> Unit, ) { val coroutineScope = rememberCoroutineScope() val pages = remember { persistentListOf(DevicePage.Photos, DevicePage.Timelapse, DevicePage.Info) } val pagerState = rememberPagerState(pageCount = { pages.size }) LaunchedEffect(key1 = true) { onSetAppBarTitle(R.string.device_screen_title) } Column( modifier = Modifier.fillMaxSize() ) { TabRow( selectedTabIndex = pagerState.currentPage, containerColor = MaterialTheme.colorScheme.background, divider = { HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant) }, tabs = { pages.forEach { devicePage -> Tab( icon = { Icon( painter = painterResource(id = devicePage.drawableId), contentDescription = null ) }, text = { Text(stringResource(id = devicePage.titleId)) }, selected = pagerState.currentPage == devicePage.index, selectedContentColor = MaterialTheme.colorScheme.primary, unselectedContentColor = MaterialTheme.colorScheme.onSurface, onClick = { coroutineScope.launch { pagerState.animateScrollToPage(devicePage.index) } }, ) } }, modifier = Modifier.zIndex(1f) ) HorizontalPager( state = pagerState, modifier = Modifier.fillMaxSize() ) { page -> when (page) { DevicePage.Photos.index -> DevicePhotosScreen( snackbarHostState = snackbarHostState, navigateToPhotoPreview = navigateToPhotoPreview, navigateToRemovePhotosDialog = navigateToRemovePhotosDialog, navigateToSavePhotosDialog = navigateToSavePhotosDialog, navigateToTimelapseCreatorScreen = navigateToTimelapseCreatorScreen ) DevicePage.Timelapse.index -> DeviceTimelapsesScreen( snackbarHostState = snackbarHostState ) DevicePage.Info.index -> DeviceInfoScreen( snackbarHostState = snackbarHostState ) } } } }
0
Kotlin
0
2
4a6eabdef30af464f39447b55cccee09d8a0d9ab
4,288
esp_monitoring_app
MIT License
finiteDifference-examples/src/main/kotlin/io/improbable/swayze/examples/navierStokes/Burgers.kt
improbable-research
131,702,951
false
{"Kotlin": 70259, "Java": 11945}
package io.improbable.swayze.examples.navierStokes import gnuPlotLib.* import io.improbable.swayze.finiteDifference.* import io.improbable.keanu.kotlin.ArithmeticDouble /** * In this example we implement and solve the Burgers' equation - handy because it contains the full convective * nonlinearity of the flow equations */ class Burgers (var params: FieldParams) { var domain = Domain(params.DX, params.DY, Boundary.Dirichlet(ArithmeticDouble(1.0)), Boundary.Dirichlet(ArithmeticDouble(1.0)), Boundary.Dirichlet(ArithmeticDouble(1.0)), Boundary.Dirichlet(ArithmeticDouble(1.0))) var u = Field(params.XSIZE, params.YSIZE, domain.clone(), { i, j -> if (i > params.XSIZE/4.0 && i < params.XSIZE/2.0 && j > params.YSIZE/4.0 && j < params.YSIZE/2.0) { ArithmeticDouble(2.0) } else { ArithmeticDouble(1.0) } }) var v = Field(params.XSIZE, params.YSIZE, domain.clone(), { i, j -> u[i, j] }) var plot = PlotField() fun solve() { println("Completed initialisation, beginning solve") while (params.t < params.TLENGTH) { params.t += params.DT timestep() housekeeping() } } fun timestep() { // Compute the temporal difference val Du = (((u * bd_dx(u) + v * bd_dy(u)) * -params.c) + ((d2_dx2(u) + d2_dy2(u)) * params.nu)) * params.DT val Dv = (((u * bd_dx(v) + v * bd_dy(v)) * -params.c) + ((d2_dx2(v) + d2_dy2(v)) * params.nu)) * params.DT // Increment the prognostic variable u += Du.calculate() v += Dv.calculate() } fun housekeeping() { println("t = " + params.t) plot.linePlot(plot.scalarToGNUplotMatrix(dot(u, v))) } } fun main(args: Array<String>) { // Define the params val XSIZE = 101 val YSIZE = 101 val nu = 0.01 val c = 1.0 val sigma = 0.09 val numberTimesteps = 120 val DX = 2.0 / (XSIZE - 1.0) val DY = 2.0 / (YSIZE - 1.0) val DT = sigma * DX val TLENGTH = DT * numberTimesteps var params = FieldParams(XSIZE, YSIZE, TLENGTH, DX, DY, DT) params.nu = nu params.c = c var problem = Burgers(params) problem.solve() }
0
Kotlin
0
1
588e91097f86b3ebf7ccf11a167a188860c6dc5a
2,280
swayze
MIT License
app/src/main/java/com/anafthdev/imdbmovie/data/MovieType.kt
kafri8889
423,406,173
false
{"Kotlin": 167215}
package com.anafthdev.imdbmovie.data /** * MOST_POPULAR_MOVIE | BOX_OFFICE_MOVIE | TOP_250_MOVIE | MOVIE_INFORMATION */ enum class MovieType { MOST_POPULAR_MOVIE, BOX_OFFICE_MOVIE, TOP_250_MOVIE, MOVIE_INFORMATION }
0
Kotlin
0
9
c568f460bb75c94cf52b088c0f79c5825a94ec57
228
IMDb-Movie-App-Jetpack-Compose
Apache License 2.0
Application/app/src/main/java/com/droid/code/demos/application_receiver/ApplicationReceiverActivity.kt
devrath
535,729,462
false
{"Kotlin": 12041}
package com.droid.code.demos.application_receiver import android.content.Intent import android.content.IntentFilter import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.droid.code.databinding.ActivityDynamicRecieverBinding import com.droid.code.demos.application_receiver.reciever.ApplicationReceiverBroadcastReceiver import com.droid.code.demos.dynamic_receiver.reciever.CustomDynamicBroadcastReceiver class ApplicationReceiverActivity : AppCompatActivity() { private lateinit var binding: ActivityDynamicRecieverBinding lateinit var receiver : ApplicationReceiverBroadcastReceiver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDynamicRecieverBinding.inflate(layoutInflater) setContentView(binding.root) registerReceiver() } override fun onDestroy() { super.onDestroy() unRegisterReceiver() } private fun registerReceiver() { receiver = ApplicationReceiverBroadcastReceiver() IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also { registerReceiver(receiver,it) } } private fun unRegisterReceiver() { unregisterReceiver(receiver) } } /** // ---> Sender code to be place in another app - <SENDER> val intent = Intent("com.droid.code.ACTION_SEND") intent.putExtra("com.droid.code.EXTRA_DATA","sender send data") sendBroadcast(intent) } */
0
Kotlin
0
1
027f40d935a42b19e0ad57fbfe6002dedf6506a3
1,458
droid-component-broadcastreciever
Apache License 2.0
src/main/kotlin/pl/jwizard/api/security/SecurityProperties.kt
jwizard-bot
744,983,606
false
{"Kotlin": 45083}
/* * Copyright (c) 2024 by JWizard * Originally developed by <NAME> <https://miloszgilga.pl> */ package pl.jwizard.api.security import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.context.annotation.Configuration @Configuration @ConfigurationProperties(prefix = "jwizard.security") data class SecurityProperties( var jwtSecret: String = "", var jwtIssuer: String = "", var jwtAudience: TokenAudience = TokenAudience("proxy://standalone", "http://localhost:3000"), var life: TokenLife = TokenLife(5, 3), var standaloneClients: List<StandaloneClient> = listOf() ) data class StandaloneClient( var appId: String, var appSecret: String, ) data class TokenLife( var accessMinutes: Int, var refreshDays: Int, ) data class TokenAudience( var standaloneClient: String, var webClient: String )
0
Kotlin
0
0
4e006a26c0dfccf558426e66ab4c9f7c09aded47
854
jwizard-api
Apache License 2.0
services/csm.cloud.project.api.timeseries/src/test/kotlin/com/bosch/pt/csm/cloud/projectmanagement/application/security/PatAuthenticationManagerTest.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}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2023 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.projectmanagement.application.security import com.bosch.pt.csm.cloud.common.SmartSiteMockKTest import com.bosch.pt.csm.cloud.projectmanagement.application.security.pat.authentication.PatAuthenticationManager import com.bosch.pt.csm.cloud.projectmanagement.application.security.pat.authentication.token.PatAuthenticationToken import com.bosch.pt.csm.cloud.projectmanagement.application.security.pat.authentication.InvalidPatException import com.bosch.pt.csm.cloud.projectmanagement.user.pat.query.model.PatTypeEnum import com.bosch.pt.csm.cloud.projectmanagement.user.pat.query.model.PatTypeEnum.RMSPAT1 import io.mockk.every import io.mockk.impl.annotations.RelaxedMockK import io.mockk.mockk import java.util.UUID.randomUUID import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.junit.jupiter.api.Test import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.AuthenticationManagerResolver import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication @SmartSiteMockKTest class PatAuthenticationManagerTest { @RelaxedMockK private lateinit var resolver: AuthenticationManagerResolver<PatTypeEnum> private val cut by lazy { PatAuthenticationManager(resolver) } @Test fun `authentication is null`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { cut.authenticate(null) } .withMessage("Authentication must be of type PatAuthenticationToken") } @Test fun `authentication is no pat`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { cut.authenticate(UsernamePasswordAuthenticationToken("user", "password")) } .withMessage("Authentication must be of type PatAuthenticationToken") } @Test fun `pat type not supported`() { val pat = PatAuthenticationToken("$RMSPAT1.${randomUUID().toString().replace("-","")}.XXX") every { resolver.resolve(any()) } returns null assertThatExceptionOfType(InvalidPatException::class.java) .isThrownBy { cut.authenticate(pat) } .withMessage("Invalid pat type") } @Test fun `authentication is pat`() { val authenticationManager = mockk<AuthenticationManager>() val authentication = mockk<Authentication>() every { authenticationManager.authenticate(any()) } returns authentication // List every pat type explicitly to ensure that we really support it every { resolver.resolve(RMSPAT1) } returns authenticationManager for (patType in PatTypeEnum.values()) { val pat = PatAuthenticationToken("$patType.${randomUUID().toString().replace("-","")}.XXX") assertThat(cut.authenticate(pat)).isEqualTo(authentication) } } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
3,124
bosch-pt-refinemysite-backend
Apache License 2.0
app/src/main/java/com/pillpals/pillpals/services/BootupReceiver.kt
pill-pals
196,889,464
false
{"Gradle": 3, "JSON": 2, "Java Properties": 2, "Markdown": 3, "Shell": 1, "JavaScript": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 65, "XML": 127, "Java": 6, "HTML": 1}
package com.pillpals.pillpals.services import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.pillpals.pillpals.data.model.Schedules import com.pillpals.pillpals.helpers.DatabaseHelper import com.pillpals.pillpals.helpers.NotificationUtils import com.pillpals.pillpals.ui.dashboard.DashboardFragment import io.realm.RealmResults public class BootupReceiver: BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { NotificationUtils.createNotificationChannels(context) NotificationUtils.updateAlarms(context) NotificationUtils.createQuizNotifications(context) } }
11
Kotlin
1
1
01a4b1c786272d949c2fff466afbf1bf967d93fa
680
pillbuddies-android
MIT No Attribution
explorer/explorer-device-android/src/main/java/com/tencent/iot/explorer/device/android/http/retrofit/request/GetRequest.kt
SundoggyNew
625,740,627
true
{"Java Properties": 4, "Gradle": 18, "Shell": 6, "Markdown": 215, "Batchfile": 1, "Text": 4, "Ignore List": 15, "INI": 6, "Proguard": 12, "Java": 366, "XML": 87, "GLSL": 4, "Kotlin": 28, "CMake": 4, "JSON": 23, "C++": 1, "AIDL": 10, "YAML": 3, "Public Key": 6}
package com.tencent.iot.explorer.device.android.http.retrofit.request import retrofit2.Call import retrofit2.http.GET import retrofit2.http.QueryMap import retrofit2.http.Url /** * GET请求接口 */ interface GetRequest { @GET fun get(@Url url: String): Call<String> @GET fun get(@Url url: String, @QueryMap params: HashMap<String, Any>): @JvmSuppressWildcards Call<String> }
0
null
0
0
1363c629d0d4d19df298ddb85af8db23ffe2d07b
393
iot-device-java
MIT License
base/src/main/kotlin/com/bethibande/http/impl/http2/context/Http2RequestContext.kt
Bethibande
646,437,650
false
{"Kotlin": 91005}
package com.bethibande.http.impl.http2.context import com.bethibande.http.impl.http2.Http2Connection import com.bethibande.http.request.AbstractHttpHeader import com.bethibande.http.request.HttpRequestContext import io.netty.buffer.ByteBuf import io.netty.handler.codec.Headers import io.netty.handler.codec.http2.DefaultHttp2DataFrame import io.netty.handler.codec.http2.DefaultHttp2Headers import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame import io.netty.handler.codec.http2.Http2Headers import io.netty.handler.codec.http2.Http2StreamChannel import io.netty.util.concurrent.Promise class Http2RequestContext( connection: Http2Connection, override val channel: Http2StreamChannel, promise: Promise<Any> ): HttpRequestContext(connection, channel, promise) { internal fun channel() = this.channel override fun convertNettyHeaders(headers: Headers<*, *, *>) = AbstractHttpHeader(headers as Http2Headers) { DefaultHttp2HeadersFrame(it as Http2Headers).stream(this.channel.stream()) } override fun newHeaderInstance(): AbstractHttpHeader = AbstractHttpHeader(DefaultHttp2Headers()) { DefaultHttp2HeadersFrame(it as Http2Headers).stream(this.channel.stream()) } override fun frameData(buf: ByteBuf): Any = DefaultHttp2DataFrame(buf).stream(this.channel.stream()) override fun closeContext() { super.channel.close() } }
10
Kotlin
0
1
9c74a2df52a9fc2c756a900539ddc9c068e84855
1,401
NettyHttpFramework
Apache License 2.0
app/src/main/java/com/gaugustini/shiny/data/repository/ArmorRepositoryImpl.kt
gaugustini
695,659,583
false
{"Kotlin": 65131}
package com.gaugustini.shiny.data.repository import com.gaugustini.shiny.data.dao.ArmorDao import com.gaugustini.shiny.data.mapper.toArmor import com.gaugustini.shiny.domain.model.Armor import com.gaugustini.shiny.domain.model.Query import com.gaugustini.shiny.domain.repository.ArmorRepository import com.gaugustini.shiny.util.ArmorCategory import javax.inject.Inject import javax.inject.Singleton @Singleton class ArmorRepositoryImpl @Inject constructor(private val armorDao: ArmorDao) : ArmorRepository { override suspend fun getRelevantArmorList( category: ArmorCategory, query: Query, bestList: Boolean ): List<Armor> { var armorList = armorDao.getRelevantArmorList( query.game.value, category.value, query.hunterRank, query.villageRank, query.gender.value, query.hunterType.value, query.skills.map { it.familyID } ).map { it.toArmor() } if (bestList) { armorList = getBetterList(armorList, query.skills.map { it.familyID }) } return armorList } private fun getBetterList(armorList: List<Armor>, skills: List<Int>): List<Armor> { val list = armorList.toMutableList() for (armorA in armorList) { for (armorB in armorList) { if (bestArmor(armorA, armorB, skills) && !bestArmor(armorB, armorA, skills) && list.indexOf(armorB) >= 0 ) { list.removeAt(list.indexOf(armorB)) } } } return list } private fun bestArmor(armorA: Armor, armorB: Armor, skills: List<Int>): Boolean { if (armorA.slots > armorB.slots) { return true } skills.forEach { skill -> if ((armorA.skills[skill] ?: 0) > (armorB.skills[skill] ?: 0)) { return true } } return false } }
0
Kotlin
0
0
eba84609c319f983b31b67cb7746bed8263d6463
2,003
shiny
MIT License
app/src/main/java/com/nhnextsoft/qrcode/initializer/CrashlyticsInitializer.kt
nts6920
497,127,126
false
{"Kotlin": 227192, "Java": 3990}
package com.nhnextsoft.qrcode.initializer import android.content.Context import androidx.startup.Initializer class CrashlyticsInitializer : Initializer<Unit> { override fun create(context: Context) { // FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(!BuildConfig.DEBUG) } override fun dependencies(): List<Class<out Initializer<*>>> = emptyList() }
0
Kotlin
0
0
9c114c13cb5c581b86bfb3eb0b20af432a93d62e
390
QrCode
Apache License 2.0
src/main/kotlin/br/com/zupacademy/giovanna/pix/cadastro/GerenciadorCadastroChavePix.kt
giovanna-bernardi
383,793,280
true
{"Kotlin": 112775, "Smarty": 1902, "Dockerfile": 154}
package br.com.zupacademy.giovanna.pix.cadastro import br.com.zupacademy.giovanna.excecoes.ChavePixExistenteException import br.com.zupacademy.giovanna.externos.bcb.BcbClient import br.com.zupacademy.giovanna.externos.bcb.CreatePixKeyRequest import br.com.zupacademy.giovanna.externos.itau.ErpItauClient import br.com.zupacademy.giovanna.pix.ChavePixEntity import br.com.zupacademy.giovanna.pix.ChavePixRepository import io.micronaut.http.HttpStatus import io.micronaut.http.client.exceptions.HttpClientResponseException import io.micronaut.validation.Validated import javax.inject.Singleton import javax.validation.Valid @Validated @Singleton class GerenciadorCadastroChavePix( val chavePixRepository: ChavePixRepository, val itauClient: ErpItauClient, val bcbClient: BcbClient ) { fun tentaCadastrar(@Valid novaChavePixRequest: NovaChavePixRequest): ChavePixEntity { // Verifica se chave já existe no banco if (chavePixRepository.existsByValorChave(novaChavePixRequest.valorChave)) throw ChavePixExistenteException("A chave Pix '${novaChavePixRequest.valorChave}' já existe no banco") // Busca dados da conta no ERP do ITAU val contaResponse = itauClient.buscaContaDoClientePorTipo(novaChavePixRequest.clienteId!!, novaChavePixRequest.tipoConta!!.name) val conta = contaResponse.body()?.toModel() ?: throw IllegalStateException("Cliente não encontrado no ITAU") val chavePix = novaChavePixRequest.toModel(conta) // Salva no banco de dados chavePixRepository.save(chavePix) try { // salva no Sistema Pix do BCB val bcbResponse = bcbClient.insert(CreatePixKeyRequest.of(chavePix)) // Devolve 201 se sucesso if (bcbResponse.status != HttpStatus.CREATED) { // porque não quero usar @Transactional com chamada a sistema externo e // não acho que deva salvar na minha aplicação caso ocorra erro ao tentar salvar no sistema externo chavePixRepository.delete(chavePix) throw IllegalStateException("Erro ao registrar chave Pix no Banco Central do Brasil (BCB)") } // atualizar a chave, se ALEATORIA, com o valor vindo do BCB if (chavePix.updateKeyValue(bcbResponse.body().key)) chavePixRepository.update(chavePix) } catch (e: HttpClientResponseException) { if (e.status.equals(HttpStatus.UNPROCESSABLE_ENTITY)) { // porque não quero usar @Transactional com chamada a sistema externo e // não acho que deva salvar na minha aplicação caso ocorra erro ao tentar salvar no sistema externo chavePixRepository.delete(chavePix) throw ChavePixExistenteException("Chave pix já registrada no Banco Central do Brasil (BCB)") } } return chavePix } }
0
Kotlin
0
0
646992b7e3bf4c27fd8989ce5d9e85909511a167
2,933
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/com/purplekraken/loadguard/NotificationControllerBase.kt
flimberger
219,596,486
false
null
/* * * * SPDX-License-Identifier: Apache-2.0 * * * * Copyright 2019 <NAME> <<EMAIL>> * * * * 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.purplekraken.loadguard import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.core.app.NotificationManagerCompat abstract class NotificationControllerBase( protected val ctx: Context, channelId: String, channelName: String, channelDescr: String, protected val notificationId: Int ) { companion object { private fun createNotificationChannel( ctx: Context, id: String, name: String, descr: String ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(id, name, importance).apply { description = descr } val notificationMgr = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationMgr.createNotificationChannel(channel) } } } init { createNotificationChannel(ctx, channelId, channelName, channelDescr) } protected fun showNotification(n: Notification) { with(NotificationManagerCompat.from(ctx)) { notify(notificationId, n) } } fun hideNotification() { with(NotificationManagerCompat.from(ctx)) { cancel(notificationId) } } }
1
Kotlin
0
0
3819739f0c8b94890764efc34c2b5b27ae64ff3d
2,214
loadguard
Apache License 2.0
src/main/kotlin/com/anatawa12/decompileCrasher/core/Main.kt
anatawa12
165,655,076
false
null
@file:JvmName("MainKt") package com.anatawa12.decompileCrasher.core import java.io.File import java.util.* import kotlin.system.exitProcess /** * Created by anatawa12 on 2018/09/08. */ val scanner = Scanner(System.`in`) fun main(args: Array<String>) { var runnerType: RunnerType? = null var index = 0 var indyClass: String? = null var indyMethod: String? = null var indyField: String? = null var options = true var src: String? = null var dst: String? = null var withIndyClass: Boolean? = null var debug: Boolean? = null var isRuntimeDebug: Boolean? = null var isForce = false val exclusions = mutableSetOf<String>() val excludeTargets = mutableListOf<MethodFullSignature>() while (index in args.indices) { val arg = args[index] if (options) { if (arg[0] == '-') { when (arg) { "-f", "-force" -> { isForce = true } "-jar" -> { if (runnerType != null) errorAndExit("can't use two or more -jar or -classes") runnerType = RunnerType.Jar } "-classes" -> { if (runnerType != null) errorAndExit("can't use two or more -jar or -classes") runnerType = RunnerType.Classes } "-indyClass" -> { if (indyClass != null) errorAndExit("can't duplicate -indyClass option") index++ indyClass = args[index] } "-indyMethod" -> { if (indyMethod != null) errorAndExit("can't duplicate -indyMethod option") index++ indyMethod = args[index] } "-indyField" -> { if (indyField != null) errorAndExit("can't duplicate -indyField option") index++ indyField = args[index] } "-withoutIndy" -> { if (withIndyClass != null) errorAndExit("can't duplicate -withoutIndy option") withIndyClass = false } "-e", "-exclusion" -> { index++ exclusions.add(args[index].replace('/', '.')) } "--debug" -> { if (debug != null) errorAndExit("can't duplicate --debug option") debug = true } "--runtimeDebug" -> { if (isRuntimeDebug != null) errorAndExit("can't duplicate --runtimeDebug option") isRuntimeDebug = true } "--help" -> { printHelp() exitProcess(0) } "-exclude-target" -> { printHelp() index++ excludeTargets += MethodFullSignature.perse(args[index]) } "--" -> { options = false } else -> { System.err.println("invalid argument: $arg") exitProcess(0) } } } else { options = false src = arg } } else { if (src == null) { src = arg } else { dst = arg break } } index++ } indyClass = indyClass ?: IndyClass.default.classPath indyMethod = indyMethod ?: IndyClass.default.method indyField = indyField ?: IndyClass.default.field if (src == null) errorAndExit("there is no src and dst") if (dst == null) dst = makeDstFromSrc(src) val srcFile = File(src) val dstFile = File(dst) if (runnerType == null) { runnerType = if (srcFile.isFile) RunnerType.Jar else RunnerType.Classes } val arguments = RunnerArguments(srcFile, dstFile, IndyClass(indyClass, indyMethod, indyField), withIndyClass ?: true, debug ?: false, isRuntimeDebug ?: false, isForce, exclusions, excludeTargets) when (runnerType) { RunnerType.Jar -> JarRunner.main(arguments) RunnerType.Classes -> ClassesRunner.main(arguments) } } fun makeDstFromSrc(src: String): String { return src.substringBeforeLast('.') + "-obfuscated" + src.substringAfterLast('.', "") } fun printHelp() { System.err.println("Usage: kotlin [options] <source> [destination]") System.err.println("where possible options include:") System.err.println(" -jar input and output is jar file") System.err.println(" -classes input and output is classes directory") System.err.println(" -indyClass <class name> maker class of MethodHandle for invoke dynamic") System.err.println(" -indyMethod <method name> maker method of MethodHandle for invoke dynamic to solve method") System.err.println(" -indyField <method name> maker method of MethodHandle for invoke dynamic to solve field") System.err.println(" -withoutIndy don't make maker class of MethodHandle") System.err.println(" -debug draw debug message when solve method or field") System.err.println(" -help view this message") } fun errorAndExit(message: String): Nothing { System.err.println(message) exitProcess(1) } enum class RunnerType { Jar, Classes }
3
Kotlin
0
9
3f97414bb1b9a53f0832607033d326bfa2b0ebc4
5,826
DecompileCrasher
MIT License
sample/src/main/java/com/freeletics/coredux/PopularRepositoriesActivity.kt
freeletics
154,348,495
false
null
package com.freeletics.coredux import android.app.Activity import android.arch.lifecycle.Observer import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.freeletics.coredux.businesslogic.pagination.Action import com.freeletics.coredux.util.viewModel import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.activity_main.* import javax.inject.Inject import javax.inject.Provider class PopularRepositoriesActivity : AppCompatActivity() { @Inject lateinit var viewModelProvider: Provider<PopularRepositoriesViewModel> private val viewModel by lazy { viewModel<PopularRepositoriesViewModel>(SimpleViewModelProviderFactory(viewModelProvider)) } @Inject lateinit var viewBindingFactory: ViewBindingFactory private val viewBinding by lazy { viewBindingFactory.create<PopularRepositoriesViewBinding>( PopularRepositoriesActivity::class.java, rootView ) } private val disposables = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) applicationComponent.inject(this) viewModel.state.observe(this, Observer { viewBinding.render(it!!) }) disposables.add( Observable .merge( viewBinding.endOfRecyclerViewReached.map { Action.LoadNextPageAction }, viewBinding.retryLoadFirstPage.map { Action.LoadFirstPageAction } ) .subscribe(viewModel.dispatchAction) ) viewModel.dispatchAction(Action.LoadFirstPageAction) } override fun onDestroy() { super.onDestroy() disposables.dispose() } private val Activity.applicationComponent get() = (application as SampleApplication).applicationComponent }
0
Kotlin
6
161
47127d6b56fbab24a4d00cce93f4ae1b992f581e
1,983
CoRedux
Apache License 2.0
enro/src/androidTest/java/dev/enro/core/fragment/FragmentDestinationPresentReplaceRoot.kt
isaac-udy
256,179,010
false
null
package dev.enro.core.fragment import dev.enro.core.compose.ComposableDestination import dev.enro.core.destinations.* import org.junit.Test class FragmentDestinationPresentReplaceRoot { @Test fun givenFragmentDestination_whenExecutingReplaceRoot_andTargetIsComposableDestination_thenCorrectDestinationIsOpened() { val root = launchFragmentRoot() root.assertReplacesRootTo<ComposableDestination, ComposableDestinations.Presentable>() } @Test fun givenFragmentDestination_whenExecutingReplaceRoot_andTargetIsComposableDestination_andDestinationIsClosed_thenNoDestinationIsActive() { val root = launchFragmentRoot() root.assertReplacesRootTo<ComposableDestination, ComposableDestinations.Presentable>() .assertClosesToNothing() } @Test fun givenFragmentDestination_whenExecutingReplaceRoot_andTargetIsFragmentDestination_thenCorrectDestinationIsOpened() { val root = launchFragmentRoot() root.assertReplacesRootTo<FragmentDestinations.Fragment, FragmentDestinations.Presentable>() } @Test fun givenFragmentDestination_whenExecutingReplaceRoot_andTargetIsFragmentDestination_andDestinationIsClosed_thenNoDestinationIsActive() { val root = launchFragmentRoot() root.assertReplacesRootTo<FragmentDestinations.Fragment, FragmentDestinations.Presentable>() .assertClosesToNothing() } @Test fun givenFragmentDestination_whenExecutingReplaceRoot_andTargetIsActivityDestination_thenCorrectDestinationIsOpened() { val root = launchFragmentRoot() root.assertReplacesRootTo<ActivityDestinations.Activity, ActivityDestinations.Presentable>() } @Test fun givenFragmentDestination_whenExecutingReplaceRoot_andTargetIsActivityDestination_andDestinationIsClosed_thenNoDestinationIsActive() { val root = launchFragmentRoot() root.assertReplacesRootTo<ActivityDestinations.Activity, ActivityDestinations.Presentable>() .assertClosesToNothing() } }
13
Kotlin
13
217
84dbdbd4b6dda314629353b06db6491863431a91
2,038
Enro
Apache License 2.0
cli/src/main/java/io/github/cdsap/comparescans/cli/output/CsvWriter.kt
cdsap
818,394,985
false
{"Kotlin": 60100}
package io.github.cdsap.compare2buildscans.output import io.github.cdsap.comparescans.model.Entity import io.github.cdsap.comparescans.model.MultipleBuildScanMetric import io.github.cdsap.comparescans.model.TypeMetric import io.github.cdsap.comparescans.rules.RuleMatched import java.io.BufferedWriter import java.io.File import kotlin.time.DurationUnit import kotlin.time.toDuration class CsvWriter() { fun metricsCsvMultipleScans(metrics: List<MultipleBuildScanMetric>, buildScans: List<String>) { val prefixFile = "metrics-${buildScans.joinToString("-")}" val csv = "$prefixFile.csv" val headers = "entity,name,category,type,${buildScans.joinToString(",")}\n" val startTimestamp = System.currentTimeMillis() File(csv).bufferedWriter().use { out: BufferedWriter -> out.write(headers) metrics.forEach { metric -> val line = buildString { append("${metric.metric.entity.name},${metric.metric.name},${metric.metric.subcategory},${metric.metric.type.name}") buildScans.forEach { buildScan -> append(",${metric.values[buildScan] ?: -1L}") } append("\n") } out.write(line) } } val endTime = System.currentTimeMillis() println("File $csv created in ${endTime - startTimestamp} ms") } fun matchedRulesCsv( matchedRules: List<RuleMatched>, firstBuildScan: String, secondBuildScan: String ) { val prefixFile = "matched-rules-$firstBuildScan-$secondBuildScan" val csv = "$prefixFile-${System.currentTimeMillis()}.csv" val headers = "rule entity,rule type, name, category, diff,$firstBuildScan,$secondBuildScan,$firstBuildScan raw,$secondBuildScan raw, description\n" val startTimestamp = System.currentTimeMillis() File(csv).bufferedWriter().use { out: BufferedWriter -> out.write(headers) matchedRules.forEach { matched -> val diffFormatted = when (matched.diff) { is Double -> { if (matched.metric.metric.type == TypeMetric.Counter) { (matched.diff as Double).toInt() } else { "${matched.diff}%" } } else -> { "" } } val name = if (matched.metric.metric.entity == Entity.TaskType) { matched.metric.metric.name.substringAfterLast(".") } else { matched.metric.metric.name } val firstBuildValue = matched.metric.values[firstBuildScan]?.toLong() val secondBuildValue = matched.metric.values[secondBuildScan]?.toLong() val firstBuild = if (firstBuildValue != null) { when (matched.metric.metric.type) { TypeMetric.Counter -> firstBuildValue TypeMetric.CacheSize -> formatBytes(firstBuildValue) else -> firstBuildValue.toDuration(DurationUnit.MILLISECONDS) } } else { "N/A" } val secondBuild = if (secondBuildValue != null) { when (matched.metric.metric.type) { TypeMetric.Counter -> secondBuildValue TypeMetric.CacheSize -> formatBytes(secondBuildValue) else -> secondBuildValue.toDuration(DurationUnit.MILLISECONDS) } } else { "N/A" } var desc = "" when (matched.rule.type) { TypeMetric.Duration, TypeMetric.Fingerprinting, TypeMetric.DurationMedian, TypeMetric.DurationMean, TypeMetric.FingerprintingMedian, TypeMetric.FingerprintingMean, TypeMetric.FingerprintingP90, TypeMetric.DurationP90, TypeMetric.CacheSize -> { if (matched.rule.threshold != null) { desc = "Threshold: ${matched.rule.threshold} " } if (matched.rule.value != null) { desc += "Value > ${matched.rule.value}%" } } TypeMetric.Counter -> { desc += "Counter diff" } // not covering resource usage metrics else -> { } } val line = "${matched.rule.entity},${matched.rule.type},$name,${matched.metric.metric.subcategory},$diffFormatted,$firstBuild,$secondBuild,${firstBuildValue ?: "N/A"},${secondBuildValue ?: "N/A"},${desc}\n" out.write(line) } } val endTime = System.currentTimeMillis() println("File $csv created in ${endTime - startTimestamp} ms") } } fun formatBytes(bytes: Long): String { val bytesInAKilobyte = 1_024.0 val bytesInAMegabyte = bytesInAKilobyte * 1_024 val bytesInAGigabyte = bytesInAMegabyte * 1_024 return when { bytes >= bytesInAGigabyte -> String.format("%.2f GB", bytes / bytesInAGigabyte) bytes >= bytesInAMegabyte -> String.format("%.2f MB", bytes / bytesInAMegabyte) else -> String.format("%.2f KB", bytes / bytesInAKilobyte) } }
1
Kotlin
0
13
a32530c2741deb02abe5498802d099a5ae557b6d
5,660
CompareScans
MIT License
src/day08/Day08.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
package day08 import readInput private fun Array<Array<Int>>.checkLeft(column: Int, row: Int): Boolean { val selectedColumns = (0 until column).map { this[row][it] } return selectedColumns.any { it >= this[row][column] }.not() } private fun Array<Array<Int>>.checkRight(column: Int, row: Int): Boolean { val selectedColumns = (column + 1 until this.first().size).map { this[row][it] } return selectedColumns.any { it >= this[row][column] }.not() } private fun Array<Array<Int>>.checkDown(column: Int, row: Int): Boolean { val selectedColumns = (0 until row).map { this[it][column] } return selectedColumns.any { it >= this[row][column] }.not() } private fun Array<Array<Int>>.checkUp(column: Int, row: Int): Boolean { val selectedColumns = (row + 1 until this.first().size).map { this[it][column] } return selectedColumns.any { it >= this[row][column] }.not() } private fun Array<Array<Int>>.countLeft(column: Int, row: Int): Int { val selectedColumns = (0 until column).map { this[row][it] } var isSmaller = true return selectedColumns.reversed().takeWhile { val r = isSmaller isSmaller = (it < this[row][column]) and isSmaller r }.count() } private fun Array<Array<Int>>.countRight(column: Int, row: Int): Int { val selectedColumns = (column + 1 until this.first().size).map { this[row][it] } var isSmaller = true return selectedColumns.takeWhile { val r = isSmaller isSmaller = (it < this[row][column]) and isSmaller r }.count() } private fun Array<Array<Int>>.countUp(column: Int, row: Int): Int { val selectedColumns = (0 until row).map { this[it][column] } var isSmaller = true return selectedColumns.reversed().takeWhile { val r = isSmaller isSmaller = (it < this[row][column]) and isSmaller r }.count() } private fun Array<Array<Int>>.countDown(column: Int, row: Int): Int { val selectedColumns = (row + 1 until this.first().size).map { this[it][column] } var isSmaller = true return selectedColumns.takeWhile { val r = isSmaller isSmaller = (it < this[row][column]) and isSmaller r }.count() } fun main() { fun readMap(input: List<String>) = input.map { row -> row.chunked(1).map { it.toInt() }.toTypedArray() }.toTypedArray() fun part1(input: List<String>): Int { val map = readMap(input) return map.mapIndexed { row, r -> r.mapIndexed { column, _ -> map.checkLeft(column, row) || map.checkUp(column, row) || map.checkRight(column, row) || map.checkDown(column, row) } }.flatten().count { it } } fun part2(input: List<String>): Int { val map = readMap(input) return map.mapIndexed { row, r -> r.mapIndexed { column, _ -> map.countLeft(column, row) * map.countUp(column, row) * map.countRight(column, row) * map.countDown(column, row) } }.flatten().max() } // test if implementation meets criteria from the description, like: val testInput = readInput("day08/Day08_test") println(part2(testInput)) check(part2(testInput) == 8) val input = readInput("day08/Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
3,447
advent-of-code-kotlin-2022
Apache License 2.0
core/src/androidMain/kotlin/AndroidPeripheral.kt
JuulLabs
293,227,216
false
null
package com.juul.kable import kotlinx.coroutines.flow.StateFlow public interface AndroidPeripheral : Peripheral { public fun requestConnectionPriority(priority: Priority): Boolean /** * Requests that the current connection's MTU be changed. Suspends until the MTU changes, or failure occurs. The * negotiated MTU value is returned, which may not be [mtu] value requested if the remote peripheral negotiated an * alternate MTU. * * @throws NotReadyException if invoked without an established [connection][Peripheral.connect]. * @throws GattRequestRejectedException if Android was unable to fulfill the MTU change request. * @throws GattStatusException if MTU change request failed. */ public suspend fun requestMtu(mtu: Int): Int /** * [StateFlow] of the most recently negotiated MTU. The MTU will change upon a successful request to change the MTU * (via [requestMtu]), or if the peripheral initiates an MTU change. [StateFlow]'s `value` will be `null` until MTU * is negotiated. */ public val mtu: StateFlow<Int?> }
34
Kotlin
61
528
daf79f53677a984d2ed0b9c1c4cddadabb704094
1,102
kable
Apache License 2.0
douban_android/src/main/java/com/movies/douban/interceptors/DoubanInterceptor.kt
chenshige
152,017,908
false
null
package com.movies.douban.interceptors import com.movies.douban.Douban.Companion.API_KEY import com.movies.douban.Douban.Companion.API_KEY_PARAM import okhttp3.Interceptor import okhttp3.Response /** * @author donnieSky * @created_at 2018/9/3. * @description * @version */ class DoubanInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val url = request.url() .newBuilder() .addQueryParameter(API_KEY_PARAM, API_KEY) .build() val newRequest = request.newBuilder().url(url).build() return chain.proceed(newRequest) } }
0
Kotlin
1
0
d4d4d898b334aa29a1943728673e5549ddc58766
680
Digging
MIT License
vector/src/main/java/im/vector/app/ext/data/model/QueryFilter.kt
huy22091999
542,926,323
false
{"Kotlin": 9903484, "Java": 166049, "HTML": 24691, "Shell": 23527, "Python": 17848, "FreeMarker": 7722, "JavaScript": 1782}
package im.vector.app.ext.data.model import com.google.gson.annotations.SerializedName data class QueryFilter( @SerializedName("pageIndex") val pageIndex: Int? = 1, @SerializedName("pageSize") val pageSize: Int? = 10, @SerializedName("text") val keyword: String? = null ) { override fun toString(): String { return super.toString() } }
0
Kotlin
0
0
9255297220ad63fef367b2c8b1a1065ad5241c92
381
edoctor_OCT
Apache License 2.0
app/src/main/java/com/irancell/nwg/ios/data/remote/response/audit/Name.kt
afshin1394
755,443,887
false
{"Kotlin": 803604}
package com.irancell.nwg.ios.data.remote.response.audit import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class Name( @SerializedName("name_fa") @Expose var persian: String? = null, @SerializedName("name_en") @Expose var english: String? = null ) : Parcelable{ }
0
Kotlin
0
0
23a544780da643c4fa190bbe48d3bd9aa5673d88
412
Audit
MIT License
sample/src/main/kotlin/com/getcatch/sample/App.kt
getcatch
527,652,112
false
{"Kotlin": 314904, "HTML": 511, "Shell": 441}
package com.getcatch.sample import android.app.Application import com.getcatch.android.Catch import com.getcatch.android.CatchOptions import com.getcatch.android.network.Environment import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class App : Application() { override fun onCreate() { super.onCreate() Catch.initialize( publicKey = Constants.CATCH_PUBLIC_KEY, context = this, options = CatchOptions( environment = Environment.SANDBOX, enableLogging = true, ) ) } }
2
Kotlin
0
1
d0638436dfc233593ce13171cb279629b2b799ad
588
catch-android-sdk
MIT License
src/main/kotlin/com/github/frozencure/helix/extensions/ExtensionService.kt
frozencure
253,615,832
false
null
package com.github.frozencure.helix.extensions import com.github.frozencure.helix.auth.model.AuthCredentials import com.github.frozencure.helix.exceptions.BadRequestException import com.github.frozencure.helix.extensions.model.transaction.ExtensionTransaction import com.github.frozencure.helix.http.ResourceService import io.ktor.client.* import io.ktor.client.request.* /** * Service class that can be used to access **Extensions** endpoints: * *GET extension transactions* */ class ExtensionService : ResourceService { /** * Creates a new extension service object given some authentication credentials and a HTTP client configuration. * @param credentials The authentication credentials: can be OAuth or simple credentials with only a client ID */ constructor(credentials: AuthCredentials) : super(credentials) /** * Creates a new extension service object given an HTTP client. * @param httpClient The HTTP client. */ constructor(httpClient: HttpClient) : super(httpClient) private companion object { private const val BASE_URL = "${ResourceService.BASE_URL}/extensions" } /** * Allows the retrieval of a list of transactions that have occurred for one of your extensions across all of Twitch. * Requires an app or user access token. * For more information visit the [Twitch Developer Reference](https://dev.twitch.tv/docs/api/reference#get-extension-transactions) * @param extensionId The identifier of the extension. * @param first Maximum number of transactions to return. Maximum: 100, Default: 100. * @param transactionIds Transaction IDs to look up. Can include multiple to fetch multiple transactions in a single request. * @throws BadRequestException Exception is thrown if more than 100 transaction IDs are specified. * @return A [TransactionsResponse] that holds a collection of [ExtensionTransaction] resources (can have multiple pages). * @sample samples.getExtensionTransactions */ suspend fun getTransactions(extensionId: String, first: Int = 100, transactionIds: Collection<String>? = null) : TransactionsResponse { transactionIds?.let { if (transactionIds.size > 100) { throw BadRequestException("A maximum of 100 transaction IDs can be provided.") } } return TransactionsResponse( httpClient.get("$BASE_URL/transactions") { parameter("extension_id", extensionId) parameter("first", first) transactionIds?.let { transactionIds.forEach { parameter("id", it) } } }, httpClient ) } }
3
Kotlin
3
17
285d49ad2ddf19f8ba2d0973ca17a40168fac914
2,690
twitch-client
MIT License
app/src/main/java/com/hansung/sherpa/ui/preference/calendar/ScheduleModalSheetOption.kt
KJH0506
792,786,312
false
{"Kotlin": 827793}
package com.hansung.sherpa.ui.preference.calendar enum class ScheduleModalSheetOption { ADD, EDIT }
0
Kotlin
3
0
f29a26ff0a1622f371fa43f480e5cf9a9d741439
108
Naver_Navi_TeamProject
Apache License 2.0
content/src/main/kotlin/com/alfresco/content/models/PathElement.kt
Alfresco
243,303,915
false
null
/** * NOTE: This class is auto generated by the Swagger Gradle Codegen for the following API: Alfresco Content Services REST API * * More info on this tool is available on https://github.com/Yelp/swagger-gradle-codegen */ package com.alfresco.content.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * @property id * @property name * @property nodeType * @property aspectNames */ @JsonClass(generateAdapter = true) data class PathElement( @Json(name = "id") @field:Json(name = "id") var id: String? = null, @Json(name = "name") @field:Json(name = "name") var name: String? = null, @Json(name = "nodeType") @field:Json(name = "nodeType") var nodeType: String? = null, @Json(name = "aspectNames") @field:Json(name = "aspectNames") var aspectNames: List<String>? = null )
0
Kotlin
2
2
a96507e3e60e88b70d04be53c7f66d2d662f24fb
826
alfresco-android-kotlin-api
Apache License 2.0
feature/image-stitch/src/main/java/com/t8rin/imagetoolboxlite/feature/image_stitch/domain/StitchMode.kt
T8RIN
767,600,774
false
null
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (Malik Mukhametzyanov) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.feature.image_stitch.domain sealed class StitchMode { data object Horizontal : StitchMode() data object Vertical : StitchMode() sealed class Grid : StitchMode() { data class Horizontal(val rows: Int = 2) : Grid() data class Vertical(val columns: Int = 2) : Grid() } fun gridCellsCount(): Int { return when (this) { is Grid.Horizontal -> this.rows is Grid.Vertical -> this.columns else -> 0 } } fun isHorizontal(): Boolean = this is Horizontal || this is Grid.Horizontal }
5
null
176
8
f8fe322c2bde32544e207b49a01cfeac92c187ce
1,322
ImageToolboxLite
Apache License 2.0
app/src/test/java/com/reggar/summvvm/BaseTest.kt
REggar
104,240,136
false
null
package com.reggar.summvvm import android.support.annotation.CallSuper import org.junit.Before import org.mockito.MockitoAnnotations open class BaseTest { @CallSuper @Before open fun setUp() { MockitoAnnotations.initMocks(this) } }
0
Kotlin
0
1
0e04fc95457ba9cb2dc5c944fe803e80759a6a6f
258
SumMVVM
Apache License 2.0
lib/src/main/kotlin/com/konigsoftware/decimal/KonigDecimalScale.kt
konigsoftware
710,058,752
false
{"Kotlin": 63329}
package com.konigsoftware.decimal import java.math.BigDecimal import java.math.RoundingMode import java.math.RoundingMode.HALF_EVEN /** * Represents the scale of a KonigDecimal. Scale is defined as the total number of digits to the right of the decimal point. * For example, the number `1.123456` has a scale of `6`, or "Micros" scale. * * To add your own custom scale, create an object that extends the `KonigDecimalScale` interface. This example has a scale * of 7: * ```kotlin * object MyCustomScale : KonigDecimalScale { * override val scale = 7 * override val roundingMode = RoundingMode.HALF_EVEN * } * ``` */ interface KonigDecimalScale { /** * The integer scale that this class represents. Scale is defined as the total number of digits to the right of the decimal point. * For example, the number `1.123456` would have a scale of `6`. */ val scale: Int /** * The [RoundingMode] used when rounding a decimal to the scale defined by [scale] */ val roundingMode: RoundingMode /** * Attos scale is 10^-18 */ object Attos : KonigDecimalScale { override val roundingMode = HALF_EVEN override val scale = 18 } /** * Nanos scale is 10^-9 */ object Nanos : KonigDecimalScale { override val roundingMode = HALF_EVEN override val scale = 9 } /** * Octos scale is 10^-8 */ object Octos : KonigDecimalScale { override val roundingMode = HALF_EVEN override val scale = 8 } /** * Micros scale is 10^-6 */ object Micros : KonigDecimalScale { override val roundingMode = HALF_EVEN override val scale = 6 } /** * Quatros scale is 10^-4 */ object Quatros : KonigDecimalScale { override val roundingMode = HALF_EVEN override val scale = 4 } /** * Centis scale is 10^-2 */ object Centis : KonigDecimalScale { override val roundingMode = HALF_EVEN override val scale = 2 } } internal fun KonigDecimalScale.round(amount: BigDecimal): KonigDecimal = KonigDecimal(amount.setScale(scale, roundingMode).toPlainString())
5
Kotlin
0
2
318a895087d4235ed21d01f568fe116ba8aab389
2,197
konig-decimal
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/ShareAltSquare.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold 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.rounded.Icons public val Icons.Bold.ShareAltSquare: ImageVector get() { if (_shareAltSquare != null) { return _shareAltSquare!! } _shareAltSquare = Builder(name = "ShareAltSquare", 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) { moveToRelative(12.984f, 10.208f) lineToRelative(-2.071f, 1.104f) curveToRelative(0.052f, 0.222f, 0.087f, 0.45f, 0.087f, 0.687f) reflectiveCurveToRelative(-0.034f, 0.466f, -0.087f, 0.687f) lineToRelative(2.071f, 1.104f) curveToRelative(0.533f, -0.487f, 1.237f, -0.792f, 2.016f, -0.792f) curveToRelative(1.657f, 0.0f, 3.0f, 1.343f, 3.0f, 3.0f) reflectiveCurveToRelative(-1.343f, 3.0f, -3.0f, 3.0f) reflectiveCurveToRelative(-3.0f, -1.343f, -3.0f, -3.0f) curveToRelative(0.0f, -0.152f, 0.023f, -0.297f, 0.045f, -0.443f) lineToRelative(-2.225f, -1.187f) curveToRelative(-0.506f, 0.389f, -1.132f, 0.63f, -1.819f, 0.63f) curveToRelative(-1.657f, 0.0f, -3.0f, -1.343f, -3.0f, -3.0f) reflectiveCurveToRelative(1.343f, -3.0f, 3.0f, -3.0f) curveToRelative(0.688f, 0.0f, 1.313f, 0.24f, 1.819f, 0.63f) lineToRelative(2.225f, -1.187f) curveToRelative(-0.022f, -0.146f, -0.045f, -0.291f, -0.045f, -0.443f) curveToRelative(0.0f, -1.657f, 1.343f, -3.0f, 3.0f, -3.0f) reflectiveCurveToRelative(3.0f, 1.343f, 3.0f, 3.0f) reflectiveCurveToRelative(-1.343f, 3.0f, -3.0f, 3.0f) curveToRelative(-0.779f, 0.0f, -1.482f, -0.305f, -2.016f, -0.792f) close() moveTo(24.0f, 5.5f) verticalLineToRelative(13.0f) curveToRelative(0.0f, 3.033f, -2.468f, 5.5f, -5.5f, 5.5f) lineTo(5.5f, 24.0f) curveToRelative(-3.032f, 0.0f, -5.5f, -2.467f, -5.5f, -5.5f) lineTo(0.0f, 5.5f) curveTo(0.0f, 2.467f, 2.468f, 0.0f, 5.5f, 0.0f) horizontalLineToRelative(13.0f) curveToRelative(3.032f, 0.0f, 5.5f, 2.467f, 5.5f, 5.5f) close() moveTo(21.0f, 5.5f) curveToRelative(0.0f, -1.378f, -1.121f, -2.5f, -2.5f, -2.5f) lineTo(5.5f, 3.0f) curveToRelative(-1.379f, 0.0f, -2.5f, 1.122f, -2.5f, 2.5f) verticalLineToRelative(13.0f) curveToRelative(0.0f, 1.378f, 1.121f, 2.5f, 2.5f, 2.5f) horizontalLineToRelative(13.0f) curveToRelative(1.379f, 0.0f, 2.5f, -1.122f, 2.5f, -2.5f) lineTo(21.0f, 5.5f) close() } } .build() return _shareAltSquare!! } private var _shareAltSquare: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,765
icons
MIT License
core-database/src/main/kotlin/io/getstream/avengerschat/core/database/entity/mapper/AvengerEntityMapper.kt
GetStream
420,033,848
false
{"Kotlin": 143313}
/* * Copyright 2022 Stream.IO, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.avengerschat.core.database.entity.mapper import io.getstream.avengerschat.core.database.entity.AvengerEntity import io.getstream.avengerschat.core.model.Avenger object AvengerEntityMapper : EntityMapper<Avenger, AvengerEntity> { override fun asEntity(domain: Avenger): AvengerEntity { return AvengerEntity( id = domain.id, name = domain.name, token = domain.token, color = domain.color, quote = domain.quote, video = domain.video, livecid = domain.livecid, poster = domain.poster ) } override fun asDomain(entity: AvengerEntity): Avenger { return Avenger( id = entity.id, name = entity.name, token = entity.token, color = entity.color, quote = entity.quote, video = entity.video, livecid = entity.livecid, poster = entity.poster ) } } fun Avenger.asEntity(): AvengerEntity { return AvengerEntityMapper.asEntity(this) } fun AvengerEntity.asDomain(): Avenger { return AvengerEntityMapper.asDomain(this) }
1
Kotlin
37
364
d712bf44d89fa342d65dc4e8b81f9aa955a9f1ce
1,671
AvengersChat
Apache License 2.0
couchbase-lite/src/jvmCommonMain/kotlin/kotbase/ReplicatorStatus.jvmCommon.kt
jeffdgr8
518,984,559
false
{"Kotlin": 2289925, "Python": 294}
/* * Copyright 2022-2023 Jeff Lockhart * * 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 kotbase import kotbase.internal.DelegatedClass import com.couchbase.lite.ReplicatorStatus as CBLReplicatorStatus public actual class ReplicatorStatus internal constructor(actual: CBLReplicatorStatus) : DelegatedClass<CBLReplicatorStatus>(actual) { public actual val activityLevel: ReplicatorActivityLevel by lazy { ReplicatorActivityLevel.from(actual.activityLevel) } public actual val progress: ReplicatorProgress by lazy { ReplicatorProgress(actual.progress) } public actual val error: CouchbaseLiteException? get() = actual.error }
0
Kotlin
0
7
188723bf0c4609b649d157988de44ac140e431dd
1,194
kotbase
Apache License 2.0
app/src/main/java/dev/esnault/bunpyro/android/display/notification/INotificationService.kt
esnaultdev
242,479,002
false
null
package dev.esnault.bunpyro.android.display.notification interface INotificationService { // region Sync fun buildSyncNotification(): NotificationWithId fun hideSyncNotification() // endregion // region Reviews fun showReviewsNotification(count: Int) fun hideReviewsNotification() fun openReviewsNativeSettings() suspend fun isReviewsNotificationEnabled(): Boolean // endregion }
2
Kotlin
1
9
89b3c7dad2c37c22648c26500016d6503d27019e
429
BunPyro
Intel Open Source License
Checkbox/Checkbox.kt
KieuApps
558,096,830
false
{"Kotlin": 116129}
import androidx.compose.material3.Checkbox import androidx.compose.material3.CheckboxDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color @Composable fun Examples() { var checked by rememberSaveable { mutableStateOf(false) } // Checkbox Checkbox( checked = checked, onCheckedChange = { checked = it } ) // Checkbox Colors Checkbox( checked = checked, onCheckedChange = { checked = it }, colors = CheckboxDefaults.colors( checkedColor = Color(0xFFD88A71), uncheckedColor = Color(0xFFD88A71), checkmarkColor = MaterialTheme.colorScheme.background ) ) }
0
Kotlin
1
1
6c5880d59c8f3b0e6e80c12547922cf67668cd7a
945
Material_3_Github_Examples
MIT License
android/domain/src/main/java/co/nimblehq/smsforwarder/domain/usecase/NotifyNewIncomingSmsUseCase.kt
nimblehq
367,302,182
false
null
package co.nimblehq.smsforwarder.domain.usecase import co.nimblehq.smsforwarder.domain.data.IncomingSmsEntity import co.nimblehq.smsforwarder.domain.data.error.DataError.GetDataError import co.nimblehq.smsforwarder.domain.persistence.IncomingSmsPersistence import co.nimblehq.smsforwarder.domain.schedulers.BaseSchedulerProvider import co.nimblehq.smsforwarder.domain.usecase.base.SingleUseCase import io.reactivex.Single import javax.inject.Inject class NotifyNewIncomingSmsUseCase @Inject constructor( schedulerProvider: BaseSchedulerProvider, private val persistence: IncomingSmsPersistence ) : SingleUseCase<NotifyNewIncomingSmsUseCase.Input, Unit>( schedulerProvider.io(), schedulerProvider.main(), ::GetDataError ) { data class Input( val sender: String, val messageBody: String ) override fun create(input: Input): Single<Unit> { val entity = IncomingSmsEntity( input.sender, input.messageBody ) return Single.fromCallable { persistence.newIncomingSms(entity) } } }
15
Kotlin
0
7
39bd275698276f531b8fde4030785c2bad55c83b
1,097
sms-forwarder
MIT License
app/src/main/java/com/fluffydevs/journeybeacon/data/login/LoginRequestBody.kt
BisiPaul
639,972,897
false
null
package com.fluffydevs.journeybeacon.data.login data class LoginRequestBody( val email: String, val userId: String, val idToken: String, val displayName: String )
0
Kotlin
0
0
30709d024b55b049846ddc90fbc9af5a3d5ca0b4
179
JourneyBeaconAndroid
MIT License
app/src/main/java/com/fluffydevs/journeybeacon/data/login/LoginRequestBody.kt
BisiPaul
639,972,897
false
null
package com.fluffydevs.journeybeacon.data.login data class LoginRequestBody( val email: String, val userId: String, val idToken: String, val displayName: String )
0
Kotlin
0
0
30709d024b55b049846ddc90fbc9af5a3d5ca0b4
179
JourneyBeaconAndroid
MIT License
src/test/kotlin/com/tfowl/cosmobuzz/fakes/FakeCosmoSocketFactory.kt
T-Fowl
403,921,630
false
{"Kotlin": 18884}
package com.tfowl.cosmobuzz.fakes import com.tfowl.cosmobuzz.CosmoSocket import com.tfowl.cosmobuzz.CosmoSocketFactory class FakeCosmoSocketFactory(val socket: FakeCosmoSocket) : CosmoSocketFactory { override suspend fun create(): CosmoSocket { return socket } }
9
Kotlin
0
0
5134a9a101788eb0a94624dfc02e83600abcfdc6
280
cosmobuzz-client-kotlin
MIT License
kotest-core/src/jsMain/kotlin/io/kotest/core/test/timeout.kt
nagellack5C
235,292,077
true
{"Kotlin": 1862796, "HTML": 423, "Java": 153, "Shell": 125}
package io.kotest.core.test import io.kotest.core.config.Project import kotlin.time.Duration import kotlin.time.ExperimentalTime
0
null
0
0
6c3b7967ec7c9d7604d237a8cf37fb023ab46f09
130
kotlintest
Apache License 2.0
app/src/main/java/com/meksconway/covid/viewmodel/Input.kt
meksconways
256,483,114
false
null
package com.meksconway.covid.viewmodel interface Input
0
Kotlin
1
2
8feaacf6dc251b6359c19113e2dd0e2f05575d8d
55
Covid-19-Android
MIT License
android/app/src/main/kotlin/com/radhe/flutter_git_hook/MainActivity.kt
RadheshyamSingh
297,699,609
false
{"Dart": 2623, "Shell": 784, "Swift": 404, "Kotlin": 131, "Objective-C": 38}
package com.radhe.flutter_git_hook import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
d253e259fb33d6baae3a115519d268fb9ea893e5
131
gitHookFlutter
Apache License 2.0
src/main/kotlin/org/cdb/homunculus/controller/StorageController.kt
CodeDrillBrigade
714,769,385
false
{"Kotlin": 122651, "Dockerfile": 336}
package org.cdb.homunculus.controller import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import kotlinx.coroutines.flow.toList import org.cdb.homunculus.logic.StorageLogic import org.cdb.homunculus.models.StorageRoom import org.cdb.homunculus.models.embed.storage.Cabinet import org.cdb.homunculus.models.embed.storage.Shelf import org.cdb.homunculus.models.identifiers.ShortId import org.cdb.homunculus.models.security.Permissions import org.cdb.homunculus.requests.authenticatedDelete import org.cdb.homunculus.requests.authenticatedGet import org.cdb.homunculus.requests.authenticatedPost import org.cdb.homunculus.requests.authenticatedPut import org.koin.ktor.ext.inject fun Routing.storageController() = route("/storage") { val storageLogic by inject<StorageLogic>() authenticatedGet("") { call.respond(storageLogic.getAll().toList()) } authenticatedPost("", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageToCreate = call.receive<StorageRoom>() call.respond(storageLogic.create(storageToCreate)) } authenticatedPut("", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageToUpdate = call.receive<StorageRoom>() call.respond(storageLogic.update(storageToUpdate)) } authenticatedDelete("/{storageRoomId}", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageRoomId = requireNotNull(call.parameters["storageRoomId"]) { "Storage Room Id must not be null" } call.respond(storageLogic.delete(ShortId(storageRoomId))) } authenticatedPost("/{storageRoomId}/cabinet", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageRoomId = requireNotNull(call.parameters["storageRoomId"]) { "Storage Room Id must not be null" } val cabinetToCreate = call.receive<Cabinet>() call.respond(storageLogic.addCabinet(ShortId(storageRoomId), cabinetToCreate)) } authenticatedPut("/{storageRoomId}/cabinet", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageRoomId = requireNotNull(call.parameters["storageRoomId"]) { "Storage Room Id must not be null" } val cabinetToUpdate = call.receive<Cabinet>() call.respond(storageLogic.update(ShortId(storageRoomId), cabinetToUpdate)) } authenticatedDelete("/{storageRoomId}/cabinet/{cabinetId}", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageRoomId = requireNotNull(call.parameters["storageRoomId"]) { "Storage Room Id must not be null" } val cabinetId = requireNotNull(call.parameters["cabinetId"]) { "Cabinet Id must not be null" } call.respond(storageLogic.delete(ShortId(storageRoomId), ShortId(cabinetId))) } authenticatedPost("/{storageRoomId}/cabinet/{cabinetId}/shelf", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageRoomId = requireNotNull(call.parameters["storageRoomId"]) { "Storage Room Id must not be null" } val cabinetId = requireNotNull(call.parameters["cabinetId"]) { "Cabinet Id must not be null" } val shelfToCreate = call.receive<Shelf>() call.respond(storageLogic.addShelf(ShortId(storageRoomId), ShortId(cabinetId), shelfToCreate)) } authenticatedPut("/{storageRoomId}/cabinet/{cabinetId}/shelf", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageRoomId = requireNotNull(call.parameters["storageRoomId"]) { "Storage Room Id must not be null" } val cabinetId = requireNotNull(call.parameters["cabinetId"]) { "Cabinet Id must not be null" } val shelfToUpdate = call.receive<Shelf>() call.respond(storageLogic.update(ShortId(storageRoomId), ShortId(cabinetId), shelfToUpdate)) } authenticatedDelete("/{storageRoomId}/cabinet/{cabinetId}/shelf/{shelfId}", permissions = setOf(Permissions.MANAGE_STORAGE)) { val storageRoomId = requireNotNull(call.parameters["storageRoomId"]) { "Storage Room Id must not be null" } val cabinetId = requireNotNull(call.parameters["cabinetId"]) { "Cabinet Id must not be null" } val shelfId = requireNotNull(call.parameters["shelfId"]) { "ShelfId must not be null" } call.respond(storageLogic.delete(ShortId(storageRoomId), ShortId(cabinetId), ShortId(shelfId))) } }
0
Kotlin
0
0
64aa91cd4513b17ace0e3fe833a11f9a715e4712
4,157
Homunculus
MIT License
aws-lambdas/base/src/main/kotlin/com/bkahlert/aws/lambda/APIGatewayProxyResponseEvents.kt
bkahlert
439,967,726
false
{"Kotlin": 1770181, "CSS": 20318, "JavaScript": 11584, "Shell": 6384, "HTML": 2857, "SCSS": 588}
package com.bkahlert.aws.lambda import com.amazonaws.services.lambda.runtime.Context import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonArrayBuilder import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.add import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put public fun errorResponse( errorMessage: String?, context: Context? = null, ): APIGatewayProxyResponseEvent = errorResponse(500, errorMessage, context) public fun errorResponse( statusCode: Int, errorMessage: String?, context: Context? = null, ): APIGatewayProxyResponseEvent = errorResponse(RuntimeException(errorMessage), context, statusCode) public fun errorResponse( exception: Throwable, context: Context? = null, status: Int = when (exception) { is IllegalArgumentException -> 400 else -> 500 }, ): APIGatewayProxyResponseEvent = jsonObjectResponse(statusCode = status) { put("status", status) exception.message?.also { put("errorMessage", it) } exception::class.simpleName?.also { put("errorType", it) } exception.stackTrace?.also { it -> put("stackTrace", buildJsonArray { it.forEach { add(it.toString()) } }) } context?.awsRequestId?.also { put("requestId", it) } } /** * Returns a [APIGatewayProxyResponseEvent] * with the body being the string-encoded [JsonArray] built using the specified [block], the specified [statusCode], and [headers]. */ public inline fun jsonArrayResponse( statusCode: Int = 200, vararg headers: Pair<String, String>, block: JsonArrayBuilder.() -> Unit, ): APIGatewayProxyResponseEvent = jsonResponse(buildJsonArray(block), statusCode, *headers) /** * Returns a [APIGatewayProxyResponseEvent] * with the body being the string-encoded [JsonObject] built using the specified [block], the specified [statusCode], and [headers]. */ public inline fun jsonObjectResponse( statusCode: Int = 200, vararg headers: Pair<String, String>, block: JsonObjectBuilder.() -> Unit, ): APIGatewayProxyResponseEvent = jsonResponse(buildJsonObject(block), statusCode, *headers) /** * Returns a [APIGatewayProxyResponseEvent] * with the body being the string-encoded [value], the specified [statusCode], and [headers]. */ public fun jsonResponse( value: Number?, statusCode: Int = 200, vararg headers: Pair<String, String>, ): APIGatewayProxyResponseEvent = jsonResponse(JsonPrimitive(value), statusCode, *headers) /** * Returns a [APIGatewayProxyResponseEvent] * with the body being the string-encoded [value], the specified [statusCode], and [headers]. */ public fun jsonResponse( value: String?, statusCode: Int = 200, vararg headers: Pair<String, String>, ): APIGatewayProxyResponseEvent = jsonResponse(JsonPrimitive(value), statusCode, *headers) /** * Returns a [APIGatewayProxyResponseEvent] * with the body being the string-encoded [value], the specified [statusCode], and [headers]. */ public fun jsonResponse( value: Boolean?, statusCode: Int = 200, vararg headers: Pair<String, String>, ): APIGatewayProxyResponseEvent = jsonResponse(JsonPrimitive(value), statusCode, *headers) /** * Returns a [APIGatewayProxyResponseEvent] * with the specified [statusCode], and [headers]. */ public fun jsonResponse( @Suppress("UNUSED_PARAMETER") value: Nothing?, statusCode: Int = 200, vararg headers: Pair<String, String>, ): APIGatewayProxyResponseEvent = jsonResponse(JsonNull, statusCode, *headers) /** * Returns a [APIGatewayProxyResponseEvent] * with the specified [statusCode], and [headers]. */ public fun jsonResponse( statusCode: Int = 200, vararg headers: Pair<String, String>, ): APIGatewayProxyResponseEvent = jsonResponse(JsonNull, statusCode, *headers) /** * Returns a [APIGatewayProxyResponseEvent] * with the body being the string-encoded [value], the specified [statusCode], and [headers]. */ public fun jsonResponse( value: JsonElement, statusCode: Int = 200, vararg headers: Pair<String, String>, ): APIGatewayProxyResponseEvent = response(Json.encodeToString(value), statusCode, "Content-Type" to "application/json", *headers) /** * Returns a [APIGatewayProxyResponseEvent] * with the specified [body], the specified [statusCode], and [headers]. */ public fun response( statusCode: Int = 200, vararg headers: Pair<String, String>, ): APIGatewayProxyResponseEvent = APIGatewayProxyResponseEvent() .withStatusCode(statusCode) .withHeaders(headers.toMap()) /** * Returns a [APIGatewayProxyResponseEvent] * with the specified [body], the specified [statusCode], and [headers]. */ public fun response( body: String?, statusCode: Int = 200, vararg headers: Pair<String, String>, ): APIGatewayProxyResponseEvent = APIGatewayProxyResponseEvent() .withStatusCode(statusCode) .withHeaders(headers.toMap()) .withBody(body)
0
Kotlin
0
0
0bb812cafe5256fe793cdfbfd8ec00dde0b4c084
5,412
hello
MIT License
testcaller/src/main/kotlin/pers/shawxingkwok/test/server/ManualApiImpl.kt
ShawxingKwok
702,423,277
false
{"Kotlin": 122297}
package pers.shawxingkwok.test.server import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* object ManualApiImpl : Phone.ManualApi { override suspend fun directGet(): CommonConnector<Long> = { 1 } override suspend fun exchange(id: String): CommonConnector<List<String>> = { val receivedBytes = call.receive<ByteArray>() call.respond(receivedBytes) listOf(id) } override suspend fun getIdLength(id: String?): CommonConnector<Int?> = { id?.length } override suspend fun getUnit(id: String): CommonConnector<Unit> = { } }
0
Kotlin
0
0
402c4c6c351bb743736a6fb50724a177be6dc95e
645
Phone
Apache License 2.0
import-export/domain/src/main/kotlin/studio/lunabee/onesafe/importexport/model/SafeAutoBackupEnabled.kt
LunabeeStudio
624,544,471
false
{"Kotlin": 3214461, "Java": 11987, "Python": 3979}
/* * Copyright (c) 2024 Lunabee Studio * * 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. * * Created by Lunabee Studio / Date - 6/24/2024 - for the oneSafe6 SDK. * Last modified 6/24/24, 3:07 PM */ package studio.lunabee.onesafe.importexport.model import studio.lunabee.onesafe.domain.model.safe.SafeId data class SafeAutoBackupEnabled( val safeId: SafeId, val cloudAutoBackupEnabled: Boolean, )
1
Kotlin
1
2
4d6199939c91e0d6d31aa5328549a3ac442d046a
918
oneSafe6_SDK_Android
Apache License 2.0
application/src/main/java/org/zhiwei/app/AppActivity.kt
iOrchid
224,837,266
false
{"Kotlin": 30034}
package org.zhiwei.app import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import org.zhiwei.application.R /** * 作者: 志威 zhiwei.org * 主页: Github: https://github.com/zhiwei1990 * 日期: 2019年12月02日 9:43 * 签名: 天行健,君子以自强不息;地势坤,君子以厚德载物。 * _ _ _ _ ____ _ _ _ * / \ _ __ __| |_ __ ___ (_) __| | / ___|| |_ _ _ __| (_) ___ * / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \ * / ___ \| | | | (_| | | | (_) | | (_| | ___) | |_| |_| | (_| | | (_) | * /_/ \_\_| |_|\__,_|_| \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/ -- 志威 zhiwei.org * * You never know what you can do until you try ! * ---------------------------------------------------------------- * Android系统的 application相关api的演示界面 * */ class AppActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_application) } }
0
Kotlin
4
3
a81138e57b31551251a6df4a90861b63d1e00512
1,012
ApiDemos
Apache License 2.0
plugin/buildSrc/src/main/kotlin/embeddable.kt
facebookresearch
498,810,868
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ @file:Suppress("unused") // usages in build scripts are not tracked properly import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar // The below code was taken from the Bridge plugin: https://github.com/facebookincubator/differentiable/pull/519/files val kotlinEmbeddableRootPackage = "org.jetbrains.kotlin" val packagesToRelocate = listOf("com.intellij", "com.google", "com.sampullara", "org.apache", "org.jdom", "org.picocontainer", "org.jline", "kotlinx.coroutines", "net.jpountz", "one.util.streamex") /* * Relocation logic taken from <KotlinRoot>/buildSrc/src/main/kotlin/embeddable.kt * Allows us to go from kotlin-compiler -> kotlin-compiler-embeddable */ fun ShadowJar.relocateCompilerPackages() { relocate("com.google.protobuf", "org.jetbrains.kotlin.protobuf") relocate("com.intellij.openapi.util", "org.jetbrains.kotlin.com.intellij.openapi.util") packagesToRelocate.forEach { relocate(it, "$kotlinEmbeddableRootPackage.$it") { exclude("com.google.auto.service.AutoService") } } relocate("org.fusesource", "$kotlinEmbeddableRootPackage.org.fusesource") { exclude("org.fusesource.jansi.internal.CLibrary") } }
15
Kotlin
2
8
b80b7484b8f1033fbef3e76a401b7a0237a35e05
1,468
shapekt
MIT License
anthropic-sdk-kotlin-demo-jvm/src/main/kotlin/Demo02Streaming.kt
xemantic
865,480,026
false
{"Kotlin": 8370, "Java": 295}
package com.xemantic.anthropic.demo import com.xemantic.anthropic.Anthropic import com.xemantic.anthropic.event.ContentBlockDeltaEvent import com.xemantic.anthropic.event.Delta import com.xemantic.anthropic.message.Message import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking fun main() { val client = Anthropic() runBlocking { client.messages.stream { +Message { +"Write me a poem." } } .filterIsInstance<ContentBlockDeltaEvent>() .map { (it.delta as Delta.TextDelta).text } .collect { delta -> print(delta) } } }
0
Kotlin
0
0
0f369b0b0a89017f44d8418e6e4f6bb495ddc948
623
anthropic-sdk-kotlin-demo
MIT License
app/src/main/java/se/kruskakli/nso/data/packages/NsoPackages.kt
etnt
751,577,496
false
{"Kotlin": 182621}
package se.kruskakli.nso.data.packages import com.squareup.moshi.Json data class NsoPackages( @Json(name = "tailf-ncs:packages") val tailfNcsPackages: TailfNcsPackages )
0
Kotlin
0
0
b4e8a04ac1ce5feeb375269c7062714ac6421a7c
175
Nso-Mobile
Apache License 2.0
shared/src/commonMain/kotlin/ru/akella/cryptocoin/data/api/Consts.kt
akella266
651,284,444
false
null
package ru.akella.cryptocoin.data.api val BASE_URL = "https://pro-api.coinmarketcap.com" data class Sort( val direction: SortDirection, val field: String, ) enum class SortDirection { ASC, DESC }
0
Kotlin
0
0
b89141c29e6bb805267e7ab40383be1acbbc2c8e
210
CryptoCoin
Apache License 2.0
core/src/main/java/com/oscarg798/amiibowiki/core/usecases/UpdateAmiiboTypeUseCase.kt
oscarg798
275,942,605
false
null
/* * Copyright 2020 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * */ package com.oscarg798.amiibowiki.core.usecases import com.oscarg798.amiibowiki.core.failures.AmiiboTypeFailure import com.oscarg798.amiibowiki.core.repositories.AmiiboTypeRepository import javax.inject.Inject class UpdateAmiiboTypeUseCase @Inject constructor( private val amiiboTypeRepository: AmiiboTypeRepository ) { suspend fun execute() { runCatching { amiiboTypeRepository.updateTypes() }.getOrElse { if (it !is AmiiboTypeFailure || !amiiboTypeRepository.hasTypes()) { throw it } } } }
0
Kotlin
3
10
e3f7f3f97af3ffb4998a3e8d4cb2144c82a5221c
1,660
AmiiboWiki
MIT License
src/main/kotlin/me/sudodios/codewalker/ui/components/CustomModifiers.kt
SudoDios
758,517,419
false
{"Rust": 163883, "Kotlin": 133069}
package me.sudodios.codewalker.ui.components import androidx.compose.foundation.ScrollState import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.runtime.toMutableStateList import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.* import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import org.jetbrains.skia.FilterTileMode import org.jetbrains.skia.ImageFilter import org.jetbrains.skia.RuntimeEffect import org.jetbrains.skia.RuntimeShaderBuilder import kotlin.math.min @Composable fun <T: Any> rememberMutableStateListOf(vararg elements: T): SnapshotStateList<T> { return rememberSaveable(saver = listSaver(save = { stateList -> if (stateList.isNotEmpty()) { val first = stateList.first() if (!canBeSaved(first)) { throw IllegalStateException("${first::class} cannot be saved. By default only types which can be stored in the Bundle class can be saved.") } } stateList.toList() }, restore = { it.toMutableStateList() }) ) { elements.toList().toMutableStateList() } } @Composable fun Modifier.clickable() = this.then( clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} ) fun Modifier.fadingEdges( scrollState: ScrollState, topEdgeHeight: Dp = 48.dp, bottomEdgeHeight: Dp = 48.dp ): Modifier = this.then( Modifier.graphicsLayer { alpha = 0.99F }.drawWithContent { drawContent() val topColors = listOf(Color.Transparent, Color.Black) val topStartY = scrollState.value.toFloat() val topGradientHeight = min(topEdgeHeight.toPx(), topStartY) drawRect(brush = Brush.verticalGradient(colors = topColors, startY = topStartY, endY = topStartY + topGradientHeight), blendMode = BlendMode.DstIn) val bottomColors = listOf(Color.Black, Color.Transparent) val bottomEndY = size.height - scrollState.maxValue + scrollState.value val bottomGradientHeight = min(bottomEdgeHeight.toPx(), scrollState.maxValue.toFloat() - scrollState.value) if (bottomGradientHeight != 0f) drawRect( brush = Brush.verticalGradient(colors = bottomColors, startY = bottomEndY - bottomGradientHeight, endY = bottomEndY), blendMode = BlendMode.DstIn ) } ) @Composable fun Modifier.areaBlur( leftTop : Offset = Offset(0f,0f), size : Offset, radius : Float = 0f ) : Modifier { val areaBlurSksl = """ uniform shader content; uniform shader blur; uniform vec4 rectangle; uniform float radius; float roundedRectangleSDF(vec2 position, vec2 box, float radius) { vec2 q = abs(position) - box + vec2(radius); return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - radius; } vec4 main(vec2 coord) { vec2 shiftRect = (rectangle.zw - rectangle.xy) / 2.0; vec2 shiftCoord = coord - rectangle.xy; float distanceToClosestEdge = roundedRectangleSDF( shiftCoord - shiftRect, shiftRect, radius); vec4 c = content.eval(coord); if (distanceToClosestEdge > 0.0) { if (distanceToClosestEdge < 2.0) { float darkenFactor = (2.0 - distanceToClosestEdge) / 2.0; darkenFactor = pow(darkenFactor, 1.6); return c * (0.9 + (1.0 - darkenFactor) / 10.0); } return c; } vec4 b = blur.eval(coord); return b; } """ val compositeRuntimeEffect = RuntimeEffect.makeForShader(areaBlurSksl) val compositeShaderBuilder = RuntimeShaderBuilder(compositeRuntimeEffect) val density = LocalDensity.current.density compositeShaderBuilder.uniform("rectangle", leftTop.x * density, leftTop.y * density, size.x * density, (size.y) * density) compositeShaderBuilder.uniform("radius", radius * density) return graphicsLayer { this.renderEffect = ImageFilter.makeRuntimeShader( runtimeShaderBuilder = compositeShaderBuilder, shaderNames = arrayOf("content", "blur"), inputs = arrayOf(null, ImageFilter.makeBlur(sigmaX = 13.0f, sigmaY = 13.0f, mode = FilterTileMode.CLAMP)) ).asComposeRenderEffect() } }
0
Rust
0
0
c844d54b44c16b2fae7ad67bce82182cd815fe43
5,250
CodeWalker
Apache License 2.0
app/src/main/java/com/creepersan/switchhost/bean/WelcomeItem.kt
CreeperSan
216,014,973
false
null
package com.creepersan.switchhost.bean import android.graphics.Color import androidx.annotation.ColorInt import com.creepersan.switchhost.manager.SizeManager data class WelcomeItem( var img : Int = 0, var hintString : String = "", var hintStringSizeSP : Float = 14f, @ColorInt var hintStringColor : Int = Color.BLACK, var buttonText : String = "", var buttonClickAction : (()->Unit)? = null )
0
Kotlin
0
4
103fee3880a9544d46c460fa0312b9cefd32e349
419
SwitchHost-Android
Apache License 2.0
app/src/main/java/com/routinely/routinely/task/addTaskModule.kt
RoutinelyOrganization
609,263,361
false
{"Kotlin": 211801}
package com.routinely.routinely.task import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val addTaskModule = module { viewModel<AddTaskViewModel> { AddTaskViewModel(get(), get()) } }
18
Kotlin
1
3
a68ef34e40be46351fb2f66cfa793a376b6347ba
224
routinely-mobile
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/lambda/CfnAliasAliasRoutingConfigurationPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.lambda import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.Any import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.lambda.CfnAlias /** * The * [traffic-shifting](https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) * configuration of a Lambda function alias. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.lambda.*; * AliasRoutingConfigurationProperty aliasRoutingConfigurationProperty = * AliasRoutingConfigurationProperty.builder() * .additionalVersionWeights(List.of(VersionWeightProperty.builder() * .functionVersion("functionVersion") * .functionWeight(123) * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-alias-aliasroutingconfiguration.html) */ @CdkDslMarker public class CfnAliasAliasRoutingConfigurationPropertyDsl { private val cdkBuilder: CfnAlias.AliasRoutingConfigurationProperty.Builder = CfnAlias.AliasRoutingConfigurationProperty.builder() private val _additionalVersionWeights: MutableList<Any> = mutableListOf() /** * @param additionalVersionWeights The second version, and the percentage of traffic that's * routed to it. */ public fun additionalVersionWeights(vararg additionalVersionWeights: Any) { _additionalVersionWeights.addAll(listOf(*additionalVersionWeights)) } /** * @param additionalVersionWeights The second version, and the percentage of traffic that's * routed to it. */ public fun additionalVersionWeights(additionalVersionWeights: Collection<Any>) { _additionalVersionWeights.addAll(additionalVersionWeights) } /** * @param additionalVersionWeights The second version, and the percentage of traffic that's * routed to it. */ public fun additionalVersionWeights(additionalVersionWeights: IResolvable) { cdkBuilder.additionalVersionWeights(additionalVersionWeights) } public fun build(): CfnAlias.AliasRoutingConfigurationProperty { if (_additionalVersionWeights.isNotEmpty()) cdkBuilder.additionalVersionWeights(_additionalVersionWeights) return cdkBuilder.build() } }
4
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
2,733
awscdk-dsl-kotlin
Apache License 2.0
app/src/test/java/cz/fontan/gomoku_gui/game/GameTest.kt
Hexik
369,313,533
false
{"C++": 723092, "Kotlin": 72860, "CMake": 6436, "Java": 598}
package cz.fontan.gomoku_gui.game import org.junit.Test class GameTest { @Test fun empty() { val game = Game(BOARD_SIZE_MAX) assert(game.moveCount() == 0) assert(game.playerToMove == EnumMove.Black) assert(game.canMakeMove(Move(0, 0))) assert(game.canMakeMove(Move(BOARD_SIZE_MAX - 1, BOARD_SIZE_MAX - 1))) } @Test fun makeMove() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)) assert(game[0] == Move(1, 1, EnumMove.Black)) assert(game.moveCount() == 1) assert(game.playerToMove == EnumMove.White) assert(!game.canMakeMove(Move(1, 1))) } @Test fun undoMove() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)).undoMove() assert(game.moveCount() == 0) assert(game.playerToMove == EnumMove.Black) assert(game.canMakeMove(Move(1, 1))) } @Test fun newGame() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)).newGame() assert(game.moveCount() == 0) assert(game.playerToMove == EnumMove.Black) assert(game.canMakeMove(Move(0, 0))) assert(game.canMakeMove(Move(1, 1))) assert(game.canMakeMove(Move(BOARD_SIZE_MAX - 1, BOARD_SIZE_MAX - 1))) } @Test fun reset() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)).reset() assert(game.moveCount() == 0) assert(game.playerToMove == EnumMove.Black) assert(game.canMakeMove(Move(0, 0))) assert(game.canMakeMove(Move(1, 1))) assert(game.canMakeMove(Move(BOARD_SIZE_MAX - 1, BOARD_SIZE_MAX - 1))) } @Test fun redoMove() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)).undoMove().redoMove() assert(game.moveCount() == 1) assert(game.playerToMove == EnumMove.White) assert(!game.canMakeMove(Move(1, 1))) game.makeMove(Move(2, 2, EnumMove.White)).undoMove().redoMove() assert(game.moveCount() == 2) assert(game.playerToMove == EnumMove.Black) assert(!game.canMakeMove(Move(1, 1))) assert(!game.canMakeMove(Move(2, 2))) game.undoMove().undoMove().redoMove().redoMove() assert(game.moveCount() == 2) assert(game.playerToMove == EnumMove.Black) assert(!game.canMakeMove(Move(1, 1))) assert(!game.canMakeMove(Move(2, 2))) } @Test(expected = IllegalArgumentException::class) fun undo2Move() { Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)).undoMove().undoMove() } @Test(expected = IllegalArgumentException::class) fun redo2Move() { Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)).undoMove().redoMove().redoMove() } @Test fun to_board_empty() { assert(Game(BOARD_SIZE_MAX).toBoard(false) == "yxboard\ndone") } @Test fun to_board_B() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)) assert(game.toBoard(true) == "board\n1,1,2\ndone") } @Test fun to_board_BW() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)) .makeMove(Move(2, 2, EnumMove.White)) assert(game.toBoard(true) == "board\n1,1,1\n2,2,2\ndone") } @Test fun to_board_BWB() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)) .makeMove(Move(2, 2, EnumMove.White)).makeMove(Move(3, 3, EnumMove.Black)) assert(game.toBoard(false) == "yxboard\n1,1,2\n2,2,1\n3,3,2\ndone") } @Test fun to_board_BWBW() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)) .makeMove(Move(2, 2, EnumMove.White)).makeMove(Move(3, 3, EnumMove.Black)) .makeMove(Move(4, 4, EnumMove.White)) assert(game.toBoard(true) == "board\n1,1,1\n2,2,2\n3,3,1\n4,4,2\ndone") } @Test fun to_stream_empty() { assert(Game(BOARD_SIZE_MAX).toStream() == "$BOARD_SIZE_MAX\n$BOARD_SIZE_MAX\n1\n") } @Test fun to_stream_moves() { val game = Game(BOARD_SIZE_MAX).makeMove(Move(1, 1, EnumMove.Black)) .makeMove(Move(2, 2, EnumMove.White)) .makeMove(Move(3, 3, EnumMove.Black)).makeMove(Move(4, 4, EnumMove.White)) assert( game.toStream() == """ |$BOARD_SIZE_MAX |$BOARD_SIZE_MAX |1 |1 1 |2 2 |3 3 |4 4 |""".trimMargin() ) } @Test fun from_stream_moves() { val s = """ |$BOARD_SIZE_MAX |$BOARD_SIZE_MAX |1 |1 1 |2 2 |3 3 |4 4 |""".trimMargin() assert( Game(BOARD_SIZE_MAX).fromStream(s) .toBoard(true) == "board\n1,1,1\n2,2,2\n3,3,1\n4,4,2\ndone" ) } @Test(expected = IllegalArgumentException::class) fun from_stream_empty() { Game(BOARD_SIZE_MAX).fromStream("") } @Test(expected = IllegalArgumentException::class) fun from_stream_bad_move() { Game(BOARD_SIZE_MAX) .fromStream( """ |$BOARD_SIZE_MAX |$BOARD_SIZE_MAX |1 |1 |""".trimMargin() ) } @Test(expected = IllegalArgumentException::class) fun from_stream_bad_number() { Game(BOARD_SIZE_MAX) .fromStream( """ |$BOARD_SIZE_MAX |$BOARD_SIZE_MAX |1 |1 w |""".trimMargin() ) } @Test(expected = IllegalArgumentException::class) fun from_stream_bad_dimension() { Game(BOARD_SIZE_MAX) .fromStream( """ |$BOARD_SIZE_MAX |$BOARD_SIZE_MAX - 1 |1 |""".trimMargin() ) } }
0
C++
1
2
36940e0d5390cc8ca91370535993ee278ec6a288
6,016
Gomoku_GUI
MIT License
app/src/main/java/com/ei1039_1048/notesapp/ui/note/NoteItem.kt
matey97
658,761,056
false
{"Kotlin": 45629}
package com.ei1039_1048.notesapp.ui.note import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api 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.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.ei1039_1048.notesapp.R import com.ei1039_1048.notesapp.data.Note import com.ei1039_1048.notesapp.ui.theme.NotesAppTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun NoteItemCard( modifier: Modifier = Modifier, note: Note, onEditTap: (Note) -> Unit, onDeleteTap: (Note) -> Unit ) { var isExpanded by remember { mutableStateOf(false) } ElevatedCard( onClick = { isExpanded = !isExpanded }, modifier = modifier, colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.secondaryContainer ) ) { Column( modifier = modifier .padding(4.dp) .animateContentSize( animationSpec = spring( dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow ) ) ) { Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = note.title, modifier = Modifier.weight(1f), style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.SemiBold ) Text( text = note.date.toString(), color = MaterialTheme.colorScheme.onSecondaryContainer, fontWeight = FontWeight.Light ) } Text( text = note.description.ifEmpty { stringResource(R.string.null_description) }, maxLines = if (isExpanded) Int.MAX_VALUE else 2, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyLarge, fontStyle = if (note.description.isEmpty()) FontStyle.Italic else FontStyle.Normal ) if (isExpanded) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End ) { IconButton( onClick = { onEditTap(note) }, ) { Icon( imageVector = Icons.Default.Edit, contentDescription = "Edit note button" ) } IconButton( onClick = { onDeleteTap(note) } ) { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete note button" ) } } } } } } @Preview(showBackground = true, widthDp = 300) @Composable fun NoteCardPreview() { NotesAppTheme { NoteItemCard( modifier = Modifier.padding(8.dp), note = Note("0", "Title", "Description"), onEditTap = {}, onDeleteTap = {} ) } }
0
Kotlin
0
0
5838e45c83545ad9e71cf6602a64f02dd41492d4
4,704
NotesAppAndroid
Apache License 2.0
Android/app/src/main/java/ru/alexskvortsov/policlinic/domain/states/registry/RegistryProfilePartialState.kt
AlexSkvor
244,438,301
false
null
package ru.alexskvortsov.policlinic.domain.states.registry sealed class RegistryProfilePartialState(val log: String) { object PersonSaved: RegistryProfilePartialState("PersonSaved") data class Loading(val flag: Boolean) : RegistryProfilePartialState("Loading $flag") data class Error(val e: Throwable) : RegistryProfilePartialState("Error $e") data class PersonLoaded(val person: RegistryPerson) : RegistryProfilePartialState("PersonLoaded $person") data class LoginVerified(val unique: Boolean) : RegistryProfilePartialState("LoginCanBeSaved $unique") data class NewName(val name: String) : RegistryProfilePartialState("NewName $name") data class NewSurname(val surname: String) : RegistryProfilePartialState("NewSurname $surname") data class NewFathersName(val fathersName: String) : RegistryProfilePartialState("NewFathersName $fathersName") data class NewLogin(val login: String) : RegistryProfilePartialState("NewLogin $login") fun partial() = this override fun toString(): String = log }
0
Kotlin
0
0
5cc6a10a1399ee08643e69308afd4626938882b0
1,043
polyclinic
Apache License 2.0
app/src/main/java/com/wahibhaq/locationservicelivedata/MainViewModel.kt
KI-labs
135,055,942
false
null
package com.wahibhaq.locationservicelivedata import android.Manifest import android.app.Application import android.app.NotificationManager import android.arch.lifecycle.AndroidViewModel import android.content.Context import android.content.Intent class MainViewModel(application: Application) : AndroidViewModel(application) { private val locationServiceListener = LocationServiceListener(application, Intent(application, LocationService::class.java)) private val notificationsUtil = NotificationsUtil(application, application.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) val gpsStatusLiveData = GpsStatusListener(application) val locationPermissionStatusLiveData = PermissionStatusListener(application, Manifest.permission.ACCESS_FINE_LOCATION) fun startLocationTracking() = locationServiceListener.subscribeToLocationUpdates() fun stopLocationTracking() { locationServiceListener.unsubscribeFromLocationUpdates() notificationsUtil.cancelAlertNotification() } }
13
Kotlin
10
39
cbbd7608810b4a3bba3d99474ba67316d0460600
1,078
gps-permission-checks-livedata
MIT License
virtualjoystick/src/main/java/com/yoimerdr/android/virtualjoystick/exceptions/InvalidControlPositionException.kt
yoimerdr
752,392,779
false
{"Kotlin": 112504, "CSS": 2645}
package com.yoimerdr.android.virtualjoystick.exceptions /** * Represents an invalid control position exception. * It is usually thrown when one of the x or y coordinates is negative. */ class InvalidControlPositionException( message: String? ) : Exception(message) { constructor() : this("None of the coordinates of the control position can be negative.") }
0
Kotlin
0
0
1ede27026dae3058a37b52ce6fc91272441fb601
370
AndroidVirtualJoystick
Apache License 2.0
components/faphub/installation/queue/impl/src/main/java/com/flipperdevices/faphub/installation/queue/impl/model/FapInternalQueueState.kt
flipperdevices
288,258,832
false
{"Kotlin": 2760721, "FreeMarker": 10084, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.faphub.installation.queue.impl.model import com.flipperdevices.faphub.installation.queue.api.model.FapActionRequest import com.flipperdevices.faphub.installation.queue.api.model.FapQueueState sealed class FapInternalQueueState { abstract val request: FapActionRequest data class Scheduled( override val request: FapActionRequest ) : FapInternalQueueState() data class InProgress( override val request: FapActionRequest, val float: Float ) : FapInternalQueueState() data class Failed( override val request: FapActionRequest, val throwable: Throwable ) : FapInternalQueueState() fun toFapQueueState() = when (this) { is FapInternalQueueState.Failed -> FapQueueState.Failed( request, throwable ) is FapInternalQueueState.Scheduled -> FapQueueState.Pending(request) is FapInternalQueueState.InProgress -> FapQueueState.InProgress( request, float ) } }
13
Kotlin
131
999
ef27b6b6a78a59b603ac858de2c88f75b743f432
1,046
Flipper-Android-App
MIT License
app/src/main/java/cbedoy/stateshopapp/dto/PokeProductResponse.kt
cbedoy
339,294,675
false
null
package cbedoy.stateshopapp.dto import com.google.gson.annotations.SerializedName data class PokeProductResponse( val results: List<PokeProductResponseItem> = emptyList() ) data class PokeProductResponseItem( val name: String = "", val url: String = "" ) data class PokeItemResponse( val id: String? = "", val name: String? = "", val url: String? = "", val weight: Int? = 0, val sprites: PokeSpriteResponse? = PokeSpriteResponse(), val types: List<PokeTypesResponse>? = emptyList(), val moves: List<PokeMovesResponse>? = emptyList(), val abilities: List<PokeAbilitiesResponse>? = emptyList(), ) data class PokeAbilitiesResponse( val ability: PokeAbilityResponse? = PokeAbilityResponse() ) data class PokeAbilityResponse( val name: String? = "" ) data class PokeSpriteResponse( @SerializedName("front_default") val avatar: String? = "" ) data class PokeMovesResponse( val move: PokeMoveResponse? = PokeMoveResponse() ) data class PokeMoveResponse( val name: String? = "" ) data class PokeTypesResponse( val type: PokeTypeResponse? = PokeTypeResponse() ) data class PokeTypeResponse( val name: String? = "" )
0
Kotlin
0
0
69711c937fd59b547fbb9521dec104f60b963994
1,269
StateShopApp
MIT License
src/main/kotlin/no/nav/syfo/pdl/redis/PdlPersonRedisModel.kt
navikt
375,347,237
false
null
package no.nav.syfo.pdl.redis import no.nav.syfo.pdl.model.Navn import no.nav.syfo.pdl.model.PdlPerson data class PdlPersonRedisModel( val navn: NavnRedisModel, val fnr: String, val aktorId: String ) data class NavnRedisModel( val fornavn: String, val mellomnavn: String?, val etternavn: String ) fun PdlPerson.toPdlPersonRedisModel(): PdlPersonRedisModel { return PdlPersonRedisModel( navn = NavnRedisModel(fornavn = navn.fornavn, mellomnavn = navn.mellomnavn, etternavn = navn.etternavn), aktorId = aktorId!!, fnr = fnr!! ) } fun PdlPersonRedisModel.toPdlPerson(): PdlPerson { return PdlPerson( navn = Navn(fornavn = navn.fornavn, mellomnavn = navn.mellomnavn, etternavn = navn.etternavn), aktorId = aktorId, fnr = fnr ) }
1
Kotlin
6
0
ecbdb6d3e12629090107606dca2af2c34e9ea257
818
narmesteleder
MIT License
src/main/kotlin/MobUnitLogic.kt
argcc
777,572,651
false
{"Kotlin": 545918}
package org.example class MobUnitLogic(obj: MobNode? = null, li: UnitLogic) : MobNode(obj) { var logic_info: UnitLogic = li override fun ReadNodeData() { when (node_type_id) { 0xbbbd0000u -> { logic_info.points.add(GuartPt()) logic_info.points.last().position = Vec3f() val mob_guard = MobGuardPt(this, logic_info.points.last()) mob_guard.ReadNodes() } 0xbbbc0001u -> { val am = ReadByte().toUInt()//!!! должно быть null? if (am != 0u && logic_info.agression_mode > 0u) { logic_info.agression_mode = 0u } } 0xbbbc0002u -> logic_info.cyclic = ReadByte().toUInt() 0xbbbc0003u -> logic_info.model = ReadUInt() 0xbbbc0004u -> logic_info.r = ReadFloat() 0xbbbc0005u -> logic_info.pt = ReadVec3f() 0xbbbc0006u -> logic_info.nalarm = ReadByte().toUInt() 0xbbbc0007u -> logic_info.use = ReadByte().toUInt() 0xbbbc0008u -> { val am = ReadByte().toUInt()//!!! должно быть null? if (am != 0u && logic_info.agression_mode > 1u) { logic_info.agression_mode = 1u } } 0xbbbc0009u -> { val am = ReadByte().toUInt()//!!! должно быть null? if (am != 0u && logic_info.agression_mode > 2u) { logic_info.agression_mode = 2u } } 0xbbbc000au -> logic_info.wait = ReadFloat() 0xbbbc000bu -> logic_info.alarm_condition = ReadByte().toUInt() 0xbbbc000cu -> logic_info.help = ReadFloat() 0xbbbc000du -> { if (ReadByte().toInt() == 0) { logic_info.flags = logic_info.flags and 0xfffffff7u } else { logic_info.flags = logic_info.flags or 0x8u } } 0xbbbc000eu -> logic_info.agression_mode = ReadByte().toUInt() else -> {} } } }
0
Kotlin
0
0
9e207ca143dfccbd9d5341bbf9df00fa96bfd4d9
2,142
ei_reverse_consp
MIT License
automotive/src/main/java/com/volvocars/wearablemonitor/domain/usecase/SetPreferenceFromServerStatus.kt
volvo-cars
309,467,507
false
{"Kotlin": 127151, "HTML": 36742}
package com.volvocars.wearablemonitor.domain.usecase import com.volvocars.wearablemonitor.domain.model.ServerStatus import com.volvocars.wearablemonitor.domain.repository.PreferenceRepository import javax.inject.Inject class SetPreferenceFromServerStatus @Inject constructor( private val repository: PreferenceRepository ) { operator fun invoke(serverStatus: ServerStatus) { repository.setPreferenceFromServerStatus(serverStatus) } }
0
Kotlin
0
6
78ef44a021208c4b1f6f181511d1e79d97648233
455
sample-android-automotive-wearable-monitoring
Apache License 2.0
compiler/testData/compileKotlinAgainstKotlin/constructorWithInlineClassParametersInBinaryDependenciesOldMangling.kt
cortinico
282,973,729
true
null
// TARGET_BACKEND: JVM // !LANGUAGE: +InlineClasses // FILE: A.kt // KOTLIN_CONFIGURATION_FLAGS: +JVM.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME package lib inline class S(val string: String) class Test(val s: S) // FILE: B.kt import lib.* fun box() = Test(S("OK")).s.string
0
null
0
1
2fce6a4af9044de7975392474a6eb3b8c3985bd5
274
kotlin
Apache License 2.0
core/src/main/kotlin/org.rscarela.security.reactive.pendragon.core/credentials/UserCredentials.kt
rscarela
879,027,195
false
{"Kotlin": 25169}
package org.rscarela.security.reactive.pendragon.core.credentials import java.io.Serializable interface UserCredentials : Serializable { /** * @return username required for authentication. */ fun getUsername(): String /** * @return password required for authentication. */ fun getPassword(): String }
0
Kotlin
0
0
1b472cdc7f8273bb4cbfd2366b407d09bc64e8df
341
pendragon-reactive
Apache License 2.0
fontawesome/src/de/msrd0/fontawesome/icons/FA_X_RAY.kt
msrd0
363,665,023
false
null
/* @generated * * This file is part of the FontAwesome Kotlin library. * https://github.com/msrd0/fontawesome-kt * * This library is not affiliated with FontAwesome. * * 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 de.msrd0.fontawesome.icons import de.msrd0.fontawesome.Icon import de.msrd0.fontawesome.Style import de.msrd0.fontawesome.Style.SOLID object FA_X_RAY: Icon { override val name get() = "X-Ray" override val unicode get() = "f497" override val styles get() = setOf(SOLID) override fun svg(style: Style) = when(style) { SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M240 384c-8.8 0-16 7.2-16 16s7.2 16 16 16 16-7.2 16-16-7.2-16-16-16zm160 32c8.8 0 16-7.2 16-16s-7.2-16-16-16-16 7.2-16 16 7.2 16 16 16zM624 0H16C7.2 0 0 7.2 0 16v32c0 8.8 7.2 16 16 16h608c8.8 0 16-7.2 16-16V16c0-8.8-7.2-16-16-16zm0 448h-48V96H64v352H16c-8.8 0-16 7.2-16 16v32c0 8.8 7.2 16 16 16h608c8.8 0 16-7.2 16-16v-32c0-8.8-7.2-16-16-16zM480 248c0 4.4-3.6 8-8 8H336v32h104c4.4 0 8 3.6 8 8v16c0 4.4-3.6 8-8 8H336v32h64c26.5 0 48 21.5 48 48s-21.5 48-48 48-48-21.5-48-48v-16h-64v16c0 26.5-21.5 48-48 48s-48-21.5-48-48 21.5-48 48-48h64v-32H200c-4.4 0-8-3.6-8-8v-16c0-4.4 3.6-8 8-8h104v-32H168c-4.4 0-8-3.6-8-8v-16c0-4.4 3.6-8 8-8h136v-32H200c-4.4 0-8-3.6-8-8v-16c0-4.4 3.6-8 8-8h104v-24c0-4.4 3.6-8 8-8h16c4.4 0 8 3.6 8 8v24h104c4.4 0 8 3.6 8 8v16c0 4.4-3.6 8-8 8H336v32h136c4.4 0 8 3.6 8 8v16z"/></svg>""" else -> null } }
0
Kotlin
0
0
2fc4755051325e730e9d012c9dfe94f5ea800fdd
1,987
fontawesome-kt
Apache License 2.0
app/src/main/java/com/example/mycookbook/di/MainModule.kt
LucasMelll0
511,222,971
false
{"Kotlin": 34085}
package com.example.mycookbook.di import com.example.mycookbook.database.AppDataBase import com.example.mycookbook.repository.ReceitaRepository import com.example.mycookbook.ui.viewmodel.ReceitaViewModel import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val receitaModule = module { factory { ReceitaRepository(get()) } factory { AppDataBase.instancia(androidContext()).ReceitaDAO() } viewModel { ReceitaViewModel( get() ) } }
0
Kotlin
0
2
39e0a54398d7990cc2b8713df121749ff851d351
570
MyCookBook-With-Kotlin
Apache License 2.0
MyApplication/app/src/main/java/com/example/myapplication/activity/LoginActivity.kt
Roba42
636,406,586
false
null
package com.example.myapplication.activity
13
Kotlin
0
1
3a46224bc0e1d8e31d072402b2a2c5cd2d7dff72
44
MoCo_SS23_FootPrintHero
MIT License
app/src/main/kotlin/io/dolphin/move/android/features/messages/presentation/messages/MessagesViewModel.kt
dolphin-technologies
603,088,245
false
{"Kotlin": 624279}
package io.dolphin.move.android.features.messages.presentation.messages import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import io.dolphin.move.android.basepresentation.BaseViewModel import io.dolphin.move.android.basepresentation.components.ErrorState import io.dolphin.move.android.basepresentation.delegate import io.dolphin.move.android.basepresentation.mapDistinct import io.dolphin.move.android.domain.State import io.dolphin.move.android.features.messages.domain.MessagesInteractor import io.dolphin.move.android.features.messages.domain.RemoveMessageInteractor import javax.inject.Inject import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch @HiltViewModel class MessagesViewModel @Inject constructor( private val messagesInteractor: MessagesInteractor, private val removeMessageInteractor: RemoveMessageInteractor, ) : BaseViewModel(), MessagesView { private val liveState = MutableLiveData(MessagesViewState()) private var viewState: MessagesViewState by liveState.delegate() val messagesState = liveState.mapDistinct { it } init { requestMessages() messagesInteractor.getMessagesFlow() .onEach { messagesList -> viewState = viewState.copy( messages = messagesList.map { it.mapToMessageState() }, error = null, onRemoveErrorReset = false, ) hideProgress() } .launchIn(viewModelScope) } override fun retryOnError() { requestMessages() } override fun onRemoveItem(id: Long) { showProgress() viewModelScope.launch { removeMessageInteractor(id) } } override fun markAsRead(id: Long) { /*val updatedList = buildList { viewState.messages.forEach { messageState -> if (messageState.id == id) { add(messageState.copy(isNew = false)) } else { add(messageState) } } } viewState = viewState.copy( messages = updatedList, onRemoveErrorReset = false, )*/ } private fun requestMessages() { viewModelScope.launch { showProgress() when (messagesInteractor.requestMessages()) { is State.Error -> { hideProgress() viewState = MessagesViewState(error = ErrorState()) } is State.Data, State.Loading, State.None -> { /* do nothing*/ } } } } }
1
Kotlin
0
0
519ff6e880104ad50770d2b9bf0ac6320eeaaa67
2,802
MOVE-App-Android
Apache License 2.0
services/csm.cloud.project.project/src/test/kotlin/com/bosch/pt/iot/smartsite/project/message/shared/model/MessageBuilder.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}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2024 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.project.message.shared.model import com.bosch.pt.iot.smartsite.project.message.domain.MessageId import com.bosch.pt.iot.smartsite.project.topic.shared.model.Topic import com.bosch.pt.iot.smartsite.project.topic.shared.model.TopicBuilder import com.bosch.pt.iot.smartsite.user.model.User import java.time.LocalDateTime /** Builder for [Message]. */ @Deprecated("To be removed with the cleanup of the old test data creation") class MessageBuilder /** Private constructor. */ private constructor() { private var topic: Topic? = null private var content: String? = null private var identifier: MessageId = MessageId() private var createdBy: User? = null private var lastModifiedBy: User? = null private var createdDate = LocalDateTime.now() private var lastModifiedDate = LocalDateTime.now() /** * Sets the topic the message belongs to. * * @param topic the topic * @return the builder */ fun withTopic(topic: Topic): MessageBuilder { this.topic = topic return this } /** * Sets the content of the message. * * @param content the content of the message * @return the builder */ fun withContent(content: String?): MessageBuilder { this.content = content return this } /** * Sets the creator of the message. * * @param user the user * @return the builder */ fun withCreatedBy(user: User): MessageBuilder { createdBy = user return this } /** * Sets the identifier of the message. * * @param identifier the identifier * @return the builder */ fun withIdentifier(identifier: MessageId): MessageBuilder { this.identifier = identifier return this } /** * Sets the user who modified the message last. * * @param lastModifiedBy the user * @return the builder */ fun withLastModifiedBy(lastModifiedBy: User): MessageBuilder { this.lastModifiedBy = lastModifiedBy return this } /** * Sets creation date. * * @param createdDate the date of creation * @return the builder */ fun withCreatedDate(createdDate: LocalDateTime): MessageBuilder { this.createdDate = createdDate return this } /** * Sets date of last modification. * * @param lastModifiedDate the date of last modification * @return the builder */ fun withLastModifiedDate(lastModifiedDate: LocalDateTime): MessageBuilder { this.lastModifiedDate = lastModifiedDate return this } /** * Creates the target [Message]. * * @return target message */ fun build(): Message { val message = Message(identifier, content, topic!!) message.setCreatedDate(createdDate) message.setLastModifiedDate(lastModifiedDate) message.topic = topic!! message.identifier = identifier createdBy?.getAuditUserId()?.let { message.setCreatedBy(it) } createdBy?.getAuditUserId()?.let { message.setLastModifiedBy(it) } return message } companion object { /** * Creates new builder. * * @return new builder */ fun message(): MessageBuilder = MessageBuilder() .withIdentifier(MessageId()) .withContent("content") .withTopic(TopicBuilder.topic().build()) } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
3,481
bosch-pt-refinemysite-backend
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/service/events/handlers/OffenderMergedEventHandlerTest.kt
ministryofjustice
533,838,017
false
{"Kotlin": 3614888, "Shell": 8572, "Dockerfile": 1478}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.events.handlers import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.reset import org.mockito.kotlin.stub import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.client.prisonapi.api.PrisonApiApplicationClient import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.config.Feature import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.config.FeatureSwitches import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.Allocation import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.helpers.MOORLAND_PRISON_CODE import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.helpers.isBool import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.helpers.rolloutPrison import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AllocationRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AppointmentAttendeeRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AttendanceRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AuditRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.EventReviewRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.RolloutPrisonRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.WaitingListRepository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.InmateDetailFixture import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.TransactionHandler import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.events.offenderMergedEvent import java.time.LocalDate class OffenderMergedEventHandlerTest { private val rolloutPrisonRepository: RolloutPrisonRepository = mock() private val prisonerApiClient: PrisonApiApplicationClient = mock() private val allocationRepository: AllocationRepository = mock() private val attendanceRepository: AttendanceRepository = mock() private val waitingListRepository: WaitingListRepository = mock() private val auditRepository: AuditRepository = mock() private val eventReviewRepository: EventReviewRepository = mock() private val appointmentAttendeeRepository: AppointmentAttendeeRepository = mock() private val featureSwitches: FeatureSwitches = mock { on { isEnabled(Feature.OFFENDER_MERGED_ENABLED) } doReturn true } // Define old and new prisoner numbers in the merge private val oldNumber = "A1111AA" private val newNumber = "B2222BB" private val oldBookingId = 111111L private val newBookingId = 999999L private val prisonerSearchResult = InmateDetailFixture.instance( agencyId = MOORLAND_PRISON_CODE, offenderNo = newNumber, firstName = "Stephen", lastName = "Macdonald", bookingId = newBookingId, ) private val handler = OffenderMergedEventHandler( rolloutPrisonRepository, prisonerApiClient, allocationRepository, attendanceRepository, waitingListRepository, auditRepository, eventReviewRepository, appointmentAttendeeRepository, TransactionHandler(), featureSwitches, ) @BeforeEach fun beforeTests() { reset( rolloutPrisonRepository, prisonerApiClient, allocationRepository, attendanceRepository, waitingListRepository, auditRepository, eventReviewRepository, appointmentAttendeeRepository, ) rolloutPrisonRepository.stub { on { findByCode(MOORLAND_PRISON_CODE) } doReturn rolloutPrison().copy( activitiesToBeRolledOut = true, activitiesRolloutDate = LocalDate.now().plusDays(-1), ) } prisonerApiClient.stub { on { getPrisonerDetailsLite(newNumber) } doReturn prisonerSearchResult } val allocation: Allocation = mock() allocationRepository.stub { on { findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, newNumber) } doReturn listOf(allocation) } } @Test fun `inbound merged event is processed when the prisoner is at a rolled out prison`() { val inboundEvent = offenderMergedEvent(prisonerNumber = newNumber, removedPrisonerNumber = oldNumber) handler.handle(inboundEvent).also { it.isSuccess() isBool true } verify(prisonerApiClient).getPrisonerDetailsLite(newNumber) verify(rolloutPrisonRepository).findByCode(MOORLAND_PRISON_CODE) verify(allocationRepository).findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, newNumber) verify(allocationRepository).findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, oldNumber) inOrder(allocationRepository) { verify(allocationRepository).mergePrisonerToNewBookingId(newNumber, newBookingId) verify(allocationRepository).mergeOldPrisonerNumberToNew(oldNumber, newNumber, newBookingId) } verify(attendanceRepository).findByPrisonerNumber(oldNumber) verify(attendanceRepository).mergeOldPrisonerNumberToNew(oldNumber, newNumber) verify(waitingListRepository).findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, newNumber) verify(waitingListRepository).findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, oldNumber) inOrder(waitingListRepository) { verify(waitingListRepository).mergePrisonerToNewBookingId(newNumber, newBookingId) verify(waitingListRepository).mergeOldPrisonerNumberToNew(oldNumber, newNumber, newBookingId) } verify(auditRepository).findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, oldNumber) verify(auditRepository).mergeOldPrisonerNumberToNew(oldNumber, newNumber) verify(eventReviewRepository).findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, newNumber) verify(eventReviewRepository).findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, oldNumber) inOrder(eventReviewRepository) { verify(eventReviewRepository).mergePrisonerToNewBookingId(newNumber, newBookingId) verify(eventReviewRepository).mergeOldPrisonerNumberToNew(oldNumber, newNumber, newBookingId) } verify(appointmentAttendeeRepository).findByPrisonerNumber(newNumber) verify(appointmentAttendeeRepository).findByPrisonerNumber(oldNumber) inOrder(appointmentAttendeeRepository) { verify(appointmentAttendeeRepository).mergePrisonerToNewBookingId(newNumber, newBookingId) verify(appointmentAttendeeRepository).mergeOldPrisonerNumberToNew(oldNumber, newNumber, newBookingId) } verify(auditRepository).findByPrisonCodeAndPrisonerNumber(MOORLAND_PRISON_CODE, oldNumber) verify(auditRepository).mergeOldPrisonerNumberToNew(oldNumber, newNumber) verify(auditRepository).save(any()) } @Test fun `inbound merged event is ignored when the prisoner is not at a rolled out prison`() { val inboundEvent = offenderMergedEvent(prisonerNumber = newNumber, removedPrisonerNumber = oldNumber) rolloutPrisonRepository.stub { on { findByCode(MOORLAND_PRISON_CODE) } doReturn rolloutPrison().copy( activitiesToBeRolledOut = false, activitiesRolloutDate = null, ) } handler.handle(inboundEvent).also { it.isSuccess() isBool true } verify(prisonerApiClient).getPrisonerDetailsLite(newNumber) verify(rolloutPrisonRepository).findByCode(MOORLAND_PRISON_CODE) verifyNoInteractions( allocationRepository, attendanceRepository, waitingListRepository, auditRepository, eventReviewRepository, appointmentAttendeeRepository, ) } }
3
Kotlin
0
1
c4fc5a7966d71151d2d2257c4063c91d195364aa
7,849
hmpps-activities-management-api
MIT License
alert/src/main/java/com/hymnal/alert/Custom.kt
Hymn-Qin
215,482,049
false
null
package com.hymnal.alert import android.content.DialogInterface import android.content.res.Configuration import android.os.Bundle import android.support.v4.app.DialogFragment import android.view.* import android.widget.LinearLayout import org.jetbrains.anko.* import org.jetbrains.anko.support.v4.UI internal class Custom : DialogFragment() { var run: ((View) -> Unit)? = null var title: String? = null lateinit var viewCustom: View var left: String? = null var right: String? = null var listener: ((Boolean) -> Unit)? = null var dialogInterface: DialogInterface? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val dm = context!!.resources.displayMetrics val width = if (dm.widthPixels < dm.heightPixels) dm.widthPixels else dm.heightPixels val height = if ((width / 10) > 16 * 9 ) width / 10 else 16 * 9 return UI { verticalLayout { if (!title.isNullOrEmpty()) { textView { gravity = Gravity.CENTER background = context.drawable(R.drawable.dialog_line_btm) text = title textSize = 15f textColor = context.color(R.color.dialog_msg_text_block) }.lparams(width = matchParent, height = height) { } } verticalLayout { gravity = Gravity.CENTER addView(viewCustom) background = context.drawable(R.drawable.dialog_line_btm) }.lparams(width = matchParent, height = wrapContent) { } verticalLayout { orientation = LinearLayout.HORIZONTAL if (!this@Custom.left.isNullOrEmpty() && !this@Custom.right.isNullOrEmpty()) { textView { background = context.drawable(R.drawable.dialog_btn_left_bg_pressed) gravity = Gravity.CENTER setOnClickListener { dismiss() listener?.invoke(false) } text = this@Custom.left textSize = 14f textColor = context.color(R.color.dialog_msg_text_block) }.lparams(width = matchParent, height = height, weight = 1f) view { background = context.drawable(R.drawable.dialog_line_ver) }.lparams(width = 1, height = matchParent) { gravity = Gravity.CENTER } } textView { gravity = Gravity.CENTER background = if (!this@Custom.left.isNullOrEmpty() && !this@Custom.right.isNullOrEmpty()) { context.drawable(R.drawable.dialog_btn_right_bg_pressed) } else { context.drawable(R.drawable.dialog_btn_bottom_bg_pressed) } setOnClickListener { dismiss() listener?.invoke(true) } text = this@Custom.right textSize = 14f textColor = context.color(R.color.base_dialog_text) }.lparams(width = matchParent, height = height, weight = 1f) } }.apply { layoutParams = ViewGroup.LayoutParams(matchParent, wrapContent) background = context.drawable(R.drawable.dialog_bg) } }.view } override fun onStart() { super.onStart() dialog?.window?.apply { setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) setWindowAnimations(R.style.AlertPageAnim) //消除白边window.setBackgroundDrawable(BitmapDrawable()) setBackgroundDrawableResource(android.R.color.transparent) val windowParams: WindowManager.LayoutParams = attributes val dm = context!!.resources.displayMetrics //屏幕状态 when (context!!.resources.configuration.orientation) { Configuration.ORIENTATION_LANDSCAPE -> windowParams.width = (dm.heightPixels * 0.8).toInt() Configuration.ORIENTATION_PORTRAIT -> windowParams.width = (dm.widthPixels * 0.8).toInt() } windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT windowParams.dimAmount = 0.5f //遮罩透明度 attributes = windowParams } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) run?.invoke(view) } override fun onCancel(dialog: DialogInterface?) { super.onCancel(dialog) dialogInterface?.cancel() } override fun onDismiss(dialog: DialogInterface?) { super.onDismiss(dialog) dialogInterface?.dismiss() } }
0
Kotlin
0
0
6b6232ee99d0cb5f8c6fd11a77448a4b17af06c6
5,424
alert
Apache License 2.0
presentation/src/main/java/com/yapp/buddycon/presentation/ui/login/KaKaoLoginViewModel.kt
YAPP-Github
561,172,522
false
null
package com.yapp.buddycon.presentation.ui.login import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.yapp.buddycon.domain.model.UserInfo import com.yapp.buddycon.domain.usecase.login.GetUserInfoUseCase import com.yapp.buddycon.domain.usecase.token.SaveTokenUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class KaKaoLoginViewModel @Inject constructor( private val getUserInfoUseCase: GetUserInfoUseCase, private val saveTokenUseCase: SaveTokenUseCase ) : ViewModel() { private val _loginState = MutableSharedFlow<KaKaoLoginState>() val loginState: SharedFlow<KaKaoLoginState> = _loginState.asSharedFlow() init { viewModelScope.launch { _loginState.emit(KaKaoLoginState.LogOut) } } fun requestUserInfo( kakaoAccessToken: String, name: String, email: String?, gender: String?, ageRange: String? ) = getUserInfoUseCase(kakaoAccessToken, name, email, gender, ageRange) .catch { e -> _loginState.emit(KaKaoLoginState.Error(e)) } .onEach { //saveTokenUseCase(it.accessToken, it.accessTokenExpiresIn, it.refreshToken) saveTokenUseCase( "eyJhbGciOiJIUzI1NiJ9.eyJtZW1iZXJJZCI6MSwiaWF0IjoxNjc0ODEyMjk5LCJleHAiOjE2ODA4MTcwOTl9.8buxTCLp_erwERq7d96AORKCyzbLNaqhg7ozNFKs0_M", Long.MAX_VALUE, "" ) _loginState.emit(KaKaoLoginState.Login(it)) }.launchIn(viewModelScope) fun loginGuest(){ viewModelScope.launch { saveTokenUseCase( "eyJhbGciOiJIUzI1NiJ9.eyJtZW1iZXJJZCI6MTAsImlhdCI6MTY3NjgyNTIxMywiZXhwIjoxNjgyODczMjEzfQ._BOIpITxcnRKNY3VNUKwSOha92ybSHMLnkbnBGr5EV4", 1682873213340, "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2Nzc0MzAwMTN9.fRdkH8YnbtWRC7JWqpgYjHERM32dKo0dJEiqmPCcQ54" ) _loginState.emit(KaKaoLoginState.Login( UserInfo( "eyJhbGciOiJIUzI1NiJ9.eyJtZW1iZXJJZCI6MTAsImlhdCI6MTY3NjgyNTIxMywiZXhwIjoxNjgyODczMjEzfQ._BOIpITxcnRKNY3VNUKwSOha92ybSHMLnkbnBGr5EV4", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2Nzc0MzAwMTN9.fRdkH8YnbtWRC7JWqpgYjHERM32dKo0dJEiqmPCcQ54", 1682873213340 ) )) } } }
33
Kotlin
0
8
dcd6324f1c313a2af05b328ea21673b096caca51
2,404
21st-Android-Team-1-Android
Apache License 2.0
app/src/main/java/com/example/instabus/stations/StationsListActivity.kt
Dramaix
238,223,346
false
null
package com.example.instabus.stations import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.MenuItem import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.example.instabus.AboutActivity import com.example.instabus.HomeActivity import com.example.instabus.R import com.example.instabus.models.Station import com.google.android.material.navigation.NavigationView import kotlinx.android.synthetic.main.activity_station_list_nav.* import kotlinx.android.synthetic.main.content_home.* import kotlinx.android.synthetic.main.toolbar.* @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") @SuppressLint("Registered") class StationsListActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, StationsAdapter.StationsItemListener { private val TAG = "StationsListActivity" companion object { const val EXTRA_STATION_FILTER = "station_filter" fun start(context: Context) { val intent = Intent(context, StationsListActivity::class.java) context.startActivity(intent) } } private val drawerLayout by lazy { findViewById<DrawerLayout>(R.id.drawer) } private lateinit var swipeLayout: SwipeRefreshLayout private lateinit var recyclerView: RecyclerView private lateinit var viewModel: StationsViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_station_list_nav) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) nav_view.setNavigationItemSelectedListener(this) val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_nav_drawer, R.string.close_nav_drawer) drawerLayout.addDrawerListener(toggle) toggle.syncState() recyclerView=findViewById(R.id.recycler_view) viewModel= StationsViewModel(this.application) viewModel.station.observe(this, Observer { val adapter = StationsAdapter(this@StationsListActivity,it,this@StationsListActivity) recyclerView.layoutManager=LinearLayoutManager(this) recyclerView.adapter=adapter }) Log.i(TAG, "onCreate") } override fun onNavigationItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_about -> AboutActivity.start(this) R.id.action_cocktails -> start(this) R.id.action_home -> HomeActivity.start(this) } return true } override fun onStationsItemClick(stations: Station) { StationsDetailActivity.start(this, stations) } }
2
Kotlin
0
0
b242078c8893a07b6d7f55c872fecd81613014ce
3,214
InstaBus
MIT License
presentation/src/main/java/org/lotka/xenon/presentation/screen/edit_profile/EditProfileScreen.kt
armanqanih
860,856,530
false
{"Kotlin": 300166}
package org.lotka.xenon.presentation.screen.edit_profile import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import org.lotka.xenon.domain.util.Constants.SpaceMedium import org.lotka.xenon.domain.util.Constants.SpaceSmall import org.lotka.xenon.domain.util.Constants.SpaceToLarge import org.lotka.xenon.presentation.compose.StandardButton import org.lotka.xenon.presentation.compose.StandardTextField import org.lotka.xenon.presentation.compose.StandardTopBar import org.lotka.xenon.presentation.screen.auth.login.LoginViewModel import org.lotka.xenon.presentation.screen.edit_profile.compose.ProfileSection import org.lotka.xenon.presentation.util.CropActivityResultContract import org.lotka.xenon.presentation.util.PasswordTextFieldState import org.lotka.xenon.presentation.util.StandardTextFieldState import org.lotka.xenon.presentation.util.UiEvent @Composable fun EditProfileScreen( viewModel: EditProfileViewModel = hiltViewModel(), onNavigateUp: () -> Unit, ) { val state = viewModel.state.collectAsState().value val user = viewModel.state.collectAsState().value.user val passwordState = viewModel.passwordState.collectAsState().value val scaffoldState = rememberScaffoldState() LaunchedEffect(key1 = true) { viewModel.eventFlow.collect { event -> when (event) { is UiEvent.ShowSnakeBar -> { scaffoldState.snackbarHostState.showSnackbar( message = event.message, ) } is UiEvent.onNavigateUp -> { onNavigateUp() } is UiEvent.Navigate -> TODO() } } } val cropProfileImageLauncher = rememberLauncherForActivityResult( contract = CropActivityResultContract(1f,1f) ) { uri -> uri?.let { viewModel.onEvent(EditProfileEvent.CropProfilePicture(it)) } } val profilePictureGalleryLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ) { uri -> uri?.let { cropProfileImageLauncher.launch(it) } } Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ){ if (state.isLoading){ CircularProgressIndicator() } state.error.let { Text(text = "Oops Somethings Went wrong ${state.error.toString()}", style = MaterialTheme.typography.h2, color = Color.Red, fontWeight = FontWeight.Bold ) } } Scaffold (scaffoldState = scaffoldState){ Column( modifier = Modifier .fillMaxSize().padding(it) .padding(start = SpaceSmall.dp, end = SpaceSmall.dp), horizontalAlignment = Alignment.CenterHorizontally ) { StandardTopBar( onNavigateUp = onNavigateUp, showCancelIcon = true, title = { Text( text = "Edit Profile", style = MaterialTheme.typography.body1.copy( fontSize = 24.sp ), maxLines = 1, overflow = TextOverflow.Ellipsis, color = MaterialTheme.colors.onSurface, fontWeight = FontWeight.SemiBold ) } ) Spacer(modifier = Modifier.height(SpaceToLarge.dp)) ProfileSection( profileImageUri = state.profileImageUri?.toString(), onEditProfilePictureClick = { profilePictureGalleryLauncher.launch("image/*") } ) state.userNameState?.let { it1 -> StandardTextField( modifier = Modifier.padding(start = SpaceSmall.dp, end = SpaceSmall.dp), value = it1, hint = "User Name", maxLines = 1, keyboardType = KeyboardType.Text, onValueChange = { viewModel.onEvent( EditProfileEvent.UserNameChange(it) ) } ) } Spacer(modifier = Modifier.height(SpaceMedium.dp)) state.emailState?.let { it1 -> StandardTextField( modifier = Modifier.padding(start = SpaceSmall.dp, end = SpaceSmall.dp), value = it1, hint = "Email", maxLines = 1, onValueChange = { viewModel.onEvent( EditProfileEvent.EmailChange(it) ) }, keyboardType = KeyboardType.Email ) } Spacer(modifier = Modifier.height(SpaceMedium.dp)) // StandardTextField( // modifier = Modifier.padding(start = SpaceSmall.dp, end = SpaceSmall.dp), // value = passwordState.text, // // hint = "password", // maxLines = 1, // onValueChange = { // viewModel.onEvent( // EditProfileEvent.PasswordChange( // PasswordTextFieldState(text = it) // ) // ) // }, // keyboardType = KeyboardType.Password, // isPasswordVisible = passwordState.isPasswordVisible, // onPasswordToggleClick = { // viewModel.onEvent(EditProfileEvent.IsPasswordVisibility) // }, // // // ) Text( modifier = Modifier .fillMaxWidth() .padding(start = SpaceSmall.dp), text = "forget and Change password", style = MaterialTheme.typography.body2, color = MaterialTheme.colors.surface, textAlign = TextAlign.Start, fontWeight = FontWeight.SemiBold ) Spacer(modifier = Modifier.height(80.dp)) StandardButton( modifier = Modifier .fillMaxWidth() .padding(start = SpaceSmall.dp, end = SpaceSmall.dp) .size(60.dp), title = "Save", onButtonClick = { viewModel.onEvent(EditProfileEvent.UpdateProfile) } ) } } }
0
Kotlin
0
0
6b639355540fcc96477726f700c8dee702c99a1d
7,644
ModernNews
Apache License 2.0
app/src/main/java/com/pigeoff/rss/adapters/SwipeAdapter.kt
16arpi
357,496,459
false
null
package com.pigeoff.rss.adapters import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.text.Html import android.util.Base64 import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.browser.customtabs.CustomTabsIntent import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import com.pigeoff.rss.R import com.pigeoff.rss.activities.ReadActivity import com.pigeoff.rss.db.RSSDbItem import com.pigeoff.rss.util.ArticleExtended import com.pigeoff.rss.util.Util import com.prof.rssparser.Article import com.prof.rssparser.Image import com.squareup.picasso.Picasso import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.Exception import kotlin.reflect.typeOf class SwipeAdapter( private val context: Context, private val articles: MutableList<RSSDbItem>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { val URL_EXTRA: String = "urlextra" override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.adapter_swipe, parent, false)) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder::class == ViewHolder::class) { holder as ViewHolder val art = articles.get(position) Log.i("IMG Cover", art.mainImg) holder.imgCover.setImageDrawable(context.getDrawable(R.drawable.bg)) CoroutineScope(Dispatchers.IO).launch { if (art.mainImg.isNotEmpty()) { try { withContext(Dispatchers.Main) { Picasso.get().load(art.mainImg).into(holder.imgCover) } } catch (e: Exception) { } } } holder.favicon.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_feeds_white)) CoroutineScope(Dispatchers.IO).launch { if (art.link.isNotEmpty()) { try { val url = Util.getFaviconUrl(art.link) withContext(Dispatchers.Main) { articles[position].channelImageUrl = url Picasso.get().load(url).into(holder.favicon) } } catch (e: Exception) {} } } if (art.title.isNotEmpty()) { holder.title.text = art.title } else { holder.title.text = context.getString(R.string.article_no_title) } if (art.channelTitle.isNotEmpty()) { holder.source.visibility = View.VISIBLE holder.source.text = art.channelTitle } else { holder.source.visibility = View.GONE } if (art.description.isNotEmpty()) { holder.description.visibility = View.VISIBLE if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { holder.description.text = Html.fromHtml(art.description, Html.FROM_HTML_MODE_LEGACY) } else { holder.description.text = Html.fromHtml(art.description) } } else { holder.description.visibility = View.GONE } /* CARD ACTION */ holder.cardView.setOnClickListener { openUrl(art.link) } } } override fun getItemCount(): Int { return articles.count() } class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { val favicon = v.findViewById<ImageView>(R.id.feedFavicon) val imgCover = v.findViewById<ImageView>(R.id.imageView) val title = v.findViewById<TextView>(R.id.cdTitle) val source = v.findViewById<TextView>(R.id.cdSource) val description = v.findViewById<TextView>(R.id.cdDescription) val cardView = v.findViewById<CardView>(R.id.cardView) } private fun openUrl(url: String?) { if (!url.isNullOrEmpty()) { val intent = Intent(context.applicationContext, ReadActivity::class.java); intent.putExtra(URL_EXTRA, url) context.startActivity(intent) } else { Toast.makeText(context, R.string.error_no_url, Toast.LENGTH_SHORT).show() } } }
0
Kotlin
1
0
ecd1c3185e8682b7bdc677385a1b97e8c0c8ea88
4,906
Fox-RSS
Apache License 2.0
src/main/kotlin/kotlinmud/action/impl/admin/room/RoomDescriptionChange.kt
danielmunro
241,230,796
false
null
package kotlinmud.action.impl.admin.room import kotlinmud.action.builder.ActionBuilder import kotlinmud.action.model.Action import kotlinmud.action.type.Command import kotlinmud.io.factory.messageToActionCreator import kotlinmud.io.factory.roomChangeDescription import kotlinmud.io.type.Syntax import kotlinmud.mob.type.Role fun createRoomDescriptionChangeAction(): Action { return ActionBuilder(Command.ROOM_DESCRIPTION_CHANGE).also { it.syntax = roomChangeDescription() it.minimumRole = Role.Admin } build { val lineToChange = it.get<Int>(Syntax.VALUE) it.changeRoomDescription(it.getRoom().id, it.get(Syntax.FREE_FORM), lineToChange) it.createOkResponse(messageToActionCreator("room description changed at line $lineToChange")) } }
0
Kotlin
1
9
b7ee0d21ae813990896b1b8c6703da9bd1f1fc5b
789
kotlinmud
MIT License
Shudipto Trafder/Sticker Generator/app/src/main/java/com/example/myapplication/FinalActivity.kt
kkech
196,375,756
false
null
package com.example.myapplication import android.Manifest import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Build import android.os.Bundle import android.os.Environment import android.os.Environment.getExternalStoragePublicDirectory import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.core.graphics.drawable.toBitmap import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_final.* import kotlinx.android.synthetic.main.content_final.* import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.text.SimpleDateFormat import java.util.* class FinalActivity : AppCompatActivity() { private val code = 121 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_final) setSupportActionBar(toolbar) val data = intent.getStringExtra("Path") if (data == null){ textView2.text = "Something went wrong! please try again." } else{ process(data) } fab.setOnClickListener { save() } supportActionBar?.setDisplayHomeAsUpEnabled(true) } private fun save() { //check permission first if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), code) } else{ savePic() } } else savePic() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (requestCode == code){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { savePic() Timber.i("Permission Granted") } else{ Snackbar.make(finalLay, "Sorry you have to provide write permission.", Snackbar.LENGTH_SHORT).show() Timber.i("Permission Denied") } } } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } @Suppress("DEPRECATION") private fun savePic(){ val path = getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES ) Timber.i("File: ${path.path}") //due to lack of time use this process val date = Date() val ext = "${date.day}-${date.hours}-${date.minutes}" val name = "Sticker Generator $ext.png" val file = File(path.absolutePath, name) val stream = FileOutputStream(file) Timber.i("File: saved ${file.path}") try { val bit = imageView3.drawable.toBitmap() val pic = bit.compress(Bitmap.CompressFormat.PNG, 100, stream) if (pic){ Snackbar.make(finalLay, "File Saved at ${file.path}", Snackbar.LENGTH_LONG).show() } else{ Snackbar.make(finalLay, "Something went wrong. Try again!", Snackbar.LENGTH_SHORT).show() } } catch (e:Exception){ Timber.e(e) Snackbar.make(finalLay, "Something went wrong. Try again!", Snackbar.LENGTH_SHORT).show() } finally { stream.flush() stream.close() } } private fun process(path: String) { val file = File(path) Timber.i("Final path: ${file.path}") val arr:ByteArray = file.readBytes() Timber.i("Byte Array Length: ${arr.size}") val bitmap = BitmapFactory.decodeByteArray(arr, 0, arr.size) imageView3.setImageBitmap(bitmap) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> onBackPressed() } return super.onOptionsItemSelected(item) } }
11
Jupyter Notebook
195
25
e347e919e75ba62e2d56fabfe626cbee94378a15
4,305
UdacityOpenSource
Apache License 2.0
app/app/src/main/java/dev/kdrag0n/quicklock/ui/QrScanActivity.kt
kdrag0n
512,900,415
false
{"Kotlin": 127083, "JavaScript": 94229, "Rust": 88205, "TypeScript": 53751, "Java": 43766, "Shell": 4854, "HTML": 1777, "CSS": 930}
package dev.kdrag0n.quicklock.ui import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.util.Size import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.ExperimentalGetImage import androidx.camera.core.ImageAnalysis import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.core.content.ContextCompat import com.google.mlkit.vision.barcode.BarcodeScannerOptions import com.google.mlkit.vision.barcode.BarcodeScanning import com.google.mlkit.vision.barcode.common.Barcode import com.google.mlkit.vision.common.InputImage import dagger.hilt.android.AndroidEntryPoint import dev.kdrag0n.quicklock.R import dev.kdrag0n.quicklock.util.launchCollect import dev.kdrag0n.quicklock.util.launchStarted import java.util.concurrent.Executors @AndroidEntryPoint @ExperimentalGetImage class QrScanActivity : AppCompatActivity(R.layout.activity_qr_scan) { private val model: QrScanViewModel by viewModels() private val launcher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> if (granted) { startCamera() } else { finish() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { startCamera() } else { launcher.launch(Manifest.permission.CAMERA) } launchStarted { model.pairFinishedFlow.launchCollect(this) { finish() } model.confirmFlow.launchCollect(this) { startActivity(Intent(this@QrScanActivity, ConfirmDelegationActivity::class.java)) finish() } } } private fun startCamera() { val view = findViewById<PreviewView>(R.id.camera_view) val future = ProcessCameraProvider.getInstance(this) val options = BarcodeScannerOptions.Builder().run { setBarcodeFormats(Barcode.FORMAT_QR_CODE) build() } val scanner = BarcodeScanning.getClient(options) future.addListener({ val cameraProvider = future.get() val cameraSelector = CameraSelector.Builder().run { requireLensFacing(CameraSelector.LENS_FACING_BACK) build() } val preview = Preview.Builder().run { build() } preview.setSurfaceProvider(view.surfaceProvider) val executor = Executors.newSingleThreadExecutor() val imageAnalysis = ImageAnalysis.Builder().run { setTargetResolution(Size(1280, 720)) setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) build() } imageAnalysis.setAnalyzer(executor) { proxy -> proxy.image?.let { mediaImage -> val img = InputImage.fromMediaImage(mediaImage, proxy.imageInfo.rotationDegrees) scanner.process(img) .addOnSuccessListener { processBarcodes(it) } .addOnCompleteListener { proxy.close() } } } cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis) }, ContextCompat.getMainExecutor(this)) } private fun processBarcodes(barcodes: List<Barcode>) { for (code in barcodes) { code.rawValue?.let { model.onQrScanned(it) return } } } }
0
Kotlin
0
2
86297ee58e0a757a4542bca9efb1a4b8961d3f0c
4,021
quicklock
MIT License
attribution/src/main/java/com/affise/attribution/parameters/UuidProvider.kt
affise
496,592,599
false
null
package com.affise.attribution.parameters import com.affise.attribution.parameters.base.StringPropertyProvider import com.affise.attribution.utils.generateUUID /** * Provider for parameter [Parameters.UUID] */ class UuidProvider : StringPropertyProvider() { override fun provide(): String? = generateUUID().toString() }
0
Kotlin
0
3
ed6209e9eff536569c2ce618945365e63c9419fd
328
sdk-android
The Unlicense
src/main/java/com/sayzen/campfiresdk/controllers/notifications/chat/NotificationChatAnswerParser.kt
HorsePower68
230,018,763
true
{"Kotlin": 1489208}
package com.sayzen.campfiresdk.controllers.notifications.chat import android.content.Intent import com.dzen.campfire.api.models.chat.ChatTag import com.dzen.campfire.api.models.notifications.chat.NotificationChatAnswer import com.sayzen.campfiresdk.R import com.sayzen.campfiresdk.controllers.ControllerNotifications import com.sayzen.campfiresdk.controllers.ControllerSettings import com.sayzen.campfiresdk.screens.chat.SChat import com.sup.dev.android.app.SupAndroid import com.sup.dev.android.libs.screens.navigator.Navigator import com.sup.dev.android.tools.ToolsResources public class NotificationChatAnswerParser(override val n: NotificationChatAnswer) : ControllerNotifications.Parser(n) { override fun post(icon: Int, intent: Intent, text: String, title: String, tag: String, sound: Boolean) { val publication = n.publicationChatMessage val tagV = n.tag.asTag() (if (sound) ControllerNotifications.chanelChatMessages else ControllerNotifications.chanelChatMessages_salient).post(icon, publication.fandomName, text, intent, tagV) } override fun asString(html: Boolean): String { return if (n.publicationChatMessage.resourceId != 0L && n.publicationChatMessage.text.isEmpty()) n.publicationChatMessage.creatorName + ": " + ToolsResources.s(R.string.app_image) else if (n.publicationChatMessage.stickerId != 0L && n.publicationChatMessage.text.isEmpty()) n.publicationChatMessage.creatorName + ": " + ToolsResources.s(R.string.app_sticker) else n.publicationChatMessage.creatorName + ": " + n.publicationChatMessage.text } override fun canShow() = canShowNotificationChatAnswer(n) override fun doAction() { doActionNotificationChatAnswer(n) } private fun canShowNotificationChatAnswer(n: NotificationChatAnswer): Boolean { if (!ControllerSettings.notificationsChatAnswers) return false if (SupAndroid.activityIsVisible && Navigator.getCurrent() is SChat) { val screen = Navigator.getCurrent() as SChat return screen.tag != n.tag } else { return true } } private fun doActionNotificationChatAnswer(n: NotificationChatAnswer) { SChat.instance(ChatTag(n.publicationChatMessage.chatType, n.publicationChatMessage.fandomId, n.publicationChatMessage.languageId), n.publicationChatMessage.id, true, Navigator.TO) } }
0
null
0
0
214a4ee9262e185eb33a0ddcfc3a6803f22d54fd
2,401
CampfireSDK
Apache License 2.0
paradox-language-support/src/main/kotlin/com/windea/plugin/idea/paradox/script/refactoring/ParadoxScriptRefactoringSupportProvider.kt
fonata
320,514,128
true
{"Kotlin": 532553, "Lex": 41918, "HTML": 3712}
package com.windea.plugin.idea.paradox.script.refactoring import com.intellij.lang.refactoring.* import com.intellij.psi.* import com.windea.plugin.idea.paradox.localisation.psi.* import com.windea.plugin.idea.paradox.script.psi.* class ParadoxScriptRefactoringSupportProvider : RefactoringSupportProvider() { override fun isMemberInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean { return element is PsiNameIdentifierOwner } }
0
Kotlin
0
0
edf37fb29407701d65749e76a70f73ff55614461
459
Idea-Plugins
MIT License
paradox-language-support/src/main/kotlin/com/windea/plugin/idea/paradox/script/refactoring/ParadoxScriptRefactoringSupportProvider.kt
fonata
320,514,128
true
{"Kotlin": 532553, "Lex": 41918, "HTML": 3712}
package com.windea.plugin.idea.paradox.script.refactoring import com.intellij.lang.refactoring.* import com.intellij.psi.* import com.windea.plugin.idea.paradox.localisation.psi.* import com.windea.plugin.idea.paradox.script.psi.* class ParadoxScriptRefactoringSupportProvider : RefactoringSupportProvider() { override fun isMemberInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean { return element is PsiNameIdentifierOwner } }
0
Kotlin
0
0
edf37fb29407701d65749e76a70f73ff55614461
459
Idea-Plugins
MIT License
src/test/kotlin/info/jdavid/asynk/sql/ResultSetTests.kt
programingjd
122,729,739
false
null
package info.jdavid.asynk.sql import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ChannelIterator import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* class ResultSetTests { @Test fun testToCollection() { runBlocking { TestResultSet(channel(sequenceOf("a", "b", "c"))).apply { assertEquals("a,b,c", toList().joinToString(",")) assertFalse(iterate { it.hasNext() }) } TestResultSet(channel(sequenceOf("a", "b", "a", "c"))).apply { assertEquals("a,b,c", toCollection(LinkedHashSet()).joinToString(",")) assertFalse(iterate { it.hasNext() }) } } } @Test fun testAssociate() { runBlocking { TestResultSet(channel(sequenceOf("a", "b", "c"))).apply { assertEquals( "ka->va,kb->vb,kc->vc", associate { "k$it" to "v$it" }.map { "${it.key}->${it.value}" }.joinToString(",") ) assertFalse(iterate { it.hasNext() }) } TestResultSet(channel(sequenceOf("a", "b", "a", "c"))).apply { assertEquals( "A->a,B->b,C->c", associateBy { it.toUpperCase() }.map { "${it.key}->${it.value}" }.joinToString(",") ) assertFalse(iterate { it.hasNext() }) } TestResultSet(channel(sequenceOf("a", "b", "a", "c"))).apply { assertEquals( "ka->va,kb->vb,kc->vc", associateBy({ "k$it" }, { "v$it" }).map { "${it.key}->${it.value}" }.joinToString(",") ) assertFalse(iterate { it.hasNext() }) } } } @Test fun testFlapMap() { runBlocking { TestResultSet(channel(sequenceOf("abc", "def"))).let { rs -> assertEquals( "a,b,c,d,e,f", mutableListOf<String>().apply { rs.flatMapTo(this) { it.chunked(1).asSequence() } }.joinToString(",") ) assertFalse(rs.iterate { it.hasNext() }) } } } @Test fun testFold() { runBlocking { TestResultSet(channel(sequenceOf("abc", "def"))).apply { assertEquals( "abcdef", fold(StringBuilder()) { sb, it -> sb.append(it) }.toString() ) assertFalse(iterate { it.hasNext() }) } TestResultSet(channel(sequenceOf("a", "b", "c", "d", "e", "f"))).apply { assertEquals( "1a2b3c4d5e6f", foldIndexed(StringBuilder()) { i, sb, it -> sb.append(i+1).append(it) }.toString() ) assertFalse(iterate { it.hasNext() }) } } } @Test fun testForEach() { runBlocking { TestResultSet(channel(sequenceOf("abc", "def"))).apply { val sb = StringBuilder() forEach { sb.append(it) } assertEquals( "abcdef", sb.toString() ) assertFalse(iterate { it.hasNext() }) } TestResultSet(channel(sequenceOf("a", "b", "c", "d", "e", "f"))).apply { val sb = StringBuilder() forEachIndexed { i, it -> sb.append(i+1).append(it) } assertEquals( "1a2b3c4d5e6f", sb.toString() ) assertFalse(iterate { it.hasNext() }) } } } @Test fun testGroupBy() { runBlocking { TestResultSet(channel(sequenceOf("a1", "b2", "a3", "c4"))).apply { val groups = groupBy { it.chunked(1).first() } assertEquals(3, groups.size) groups["a"].let { assertNotNull(it) assertEquals(2, it?.size) assertEquals("a1", it?.first()) assertEquals("a3", it?.last()) } groups["b"].let { assertNotNull(it) assertEquals(1, it?.size) assertEquals("b2", it?.first()) } groups["c"].let { assertNotNull(it) assertEquals(1, it?.size) assertEquals("c4", it?.first()) } assertFalse(iterate { it.hasNext() }) } TestResultSet(channel(sequenceOf("a1", "b2", "a3", "c4"))).apply { val groups = groupBy({ it.chunked(1).first() }, { it.chunked(1).last() }) assertEquals(3, groups.size) groups["a"].let { assertNotNull(it) assertEquals(2, it?.size) assertEquals("1", it?.first()) assertEquals("3", it?.last()) } groups["b"].let { assertNotNull(it) assertEquals(1, it?.size) assertEquals("2", it?.first()) } groups["c"].let { assertNotNull(it) assertEquals(1, it?.size) assertEquals("4", it?.first()) } assertFalse(iterate { it.hasNext() }) } } } @Test fun testMap() { runBlocking { TestResultSet(channel(sequenceOf("abc", "def"))).apply { assertEquals( "ABCDEF", mapTo(mutableListOf()) { it.toUpperCase() }.joinToString("") ) assertFalse(iterate { it.hasNext() }) } TestResultSet(channel(sequenceOf("a", "b", "c", "d", "e", "f"))).apply { assertEquals( "1a2b3c4d5e6f", mapIndexedTo(mutableListOf()) { i, it -> "${i+1}$it" }.joinToString("") ) assertFalse(iterate { it.hasNext() }) } } } @Test fun testReduce() { runBlocking { TestResultSet(channel(sequenceOf("abc", "def"))).apply { assertEquals( "abcdef", reduce{ a, b -> a + b } ) assertFalse(iterate { it.hasNext() }) } TestResultSet(channel(sequenceOf("a", "b", "c", "d", "e", "f"))).apply { assertEquals( "a2b3c4d5e6f", reduceIndexed { i, a, b -> a + (i+1) + b } ) assertFalse(iterate { it.hasNext() }) } } } private suspend fun <T> channel(data: Sequence<T>): ReceiveChannel<T> = Channel<T>(Channel.UNLIMITED).apply { coroutineScope { data.forEach { send(it) delay(100) } close() } } class TestResultSet<T>(private val channel: ReceiveChannel<T>): Connection.ResultSet<T> { override suspend fun <R> iterate(block: suspend (ChannelIterator<T>) -> R): R { return block(channel.iterator()) } override suspend fun close() {} } }
0
Kotlin
0
0
2c2f70275d7de25d1f22fc9b17b035dc4eca6e8a
6,327
asynk_sql
Apache License 2.0
src/main/kotlin/br/com/project/key/Errors.kt
thiagohayacizup
407,656,384
true
{"Kotlin": 91388, "Shell": 665, "Dockerfile": 278}
package br.com.project.key import br.com.project.key.model.KeyResponseData import io.grpc.Status import io.grpc.StatusRuntimeException class Errors { companion object { val bodyBcbNotFound = KeyResponseData( error = Status .NOT_FOUND .withDescription("Response body bcb not found.") .asRuntimeException() ) val errorBcb = KeyResponseData( error = Status .INTERNAL .withDescription("Error registering key in BCB") .asRuntimeException() ) val bodyNotFoundERPItau = KeyResponseData( error = Status .NOT_FOUND .withDescription("Response body erp itau not found.") .asRuntimeException() ) val errorResponseERPItau = KeyResponseData( error = Status .NOT_FOUND .withDescription("Resource not found erp itau.") .asRuntimeException() ) fun errorConstraintViolation(message: String) : StatusRuntimeException = Status.INVALID_ARGUMENT .withDescription(message) .asRuntimeException() fun alredyExisteKeyValue( value : String ) = KeyResponseData( error = Status .ALREADY_EXISTS .withDescription("Key { $value } already exists.") .asRuntimeException() ) fun invalidKey( value : String ) = KeyResponseData( error = Status .INVALID_ARGUMENT .withDescription("Invalid key value { $value }") .asRuntimeException() ) } }
0
Kotlin
0
0
f921bf1bda2ccdce54aaf2c0ddd6f5e212806a5b
1,724
orange-talents-07-template-pix-keymanager-grpc
Apache License 2.0
android/src/main/java/com/example/android/presentation/home/HomeScreen.kt
DeNyWho
584,003,645
false
{"Kotlin": 511314}
package com.example.android.presentation.home import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.navigation.NavHostController import org.koin.androidx.compose.getViewModel @Composable fun HomeScreen( navController: NavHostController, viewModel: HomeViewModel = getViewModel (), modifier: Modifier = Modifier, ) { Box ( modifier = modifier.fillMaxSize() ) { Text("Здесь будет HomeScreen", modifier = Modifier.align(Alignment.Center)) } }
0
Kotlin
0
0
4388d4eb1f0c3e52929077ba3939b7f4124d1d5b
698
AniFoxKMP
Apache License 2.0