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
implementation/src/main/kotlin/pl/beone/promena/transformer/ocr/ocrmypdf/processor/parameter/RemoveBackgroundParameter.kt
BeOne-PL
235,078,020
false
null
package pl.beone.promena.transformer.ocr.ocrmypdf.processor.parameter import pl.beone.promena.transformer.contract.model.Parameters import pl.beone.promena.transformer.ocr.ocrmypdf.OcrMyPdfOcrTransformerDefaultParameters import pl.beone.promena.transformer.ocr.ocrmypdf.applicationmodel.getRemoveBackgroundOrNull import pl.beone.promena.transformer.ocr.ocrmypdf.processor.process.OcrMyPdfProcessParameterConstants.PARAMETER_REMOVE_BACKGROUND object RemoveBackgroundParameter : AbstractParameter() { override fun create(parameters: Parameters, defaultParameters: OcrMyPdfOcrTransformerDefaultParameters): List<String> = if (parameters.getRemoveBackgroundOrNull() ?: defaultParameters.removeBackground == true) { listOf(PARAMETER_REMOVE_BACKGROUND) } else { emptyList() } }
0
Kotlin
2
0
cf5812f23c52584e9a205e2f81b6842c6aeb9928
826
promena-transformer-ocr-ocrmypdf
Apache License 2.0
src/test/kotlin/de/hpi/dbs1/fixtures/Actors.kt
HPI-Information-Systems-Teaching
815,821,182
false
{"Kotlin": 12913, "Java": 11210}
package de.hpi.dbs1.fixtures import de.hpi.dbs1.entities.Actor object Actors { @JvmField val ANNE_HATHAWAY = Actor("nm0004266", "<NAME>").apply { playedIn.addAll( listOf( "Mothers' Instinct", "The Idea of You", "She Came to Me", "Armageddon Time", "Locked Down", ) ) costarNameToCount.putAll( mapOf( "<NAME>" to 3, "<NAME>" to 3, "<NAME>" to 2, "<NAME>" to 2, "<NAME>" to 2, ) ) } @JvmField val MORGAN_FREEMAN = Actor("nm0000151", "<NAME>").apply { playedIn.addAll( listOf( "My Dead Friend Zoe", "57 Seconds", "A Good Person", "The Ritual Killer", "Paradise Highway", ) ) costarNameToCount.putAll( mapOf( "<NAME>" to 5, "<NAME>" to 4, "<NAME>" to 4, "<NAME>" to 3, "<NAME>" to 3, ) ) } @JvmField val FREEMAN_WOOD = Actor("nm0939706", "Freeman Wood") @JvmField val KATHLEEN_FREEMAN = Actor("nm0293466", "Kathleen Freeman") @JvmField val HOWARD_FREEMAN = Actor("nm0293418", "<NAME>") @JvmField val MONA_FREEMAN = Actor("nm0293530", "<NAME>reeman") }
0
Kotlin
1
0
a0111cfda35304fd33c0159f20c529da656ada0f
1,487
DBS-I-2024
MIT License
acrarium/src/main/kotlin/com/faendir/acra/ui/view/app/tabs/ReportAppTab.kt
F43nd1r
91,593,043
false
null
/* * (C) Copyright 2017-2023 Lukas Morawietz (https://github.com/F43nd1r) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.faendir.acra.ui.view.app.tabs import com.faendir.acra.navigation.RouteParams import com.faendir.acra.navigation.View import com.faendir.acra.persistence.report.ReportRepository import com.faendir.acra.ui.component.ReportList import com.faendir.acra.ui.view.app.AppView import com.vaadin.flow.component.Composite import com.vaadin.flow.router.Route @View @Route(value = "report", layout = AppView::class) class ReportAppTab( private val reportListFactory: ReportList.Factory, private val routeParams: RouteParams, ) : Composite<ReportList>() { override fun initContent() = reportListFactory.create(routeParams.appId(), ReportRepository::getProvider) }
7
null
51
200
31576a37d2c1eb61bb1d2641d7b214c87ce23fe1
1,314
Acrarium
Apache License 2.0
datasource-recipes-network/src/main/java/pl/smcebi/recipeme/recipes/network/RecipesNetworkModule.kt
Seba0855
616,026,534
false
{"Kotlin": 89067}
package pl.smcebi.recipeme.recipes.network import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import pl.smcebi.recipeme.datasource.common.Mock import pl.smcebi.recipeme.recipes.RecipesDataSource @Module @InstallIn(SingletonComponent::class) internal interface RecipesNetworkModule { @Binds fun bindDataSource(impl: RecipesNetworkDataSource): RecipesDataSource @Binds @Mock fun bindMockDataSource(impl: MockRecipesDataSource): RecipesDataSource }
0
Kotlin
0
0
04a9966a50929063f3f85c2c270c91ce3133575e
538
recipe.me
Apache License 2.0
eco-core/core-backend/src/main/kotlin/com/willfp/eco/internal/items/ArgParserColor.kt
Auxilor
325,856,799
false
{"Kotlin": 784230, "Java": 740080}
package com.willfp.eco.internal.items import com.willfp.eco.core.items.args.LookupArgParser import org.bukkit.Color import org.bukkit.inventory.ItemStack import org.bukkit.inventory.meta.ItemMeta import org.bukkit.inventory.meta.LeatherArmorMeta import java.util.function.Predicate object ArgParserColor : LookupArgParser { override fun parseArguments(args: Array<out String>, meta: ItemMeta): Predicate<ItemStack>? { if (meta !is LeatherArmorMeta) { return null } var color: String? = null for (arg in args) { val argSplit = arg.split(":") if (!argSplit[0].equals("color", ignoreCase = true)) { continue } if (argSplit.size < 2) { continue } color = argSplit[1].replace("#","") } color ?: return null meta.setColor(Color.fromRGB(Integer.parseInt(color, 16))) return Predicate { val testMeta = it.itemMeta as? LeatherArmorMeta ?: return@Predicate false color.equals( Integer.toHexString(testMeta.color.red) + Integer.toHexString(testMeta.color.green) + Integer.toHexString(testMeta.color.blue), ignoreCase = true ) } } override fun serializeBack(meta: ItemMeta): String? { if (meta !is LeatherArmorMeta) { return null } return "color:#${Integer.toHexString(meta.color.asRGB())}" } }
83
Kotlin
53
156
81de46a1c122a3cd6be06696b5b02d55fd9a73e5
1,548
eco
MIT License
src/jvmMain/kotlin/util/NativeEventUtil.kt
flben233
680,857,766
false
{"Kotlin": 83989, "Java": 135}
package util import com.github.kwhat.jnativehook.NativeInputEvent sealed class NativeEventUtil { companion object Default: NativeEventUtil() fun consumeEvent(nativeInputEvent: NativeInputEvent?) { if (nativeInputEvent == null) { return } try { val field = NativeInputEvent::class.java.getDeclaredField("reserved") field.isAccessible = true field.setShort(nativeInputEvent, (0x01).toShort()) } catch (e: Exception) { LoggerUtil.logStackTrace(e) } } }
2
Kotlin
1
64
ba35ca7e2102241537ffad65afab5144ae2f6fa0
564
TyuShare
Apache License 2.0
java/dzjforex/src/main/kotlin/com/jforex/dzjforex/zorro/ZorroConstants.kt
juxeii
81,964,776
false
null
package com.jforex.dzjforex.zorro const val LOGIN_OK = 1 const val LOGIN_FAIL = 0 const val LOGOUT_OK = 0 const val SUBSCRIBE_OK = 1 const val SUBSCRIBE_FAIL = 0 const val ASSET_AVAILABLE = 1 const val ASSET_UNAVAILABLE = 0 const val CONNECTION_LOST_NEW_LOGIN_REQUIRED = 0 const val CONNECTION_OK_BUT_MARKET_CLOSED = 1 const val CONNECTION_OK_BUT_TRADING_NOT_ALLOWED = 1 const val CONNECTION_OK = 2 const val ACCOUNT_UNAVAILABLE = 0 const val ACCOUNT_AVAILABLE = 1 const val BROKER_BUY_FAIL = 0 const val BROKER_BUY_FILL_TIMEOUT = 0 const val BROKER_BUY_NO_RESPONSE = -2 const val BROKER_BUY_OPPOSITE_CLOSE = 1 const val BROKER_SELL_FAIL = 0 const val BROKER_ORDER_NOT_YET_FILLED = 0 const val BROKER_TRADE_FAIL = 0 const val BROKER_HISTORY_UNAVAILABLE = 0 const val BROKER_ADJUST_SL_FAIL = 0 const val BROKER_ADJUST_SL_OK = 1 const val heartBeatIndication = 1 const val demoLoginType = "Demo" const val realLoginType = "Real" const val lotScale = 1000000.0 const val fillTimeout = 30L const val tickPeriod = 0 const val BROKER_COMMAND_OK = 1.0 const val BROKER_COMMAND_ERROR = 0.0
1
C++
6
8
9894a872441fd38d2e2b42029941f72c7d30ea52
1,093
dztools
MIT License
client-dynamodb-v2/src/main/kotlin/app/cash/backfila/client/dynamodbv2/internal/DynamoDbBackfillOperator.kt
cashapp
209,384,085
false
null
package app.cash.backfila.client.dynamodbv2.internal import app.cash.backfila.client.dynamodbv2.DynamoDbBackfill import app.cash.backfila.client.spi.BackfilaParametersOperator import app.cash.backfila.client.spi.BackfillOperator import app.cash.backfila.protos.clientservice.GetNextBatchRangeRequest import app.cash.backfila.protos.clientservice.GetNextBatchRangeResponse import app.cash.backfila.protos.clientservice.KeyRange import app.cash.backfila.protos.clientservice.PrepareBackfillRequest import app.cash.backfila.protos.clientservice.PrepareBackfillResponse import app.cash.backfila.protos.clientservice.RunBatchRequest import app.cash.backfila.protos.clientservice.RunBatchResponse import com.google.common.base.Stopwatch import java.time.Duration import software.amazon.awssdk.services.dynamodb.DynamoDbClient import software.amazon.awssdk.services.dynamodb.model.AttributeValue import software.amazon.awssdk.services.dynamodb.model.BillingMode import software.amazon.awssdk.services.dynamodb.model.ScanRequest class DynamoDbBackfillOperator<I : Any, P : Any>( private val dynamoDbClient: DynamoDbClient, override val backfill: DynamoDbBackfill<I, P>, private val parametersOperator: BackfilaParametersOperator<P>, private val keyRangeCodec: DynamoDbKeyRangeCodec, ) : BackfillOperator { override fun name(): String = backfill.javaClass.toString() override fun prepareBackfill(request: PrepareBackfillRequest): PrepareBackfillResponse { val config = parametersOperator.constructBackfillConfig(request) backfill.validate(config) var table = dynamoDbClient.describeTable { it.tableName(backfill.dynamoDbTable.tableName()) }.table() if (backfill.mustHaveProvisionedBillingMode()) { var billingModeSummary = table.billingModeSummary() // It's odd but a null billingModeSummary implies "PROVISIONED" require( billingModeSummary == null || billingModeSummary.billingMode() == BillingMode.PROVISIONED, ) { "Trying to prepare a backfill on a Dynamo table named ${backfill.dynamoDbTable.tableName()} " + "with a billing mode that is not PROVISIONED, it is " + "${backfill.dynamoDbTable.tableName()}. This can get very expensive. " + "Please provision your dynamo capacity for this table and try again." } } val partitionCount = backfill.partitionCount(config) // We will assume the batch size is the default of 100. We are aiming for a batch per segment. val desiredSegmentCount = (table.itemCount() / 100L).coerceIn(partitionCount.toLong(), 524288L) val defaultSegmentCount = desiredSegmentCount.takeHighestOneBit().toInt() // closest power of 2 val segmentCount = backfill.fixedSegmentCount(config) ?: defaultSegmentCount require( partitionCount in 1..segmentCount && Integer.bitCount(partitionCount) == 1 && Integer.bitCount(segmentCount) == 1, ) { "partitionCount and segmentCount must be positive powers of 2, and segmentCount must be " + "greater than partitionCount (partitionCount=$partitionCount, segmentCount=$segmentCount)" } val segmentsPerPartition = segmentCount / partitionCount val partitions = mutableListOf<PrepareBackfillResponse.Partition>() for (i in 0 until partitionCount) { val segmentStartInclusive = i * segmentsPerPartition val segmentEndExclusive = (i + 1) * segmentsPerPartition partitions += PrepareBackfillResponse.Partition.Builder() .partition_name("$i of $partitionCount") .backfill_range( keyRangeCodec.encodeKeyRange( segmentStartInclusive, segmentEndExclusive, segmentCount, ), ) .build() } return PrepareBackfillResponse.Builder() .partitions(partitions) .build() } override fun getNextBatchRange(request: GetNextBatchRangeRequest): GetNextBatchRangeResponse { var (start, end, count) = keyRangeCodec.decodeKeyRange(request.backfill_range) // If this isn't the first batch range, start where we last left off. if (request.previous_end_key != null) { val segmentData = keyRangeCodec.decodeSegment(request.previous_end_key) require(segmentData.count == count) // Segment count cannot change. require(segmentData.lastEvaluatedKey == null) // No partial batches until a batch is running. start = segmentData.offset } val batches = mutableListOf<GetNextBatchRangeResponse.Batch>() for (i in start until minOf(start + 1, end)) { batches += GetNextBatchRangeResponse.Batch.Builder() .batch_range(keyRangeCodec.encodeKeyRange(i, i + 1, count)) // In order to keep costs down we do not perform any queries here for an accurate count. We // may consider adding that feature at a later date. .matching_record_count(1L) .scanned_record_count(1L) .build() } return GetNextBatchRangeResponse.Builder() .batches(batches) .build() } override fun runBatch(request: RunBatchRequest): RunBatchResponse { val keyRange = keyRangeCodec.decodeKeyRange(request.batch_range) require(keyRange.end == keyRange.start + 1) val config = parametersOperator.constructBackfillConfig(request) var lastEvaluatedKey: Map<String, AttributeValue>? = keyRange.lastEvaluatedKey val stopwatch = Stopwatch.createStarted() do { val scanRequest = ScanRequest.builder() .tableName(backfill.dynamoDbTable.tableName()) .segment(keyRange.start) .totalSegments(keyRange.count) .limit(request.batch_size.toInt()) .let { if (lastEvaluatedKey != null && lastEvaluatedKey!!.isNotEmpty()) { it.exclusiveStartKey(lastEvaluatedKey) } else { it } } .filterExpression(backfill.filterExpression(config)) .expressionAttributeValues(backfill.expressionAttributeValues(config)) .expressionAttributeNames(backfill.expressionAttributeNames(config)) .build() val result = dynamoDbClient.scan(scanRequest) backfill.runBatch( result.items().map { backfill.dynamoDbTable.tableSchema().mapToItem(it) }, config, ) lastEvaluatedKey = result.lastEvaluatedKey() if (stopwatch.elapsed() > Duration.ofMillis(1_000L)) { break } } while (lastEvaluatedKey != null && lastEvaluatedKey.isNotEmpty()) return RunBatchResponse.Builder() .let { if (lastEvaluatedKey != null && lastEvaluatedKey.isNotEmpty()) { it.remaining_batch_range(lastEvaluatedKey.toKeyRange(keyRange)) } else { it.remaining_batch_range(null) } } .build() } private fun Map<String, AttributeValue>.toKeyRange(originalRange: DynamoDbKeyRange): KeyRange { require(originalRange.start + 1 == originalRange.end) return keyRangeCodec.encodeKeyRange( originalRange.start, originalRange.end, originalRange.count, this, ) } }
50
null
47
31
983c74b0516ef2cee75a8774dc3b233fdf641dc1
7,080
backfila
Apache License 2.0
src/main/kotlin/io/github/cgglyle/bean/BeanDefinition.kt
cgglyle
730,541,788
false
{"Kotlin": 19977}
package io.github.cgglyle.bean class BeanDefinition( val type: Class<*>, // 提供默认值 val scope: BeanScope = BeanScope.SINGLETON, ){ val propertyValues: MutableList<PropertyValue> = mutableListOf() fun setProperty(name: String, value: Any) { propertyValues.add(PropertyValue(name, value)) } }
0
Kotlin
0
0
db0ef0ab584713c7c5440dad1c8c8e0414898ecc
322
kotlin-spring
Apache License 2.0
plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/res/IDEAndroidLayoutXmlFileManager.kt
gigliovale
89,726,097
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.android.synthetic.idea.res import com.android.builder.model.SourceProvider import com.android.tools.idea.gradle.AndroidGradleModel import com.intellij.openapi.module.Module import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.impl.PsiTreeChangePreprocessor import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import org.jetbrains.android.facet.AndroidFacet import org.jetbrains.kotlin.android.synthetic.AndroidConst.SYNTHETIC_PACKAGE_PATH_LENGTH import org.jetbrains.kotlin.android.synthetic.idea.AndroidPsiTreeChangePreprocessor import org.jetbrains.kotlin.android.synthetic.idea.AndroidXmlVisitor import org.jetbrains.kotlin.android.synthetic.res.* import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe class IDEAndroidLayoutXmlFileManager(val module: Module) : AndroidLayoutXmlFileManager(module.project) { override val androidModule: AndroidModule? get() = module.androidFacet?.toAndroidModuleInfo() @Volatile private var _moduleData: CachedValue<AndroidModuleData>? = null override fun getModuleData(): AndroidModuleData { if (androidModule == null) { _moduleData = null } else { if (_moduleData == null) { _moduleData = cachedValue(project) { CachedValueProvider.Result.create(super.getModuleData(), getPsiTreeChangePreprocessor()) } } } return _moduleData?.value ?: AndroidModuleData.EMPTY } private fun getPsiTreeChangePreprocessor(): PsiTreeChangePreprocessor { return project.getExtensions(PsiTreeChangePreprocessor.EP_NAME).first { it is AndroidPsiTreeChangePreprocessor } } override fun doExtractResources(files: List<PsiFile>, module: ModuleDescriptor): List<AndroidResource> { val widgets = arrayListOf<AndroidResource>() val visitor = AndroidXmlVisitor { id, widgetType, attribute -> widgets += parseAndroidResource(id, widgetType, attribute.valueElement) } files.forEach { it.accept(visitor) } return widgets } override fun propertyToXmlAttributes(propertyDescriptor: PropertyDescriptor): List<PsiElement> { val fqPath = propertyDescriptor.fqNameUnsafe.pathSegments() if (fqPath.size <= SYNTHETIC_PACKAGE_PATH_LENGTH) return listOf() fun handle(variantData: AndroidVariantData, defaultVariant: Boolean = false): List<PsiElement>? { val layoutNamePosition = SYNTHETIC_PACKAGE_PATH_LENGTH + (if (defaultVariant) 0 else 1) val layoutName = fqPath[layoutNamePosition].asString() val layoutFiles = variantData[layoutName] ?: return null if (layoutFiles.isEmpty()) return null val propertyName = propertyDescriptor.name.asString() val attributes = arrayListOf<PsiElement>() val visitor = AndroidXmlVisitor { retId, wClass, valueElement -> if (retId == propertyName) attributes.add(valueElement) } layoutFiles.forEach { it.accept(visitor) } return attributes } for (variantData in getModuleData()) { if (variantData.variant.isMainVariant && fqPath.size == SYNTHETIC_PACKAGE_PATH_LENGTH + 2) { handle(variantData, true)?.let { return it } } else if (fqPath[SYNTHETIC_PACKAGE_PATH_LENGTH].asString() == variantData.variant.name) { handle(variantData)?.let { return it } } } return listOf() } private val Module.androidFacet: AndroidFacet? get() = AndroidFacet.getInstance(this) private fun SourceProvider.toVariant() = AndroidVariant(name, resDirectories.map { it.absolutePath }) private fun AndroidFacet.toAndroidModuleInfo(): AndroidModule? { val applicationPackage = manifest?.`package`?.toString() if (applicationPackage != null) { val mainVariant = mainSourceProvider.toVariant() val method = try { javaClass.getMethod("getFlavorSourceProviders") } catch (e: NoSuchMethodException) { null } val variants: List<AndroidVariant>? = if (method != null) { val sourceProviders = method.invoke(this) as List<SourceProvider>? sourceProviders?.map { it.toVariant() } ?: listOf() } else { val model = AndroidGradleModel.get(module) model?.flavorSourceProviders?.map { it.toVariant() } } if (variants != null) { return AndroidModule(applicationPackage, listOf(mainVariant) + variants) } } return null } }
1
null
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
5,504
kotlin
Apache License 2.0
hermit-core/src/main/kotlin/hermit/test/internal/LazyResetsImpl.kt
RBusarow
262,948,697
false
{"Kotlin": 83045, "SCSS": 3085, "Shell": 1859}
/* * Copyright (C) 2021-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 hermit.test.internal import hermit.test.LazyResets import hermit.test.ResetManager import kotlinx.coroutines.runBlocking /** * Lazy instance which can be reset. After a reset, the next access will create a new instance. * * Each time a new instance is created, it is registered with the * [ResetManager] and will be reset with the next [ResetManager.resetAll]. * * @sample samples.LazyResetsSample.lazyResetClassSample */ internal class LazyResetsImpl<out T : Any>( private val resetManager: ResetManager, private val valueFactory: suspend () -> T ) : LazyResets<T> { private var lazyHolder: Lazy<T> = createLazy() override val value: T get() = lazyHolder.value override fun isInitialized(): Boolean = lazyHolder.isInitialized() private fun createLazy() = lazy { resetManager.register(this) runBlocking { valueFactory() } } override fun reset() { lazyHolder = createLazy() } }
12
Kotlin
2
0
b5ff7d941cc72b19a1ea0a1833598f91b079cc37
1,531
Hermit
Apache License 2.0
app/src/main/java/com/devallannascimento/agendebem/fragments/AgendamentosFragment.kt
devallannascimento
745,705,769
false
{"Kotlin": 46837}
package com.devallannascimento.agendebem.fragments import ConsultasAdapter import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.devallannascimento.agendebem.MainActivity.Companion.TAG import com.devallannascimento.agendebem.databinding.FragmentAgendamentosBinding import com.devallannascimento.agendebem.model.Consulta import com.devallannascimento.agendebem.utils.exibirMensagem import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore class AgendamentosFragment : Fragment() { private var agendamentosBinding: FragmentAgendamentosBinding? = null private val binding get() = this.agendamentosBinding!! private val consultasAdapter = ConsultasAdapter() private val firebaseAuth by lazy { FirebaseAuth.getInstance() } private val idUsuario = firebaseAuth.currentUser?.uid private val firebaseFirestore by lazy { FirebaseFirestore.getInstance() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { this.agendamentosBinding = FragmentAgendamentosBinding.inflate(inflater, container, false) recuperarConsultas() return this.binding.root } private fun recuperarConsultas() { firebaseFirestore .collection("usuarios") .document(idUsuario!!) .collection("consultas") .get() .addOnSuccessListener { querySnapshot -> val consultasList = mutableListOf<Consulta>() querySnapshot.documents.forEach { document -> // Converter documento para objeto Consulta val id = document.id val especialidade = document.getString("especialidade") ?: "" val medico = document.getString("medico") ?: "" val crm = document.getString("crm") ?: "" val data = document.getString("data") ?: "" val hora = document.getString("hora") ?: "" val valor = document.getString("valor") ?: "" val disponivel = document.getString("disponivel") ?: "" val consulta = Consulta(id, especialidade, medico, crm, data, hora, valor, disponivel) if (disponivel == "true") { consultasList.add(consulta) } } inicializarRecyclerView(consultasList) } } private fun inicializarRecyclerView(consultasList: List<Consulta>) { val recyclerView: RecyclerView = binding.recyclerViewConsultas if (consultasList.isEmpty()) { binding.textHistoricoVazio.visibility = View.VISIBLE recyclerView.visibility = View.GONE } else { val layoutManager = LinearLayoutManager(requireContext()) recyclerView.layoutManager = layoutManager recyclerView.adapter = consultasAdapter consultasAdapter.atualizarConsultas(consultasList) recyclerView.addOnItemTouchListener( object : RecyclerView.OnItemTouchListener { override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {} override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean { val child = rv.findChildViewUnder(e.x, e.y) if (child != null && e.action == MotionEvent.ACTION_UP) { val position = rv.getChildAdapterPosition(child) exibirDialogoConfirmacao(position) } return false } override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {} } ) } } private fun exibirDialogoConfirmacao(position: Int) { val consultaSelecionada = consultasAdapter.getConsulta(position) val id = consultaSelecionada.id val especialidade = consultaSelecionada.especialidade val medico = consultaSelecionada.medico val crm = consultaSelecionada.crm val data = consultaSelecionada.data val hora = consultaSelecionada.hora val valor = consultaSelecionada.valor consultaSelecionada.disponivel val consulta = Consulta( id, especialidade, medico, crm, data, hora, valor, "true" ) AlertDialog.Builder(requireContext()) .setTitle("Deseja cancelar a consulta?") .setMessage("\nConfirmar o cancelamento da consulta de $especialidade para o dia:\n\n$data às $hora?") .setPositiveButton("Sim") { _, _ -> recuperarConsultas() cancelarConsulta(consulta) } .setNegativeButton("Não") { _, _ -> // Lógica para lidar com o não } .create().show() } private fun cancelarConsulta(consulta: Consulta) { firebaseFirestore .collection("consultas") .document(consulta.id) .update("disponivel", "true") .addOnSuccessListener { firebaseFirestore .collection("usuarios") .document(idUsuario!!) .collection("consultas") .document(consulta.id) .delete() recuperarConsultas() exibirMensagem("Consulta cancelada") } } }
0
Kotlin
0
0
67a1bc1b6d49392ec29b5bc5bc46d593b79e4536
6,120
App-AgendeBem
Apache License 2.0
entityconverter/src/main/java/com/androidkotlincore/entityconverter/ConvertersContext.kt
i-petro
119,085,966
false
null
package com.androidkotlincore.entityconverter import kotlin.reflect.KFunction3 /** * Context of converters interface. */ interface ConvertersContext { /** * Registers converter between two entity classes * * @param inClass input class - abstract as possible * @param outClass output class - concrete as possible * @param converter convert function reference * * Sample: * convertersContext.registerConverter(UserRest::class.java, UserDb::class.java, this::restToDb) * private fun restToDb(rest: UserRest, token: Any?, convertersContext: ConvertersContext): UserDb {...} */ fun <IN : Any, OUT : Any> registerConverter( inClass: Class<IN>, outClass: Class<OUT>, converter: KFunction3< @ParameterName(name = "input") IN, @ParameterName(name = "token") Any?, @ParameterName(name = "convertersContext") ConvertersContext, OUT>) /** * Registers converter between two entity classes * * @param inClass input class - abstract as possible * @param outClass output class - concrete as possible * @param converter convert function reference */ fun <IN : Any, OUT : Any> registerConverter( inClass: Class<IN>, outClass: Class<OUT>, converter: (IN, Any?, ConvertersContext) -> OUT) { registerConverter(inClass, outClass, converter::invoke) } /** * Convert single object to another type. * * @param input some object * @param token token that will be passed in [ConvertersContext.convert] method. * @param outClass class of type you want convert object to * @return converted object */ fun <IN : Any, OUT : Any> convert(input: IN, token: Any?, outClass: Class<OUT>): OUT fun <IN : Any, OUT : Any> convert(input: IN, outClass: Class<OUT>): OUT = convert(input, Unit, outClass) /** * Convert collection of objects to another type. * * @param collection collection of objects * @param token token that will be passed in [ConvertersContext.convert] method. * @param outClass class of type you want convert collection to * @return collection of converted objects */ fun <IN : Any, OUT : Any> convertCollection(collection: Iterable<IN>, token: Any?, outClass: Class<OUT>): List<OUT> fun <IN : Any, OUT : Any> convertCollection(collection: Iterable<IN>, outClass: Class<OUT>): List<OUT> = convertCollection(collection, Unit, outClass) /** * Returns converter as a function * * @param outClass output class * @param <IN> type of input object * @param <OUT> type of output object * @return converted object with type OUT */ fun <IN : Any, OUT : Any> convertFunc(outClass: Class<OUT>): (input: IN) -> OUT = { convert(it, outClass) } fun <IN : Any, OUT : Any> convertFunc(outClass: Class<OUT>, token: Any?): (input: IN) -> OUT = { convert(it, token, outClass) } /** * Returns converter as a function * * @param outClass output class * @param <IN> type of input objects * @param <OUT> type of output objects * @return converted list of objects with type OUT */ fun <IN : Any, OUT : Any> convertCollectionFunc(outClass: Class<OUT>): (input: Iterable<IN>) -> List<OUT> = { convertCollection(it, outClass) } }
1
Kotlin
1
5
3f98be9b7e93e806ea014daaf5ee640887adaa62
3,511
AndroidKotlinCore
MIT License
app/src/main/java/com/zp/zfile_manager/super_/SuperActivity.kt
zippo88888888
281,615,129
false
null
package com.zp.zfile_manager.super_ import android.app.ProgressDialog import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.zp.z_file.async.ZFileStipulateAsync import com.zp.z_file.content.* import com.zp.z_file.dsl.result import com.zp.zfile_manager.R import com.zp.zfile_manager.content.Content import com.zp.zfile_manager.content.Content.FILTER import com.zp.zfile_manager.content.Content.QQ_MAP import com.zp.zfile_manager.content.Content.TITLES import com.zp.zfile_manager.diy.MyQWFileListener import com.zp.zfile_manager.diy.SunActivity import kotlinx.android.synthetic.main.activity_super.* class SuperActivity : AppCompatActivity() { private var dialog: ProgressDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_super) dialog = ProgressDialog(this).run { setMessage("获取中,请稍后...") setCancelable(false) this } super_picTxt.setOnClickListener { showDialog(arrayOf(PNG, JPEG, JPG, GIF)) } super_videoTxt.setOnClickListener { showDialog(arrayOf(MP4, _3GP)) } super_audioTxt.setOnClickListener { showDialog(arrayOf(MP3, AAC, WAV, M4A)) } super_fileTxt.setOnClickListener { showDialog(arrayOf(TXT, JSON, XML)) } super_wpsTxt.setOnClickListener { showDialog(arrayOf(DOC, DOCX, XLS, XLSX, PPT, PPTX, PDF)) } super_apkTxt.setOnClickListener { showDialog(arrayOf("apk")) } super_qqTxt.setOnClickListener { toQW(ZFileConfiguration.QQ) } super_wechatTxt.setOnClickListener { toQW(ZFileConfiguration.WECHAT) } super_otherTxt.setOnClickListener { Toast.makeText(this, "我只是一个占位格,好看的", Toast.LENGTH_SHORT).show() startActivity(Intent(this, SunActivity::class.java)) } super_group.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.super_diyRadio -> { getZFileHelp().setQWFileLoadListener(MyQWFileListener()) } else -> { getZFileHelp().setQWFileLoadListener(null) } } } super_innerTxt.setOnClickListener { getZFileHelp().setConfiguration(getZFileConfig().apply { needLongClick = false isOnlyFolder = true sortordBy = ZFileConfiguration.BY_NAME sortord = ZFileConfiguration.ASC authority = Content.AUTHORITY }).result(this) { setResultData(this) } } } private fun toQW(path: String) { Log.e("ZFileManager", "请注意:QQ、微信目前只能获取用户手动保存到手机里面的文件," + "且保存文件到手机的目录用户没有修改") Log.i("ZFileManager", "参考自腾讯自己的\"腾讯文件\"App,能力有限,部分文件无法获取") jump(path) } private fun jump(path: String) { getZFileHelp().setConfiguration(getZFileConfig().apply { boxStyle = ZFileConfiguration.STYLE2 filePath = path authority = Content.AUTHORITY if (path == ZFileConfiguration.QQ) { // 打开QQ, 模拟自定义获取 qwData = ZFileQWData().apply { titles = TITLES filterArrayMap = FILTER qqFilePathArrayMap = QQ_MAP } } else { qwData = ZFileQWData() } }).result(this) { setResultData(this) } } private fun showDialog(filterArray: Array<String>) { dialog?.show() ZFileStipulateAsync(this) { dialog?.dismiss() if (isNullOrEmpty()) { Toast.makeText(this@SuperActivity, "暂无数据", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@SuperActivity, "共找到${this?.size}条数据", Toast.LENGTH_SHORT).show() Log.i("ZFileManager", "共找到${this?.size}条数据") if (this!!.size > 100) { Log.e("ZFileManager", "这里考虑到传值大小限制,截取前100条数据") SuperDialog.newInstance(changeList(this)) .show(supportFragmentManager, "SuperDialog") } else { SuperDialog.newInstance(this as ArrayList<ZFileBean>) .show(supportFragmentManager, "SuperDialog") } } }.start(filterArray) } private fun changeList(oldList: MutableList<ZFileBean>): ArrayList<ZFileBean> { val list = ArrayList<ZFileBean>() var index = 1 oldList.forEach forEach@{ if (index >= 100) { return@forEach } list.add(it) index++ } return list } private fun setResultData(list: MutableList<ZFileBean>?) { val sb = StringBuilder() list?.forEach { sb.append(it).append("\n\n") } super_resultTxt.text = sb.toString() } override fun onDestroy() { super.onDestroy() // 这里重置,防止该页面销毁后其他演示页面无法正常获取数据! getZFileHelp().resetAll() } }
1
null
13
72
ad9c45a74fbfe4475bfd39adbfea3e0b417c2180
5,406
ZFileManager
Apache License 2.0
komapper-core/src/main/kotlin/org/komapper/core/dsl/context/EntityUpsertContext.kt
komapper
349,909,214
false
{"Kotlin": 2922039, "Java": 57131}
package org.komapper.core.dsl.context import org.komapper.core.ThreadSafe import org.komapper.core.dsl.element.Returning import org.komapper.core.dsl.expression.AssignmentDeclaration import org.komapper.core.dsl.expression.TableExpression import org.komapper.core.dsl.expression.WhereDeclaration import org.komapper.core.dsl.metamodel.EntityMetamodel import org.komapper.core.dsl.metamodel.PropertyMetamodel import org.komapper.core.dsl.options.InsertOptions import org.komapper.core.dsl.options.WhereOptions @ThreadSafe data class EntityUpsertContext<ENTITY : Any, ID : Any, META : EntityMetamodel<ENTITY, ID, META>>( val insertContext: EntityInsertContext<ENTITY, ID, META>, val target: META, val excluded: META = target.newMetamodel( table = "excluded", catalog = "", schema = "", alwaysQuote = false, disableSequenceAssignment = false, declaration = {}, ), val keys: List<PropertyMetamodel<ENTITY, *, *>> = emptyList(), val conflictTarget: String? = null, val duplicateKeyType: DuplicateKeyType, val set: AssignmentDeclaration<ENTITY, META> = {}, val where: WhereDeclaration = {}, override val returning: Returning = Returning.Expressions(emptyList()), ) : WhereProvider, TablesProvider, ReturningProvider { override val options: WhereOptions get() = insertContext.options override fun getTables(): Set<TableExpression<*>> { return setOf(target) } override fun getCompositeWhere(): WhereDeclaration { return where } internal fun copyConfigure(configure: (InsertOptions) -> InsertOptions): EntityUpsertContext<ENTITY, ID, META> { val options = configure(this.insertContext.options) val insertContext = this.insertContext.copy(options = options) return this.copy(insertContext = insertContext) } } enum class DuplicateKeyType { UPDATE, IGNORE }
8
Kotlin
14
301
9fbc0b5652ee732583e977180cdc493e116e1022
1,922
komapper
Apache License 2.0
app/src/main/java/io/aayush/relabs/network/data/node/Node.kt
theimpulson
679,298,392
false
{"Kotlin": 195396}
package io.aayush.relabs.network.data.node import com.squareup.moshi.JsonClass import io.aayush.relabs.network.adapter.singletoarray.SingleToArray @JsonClass(generateAdapter = true) data class Node( val depth: Int = 0, val description: String = String(), val display_order: Int = 0, val id: Int = 0, val kind: Kind = Kind.FORUM, val lft: Int = 0, val node_data: NodeData = NodeData(), @SingleToArray val node_type_data: List<NodeTypeData> = emptyList(), val breadcrumb_data: Map<Int, Breadcrumb> = emptyMap(), val rgt: Int = 0, val title: String = String(), val xda: XDA = XDA() )
0
Kotlin
6
160
f7b2829540d9bf9e34e0e13d7d120bffb9ca9354
631
ReLabs
Apache License 2.0
app/src/main/java/com/hm/users/remote/UserAPI.kt
himanim93
570,360,703
false
{"Kotlin": 19365}
package com.hm.users.remote import com.hm.users.data.model.UserDetails import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Query interface UserAPI { @Headers("Accept: application/vnd.github.+json") @GET("search/users") suspend fun getUserList(@Query("q") query: String, @Query("page") page: Int, @Query("per_page") pageSize: Int): Response<UserDetails> }
0
Kotlin
0
0
e7980402211f42f214d6ebf60d194154a2dbb48d
476
Kotlin-Hilt-MVVM-Retrofit-Flow
Apache License 2.0
app/src/main/java/com/aposiamp/smartliving/presentation/mapper/SettingsItemUiMapper.kt
ApostolisSiampanis
783,913,411
false
{"Kotlin": 490999}
package com.aposiamp.smartliving.presentation.mapper import com.aposiamp.smartliving.R import com.aposiamp.smartliving.domain.model.SettingsItemData import com.aposiamp.smartliving.presentation.model.SettingsItemUiModel import com.aposiamp.smartliving.presentation.ui.activity.main.navigation.MainDestination object SettingsItemUiMapper { private fun toUiModel(domain: SettingsItemData): SettingsItemUiModel { val titleResId = when (domain.title) { "Profile" -> R.string.profile "Account" -> R.string.account else -> 0 } val icon = when (domain.title) { "Profile" -> R.drawable.profile "Account" -> R.drawable.account_box else -> null } val route = when (domain.title) { "Profile" -> MainDestination.Profile.route "Account" -> MainDestination.Account.route else -> null } return SettingsItemUiModel( titleResId = titleResId, icon = icon, route = route ) } fun List<SettingsItemData>.toUiModelList(): List<SettingsItemUiModel> { return this.map { toUiModel(it) } } }
0
Kotlin
0
3
8184e402e0121dba16a08675395184bd5413f20f
1,203
Smart_Living
MIT License
identity/src/main/java/com/stripe/android/identity/networking/models/VerificationPageStaticContentTextPage.kt
stripe
6,926,049
false
null
package com.stripe.android.identity.networking.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class VerificationPageStaticContentTextPage( @SerialName("body") val body: String, @SerialName("button_text") val buttonText: String, @SerialName("title") val title: String )
64
Kotlin
522
935
bec4fc5f45b5401a98a310f7ebe5d383693936ea
366
stripe-android
MIT License
testerum-backend/testerum-runner/testerum-runner-cmdline/src/main/kotlin/com/testerum/runner_cmdline/cmdline/params/exception/CmdlineParamsParserException.kt
testerum
241,460,788
false
null
package com.testerum.runner_cmdline.cmdline.params.exception class CmdlineParamsParserException : RuntimeException { constructor(message: String) : super(message) constructor(message: String, cause: Throwable) : super(message, cause) }
33
null
3
22
0a53c71b5f659e41282114127f595aad5ab1e4fb
248
testerum
Apache License 2.0
newsapp-main/newsapp-main/NewsAppStarter/app/src/main/java/daniellopes/io/newsappstarter/util/state/local/ArticleListState.kt
juliocarvalho2019
650,383,020
false
null
package daniellopes.io.newsappstarter.util.state.local import daniellopes.io.newsappstarter.data.local.model.Article sealed class ArticleListState { data class Success(val list: List<Article>) : ArticleListState() data class ErrorMessage(val errorMessage: String) : ArticleListState() object Loading : ArticleListState() object Empty : ArticleListState() }
0
Kotlin
0
0
b79d0948394ea5506ab9afde59e86bfdbeea80de
374
News-App-Starter-MVVM
Apache License 2.0
smithy-swift-codegen/src/test/kotlin/software/amazon/smithy/swift/codegen/protocolspecificserde/xml/EnumDecodeXMLGenerationTests.kt
smithy-lang
242,852,561
false
{"Kotlin": 1077492, "Swift": 1046003, "Smithy": 121646, "Shell": 1807, "Objective-C": 136}
package software.amazon.smithy.swift.codegen.protocolspecificserde.xml /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ import io.kotest.matchers.string.shouldContainOnlyOnce import org.junit.jupiter.api.Test import software.amazon.smithy.swift.codegen.getFileContents class EnumDecodeXMLGenerationTests { @Test fun `decode enum`() { val context = setupTests("Isolated/Restxml/xml-enums.smithy", "aws.protocoltests.restxml#RestXml") val contents = getFileContents(context.manifest, "Sources/RestXml/models/XmlEnumsOutput+HttpResponseBinding.swift") val expectedContents = """ extension XmlEnumsOutput { static func httpOutput(from httpResponse: SmithyHTTPAPI.HTTPResponse) async throws -> XmlEnumsOutput { let data = try await httpResponse.data() let responseReader = try SmithyXML.Reader.from(data: data) let reader = responseReader var value = XmlEnumsOutput() value.fooEnum1 = try reader["fooEnum1"].readIfPresent() value.fooEnum2 = try reader["fooEnum2"].readIfPresent() value.fooEnum3 = try reader["fooEnum3"].readIfPresent() value.fooEnumList = try reader["fooEnumList"].readListIfPresent(memberReadingClosure: SmithyReadWrite.ReadingClosureBox<RestXmlProtocolClientTypes.FooEnum>().read(from:), memberNodeInfo: "member", isFlattened: false) return value } } """ contents.shouldContainOnlyOnce(expectedContents) } @Test fun `decode enum nested`() { val context = setupTests("Isolated/Restxml/xml-enums.smithy", "aws.protocoltests.restxml#RestXml") val contents = getFileContents(context.manifest, "Sources/RestXml/models/XmlEnumsNestedOutput+HttpResponseBinding.swift") val expectedContents = """ extension XmlEnumsNestedOutput { static func httpOutput(from httpResponse: SmithyHTTPAPI.HTTPResponse) async throws -> XmlEnumsNestedOutput { let data = try await httpResponse.data() let responseReader = try SmithyXML.Reader.from(data: data) let reader = responseReader var value = XmlEnumsNestedOutput() value.nestedEnumsList = try reader["nestedEnumsList"].readListIfPresent(memberReadingClosure: SmithyReadWrite.listReadingClosure(memberReadingClosure: SmithyReadWrite.ReadingClosureBox<RestXmlProtocolClientTypes.FooEnum>().read(from:), memberNodeInfo: "member", isFlattened: false), memberNodeInfo: "member", isFlattened: false) return value } } """ contents.shouldContainOnlyOnce(expectedContents) } }
7
Kotlin
29
28
0de17918831a547e04e86a9c306491b536ada934
2,610
smithy-swift
Apache License 2.0
ui/src/main/java/com/jeanbarrossilva/period/ui/fragment/ChemicalElementsFragment.kt
jeanbarrossilva
365,115,291
false
null
package com.jeanbarrossilva.period.ui.fragment import android.animation.ValueAnimator import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.Toolbar import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResult import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.callbacks.onDismiss import com.afollestad.materialdialogs.list.listItemsSingleChoice import com.jeanbarrossilva.period.extensions.activity.fab import com.jeanbarrossilva.period.extensions.activity.toolbar import com.jeanbarrossilva.period.extensions.animator.doOnEnd import com.jeanbarrossilva.period.extensions.context.dialog import com.jeanbarrossilva.period.extensions.context.isInLandscape import com.jeanbarrossilva.period.extensions.filter.clear import com.jeanbarrossilva.period.extensions.number.dp import com.jeanbarrossilva.period.extensions.valueanimator.addUpdateListener import com.jeanbarrossilva.period.extensions.view.updatePadding import com.jeanbarrossilva.period.extensions.viewmodelprovider.viewModelFactory import com.jeanbarrossilva.period.model.ChemicalElement import com.jeanbarrossilva.period.model.ChemicalElementSortingOption import com.jeanbarrossilva.period.ui.R import com.jeanbarrossilva.period.ui.activity.core.SearchActivity import com.jeanbarrossilva.period.ui.adapter.ChemicalElementAdapter import com.jeanbarrossilva.period.ui.listener.OnSearchEventListener import com.jeanbarrossilva.period.ui.viewmodel.ChemicalElementsViewModel class ChemicalElementsFragment: Fragment(R.layout.fragment_chemical_elements) { private val Toolbar.searchItem get() = menu.findItem(R.id.menu_item_search) private val viewModel by viewModels<ChemicalElementsViewModel> { viewModelFactory(context) } private var didRequestSortingDialog = false private var didClickOnSomeElement = false private lateinit var elementsView: RecyclerView private fun assignViews(view: View) { elementsView = view.findViewById(R.id.elements_view) } private fun configToolbar() { activity?.toolbar?.menu?.clear() activity?.toolbar?.inflateMenu(R.menu.menu_main_toolbar) activity?.toolbar?.searchItem?.setOnMenuItemClickListener { (activity as? SearchActivity)?.onSearchEvent(isSearching = true) true } } private fun configFab() { context?.let { context -> val sortingOptionTitles = ChemicalElementSortingOption.values(context).map { sortingOption -> sortingOption.title } activity?.fab?.setImageResource(R.drawable.ic_round_filter_alt_24) activity?.fab?.setOnClickListener { didRequestSortingDialog = true if (!didClickOnSomeElement) context.dialog { title(R.string.MaterialDialog_title_sort) onDismiss { didRequestSortingDialog = false } listItemsSingleChoice(items = sortingOptionTitles, initialSelection = ChemicalElementSortingOption.getPreferredIndex(context)) { _, index, _ -> val selectedSortingOption = ChemicalElementSortingOption.values(context)[index] viewModel.setSortingOption(selectedSortingOption) dismiss() } } } activity?.fab?.show() } } private fun configSearchIconVisibility() { (activity as? SearchActivity)?.addOnSearchEventListener { isSearching -> activity?.toolbar?.searchItem?.isVisible = !isSearching } } private fun configElementSearch(adapter: ChemicalElementAdapter) { (activity as? SearchActivity)?.run { addOnQueryChangeListener { query -> adapter.filter.filter(query) } addOnSearchEventListener { isSearching -> if (!isSearching) adapter.filter.clear() } } } private fun onElementClick(element: ChemicalElement) { if (!didRequestSortingDialog) { didClickOnSomeElement = true (activity as? SearchActivity)?.onSearchEvent(isSearching = false) findNavController().navigate(ChemicalElementsFragmentDirections.toDetailsOf(element)).also { viewModel.getSortingOption().value?.let { sortingOption -> setFragmentResult("sortingOption", bundleOf("sortingOption" to sortingOption)) } } } } private fun showElements() { viewModel.getSortingOption().observe(viewLifecycleOwner) { sortingOption -> elementsView.adapter = ChemicalElementAdapter(sortingOption, ::onElementClick).also(::configElementSearch) elementsView.layoutManager = if (context?.isInLandscape == true) GridLayoutManager(context, 2) else LinearLayoutManager(context) } } private fun listenToSortingOption() { viewModel.getSortingOption().observe(viewLifecycleOwner) { sortingOption -> context?.let { ChemicalElementSortingOption.prefer(it, sortingOption) } } } @Suppress("Recycle") private fun freeUpSpaceForBoxOnSearchEvent() { (activity as? SearchActivity)?.addOnSearchEventListener(OnSearchEventListener { isSearching -> val finalPaddingTop = if (isSearching) 100.dp(context) else 0 ValueAnimator .ofInt(elementsView.paddingTop, finalPaddingTop) .addUpdateListener<Int> { elementsView.updatePadding(top = it) } .doOnEnd { if (isSearching && elementsView.computeVerticalScrollOffset() <= 3000) elementsView.smoothScrollToPosition(0) } .start() }) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = super.onCreateView(inflater, container, savedInstanceState)?.also { view -> assignViews(view) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) configSearchIconVisibility() showElements() listenToSortingOption() freeUpSpaceForBoxOnSearchEvent() } override fun onResume() { super.onResume() didClickOnSomeElement = false configToolbar() configFab() } }
1
Kotlin
0
0
a59f9bdaec84b91bc45ce90b6da996cf4ccd5c53
6,988
Period
MIT License
vedtak/application/src/main/kotlin/no/nav/su/se/bakover/vedtak/application/FerdigstillVedtakService.kt
navikt
227,366,088
false
{"Kotlin": 9668820, "Shell": 4372, "TSQL": 1233, "Dockerfile": 1209}
package no.nav.su.se.bakover.vedtak.application import arrow.core.Either import arrow.core.getOrElse import arrow.core.left import arrow.core.right import behandling.domain.BehandlingMedOppgave import behandling.domain.Stønadsbehandling import dokument.domain.Dokument import dokument.domain.brev.BrevService import no.nav.su.se.bakover.common.domain.oppgave.OppgaveId import no.nav.su.se.bakover.common.persistence.TransactionContext import no.nav.su.se.bakover.domain.oppgave.OppdaterOppgaveInfo import no.nav.su.se.bakover.domain.oppgave.OppgaveService import no.nav.su.se.bakover.domain.vedtak.KunneIkkeFerdigstilleVedtak import no.nav.su.se.bakover.domain.vedtak.KunneIkkeFerdigstilleVedtakMedUtbetaling import no.nav.su.se.bakover.domain.vedtak.brev.lagDokumentKommando import no.nav.su.se.bakover.oppgave.domain.KunneIkkeLukkeOppgave import org.slf4j.LoggerFactory import satser.domain.SatsFactory import vedtak.domain.VedtakSomKanRevurderes import økonomi.domain.utbetaling.Utbetaling import java.time.Clock import java.util.UUID interface FerdigstillVedtakService { fun ferdigstillVedtakEtterUtbetaling( utbetaling: Utbetaling.OversendtUtbetaling.MedKvittering, transactionContext: TransactionContext? = null, ): Either<KunneIkkeFerdigstilleVedtakMedUtbetaling, Unit> fun ferdigstillVedtak( vedtakId: UUID, ): Either<KunneIkkeFerdigstilleVedtak, VedtakSomKanRevurderes> /** * TODO jah: Brukes kun av IverksettSøknadsbehandlingServiceImpl, flytt dit? */ fun lukkOppgaveMedBruker( behandling: Stønadsbehandling, tilordnetRessurs: OppdaterOppgaveInfo.TilordnetRessurs, ): Either<KunneIkkeLukkeOppgave, Unit> } class FerdigstillVedtakServiceImpl( private val brevService: BrevService, private val oppgaveService: OppgaveService, private val vedtakService: VedtakService, private val clock: Clock, private val satsFactory: SatsFactory, ) : FerdigstillVedtakService { private val log = LoggerFactory.getLogger(this::class.java) /** Laget spesifikt for [økonomi.application.kvittering.FerdigstillVedtakEtterMottattKvitteringKonsument] */ override fun ferdigstillVedtakEtterUtbetaling( utbetaling: Utbetaling.OversendtUtbetaling.MedKvittering, transactionContext: TransactionContext?, ): Either<KunneIkkeFerdigstilleVedtakMedUtbetaling, Unit> { return if (utbetaling.trengerIkkeFerdigstilles()) { // Merk at vi heller ikke prøver lukke oppgaver her. Det går fint så lenge vi ikke oppretter oppgaver for stans/gjenopptak. log.info("Utbetaling ${utbetaling.id} trenger ikke ferdigstilles.") Unit.right() } else { if (!utbetaling.kvittering.erKvittertOk()) { log.error("Prøver ikke å ferdigstille innvilgelse siden kvitteringen fra oppdrag ikke var OK.") Unit.right() } else { log.info("Ferdigstiller vedtak etter utbetaling") val vedtak = vedtakService.hentForUtbetaling(utbetaling.id, transactionContext) ?: return KunneIkkeFerdigstilleVedtakMedUtbetaling.FantIkkeVedtakForUtbetalingId(utbetaling.id) .left().also { log.error("Kunne ikke ferdigstille vedtak - fant ikke vedtaket som tilhører utbetaling ${utbetaling.id}.") } return ferdigstillVedtak(vedtak, transactionContext).map { Unit } } } } override fun ferdigstillVedtak( vedtakId: UUID, ): Either<KunneIkkeFerdigstilleVedtak, VedtakSomKanRevurderes> { return vedtakService.hentForVedtakId(vedtakId)!!.let { vedtak -> vedtak as VedtakSomKanRevurderes ferdigstillVedtak(vedtak, null).onLeft { log.error( "Kunne ikke ferdigstille vedtak ${vedtak.id}: $it", RuntimeException("Trigger stacktrace for enklere debugging"), ) }.map { log.info("Ferdigstilte vedtak ${vedtak.id}") vedtak } } } override fun lukkOppgaveMedBruker( behandling: Stønadsbehandling, tilordnetRessurs: OppdaterOppgaveInfo.TilordnetRessurs, ): Either<KunneIkkeLukkeOppgave, Unit> { return lukkOppgaveIntern(behandling) { oppgaveService.lukkOppgave(it, tilordnetRessurs).map { } }.map { /* Unit */ } } private fun Utbetaling.trengerIkkeFerdigstilles(): Boolean { return erStans() || erReaktivering() } private fun ferdigstillVedtak( vedtak: VedtakSomKanRevurderes, transactionContext: TransactionContext?, ): Either<KunneIkkeFerdigstilleVedtak, VedtakFerdigstilt> { val tilordnetRessurs = OppdaterOppgaveInfo.TilordnetRessurs.NavIdent(vedtak.attestant.navIdent) // Denne fungerer også som dedup. Dersom vi allerede har lagret et dokument knyttet til vedtaket vil denne gi false. return if (vedtak.skalGenerereDokumentVedFerdigstillelse()) { val dokument = lagreDokument(vedtak, transactionContext).getOrElse { return it.left() } lukkOppgaveMedSystembruker(vedtak.behandling, tilordnetRessurs).fold( { VedtakFerdigstilt.DokumentLagret.KunneIkkeLukkeOppgave(dokument, it.oppgaveId).right() }, { oppgaveId -> if (oppgaveId != null) { VedtakFerdigstilt.DokumentLagret.OppgaveLukket(dokument, oppgaveId).right() } else { VedtakFerdigstilt.DokumentLagret.SkalIkkeLukkeOppgave(dokument).right() } }, ) } else { // I disse tilfellene skal det ikke sendes brev, men vi prøver likevel å lukke oppgaven, dersom det finnes en. lukkOppgaveMedSystembruker(vedtak.behandling, tilordnetRessurs).fold( { VedtakFerdigstilt.DokumentSkalIkkeLagres.KunneIkkeLukkeOppgave(it.oppgaveId).right() }, { oppgaveId -> if (oppgaveId != null) { VedtakFerdigstilt.DokumentSkalIkkeLagres.OppgaveLukket(oppgaveId).right() } else { VedtakFerdigstilt.DokumentSkalIkkeLagres.SkalIkkeLukkeOppgave.right() } }, ) } } private fun lagreDokument( vedtak: VedtakSomKanRevurderes, transactionContext: TransactionContext?, ): Either<KunneIkkeFerdigstilleVedtak, Dokument.MedMetadata> { return brevService.lagDokument(vedtak.lagDokumentKommando(clock, satsFactory)).mapLeft { KunneIkkeFerdigstilleVedtak.KunneIkkeGenerereBrev(it) }.map { val dokumentMedMetadata: Dokument.MedMetadata = it.leggTilMetadata( metadata = Dokument.Metadata( sakId = vedtak.behandling.sakId, søknadId = null, vedtakId = vedtak.id, revurderingId = null, ), ) brevService.lagreDokument(dokumentMedMetadata, transactionContext) dokumentMedMetadata } } /** * @return null dersom behandlingen ikke har oppgave som skal lukkes. */ private fun lukkOppgaveMedSystembruker( behandling: Stønadsbehandling, tilordnetRessurs: OppdaterOppgaveInfo.TilordnetRessurs, ): Either<KunneIkkeLukkeOppgave, OppgaveId?> { return lukkOppgaveIntern(behandling) { oppgaveService.lukkOppgaveMedSystembruker(it, tilordnetRessurs).map { it.oppgaveId } } } /** * @return null dersom behandlingen ikke har oppgave som skal lukkes. */ private fun lukkOppgaveIntern( behandling: Stønadsbehandling, lukkOppgave: (oppgaveId: OppgaveId) -> Either<KunneIkkeLukkeOppgave, Unit>, ): Either<KunneIkkeLukkeOppgave, OppgaveId?> { val oppgaveId = if (behandling is BehandlingMedOppgave) { behandling.oppgaveId } else { return null.right() } return lukkOppgave(oppgaveId).onLeft { log.error("Kunne ikke lukke oppgave: $oppgaveId for behandling: ${behandling.id}") }.map { log.info("Lukket oppgave: $oppgaveId for behandling: ${behandling.id}") oppgaveId } } } /** * Inneholder kun de positive utfallene (Right). * I alle tilfeller vil dokument være lagret (dersom vi skal sende brev) */ sealed interface VedtakFerdigstilt { val dokument: Dokument.MedMetadata? val oppgaveId: OppgaveId? sealed interface DokumentLagret : VedtakFerdigstilt { override val dokument: Dokument.MedMetadata data class OppgaveLukket( override val dokument: Dokument.MedMetadata, override val oppgaveId: OppgaveId, ) : DokumentLagret data class SkalIkkeLukkeOppgave( override val dokument: Dokument.MedMetadata, ) : DokumentLagret { override val oppgaveId = null } data class KunneIkkeLukkeOppgave( override val dokument: Dokument.MedMetadata, override val oppgaveId: OppgaveId, ) : DokumentLagret } sealed interface DokumentSkalIkkeLagres : VedtakFerdigstilt { override val dokument: Dokument.MedMetadata? get() = null data class OppgaveLukket( override val oppgaveId: OppgaveId, ) : DokumentSkalIkkeLagres data object SkalIkkeLukkeOppgave : DokumentSkalIkkeLagres { override val oppgaveId = null } data class KunneIkkeLukkeOppgave( override val oppgaveId: OppgaveId, ) : DokumentSkalIkkeLagres } }
9
Kotlin
1
1
9e72c3086109f9c58472b169f86b213f929a91f1
9,929
su-se-bakover
MIT License
app/src/main/java/com/gaurav/pokemon/data/model/pokemon/TypeX.kt
gau4sar
400,800,306
false
null
package com.gaurav.pokemon.data.model.pokemon data class TypeX( val name: String, val url: String )
0
Kotlin
0
1
a6beb5f981bf33972b4af80c30f92040756eb2f9
109
Pokemon-android
Apache License 2.0
library/src/main/kotlin/org/quiltmc/qkl/library/serialization/internal/util/DataUtil.kt
QuiltMC
501,458,402
false
null
/* * Copyright 2023 The Quilt Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.quiltmc.qkl.library.serialization.internal.util import com.mojang.serialization.DataResult import com.mojang.serialization.DynamicOps import com.mojang.serialization.JsonOps import net.minecraft.util.dynamic.ForwardingDynamicOps import org.quiltmc.qkl.library.mixin.serialization.ForwardingDynamicOpsAccessor import org.quiltmc.qkl.library.serialization.ExtendedDynamicOps import org.quiltmc.qkl.library.serialization.internal.DefaultingExtendedOps import org.quiltmc.qkl.library.serialization.internal.ExtendedJsonOps @Suppress("UNCHECKED_CAST") internal tailrec fun <T : Any> DynamicOps<T>.getExtendedWithDefault(): ExtendedDynamicOps<T> { return when (this) { is ExtendedDynamicOps<*> -> DefaultingExtendedOps(this, this as ExtendedDynamicOps<T>) is JsonOps -> ExtendedJsonOps as ExtendedDynamicOps<T> is ForwardingDynamicOps<*> -> (this as ForwardingDynamicOpsAccessor<T>).delegate.getExtendedWithDefault() else -> DefaultingExtendedOps(this) } } internal fun <R> DataResult<R>.unwrap(): R { return getOrThrow(false) {} } internal fun <R> DataResult<R>.orNull(): R? { return result().orElse(null) } internal fun <T> DynamicOps<T>.getPrimitiveAsString(value: T): String? { getStringValue(value).orNull()?.let { return it } getNumberValue(value).orNull()?.let { return it.toString() } getBooleanValue(value).orNull()?.let { return it.toString() } return null }
17
null
9
52
e79adf890d4d6092b96d0fde1fce89c9155f4f78
2,088
quilt-kotlin-libraries
Apache License 2.0
app/src/main/java/vtsen/hashnode/dev/workmanagerdemo/workers/DemoWorker.kt
vinchamp77
535,182,142
false
{"Kotlin": 14505}
package vtsen.hashnode.dev.workmanagerdemo.workers import android.Manifest import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat.getSystemService import androidx.work.CoroutineWorker import androidx.work.ForegroundInfo import androidx.work.WorkerParameters import kotlinx.coroutines.delay import vtsen.hashnode.dev.workmanagerdemo.R import vtsen.hashnode.dev.workmanagerdemo.ui.MainActivity import kotlin.properties.Delegates //Note: a new worker is created everytime when it runs class DemoWorker( private val appContext: Context, params: WorkerParameters ) : CoroutineWorker(appContext, params) { private val notificationChannelId = "DemoNotificationChannelId" override suspend fun doWork(): Result { delay(5000) Log.d("DemoWorker", "do work done!") if (ActivityCompat.checkSelfPermission( appContext, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED ) { with(NotificationManagerCompat.from(applicationContext)) { notify(0, createNotification()) } } return Result.success() } override suspend fun getForegroundInfo(): ForegroundInfo { return ForegroundInfo( 0, createNotification() ) } private fun createNotification() : Notification { createNotificationChannel() val mainActivityIntent = Intent( applicationContext, MainActivity::class.java) var pendingIntentFlag by Delegates.notNull<Int>() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { pendingIntentFlag = PendingIntent.FLAG_IMMUTABLE } else { pendingIntentFlag = PendingIntent.FLAG_UPDATE_CURRENT } val mainActivityPendingIntent = PendingIntent.getActivity( applicationContext, 0, mainActivityIntent, pendingIntentFlag) return NotificationCompat.Builder( applicationContext, notificationChannelId ) .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle(applicationContext.getString(R.string.app_name)) .setContentText("Work Request Done!") .setContentIntent(mainActivityPendingIntent) .setAutoCancel(true) .build() } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationChannel = NotificationChannel( notificationChannelId, "DemoWorker", NotificationManager.IMPORTANCE_DEFAULT, ) val notificationManager: NotificationManager? = getSystemService( applicationContext, NotificationManager::class.java) notificationManager?.createNotificationChannel( notificationChannel ) } } }
0
Kotlin
0
6
1e693cf2ef3c77cb238179108516ab9986894e4a
3,447
Demo_WorkManager
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/sendlegalmailtoprisonsapi/prisonersearch/PrisonerSearchRequest.kt
ministryofjustice
424,655,284
false
{"Kotlin": 401563, "Shell": 4020, "JavaScript": 2567, "Dockerfile": 1276}
package uk.gov.justice.digital.hmpps.sendlegalmailtoprisonsapi.prisonersearch import uk.gov.justice.digital.hmpps.sendlegalmailtoprisonsapi.barcode.BarcodeRecipient import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.stream.Collectors data class PrisonerSearchRequest( val prisonNumber: String? = null, val firstName: String?, val lastName: String, val dob: LocalDate? = null ) { constructor(barcodeRecipient: BarcodeRecipient) : this( barcodeRecipient.prisonNumber, barcodeRecipient.names.first, barcodeRecipient.names.second, barcodeRecipient.dob ) fun toMatchPrisonersRequestBody(): Map<String, String?> = mapOf( "nomsNumber" to prisonNumber, "firstName" to firstName, "lastName" to lastName, "dateOfBirth" to dob?.format(DateTimeFormatter.ISO_LOCAL_DATE) ) fun toGlobalSearchRequestBody(): Map<String, String?> = mapOf( "prisonerIdentifier" to prisonNumber, "firstName" to firstName, "lastName" to lastName, "dateOfBirth" to dob?.format(DateTimeFormatter.ISO_LOCAL_DATE), "includeAliases" to "true" ) } private val BarcodeRecipient.names: Pair<String?, String> get() = name.split(" ") .let { if (it.size > 1) { it[0] to it.stream().skip(1).collect(Collectors.joining(" ")) } else { null to it.stream().collect(Collectors.joining(" ")) } }
4
Kotlin
0
4
38fe19d5f932abcf793be93a52690d674370518f
1,428
send-legal-mail-to-prisons-api
MIT License
libraries/stdlib/src/org/jetbrains/kotlin/support/AsserterLoader.kt
chirino
3,596,099
true
null
package org.jetbrains.kotlin.support fun loadAsserter(): Unit { val c = javaClass<Runnable>() println("class is $c") }
0
Java
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
127
kotlin
Apache License 2.0
src/commonMain/kotlin/com/cout970/matrix/api/IMutableMatrix2.kt
cout970
184,434,403
false
null
package com.cout970.matrix.api /** * Created by cout970 on 24/08/2016. */ interface IMutableMatrix2 : IMatrix2 { override var m00: Number override var m01: Number override var m10: Number override var m11: Number // Int override var m00i: Int get() = m00.toInt(); set(i) { m00 = i} override var m01i: Int get() = m01.toInt(); set(i) { m00 = i} override var m10i: Int get() = m10.toInt(); set(i) { m00 = i} override var m11i: Int get() = m11.toInt(); set(i) { m00 = i} // Float override var m00f: Float get() = m00.toFloat(); set(i) { m00 = i} override var m01f: Float get() = m01.toFloat(); set(i) { m00 = i} override var m10f: Float get() = m10.toFloat(); set(i) { m00 = i} override var m11f: Float get() = m11.toFloat(); set(i) { m00 = i} // Double override var m00d: Double get() = m00.toDouble(); set(i) { m00 = i} override var m01d: Double get() = m01.toDouble(); set(i) { m00 = i} override var m10d: Double get() = m10.toDouble(); set(i) { m00 = i} override var m11d: Double get() = m11.toDouble(); set(i) { m00 = i} }
0
Kotlin
0
0
eba022378e4e3a2582b749adf1673f7489891d8b
1,114
MultiplatformMatrixLib
MIT License
compiler/testData/codegen/box/coroutines/localFunctions/named/withArguments.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND_FIR: JVM_IR // WITH_RUNTIME // WITH_COROUTINES // COMMON_COROUTINES_TEST import helpers.* import COROUTINES_PACKAGE.* import COROUTINES_PACKAGE.intrinsics.* suspend fun callLocal(a: String, b: String): String { suspend fun local(a: String, b: String) = suspendCoroutineUninterceptedOrReturn<String> { it.resume(a + b) COROUTINE_SUSPENDED } return local(a, b) } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var res = "FAIL" builder { res = callLocal("O", "K") } return res }
12
null
37
83
4383335168338df9bbbe2a63cb213a68d0858104
602
kotlin
Apache License 2.0
app/src/main/java/dev/rupeshdeshmukh/locsationapp/network/service/MovieApiService.kt
rupesh0608
798,421,935
false
{"Kotlin": 12780}
package dev.rupeshdeshmukh.locsationapp.network.service import dev.rupeshdeshmukh.locsationapp.constant.Constant.API_KEY import dev.rupeshdeshmukh.locsationapp.network.data.MovieResponse import retrofit2.Call import retrofit2.http.GET interface MovieApiService { @GET("movie/popular?api_key=$API_KEY") fun getMovies(): Call<MovieResponse> }
0
Kotlin
0
0
db41cd30b64cca8333c81b8f4ca0c58b6764a969
350
LocationApp
MIT License
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/Border.kt
facebook
80,179,724
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.widget import android.graphics.Path import android.graphics.PathDashPathEffect import androidx.annotation.ColorInt import com.facebook.litho.Border import com.facebook.litho.Dimen import com.facebook.litho.ResourceResolver import com.facebook.litho.ResourcesScope import com.facebook.yoga.YogaEdge /** * Creates a border style to be applied to a component * * @param edgeAll sets the props for all edges. * * @param edgeHorizontal customises both horizontal edges. * @param edgeVertical customises both vertical edges. * @param edgeStart customises the start edge, from top to bottom. * @param edgeEnd customises end edge, from top to bottom. * * @param edgeTop customises the top edge of the border. * @param edgeBottom customises the bottom edge of the border. * @param edgeLeft customises the left edge of the border. * @param edgeRight customises for the right edge of the border. * * @param radius customises each corner radius. * * @param effect applies an effect to the border. */ inline fun ResourcesScope.Border( // separate edge properties edgeAll: BorderEdge? = null, // misc edgeHorizontal: BorderEdge? = null, edgeVertical: BorderEdge? = null, edgeStart: BorderEdge? = null, edgeEnd: BorderEdge? = null, // standard edges edgeTop: BorderEdge? = null, edgeBottom: BorderEdge? = null, edgeLeft: BorderEdge? = null, edgeRight: BorderEdge? = null, // radius properties radius: BorderRadius? = null, // extra path effects effect: BorderEffect? = null ): Border = Border.create(context) .apply { edgeAll?.let { it.apply(YogaEdge.ALL, this, resourceResolver) } edgeHorizontal?.let { it.apply(YogaEdge.VERTICAL, this, resourceResolver) } edgeVertical?.let { it.apply(YogaEdge.HORIZONTAL, this, resourceResolver) } edgeStart?.let { it.apply(YogaEdge.START, this, resourceResolver) } edgeEnd?.let { it.apply(YogaEdge.END, this, resourceResolver) } edgeTop?.let { it.apply(YogaEdge.TOP, this, resourceResolver) } edgeBottom?.let { it.apply(YogaEdge.BOTTOM, this, resourceResolver) } edgeLeft?.let { it.apply(YogaEdge.LEFT, this, resourceResolver) } edgeRight?.let { it.apply(YogaEdge.RIGHT, this, resourceResolver) } radius?.let { it.apply(this, resourceResolver) } effect?.let { it.apply(this) } } .build() /** * Stores properties that are used to customise border edges * * @param color the colour to be applied to the edge * @param width the width of the edge */ class BorderEdge(@ColorInt val color: Int? = null, val width: Dimen? = null) { @PublishedApi internal inline fun apply( edge: YogaEdge, builder: Border.Builder, resourceResolver: ResourceResolver ) { color?.let { builder.color(edge, it) } width?.let { builder.widthPx(edge, it.toPixels(resourceResolver)) } } } /** * Stores properties that are used to customise the border radii * * @param all the radius to be applied to all corners * @param topLeft the radius to be applied to the top left corner * @param topRight the radius to be applied to the top right corner * @param bottomLeft the radius to be applied to the bottom left corner * * @param bottomRight the radius to be applied to the bottom right corner */ class BorderRadius( val all: Dimen? = null, val topLeft: Dimen? = null, val topRight: Dimen? = null, val bottomLeft: Dimen? = null, val bottomRight: Dimen? = null, ) { @PublishedApi internal inline fun apply(builder: Border.Builder, resourceResolver: ResourceResolver) { all?.let { builder.radiusPx(it.toPixels(resourceResolver)) } topLeft?.let { builder.radiusPx(Border.Corner.TOP_LEFT, it.toPixels(resourceResolver)) } topRight?.let { builder.radiusPx(Border.Corner.TOP_RIGHT, it.toPixels(resourceResolver)) } bottomLeft?.let { builder.radiusPx(Border.Corner.BOTTOM_LEFT, it.toPixels(resourceResolver)) } bottomRight?.let { builder.radiusPx(Border.Corner.BOTTOM_RIGHT, it.toPixels(resourceResolver)) } } } /** * Stores properties that are used to customise an effect that is applied to the border. * * @see BorderEffect.path * @see BorderEffect.dashed * @see BorderEffect.discrete */ class BorderEffect { // shared properties var phase: Float? = null // dash properties var intervals: FloatArray? = null // path properties var pathShape: Path? = null var pathAdvance: Float? = null var pathStyle: PathDashPathEffect.Style? = null // discrete effect properties var segmentLength: Float? = null var deviation: Float? = null private constructor(intervals: FloatArray, phase: Float) { this.intervals = intervals this.phase = phase } private constructor( pathShape: Path, pathAdvance: Float, pathPhase: Float, pathStyle: PathDashPathEffect.Style ) { this.pathShape = pathShape this.pathAdvance = pathAdvance this.phase = pathPhase this.pathStyle = pathStyle } private constructor(segmentLength: Float, deviation: Float) { this.segmentLength = segmentLength this.deviation = deviation } @PublishedApi internal inline fun apply(builder: Border.Builder) { // apply dashed border effect. if (this.intervals != null) { builder.dashEffect(intervals, phase ?: 0f) } // apply path border effect. if (this.pathShape != null) { builder.pathDashEffect(pathShape, pathAdvance ?: 0f, phase ?: 0f, pathStyle) } // apply discrete path border effect. if (this.segmentLength != null) { builder.discreteEffect(segmentLength ?: 0f, deviation ?: 0f) } } companion object { /** * Applies a path dash effect to the border * * @see Border.Builder.pathDashEffect */ fun path( shape: Path, advance: Float, phase: Float, style: PathDashPathEffect.Style ): BorderEffect { return BorderEffect(shape, advance, phase, style) } /** * Applies a dash effect to the border. * * @see Border.Builder.dashEffect */ fun dashed(intervals: FloatArray, phase: Float): BorderEffect { return BorderEffect(intervals, phase) } /** * Applies a discrete effect to the border. * * @see Border.Builder.discreteEffect */ fun discrete(segmentLength: Float, deviation: Float): BorderEffect { return BorderEffect(segmentLength, deviation) } } }
88
null
765
7,703
8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0
7,173
litho
Apache License 2.0
modules/android/src/test/java/com/objectfanatics/commons/androidx/lifecycle/TransformationsUtilsTest.kt
beyondseeker
286,864,140
false
null
package com.objectfanatics.commons.androidx.lifecycle import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.mockk.confirmVerified import io.mockk.mockk import io.mockk.verify import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule class TransformationsUtilsTest { @Rule @JvmField val rule: TestRule = InstantTaskExecutorRule() interface Recorder<T> { fun record(value: T) } /** * 3つの[MutableLiveData]を[TransformationsUtils]で監視するテスト。 */ @Test fun map_forQiita1() { // テストの実行経過を記録する Recorder の用意 val recorder = mockk<Recorder<String>>(relaxed = true) // 3 つの MutableLiveData を用意 val input1: MutableLiveData<String?> = MutableLiveData() val input2: MutableLiveData<String?> = MutableLiveData() val input3: MutableLiveData<String?> = MutableLiveData() // 上記 3 つの MutableLiveData を受けて文字列を返す LiveData を用意 val output: LiveData<String> = TransformationsUtils.map(input1, input2, input3) { "${input1.value}, ${input2.value}, ${input3.value}" } // 実行結果が標準出力に表示されるように準備 output.observeForever { value -> recorder.record(value) } // テストの実行 input1.postValue("red") input2.postValue("blue") input3.postValue("green") // 実行内容の検証 verify { recorder.record("red, null, null") recorder.record("red, blue, null") recorder.record("red, blue, green") } // 実行内容の検証がすべて完了したことの確認 confirmVerified(recorder) } /** * フォーム(名前、苗字)の両方が空でない時にのみ送信ボタンが押せるという仕様を想定した内容のテスト。 * ※ Unit test としては微妙だが、qiita 記事的にわかりやすいものにした。 */ @Test fun map_forQiita2() { // テストの実行経過を記録する Recorder の用意 val recorder = mockk<Recorder<Boolean>>(relaxed = true) // 名前、苗字の MutableLiveData を用意 val firstName: MutableLiveData<String?> = MutableLiveData() val lastName: MutableLiveData<String?> = MutableLiveData() val forms = listOf(firstName, lastName) // 送信ボタンが押せるかどうかの MutableLiveData を用意。 // ※名前、苗字の両方が空でない場合のみ true になる val isSubmitButtonEnabled: LiveData<Boolean> = TransformationsUtils.map(firstName, lastName) { !forms.any { it.value.isNullOrEmpty() } } // 実行経過が Recorder に記録されるように準備 isSubmitButtonEnabled.observeForever { value -> recorder.record(value) } // テストの実行 firstName.postValue("シャミ子") lastName.postValue("吉田") // 実行内容の検証 verify { // firstName が "シャミ子" になったが lastName が null のため false recorder.record(false) // firstName が "シャミ子"、lastName が "吉田" になったため true recorder.record(true) } // 実行内容の検証がすべて完了したことの確認 confirmVerified(recorder) } }
0
Kotlin
0
0
2712bb43fd30cd3d8ef82597568233f834b309f0
2,997
of-commons
Apache License 2.0
app/src/main/java/com/lindroid/androidutilsktdemo/app/App.kt
Lindroy
172,827,942
false
null
package com.lindroid.androidutilsktdemo.app import android.app.Application import com.lindroid.androidutilskt.app.AndUtil import com.squareup.leakcanary.LeakCanary import com.youngfeng.snake.Snake /** * @author Lin * @date 2019/2/27 * @function * @Description */ class App : Application() { companion object { lateinit var instance: App } init { instance = this } override fun onCreate() { super.onCreate() // 对Snake进行初始化 Snake.init(this) AndUtil.init(this) .setLogGlobalConfig { setLogEnable(true) setMethodCount(2) } // .setDefaultSpFile() //设置SharePreferences的默认表名,默认为“sp_util” // .setServerTimeFormat() //设置时间格式化中服务器时间格式,默认为“yyyy-MM-dd'T'HH:mm:ss.SSS” if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return } LeakCanary.install(this) } }
0
null
19
48
5d6832813a4a0dba7290ad5ef92959f638ea51ab
1,073
AndroidUtilsKt
Apache License 2.0
flaircore/src/main/java/com/rasalexman/flaircore/interfaces/IMapper.kt
Rasalexman
134,755,003
false
null
package com.rasalexman.flaircore.interfaces /** * Helper interface for bind generic instances with name */ interface IMapper<T> { /** * Instances storage */ val instanceMap: HashMap<String, T> /** * Get or create instance * * @param key - key for map key * @param inst - instance for create as value */ fun <T> IMapper<T>.instance(key: String, inst: () -> T): T = this.instanceMap.getOrPut(key) { inst() } }
1
null
6
31
bb4325e958993d8a51f91361080ef6a30018c4b0
463
Flair
The Unlicense
app/src/main/java/jp/cordea/urldispatcher/LicenseLocalDataSource.kt
CORDEA
155,200,284
false
null
package jp.cordea.urldispatcher import android.content.Context import io.reactivex.Single class LicenseLocalDataSource( private val context: Context ) : LicenseRepository { override fun getLicenses(): Single<String> = Single.fromCallable { context.assets.open("licenses.html").bufferedReader().readText() } }
0
Kotlin
0
0
7ee26459caaf284741cc94813ed038e45e819c99
363
UrlDispatcher
Apache License 2.0
2016/src/main/kotlin/com/koenv/adventofcode/Day11.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode import java.util.* import java.util.regex.Pattern /** * This one is quite slow, probably due to a lot of allocations in getAdjacentStates, which allocates * a new list for every possible state */ object Day11 { fun getRequiredSteps(input: String): Int { val types = hashSetOf<String>() val floors = input.lines() .filter(String::isNotBlank) .mapIndexed { i, line -> val lineMatcher = linePattern.matcher(line) if (!lineMatcher.find()) { throw IllegalArgumentException("Invalid input: `$line`") } if (lineMatcher.group(2) == "nothing relevant") { return@mapIndexed listOf<FloorItem>() } lineMatcher.group(2).split(",").map { val matcher = itemPattern.matcher(it.trim()) if (!matcher.find()) { throw IllegalArgumentException("Invalid item: `$it`") } val type = matcher.group(2) types.add(type) FloorItem(i, matcher.group(4), type) } } .flatten() val pairs = arrayListOf<Pair<Int, Int>>() floors.map { item -> // find the beloning microchip if (item.device == "generator") { val microchip = floors.find { it.element == item.element && it.device == "microchip" }!! pairs.add(item.floor to microchip.floor) } } val startState = State(null, 0, pairs) return findRequiredStepsBfs(startState) } fun findRequiredStepsBfs(startState: State): Int { val seenStates = hashSetOf<Pair<Int, List<Pair<Int, Int>>>>() seenStates.add(startState.elevator to startState.pairs) var currentState = startState val moves: Queue<State> = LinkedList<State>() moves.add(currentState) while (moves.isNotEmpty()) { currentState = moves.poll() if (isFinalMove(currentState)) { return currentState.depth } else { // add all states to possible moves getAdjacentStates(currentState, seenStates).forEach { moves.offer(it) seenStates.add(it.elevator to it.pairs) } } } throw IllegalStateException("No final move found") } private fun printTree(state: State) { state.parent?.let { printTree(it) } state.print() } private fun getAdjacentStates(currentState: State, seenStates: HashSet<Pair<Int, List<Pair<Int, Int>>>>): List<State> { val possibleMoves = arrayListOf<State>() currentState.pairs.forEach { pair -> val newPairs = currentState.pairs.removeOne(pair) // this is quite ugly, TODO: Clean it up if (pair.first == currentState.elevator) { possibleMoves.add(State(currentState, currentState.elevator + 1, newPairs + (pair.first + 1 to pair.second), "1")) possibleMoves.add(State(currentState, currentState.elevator - 1, newPairs + (pair.first - 1 to pair.second), "2")) newPairs.forEach { other -> if (other.first == currentState.elevator) { val newestPairs = newPairs.removeOne(other) possibleMoves.add(State(currentState, currentState.elevator + 1, newestPairs + (pair.first + 1 to pair.second) + (other.first + 1 to other.second), "3")) possibleMoves.add(State(currentState, currentState.elevator - 1, newestPairs + (pair.first - 1 to pair.second) + (other.first - 1 to other.second), "4")) } if (other.second == currentState.elevator) { val newestPairs = newPairs.removeOne(other) possibleMoves.add(State(currentState, currentState.elevator + 1, newestPairs + (pair.first + 1 to pair.second) + (other.first to other.second + 1), "5")) possibleMoves.add(State(currentState, currentState.elevator - 1, newestPairs + (pair.first - 1 to pair.second) + (other.first to other.second - 1), "6")) } } if (pair.second == currentState.elevator) { possibleMoves.add(State(currentState, currentState.elevator + 1, newPairs + (pair.first + 1 to pair.second + 1), "7")) possibleMoves.add(State(currentState, currentState.elevator - 1, newPairs + (pair.first - 1 to pair.second - 1), "8")) } } if (pair.second == currentState.elevator) { possibleMoves.add(State(currentState, currentState.elevator + 1, newPairs + (pair.first to pair.second + 1), "8")) possibleMoves.add(State(currentState, currentState.elevator - 1, newPairs + (pair.first to pair.second - 1), "9")) newPairs.forEach { other -> if (other.first == currentState.elevator) { val newestPairs = newPairs.removeOne(other) possibleMoves.add(State(currentState, currentState.elevator + 1, newestPairs + (pair.first to pair.second + 1) + (other.first + 1 to other.second), "10")) possibleMoves.add(State(currentState, currentState.elevator - 1, newestPairs + (pair.first to pair.second - 1) + (other.first - 1 to other.second), "11")) } if (other.second == currentState.elevator) { val newestPairs = newPairs.removeOne(other) possibleMoves.add(State(currentState, currentState.elevator + 1, newestPairs + (pair.first to pair.second + 1) + (other.first to other.second + 1), "12")) possibleMoves.add(State(currentState, currentState.elevator - 1, newestPairs + (pair.first to pair.second - 1) + (other.first to other.second - 1), "13")) } } } } return possibleMoves.filter { isValid(it) }.filter { !seenStates.contains(it.elevator to it.pairs) } } fun isFinalMove(state: State): Boolean { return state.pairs.all { it.first == 3 && it.second == 3 } // fourth floor } fun isValid(state: State): Boolean { if (state.elevator < 0 || state.elevator > 3) { return false } val generators = state.pairs.mapIndexed { i, pair -> pair.first }.toSet() return state.pairs.all { it.first >= 0 && it.first <= 3 && it.second >= 0 && it.second <= 3 && (it.first == it.second || !generators.contains(it.second)) } } val linePattern: Pattern = Pattern.compile("The ([a-z]*) floor contains (.*).") val itemPattern: Pattern = Pattern.compile("(and )?a ([a-z]*)(-compatible)? ([a-z]*)") data class State( val parent: State?, val elevator: Int, /** * The first item in the pair is the generator, the second is the microchip */ val pairs: List<Pair<Int, Int>>, var payload: String? = null ) { val depth: Int get() { var currentParent = parent var i = 0 while (currentParent != null) { i++ currentParent = currentParent.parent } return i } fun print() { println("Depth = $depth, Valid = ${isValid(this)}, Final = ${isFinalMove(this)}, Payload = $payload") println("=".repeat(7 + pairs.size * 6)) for (i in 0..3) { val floor = 3 - i print("F$floor = ") if (elevator == floor) { print("E ") } else { print(". ") } pairs.forEachIndexed { pairIndex, pair -> if (pair.first == floor) { print((pairIndex + 'A'.toInt()).toChar()) print("G ") } else { print(". ") } if (pair.second == floor) { print((pairIndex + 'A'.toInt()).toChar()) print("M ") } else { print(". ") } } println() } println() } } data class FloorItem( val floor: Int, val device: String, val element: String ) fun <T> Iterable<T>.removeOne(element: T): List<T> { var found = false return filter { if (it == element) { if (found) { return@filter true } found = true return@filter false } true } } }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
9,305
AdventOfCode-Solutions-Kotlin
MIT License
chargeStatistics/src/main/java/at/sunilson/chargestatistics/di/ChargeStatisticsModule.kt
sunilson
271,761,302
false
null
package at.sunilson.chargestatistics.di import android.content.Context import android.location.Geocoder import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dagger.hilt.android.qualifiers.ApplicationContext import java.util.* @Module @InstallIn(SingletonComponent::class) object ChargeStatisticsModule { @Provides fun provideGeocoder(@ApplicationContext context: Context) = Geocoder(context, Locale.getDefault()) }
0
Kotlin
0
5
75577b1923d2141f9724b9d7d6b1ddb34ec7e877
509
Zoe
Apache License 2.0
src/main/kotlin/me/dkim19375/dkim19375jdautils/command/EvalCommandBase.kt
dkim19375
332,087,195
false
null
/* * MIT License * * Copyright (c) 2021 dkim19375 * * 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 me.dkim19375.dkim19375jdautils.command import dev.minn.jda.ktx.await import me.dkim19375.dkim19375jdautils.BotBase import me.dkim19375.dkim19375jdautils.data.Whitelist import me.dkim19375.dkimcore.annotation.API import me.dkim19375.dkimcore.extension.runCatchingOrNull import net.dv8tion.jda.api.events.message.MessageReceivedEvent import java.io.PrintWriter import java.io.StringWriter import javax.script.ScriptEngineManager import kotlin.system.measureTimeMillis private val codeBlock = Regex("```(?:(?<lang>[a-zA-Z]+)?\\n)?((?:.|\\n)*?)```") @API open class EvalCommandBase(protected val bot: BotBase) : Command(bot) { override val aliases: Set<String> = setOf("eval") @Suppress("LeakingThis") override val arguments: Set<CommandArg> = setOf(CommandArg(this, "<code>", "The code to run")) override val command: String = "evaluate" override val description: String = "Run code for the bot!" override val minArgs: Int = 1 override val name: String = "Evaluate" override val type: CommandType = CommandType.UTILITIES override val permissions: Whitelist = Whitelist(whitelist = setOf(521485088995672084L)) open val imports: Set<String> = emptySet() open val variables: (MessageReceivedEvent) -> Map<String, Any> = { emptyMap() } private val isBukkit = runCatchingOrNull { Class.forName("org.bukkit.Bukkit") } != null @Suppress("BlockingMethodInNonBlockingContext") override suspend fun onCommand( cmd: String, args: List<String>, prefix: String, all: String, event: MessageReceivedEvent ) { val factory = ScriptEngineManager() val engine = factory.getEngineByName("nashorn") val imports = setOf( "net.dv8tion.jda.api", "net.dv8tion.jda.api.entities", "net.dv8tion.jda.api.events", "net.dv8tion.jda.api.managers", "java.io", "java.sql", "java.text", "java.lang", "java.lang.reflect", "java.lang.management", "java.math", "java.time", "java.time.chrono", "java.time.format", "java.time.temporal", "java.time.zone", "java.util", "java.util.regex", "java.util.stream", "java.util.logging", "java.util.concurrent", "java.util.concurrent.atomic", ).plus( if (!isBukkit) emptySet() else setOf( "org.bukkit", "org.bukkit.enchantments", "org.bukkit.entity", "org.bukkit.event", "org.bukkit.event.block", "org.bukkit.event.enchantment", "org.bukkit.event.entity", "org.bukkit.event.hanging", "org.bukkit.event.inventory", "org.bukkit.event.painting", "org.bukkit.event.player", "org.bukkit.event.server", "org.bukkit.event.vehicle", "org.bukkit.event.weather", "org.bukkit.event.world", "org.bukkit.generator", "org.bukkit.help", "org.bukkit.inventory", "org.bukkit.inventory.meta", "org.bukkit.map", "org.bukkit.material", "org.bukkit.metadata", "org.bukkit.plugin", "org.bukkit.plugin.java", "org.bukkit.potion", "org.bukkit.projectiles", "org.bukkit.scheduler", "org.bukkit.scoreboard", "org.spigotmc", "org.spigotmc.event.entity", "org.spigotmc.event.player" ) ).plus(this.imports) val packages = imports.filter { import -> runCatchingOrNull { Class.forName(import) } == null } val importStr = "with (new JavaImporter(${ imports.joinToString(transform = { "${if (it in packages) "Packages." else ""}$it" }) })) { " val code = "$importStr${ codeBlock.findAll(args.joinToString(" ")) .map { it.groups.last()?.value } .filterNotNull() .firstOrNull() ?: args.joinToString(" ") }}" val variables = mutableMapOf<String, Any>() variables["jda"] = event.jda variables["event"] = event variables["channel"] = event.channel variables["guild"] = event.guild variables["message"] = event.message variables["selfUser"] = event.jda.selfUser variables["bot"] = bot variables.plus(variables(event)).forEach(engine::put) val strWriter = StringWriter() val printWriter = PrintWriter(strWriter) engine.context.writer = printWriter val errorWriter = StringWriter() val errorPrintWriter = PrintWriter(errorWriter) engine.context.errorWriter = errorPrintWriter val result: String val time = measureTimeMillis { result = try { engine.eval(code)?.toString() ?: "" } catch (error: Throwable) { error.printStackTrace() event.channel.sendMessage("ERROR: ```\n${error.localizedMessage.replace("`", "`\u200B")}```").queue() return }.replace("`", "`\u200B") } val output = strWriter.toString().replace("`", "`\u200B") val error = errorWriter.toString().replace("`", "`\u200B") val messages = mutableListOf<String>() messages.addAll(splitStrSizes("Result: ", "Result: Nothing\n", result)) messages.addAll(splitStrSizes("Output: ", "Output: Nothing\n", output)) messages.addAll(splitStrSizes("Error: ", "", error)) messages.add("Took ${time}ms") val new = messages.fold(listOf<String>()) fold@{ accumulator, element -> if ((accumulator.lastOrNull()?.length?.plus(element.length) ?: 2000) < 2000) { val new = accumulator.toMutableList() val value = new.removeLast() new.add(value + element) return@fold new } else { return@fold accumulator.plus(element) } } new.forEach { event.channel.sendMessage(it).await() } } private fun splitStrSizes(beginning: String, empty: String, str: String): List<String> { if (str.isEmpty()) { return listOf(empty) } var first = true return str.chunked(1990 - beginning.length) text@{ val value = "${if (first) beginning else ""}```$it```" first = false return@text value } } }
1
Kotlin
0
0
c8a9491bf61ee965cb33c5ac58ab8623f917d81a
7,944
dkim19375JDAUtils
MIT License
novel-ai-service/src/test/kotlin/de/roamingthings/tracing/novelai/ports/driving/GenerateNovelDocumentControllerTest.kt
roamingthings
214,773,818
false
null
package de.roamingthings.tracing.novelai.ports.driving import com.nhaarman.mockitokotlin2.doReturn import de.roamingthings.tracing.novelai.usecases.document.GenerateNovelDocumentService import org.assertj.core.api.SoftAssertions.assertSoftly import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.springframework.http.HttpStatus.OK @ExtendWith(MockitoExtension::class) class GenerateNovelDocumentControllerTest { @Mock lateinit var generateNovelDocumentService: GenerateNovelDocumentService @InjectMocks lateinit var generateNovelDocumentController: GenerateNovelDocumentController @Test fun `should return an AsciiDoc document containing the novel`() { serviceReturnsGeneratedDocument() val response = generateNovelDocumentController.generateNovelDocument(NOVEL_UUID.toString()) assertSoftly { softly -> softly.assertThat(response.statusCode).isEqualTo(OK) softly.assertThat(response.body).isEqualTo(""" = The Novel Title The novel paragraph. Another Paragraph. """.trimIndent()) } } private fun serviceReturnsGeneratedDocument() { doReturn(aNovelDocument()) .`when`(generateNovelDocumentService).generateNovelDocument(NOVEL_UUID) } }
8
null
1
1
ee264dba66268763e761fb5d731f57fc3fc248d4
1,483
workbench-tracing
Apache License 2.0
common/src/main/kotlin/org/onesandzer0s/create_articulate/registry/CreativeTabs.kt
OnesAndZer0s
780,550,454
false
{"Kotlin": 149963, "Java": 12508}
package org.onesandzer0s.create_articulate.registry import net.minecraft.network.chat.Component import net.minecraft.world.item.CreativeModeTab import net.minecraft.world.item.ItemStack import org.onesandzer0s.create_articulate.CreateArticulateBlocks import org.onesandzer0s.create_articulate.CreateArticulateItems object CreativeTabs { fun create(): CreativeModeTab { return CreativeModeTab.builder(CreativeModeTab.Row.TOP, 0) .title(Component.translatable("itemGroup.create_articulate")) .icon { ItemStack(CreateArticulateBlocks.OAK_SHIP_HELM.get().asItem()) } .displayItems { _, output -> CreateArticulateItems.ITEMS.forEach { output.accept(it.get()) } } .build() } }
0
Kotlin
0
0
679e31bbb0be50ce055ecb2bbbf2fbb46f845533
789
CreateArticulate
Apache License 2.0
compiler/tests-spec/testData/codegen/box/linked/statements/assignments/simple-assignments/p-2/pos/1.1.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// WITH_STDLIB /* * KOTLIN CODEGEN BOX SPEC TEST (POSITIVE) * * SPEC VERSION: 0.1-222 * MAIN LINK: statements, assignments, simple-assignments -> paragraph 2 -> sentence 1 * NUMBER: 1 * DESCRIPTION: If a property has a setter, it is called using the right-hand side expression as its argument; */ var flag1 = false var flag2 = false val valToSet = 5 class C() { var counter = 0 set(value) { flag1 = true if (value == valToSet) flag2 = true field = value } } fun box(): String { val c = C() assert(!flag1) assert(!flag2) c.counter = valToSet if (flag1 && flag2 && c.counter == valToSet) return "OK" return "NOK" }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
720
kotlin
Apache License 2.0
plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/commands/test/splitting/TestsFilterProviderTestsSplitting.kt
JetBrains
49,584,664
false
null
package jetbrains.buildServer.dotnet.test.dotnet.commands.test.splitting import io.mockk.* import io.mockk.impl.annotations.MockK import jetbrains.buildServer.agent.Logger import jetbrains.buildServer.dotnet.commands.test.splitting.* import jetbrains.buildServer.dotnet.commands.test.splitting.TestClassParametersProcessingMode.* import jetbrains.buildServer.dotnet.commands.test.splitting.byTestName.TestsSplittingByNamesReader import org.testng.Assert import org.testng.annotations.BeforeMethod import org.testng.annotations.DataProvider import org.testng.annotations.Test class TestsFilterProviderTestsSplitting { @MockK private lateinit var _settingsMock: TestsSplittingSettings @MockK private lateinit var _testsNamesReaderMock: TestsSplittingByNamesReader @MockK private lateinit var _loggerMock: Logger @BeforeMethod fun setUp() { clearAllMocks() MockKAnnotations.init(this) mockkObject(Logger) every { Logger.getLogger(any()) } returns _loggerMock every { _settingsMock.testClassParametersProcessingMode } returns EscapeSpecialCharacters justRun { _loggerMock.debug(any<String>()) } justRun { _loggerMock.warn(any<String>()) } } @Test fun `should provide an empty filter expression if test splitting disabled`() { // arrange val provider = create() // act val result = provider.getFilterExpression(TestsSplittingMode.Disabled) // assert Assert.assertEquals(result, "") verify(exactly = 0) { _loggerMock.debug(any<String>()) } verify(exactly = 0) { _loggerMock.warn(any<String>()) } } @DataProvider fun testDataForDefaultFilterExpression() = arrayOf( arrayOf( TestsSplittingFilterType.Includes, sequenceOf("Namespace.TestClass0", "Namespace.TestClass1"), "FullyQualifiedName~Namespace.TestClass0. | FullyQualifiedName~Namespace.TestClass1." ), arrayOf( TestsSplittingFilterType.Excludes, sequenceOf("Namespace.TestClass0", "Namespace.TestClass1"), "FullyQualifiedName!~Namespace.TestClass0. & FullyQualifiedName!~Namespace.TestClass1." ), ) @Test(dataProvider = "testDataForDefaultFilterExpression") fun `should provide test class filter expression`( filterType: TestsSplittingFilterType, names: Sequence<String>, expectedFilterExpression: String ) { // arrange every { _settingsMock.filterType } answers { filterType } every { _settingsMock.testClasses } answers { names } val provider = create() // act val result = provider.getFilterExpression(TestsSplittingMode.TestClassNameFilter) // assert Assert.assertEquals(result, expectedFilterExpression) } @DataProvider fun testDataForDefaultFilterExpressionWithMoreThan1000TestClasses() = arrayOf( arrayOf(TestsSplittingFilterType.Includes, "^\\(.+\\)\\s{1}\\|\\s{1}\\(.+\\)\\s{1}\\|\\s{1}\\(.+\\)\$"), arrayOf(TestsSplittingFilterType.Excludes, "^\\(.+\\)\\s{1}&\\s{1}\\(.+\\)\\s{1}&\\s{1}\\(.+\\)\$"), ) @Test(dataProvider = "testDataForDefaultFilterExpressionWithMoreThan1000TestClasses") fun `should provide test class filter expression for more than 1000 test classes`( filterType: TestsSplittingFilterType, regex: String ) { // arrange every { _settingsMock.filterType } answers { filterType } every { _settingsMock.testClasses } answers { generateTestClassesList(2500) } val provider = create() // act val result = provider.getFilterExpression(TestsSplittingMode.TestClassNameFilter) // assert Assert.assertTrue(Regex(regex).matches(result)) } @Test fun `should provide test name filter expression`() { // arrange every { _testsNamesReaderMock.read() } answers { generateTestsNamesList(2, 2) } val provider = create() // act val result = provider.getFilterExpression(TestsSplittingMode.TestNameFilter) // assert Assert.assertEquals( result, "FullyQualifiedName=Namespace.TestClass0.Test0 | FullyQualifiedName=Namespace.TestClass0.Test1 " + "| FullyQualifiedName=Namespace.TestClass1.Test0 | FullyQualifiedName=Namespace.TestClass1.Test1" ) } @Test fun `should provide test name filter expression for more than 1000 test names`() { // arrange every { _testsNamesReaderMock.read() } answers { generateTestsNamesList(25, 100) } val provider = create() // act val result = provider.getFilterExpression(TestsSplittingMode.TestNameFilter) // assert Assert.assertTrue(Regex("^\\(.+\\)\\s{1}\\|\\s{1}\\(.+\\)\\s{1}\\|\\s{1}\\(.+\\)\$").matches(result)) } @DataProvider fun testDataForParametrisedTestClasses() = arrayOf( // no parameters arrayOf( TestsSplittingFilterType.Includes, sequenceOf("TestClass0", "TestClass1"), "FullyQualifiedName~TestClass0. | FullyQualifiedName~TestClass1.", ), arrayOf( TestsSplittingFilterType.Excludes, sequenceOf("TestClass0", "TestClass1"), "FullyQualifiedName!~TestClass0. & FullyQualifiedName!~TestClass1.", ), // one string parameter arrayOf( TestsSplittingFilterType.Includes, sequenceOf("""TestClass0("param")""", """TestClass1("param")"""), """FullyQualifiedName~TestClass0\(\"param\"\) | FullyQualifiedName~TestClass1\(\"param\"\)""", ), arrayOf( TestsSplittingFilterType.Excludes, sequenceOf("""TestClass0("param")""", """TestClass1("param")"""), """FullyQualifiedName!~TestClass0\(\"param\"\) & FullyQualifiedName!~TestClass1\(\"param\"\)""", ), // multiple different parameters with all possible special characters arrayOf( TestsSplittingFilterType.Includes, sequenceOf("""TestClass0("param",42,"\\()&|=!~")""", """TestClass1"""), """FullyQualifiedName~TestClass0\(\"param\"%2C42%2C\"\\\\\(\)\&\|\=\!\~\"\) | FullyQualifiedName~TestClass1.""", ), arrayOf( TestsSplittingFilterType.Excludes, sequenceOf("""TestClass0("param",42,"\\()&|=!~")""", """TestClass1"""), """FullyQualifiedName!~TestClass0\(\"param\"%2C42%2C\"\\\\\(\)\&\|\=\!\~\"\) & FullyQualifiedName!~TestClass1.""", ), ) @Test(dataProvider = "testDataForParametrisedTestClasses") fun `should provide test class filter expression processing test class parameters`( filterType: TestsSplittingFilterType, classNames: Sequence<String>, expectedFilterExpression: String ) { // arrange every { _settingsMock.filterType } answers { filterType } every { _settingsMock.testClasses } answers { classNames } val provider = create() // act val result = provider.getFilterExpression(TestsSplittingMode.TestClassNameFilter) // assert Assert.assertEquals(result, expectedFilterExpression) } @DataProvider fun testDataParametersProcessingModes() = arrayOf( arrayOf( Trim, sequenceOf("""TestClass("param")"""), "FullyQualifiedName~TestClass.", ), arrayOf( NoProcessing, sequenceOf("""TestClass("param")"""), """FullyQualifiedName~TestClass("param")""", ), ) @Test(dataProvider = "testDataParametersProcessingModes") fun `should provide test class filter expression processing test class parameters`( mode: TestClassParametersProcessingMode, classNames: Sequence<String>, expectedFilterExpression: String, ) { // arrange every { _settingsMock.testClassParametersProcessingMode } returns mode every { _settingsMock.filterType } answers { TestsSplittingFilterType.Includes } every { _settingsMock.testClasses } answers { classNames } val provider = create() // act val result = provider.getFilterExpression(TestsSplittingMode.TestClassNameFilter) // assert Assert.assertEquals(result, expectedFilterExpression) } @DataProvider fun testDataForTrimmingTestClassParameters() = arrayOf( arrayOf("TestClass", "FullyQualifiedName~TestClass."), arrayOf("TestClass(param", "FullyQualifiedName~TestClass(param."), arrayOf("Namespace.TestClass", "FullyQualifiedName~Namespace.TestClass."), arrayOf("Namespace.TestClass(param", "FullyQualifiedName~Namespace.TestClass(param."), arrayOf("Namespace.TestClass(param1,param2)", "FullyQualifiedName~Namespace.TestClass\\(param1%2Cparam2\\)"), arrayOf("Namespace1.Namespace2.TestClass(param1,param2)", "FullyQualifiedName~Namespace1.Namespace2.TestClass\\(param1%2Cparam2\\)"), arrayOf("Namespace.TestClass((param))", "FullyQualifiedName~Namespace.TestClass\\(\\(param\\)\\)"), arrayOf("Namespace.TestCla(ss(param)", "FullyQualifiedName~Namespace.TestCla\\(ss\\(param\\)"), ) @Test(dataProvider = "testDataForTrimmingTestClassParameters") fun `should provide test class filter expression processing test class parameters`( sourceName: String, expectedFilterExpression: String ) { // arrange every { _settingsMock.filterType } answers { TestsSplittingFilterType.Includes } every { _settingsMock.testClasses } answers { sequenceOf(sourceName) } val provider = create() // act val result = provider.getFilterExpression(TestsSplittingMode.TestClassNameFilter) // assert Assert.assertEquals(result, expectedFilterExpression) } private fun create() = TestsSplittingFilterProvider(_settingsMock, _testsNamesReaderMock) private fun generateTestClassesList(n: Int) = sequence { for (index in 0 until n) { yield("Namespace.TestClass$index") } } private fun generateTestsNamesList(n: Int, m: Int) = sequence { for (i in 0 until n) { for (j in 0 until m) { yield("Namespace.TestClass$i.Test$j") } } } }
3
null
25
94
5f444c22b3354955d1060e08478d543d2b0b99b0
10,469
teamcity-dotnet-plugin
Apache License 2.0
idea/src/org/jetbrains/kotlin/idea/debugger/stepping/KotlinLambdaMethodFilter.kt
erokhins
44,854,854
false
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.debugger.stepping import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.BreakpointStepMethodFilter import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.LambdaMethodFilter import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElementFactory import com.intellij.util.Range import com.sun.jdi.Location import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtFunctionLiteralExpression import org.jetbrains.kotlin.util.OperatorNameConventions public class KotlinLambdaMethodFilter( lambda: KtFunctionLiteralExpression, private val myCallingExpressionLines: Range<Int> ): BreakpointStepMethodFilter { private val myFirstStatementPosition: SourcePosition? private val myLastStatementLine: Int init { var firstStatementPosition: SourcePosition? = null var lastStatementPosition: SourcePosition? = null val body = lambda.getBodyExpression()!! val statements = body.getStatements() if (statements.isNotEmpty()) { firstStatementPosition = SourcePosition.createFromElement(statements.first()) if (firstStatementPosition != null) { val lastStatement = statements.last() lastStatementPosition = SourcePosition.createFromOffset(firstStatementPosition.getFile(), lastStatement.getTextRange().getEndOffset()) } } myFirstStatementPosition = firstStatementPosition myLastStatementLine = if (lastStatementPosition != null) lastStatementPosition.getLine() else -1 } override fun getBreakpointPosition(): SourcePosition? { return myFirstStatementPosition } override fun getLastStatementLine(): Int { return myLastStatementLine } override fun locationMatches(process: DebugProcessImpl, location: Location): Boolean { val method = location.method() return isLambdaName(method.name()) } override fun getCallingExpressionLines(): Range<Int>? { return myCallingExpressionLines } companion object { public fun isLambdaName(name: String?): Boolean { return name == OperatorNameConventions.INVOKE.asString() } } }
1
null
1
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
2,975
kotlin
Apache License 2.0
kotpass/src/test/kotlin/app/keemobile/kotpass/cryptography/AesKdfSpec.kt
keemobile
384,214,968
false
null
package app.keemobile.kotpass.cryptography import app.keemobile.kotpass.cryptography.format.AesKdf import app.keemobile.kotpass.database.Credentials import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.shouldBe class AesKdfSpec : DescribeSpec({ describe("Aes key derivation") { it("Transforms key values as expected 1") { val result = AesKdf.transformKey( key = "8ee89711330c1ccf39a2e65ad12bbd7d".toByteArray(), seed = "a25ca73c7189e2a2ca5acf2088b57e28".toByteArray(), rounds = 6000UL ) val expected = intArrayOf( 0x2f, 0xfa, 0x2c, 0x11, 0xeb, 0x4a, 0xcc, 0xe3, 0x45, 0xd9, 0x9b, 0x53, 0xab, 0x4b, 0x71, 0x9c, 0xbe, 0x3a, 0x8c, 0x80, 0x99, 0x6f, 0xc7, 0xae, 0xb5, 0xde, 0x76, 0xef, 0x3e, 0x4c, 0x2d, 0x57 ).map(Int::toByte) result shouldBe expected } it("Transforms key values as expected 2") { val credentials = Credentials.from(EncryptedValue.fromString("secret")) val seed = ByteArray(32) { 0x1.toByte() } val result = AesKdf.transformKey( key = KeyTransform.compositeKey(credentials), seed = seed, rounds = 10UL ) val expected = intArrayOf( 208, 2, 238, 193, 16, 181, 39, 109, 254, 40, 67, 20, 154, 21, 202, 174, 234, 11, 183, 136, 22, 136, 58, 102, 52, 40, 129, 244, 194, 223, 211, 108 ).map(Int::toByte) result shouldBe expected } } })
4
null
1
9
0e123c087c6ec516492f33c0140497debfb3ba15
1,675
kotpass
MIT License
DadoInterativo/app/src/main/java/com/example/dadointerativo/MainActivity.kt
dev-alissonalves
385,785,176
false
null
package com.example.dadointerativo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import org.w3c.dom.Text class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Inicializando uma imagem qualquer... val imagemInicial: ImageView = findViewById(R.id.dado1) val imagemInicial2: ImageView = findViewById(R.id.dado2) imagemInicial.setImageResource(R.drawable.dice_1) imagemInicial2.setImageResource(R.drawable.dice_1) //Criando a ação para quando o usuário clicar no botão. val botao_jogar_dado: Button = findViewById(R.id.button) botao_jogar_dado.setOnClickListener { criarDado() } } //Função que contém a chamada da classe que cria o objeto DADO. private fun criarDado() { val primeiroDado = Dado(6) //Criando o um objeto Dado val segundoDado = Dado(6) //Inicializando a variável que vai dar visibilidade ao TextView... var dado1_ven: TextView = findViewById(R.id.dado1_vencedor) var dado2_ven: TextView = findViewById(R.id.dado2_vencedor) var dado1_emp: TextView = findViewById(R.id.dado1_empate) var dado2_emp: TextView = findViewById(R.id.dado2_empate) //dado1_ven.visibility = View.INVISIBLE //dado2_ven.visibility = View.INVISIBLE dado1_emp.visibility = View.INVISIBLE dado2_emp.visibility = View.INVISIBLE //acessando método da classe Dado e armazenando resultado do método na variável jogada val jogada1 = primeiroDado.jogarDado() val jogada2 = segundoDado.jogarDado() //Mostrando o resultado através de uma ImageView val dadoImagem1: ImageView = findViewById(R.id.dado1) val dadoImagem2: ImageView = findViewById(R.id.dado2) //Determina qual dado será exibido de acordo com o valor de jogada... when (jogada1) { 1 -> dadoImagem1.setImageResource(R.drawable.dice_1) 2 -> dadoImagem1.setImageResource(R.drawable.dice_2) 3 -> dadoImagem1.setImageResource(R.drawable.dice_3) 4 -> dadoImagem1.setImageResource(R.drawable.dice_4) 5 -> dadoImagem1.setImageResource(R.drawable.dice_5) 6 -> dadoImagem1.setImageResource(R.drawable.dice_6) } when (jogada2) { 1 -> dadoImagem2.setImageResource(R.drawable.dice_1) 2 -> dadoImagem2.setImageResource(R.drawable.dice_2) 3 -> dadoImagem2.setImageResource(R.drawable.dice_3) 4 -> dadoImagem2.setImageResource(R.drawable.dice_4) 5 -> dadoImagem2.setImageResource(R.drawable.dice_5) 6 -> dadoImagem2.setImageResource(R.drawable.dice_6) } if (jogada1 > jogada2){ dado1_ven.visibility = View.VISIBLE dado2_ven.visibility = View.INVISIBLE } else if (jogada1 < jogada2){ dado1_ven.visibility = View.INVISIBLE dado2_ven.visibility = View.VISIBLE }else{ dado1_emp.visibility = View.VISIBLE dado2_emp.visibility = View.VISIBLE } dadoImagem1.contentDescription = jogada1.toString() dadoImagem2.contentDescription = jogada2.toString() } } //Classe responsável por descrever o objeto dado class Dado(private val numLados: Int) { //Método da classe dado responsável por gerar o número aleatório que representa os lados do Dado. fun jogarDado(): Int { return (1..numLados).random() } }
0
Kotlin
0
0
dd2a176d977ab27aca7275fda2ecd2ede3c6cf4d
3,742
android-kotlin-projects
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/sendlegalmailtoprisonsapi/barcode/BarcodeReportingConfig.kt
ministryofjustice
424,655,284
false
null
package uk.gov.justice.digital.hmpps.sendlegalmailtoprisonsapi.barcode import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.ConstructorBinding @ConstructorBinding @ConfigurationProperties(prefix = "app.barcode-stats-report") data class BarcodeReportingConfig( val recipientEmails: List<String>, )
0
Kotlin
0
3
d140dff438f1cbcb87e0a5da22f7e74bd05ec8fc
374
send-legal-mail-to-prisons-api
MIT License
sample/src/main/java/tech/thdev/androidrecyclerview/data/source/image/ImagesLocalDataSource.kt
taehwandev
71,049,057
false
null
package tech.thdev.androidrecyclerview.data.source.image import io.reactivex.rxjava3.core.Flowable import tech.thdev.androidrecyclerview.MyApplication import tech.thdev.androidrecyclerview.data.Image import java.util.* /** * Created by Tae-hwan on 17/10/2016. */ class ImagesLocalDataSource : ImagesDataSource { private val imageList = ArrayList<Image>() override fun getAllImages(): Flowable<List<Image>> { if (imageList.size < 14) { Flowable.range(1, 14) .map { val name = String.format("sample_%02d", it) val resource = MyApplication.appContext.resources.getIdentifier( name, "drawable", MyApplication.appContext.packageName ) Image(resource, name, "Message $name", 0) } .subscribe { imageList.add(it) } } return Flowable.fromArray(imageList) } }
1
Kotlin
4
9
74b70f90f8d7b3a9bf457416166045d2f5d18a78
1,041
AndroidRecyclerView
Apache License 2.0
src/nativeMain/kotlin/org/intellij/markdown/html/Url.kt
JetBrains
27,873,341
false
null
package org.intellij.markdown.html import kotlin.math.pow internal data class URL( val scheme: String, val username: String, val password: String, val host: String?, val port: Int?, val path: List<String>, val query: String?, val fragment: String?, val cannotBeABaseUrl: Boolean, val relativeNoSlash: Boolean, ) { val includesCredentials: Boolean get() = username.isNotEmpty() || password.isNotEmpty() } //https://url.spec.whatwg.org/#url-class private const val STATE_START = 0 private const val STATE_SCHEME = 1 private const val STATE_NO_SCHEME = 2 private const val STATE_SPECIAL_RELATIVE_OR_AUTHORITY = 3 private const val STATE_PATH_OR_AUTHORITY = 4 private const val STATE_RELATIVE = 5 private const val STATE_RELATIVE_SLASH = 6 private const val STATE_SPECIAL_AUTHORITY_SLASHES = 7 private const val STATE_SPECIAL_AUTHORITY_IGNORE_SLASHES = 8 private const val STATE_AUTHORITY = 9 private const val STATE_HOST = 10 private const val STATE_HOSTNAME = 11 private const val STATE_PORT = 12 private const val STATE_FILE = 13 private const val STATE_FILE_SLASH = 14 private const val STATE_FILE_HOST = 15 private const val STATE_PATH_START = 16 private const val STATE_PATH = 17 private const val STATE_CANNOT_BE_BASE_URL_PATH = 18 private const val STATE_QUERY = 19 private const val STATE_FRAGMENT = 20 @SharedImmutable private val SPECIAL_SCHEMES = arrayOf("ftp", "file", "http", "https", "ws", "wss") @SharedImmutable private val DEFAULT_PORTS = mapOf( "ftp" to 21, "file" to null, "http" to 80, "https" to 443, "ws" to 80, "wss" to 443 ) internal fun parseUrl(rawInput: String, base: URL?): URL { var scheme = "" var username = "" var password = "" var host: String? = null var port: Int? = null var path: MutableList<String> = mutableListOf() var query: String? = null var fragment: String? = null var cannotBeABaseUrl = false var relativeNoSlash = false var flagAt = false var flagBracket = false var flagPasswordTokenSeen = false val buffer = StringBuilder(rawInput.length) // validation error if rawInput contains any leading or trailing C0 control or space // validation error if rawInput contains any ASCII tab or newline val input = rawInput.trim { it <= ' ' || it > '~' }.replace(Regex("[\t\r\n]"), "") var pointer = 0 var state = STATE_START fun urlIsSpecial() = scheme in SPECIAL_SCHEMES do { val c = input.getOrNull(pointer) val remainingStart = input.getOrNull(pointer + 1) when (state) { STATE_START -> { state = if (c != null && c.isLetter()) { buffer.append(c.toLowerCase()) STATE_SCHEME } else { pointer -= 1 STATE_NO_SCHEME } } STATE_SCHEME -> { if (c != null && (c.isLetterOrDigit() || c in "+-/")) { buffer.append(c.toLowerCase()) } else if (c == ':') { scheme = buffer.toString() buffer.clear() state = when { scheme == "file" -> { require(remainingStart == '/') { "Invalid URI" } STATE_FILE } urlIsSpecial() -> when (base?.scheme) { scheme -> STATE_SPECIAL_RELATIVE_OR_AUTHORITY else -> STATE_SPECIAL_AUTHORITY_SLASHES } remainingStart == '/' -> { pointer += 1 STATE_PATH_OR_AUTHORITY } else -> { cannotBeABaseUrl = true path.add("") STATE_CANNOT_BE_BASE_URL_PATH } } } else { buffer.clear() state = STATE_NO_SCHEME pointer = -1 // start over at the beginning of input with this new state } } STATE_NO_SCHEME -> { // Deviation from the spec: // The spec requires an error if base is null here. We allow a null base. state = if (base != null && base.cannotBeABaseUrl && c == '#') { scheme = base.scheme path = base.path.toMutableList() query = base.query fragment = "" cannotBeABaseUrl = true STATE_FRAGMENT } else if (scheme != "file") { pointer -= 1 STATE_RELATIVE } else { pointer -= 1 STATE_FILE } } STATE_SPECIAL_RELATIVE_OR_AUTHORITY -> { state = if (c == '/' && remainingStart == '/') { pointer += 1 STATE_SPECIAL_AUTHORITY_IGNORE_SLASHES } else { // validation error pointer -= 1 STATE_RELATIVE } } STATE_PATH_OR_AUTHORITY -> { state = if (c == '/') { STATE_AUTHORITY } else { pointer -= 1 STATE_PATH } } STATE_RELATIVE -> { // Deviation from spec: // The spec does not allow a null base for relative urls. We do, and use empty // values in that case. scheme = base?.scheme ?: "" if (c == '/') { state = STATE_RELATIVE_SLASH } else if (c == '\\' && urlIsSpecial()) { // validation error state = STATE_RELATIVE_SLASH } else { username = base?.username ?: "" password = base?.password ?: "" host = base?.host port = base?.port path = base?.path?.toMutableList() ?: mutableListOf() query = base?.query if (c == '?') { query = "" state = STATE_QUERY } else if (c == '#') { fragment = "" state = STATE_FRAGMENT } else if (c != null) { query = null // Deviation from spec: // Since we allow null base with relative paths, we also keep track of // whether or not those relative paths start with a slash. `relativeNoSlash` // will remain false if control goes through STATE_RELATIVE_SLASH rather // than here. relativeNoSlash = base?.relativeNoSlash ?: true if (path.isNotEmpty()) { path.removeAt(path.lastIndex) } pointer -= 1 state = STATE_PATH } } } STATE_RELATIVE_SLASH -> { state = if (urlIsSpecial() && (c == '/' || c == '\\')) { // validation error if (c == '\\') STATE_SPECIAL_AUTHORITY_IGNORE_SLASHES } else if (c == '/') { STATE_AUTHORITY } else { // Deviation from spec: // The spec does not allow a null base for relative urls. We do, and use empty // values in that case. username = base?.username ?: "" password = base?.password ?: "" host = base?.host port = base?.port pointer -= 1 STATE_PATH } } STATE_SPECIAL_AUTHORITY_SLASHES -> { state = if (c == '/' && remainingStart == '/') { pointer -= 1 STATE_SPECIAL_AUTHORITY_IGNORE_SLASHES } else { // validation error pointer -= 1 STATE_SPECIAL_AUTHORITY_IGNORE_SLASHES } } STATE_SPECIAL_AUTHORITY_IGNORE_SLASHES -> { if (c != '/' && c != '\\') { pointer -= 1 state = STATE_AUTHORITY } // validation error otherwise } STATE_AUTHORITY -> { if (c == '@') { // validation error if (flagAt) { buffer.insert(0, "%40") } flagAt = true for (it in buffer.toString()) { if (it == ':' && !flagPasswordTokenSeen) { flagPasswordTokenSeen = true continue } val encodedCodePoints = percentEncode(it.toString(), PERCENT_ENCODE_SET_USERINFO) if (flagPasswordTokenSeen) { password += encodedCodePoints } else { username += encodedCodePoints } } buffer.clear() } else if (c == null || c in "/?#" || urlIsSpecial() && c == '\\') { require(!flagAt || buffer.isNotEmpty()) { "Invalid URI" } pointer -= buffer.length + 1 buffer.clear() state = STATE_HOST } else { buffer.append(c) } } STATE_HOST, STATE_HOSTNAME -> { if (c == ':' && !flagBracket) { require(buffer.isNotEmpty()) { "Invalid URI" } host = parseHost(buffer.toString(), isNotSpecial = !urlIsSpecial()) buffer.clear() state = STATE_PORT } else if (c == null || c in "/?#" || (urlIsSpecial() && c == '\\')) { pointer -= 1 require(!urlIsSpecial() || buffer.isNotEmpty()) { "Invalid URI" } host = parseHost(buffer.toString(), isNotSpecial = !urlIsSpecial()) buffer.clear() state = STATE_PATH_START } else { if (c == '[') flagBracket = true if (c == ']') flagBracket = false buffer.append(c) } } STATE_PORT -> { if (c != null && c.isDigit()) { buffer.append(c) } else if (c == null || c in "/?#" || (urlIsSpecial() && c == '\\')) { if (buffer.isNotEmpty()) { port = buffer.toString().toInt() require(port < (2.0.pow(16))) { "Invalid URI port" } if (port == DEFAULT_PORTS[scheme]) { port = null } buffer.clear() } pointer -= 1 state = STATE_PATH_START } else { throw IllegalArgumentException("Invalid URI port") } } STATE_FILE -> { scheme = "file" host = "" state = if (c == '\\' || c == '/') { // validation error if c == '\\' STATE_FILE_SLASH } else if (base?.scheme == "file") { host = base.host path = base.path.toMutableList() query = base.query if (c == '?') { query = "" STATE_QUERY } else if (c == '#') { fragment = "" STATE_FRAGMENT } else if (c != null) { query = null if (!startsWithWindowsDriveLetter(input.substring(pointer))) { shortenPath(path, scheme) } else { // validation error path.clear() } pointer -= 1 STATE_PATH } else { STATE_FILE } } else { pointer -= 1 STATE_PATH } } STATE_FILE_SLASH -> { if (c == '/' || c == '\\') { // validation error if c == '\\' state = STATE_FILE_HOST } else { if (base?.scheme == "file") { host = base.host if (!startsWithWindowsDriveLetter(input.substring(pointer)) && base.path.isNotEmpty() && isNormalizedWindowsDriveLetter(base.path[0])) { path.add(base.path[0]) } pointer -= 1 state = STATE_PATH } } } STATE_FILE_HOST -> { if (c == null || c in "/\\?#") { pointer -= 1 if (isWindowsDriveLetter(buffer.toString())) { // validation error state = STATE_PATH } else if (buffer.isEmpty()) { host = "" state = STATE_PATH_START } else { host = parseHost(buffer.toString(), isNotSpecial = !urlIsSpecial()) if (host == "localhost") { host = "" } buffer.clear() state = STATE_PATH_START } } else { buffer.append(c) } } STATE_PATH_START -> { if (urlIsSpecial()) { //validation error if c == '\\' state = STATE_PATH if (c != '/' && c != '\\') { pointer -= 1 } } else if (c == '?') { query = "" state = STATE_QUERY } else if (c == '#') { fragment = "" state = STATE_FRAGMENT } else if (c != null) { if (c != '/') { pointer -= 1 } state = STATE_PATH } } STATE_PATH -> { if (c == null || c == '/' || urlIsSpecial() && c == '\\' || c in "?#" ) { // validation error if (urlIsSpecial() && c == '\\') if (isDoubleDotPathSegment(buffer.toString())) { shortenPath(path, scheme) if (c != '/' && !urlIsSpecial() && c != '\\') { path.add("") } } else if (isSingleDotPathSegment(buffer.toString()) && c != '/' && !urlIsSpecial() && c != '\\') { path.add("") } else if (!isSingleDotPathSegment(buffer.toString())) { if (scheme == "file" && path.isEmpty() && isWindowsDriveLetter(buffer.toString())) { buffer[1] = ':' } path.add(buffer.toString()) } buffer.clear() if (c == '?') { query = "" state = STATE_QUERY } if (c == '#') { fragment = "" state = STATE_FRAGMENT } } else { // validation error if c is not a URL code point (i.e. unicode) // validation error if c == '%' && remaining does not start with two ASCII hex digits) buffer.append(percentEncode(c.toString(), PERCENT_ENCODE_SET_PATH)) } } STATE_CANNOT_BE_BASE_URL_PATH -> { if (c == '?') { query = "" state = STATE_QUERY } else if (c == '#') { fragment = "" state = STATE_FRAGMENT } else { // validation error if c != null && c != '%' && c is not a URL code point // validation error if c == '%' and remaining does not start with two ASCII hex digits if (c != null) { path[0] = path[0] + percentEncode(c.toString(), PERCENT_ENCODE_SET_C0) } } } STATE_QUERY -> { if (c == null || c == '#') { val queryPercentEncodeSet = when { urlIsSpecial() -> PERCENT_ENCODE_SET_SPECIAL_QUERY else -> PERCENT_ENCODE_SET_QUERY } query = query!! + percentEncode(buffer.toString(), queryPercentEncodeSet) buffer.clear() if (c == '#') { fragment = "" state = STATE_FRAGMENT } } else { // validation error if c is not a URL code point and not U+0025 (%) // validation error if c == '%' && remaining does not start with two ASCII hex digit buffer.append(c) } } STATE_FRAGMENT -> { if (c != null) { // validation error if c is not a URL code point and not U+0025 (%) // validation error if c == '%' && remaining does not start with two ASCII hex digit fragment = fragment!! + percentEncode(c.toString(), PERCENT_ENCODE_SET_FRAGMENT) } } } pointer += 1 } while (pointer <= input.length) return URL(scheme, username, password, host, port, path, query, fragment, cannotBeABaseUrl, relativeNoSlash) } // Deviation from spec: // The spec parses IP addresses into integers. We don't need that functionality, so we skip those // steps. // https://url.spec.whatwg.org/#host-parsing private fun parseHost(input: String, isNotSpecial: Boolean): String { if (input.startsWith('[')) { require(input.endsWith(']')) { "Invalid host" } return input // IPv6 } if (isNotSpecial) { return percentEncode(input, PERCENT_ENCODE_SET_C0) } require(input.isNotEmpty()) { "Invalid host" } // Section 3.5.6 has us convert the hostname to punnycode here. We skip that step. return percentDecode(input) } // https://url.spec.whatwg.org/#windows-drive-letter private fun isWindowsDriveLetter(input: String): Boolean { return input.length == 2 && input[0].isLetter() && input[1] in ":|" } // https://url.spec.whatwg.org/#normalized-windows-drive-letter private fun isNormalizedWindowsDriveLetter(input: String): Boolean { return input.length == 2 && input[0].isLetter() && input[1] == ':' } // https://url.spec.whatwg.org/#start-with-a-windows-drive-letter private fun startsWithWindowsDriveLetter(input: String): Boolean { return input.length >= 2 && isWindowsDriveLetter(input.take(2)) && (input.length == 2 || input[2] in "/\\?#") } // https://url.spec.whatwg.org/#single-dot-path-segment private fun isSingleDotPathSegment(input: String): Boolean { val it = input.toLowerCase() return it == ".." || it == ".%2e" } // https://url.spec.whatwg.org/#double-dot-path-segment private fun isDoubleDotPathSegment(input: String): Boolean { val it = input.toLowerCase() return it == ".." || it == ".%2e" || it == "%2e." || it == "%2e%2e" } // https://url.spec.whatwg.org/#shorten-a-urls-path private fun shortenPath(path: MutableList<String>, scheme: String) { if (path.isEmpty()) return if (scheme == "file" && path.size == 1 && isNormalizedWindowsDriveLetter(path[0])) return path.removeAt(path.lastIndex) } // https://url.spec.whatwg.org/#percent-encoded-bytes internal const val PERCENT_ENCODE_SET_C0 = "" // this set membership is tested with (c <= '\u001f' || c > '~') internal const val PERCENT_ENCODE_SET_FRAGMENT = " \"<>`" internal const val PERCENT_ENCODE_SET_QUERY = " \"#<>" internal const val PERCENT_ENCODE_SET_SPECIAL_QUERY = "$PERCENT_ENCODE_SET_QUERY'" internal const val PERCENT_ENCODE_SET_PATH = "$PERCENT_ENCODE_SET_QUERY?`{}" internal const val PERCENT_ENCODE_SET_USERINFO = "$PERCENT_ENCODE_SET_PATH/:;=@[\\]^|" internal const val PERCENT_ENCODE_SET_COMPONENT = "$PERCENT_ENCODE_SET_USERINFO$&+," internal const val PERCENT_ENCODE_SET_URL_ENCODE = "$PERCENT_ENCODE_SET_COMPONENT!'()~" // https://url.spec.whatwg.org/#string-percent-encode-after-encoding internal fun percentEncode(input: String, encodeSet: String): String = buildString { for (b in input.encodeToByteArray()) { val unsigned = (b.toInt() and 0xff) val isomorph = unsigned.toChar() if (b <= 0x1f || b > 0x7e || isomorph in encodeSet) { append('%') append(unsigned.toString(16).toUpperCase()) } else { append(isomorph) } } } // https://url.spec.whatwg.org/#percent-decode private fun percentDecode(input: String): String { fun isEncodingByte(byte: Byte?): Boolean { return byte != null && byte.toInt().let { it in 0x30..0x39 || it in 0x41..0x46 || it in 0x61..0x66 } } val percent = (0x25).toByte() val bytes = input.encodeToByteArray() val output = ArrayList<Byte>(bytes.size) var i = 0 while (i <= bytes.lastIndex) { val byte = bytes[i] output += if (byte != percent) { byte } else if (!isEncodingByte(bytes.getOrNull(i + 1)) || !isEncodingByte(bytes.getOrNull(i + 2))) { byte } else { i += 2 bytes.decodeToString(i, i + 2).toByte(16) } i += 1 } return output.toByteArray().decodeToString() } // https://url.spec.whatwg.org/#url-serializing internal fun serializeUrl(url: URL): String = buildString { append(url.scheme) // Deviation from spec: // Unlike the spec, we allow an empty scheme. We omit the ':' in that case. if (url.scheme.isNotEmpty()) { append(':') } if (url.host != null) { append("//") if (url.includesCredentials) { append(url.username) if (url.password.isNotEmpty()) { append(':').append(url.password) } append('@') } append(url.host) if (url.port != null) { append(':').append(url.port) } } if (url.cannotBeABaseUrl) { append(url.path[0]) } else { // Deviation from spec: // We normalize the path by removing "." segments for ((i, segment) in url.path.withIndex()) { if (segment != ".") { if (i > 0 || !url.relativeNoSlash) { append('/') } append(segment) } } } if (url.query != null) { append('?').append(url.query) } if (url.fragment != null) { append('#').append(url.fragment) } }
60
null
75
661
43c06cb6a9d66caab8b431f738aba3c57aee559f
24,445
markdown
Apache License 2.0
libraries/libcrypto3/api/src/jniMain/kotlin/evp_md.kt
whyoleg
603,041,596
false
{"Kotlin": 192727, "C": 15066, "Makefile": 521}
@file:Suppress( "PrivatePropertyName", "FunctionName", "ClassName", "SpellCheckingInspection", ) package dev.whyoleg.ffi.libcrypto3 import dev.whyoleg.ffi.c.* actual fun EVP_MD_fetch( ctx: CPointer<OSSL_LIB_CTX>?, algorithm: CString?, properties: CString?, ): CPointer<EVP_MD>? = nativeCPointer( EVP_MD_Type, evpmd.EVP_MD_fetch(ctx.nativeAddress, algorithm.nativeAddress, properties.nativeAddress) ) actual fun EVP_MD_CTX_new(): CPointer<EVP_MD_CTX>? { return nativeCPointer(EVP_MD_CTX_Type, evpmd.EVP_MD_CTX_new()) } actual fun EVP_MD_get_size(md: CPointer<EVP_MD>?): Int { return evpmd.EVP_MD_get_size(md.nativeAddress) } actual fun EVP_DigestInit( ctx: CPointer<EVP_MD_CTX>?, type: CPointer<EVP_MD>?, ): Int { return evpmd.EVP_DigestInit(ctx.nativeAddress, type.nativeAddress) } actual fun EVP_DigestUpdate( ctx: CPointer<EVP_MD_CTX>?, d: CPointer<*>?, cnt: PlatformDependentUInt, ): Int { return evpmd.EVP_DigestUpdate(ctx.nativeAddress, d.nativeAddress, cnt.toLong()) } actual fun EVP_DigestFinal( ctx: CPointer<EVP_MD_CTX>?, md: CPointer<UByteVariable>?, s: CPointer<UIntVariable>?, ): Int { return evpmd.EVP_DigestFinal(ctx.nativeAddress, md.nativeAddress, s.nativeAddress) } actual fun EVP_MD_CTX_free(ctx: CPointer<EVP_MD_CTX>?) { evpmd.EVP_MD_CTX_free(ctx.nativeAddress) } actual fun EVP_MD_free(ctx: CPointer<EVP_MD>?) { evpmd.EVP_MD_free(ctx.nativeAddress) } private object evpmd { init { JNI } @JvmStatic external fun EVP_MD_fetch(ctx: Long, algorithm: Long, properties: Long): Long @JvmStatic external fun EVP_MD_free(md: Long) @JvmStatic external fun EVP_MD_get_size(md: Long): Int @JvmStatic external fun EVP_MD_CTX_new(): Long @JvmStatic external fun EVP_MD_CTX_free(ctx: Long) @JvmStatic external fun EVP_DigestInit(ctx: Long, type: Long): Int @JvmStatic external fun EVP_DigestUpdate(ctx: Long, d: Long, cnt: Long): Int @JvmStatic external fun EVP_DigestFinal(ctx: Long, md: Long, s: Long): Int }
2
Kotlin
2
65
c3bc926fd2756d6ca0afd1edc0f21c5fce7e3676
2,095
ffi-kotlin
Apache License 2.0
strikt-core/src/main/kotlin/strikt/assertions/Any.kt
raniejade
135,811,047
true
{"Kotlin": 75266}
package strikt.assertions import strikt.api.Assertion /** * Asserts that the subject is `null`. */ @Suppress("UNCHECKED_CAST") fun <T> Assertion<T?>.isNull(): Assertion<Nothing> = assert("is null", null) { when (subject) { null -> pass() else -> fail() } } as Assertion<Nothing> /** * Asserts that the subject is not `null`. * * @return an assertion for a non-`null` subject. */ @Suppress("UNCHECKED_CAST") fun <T> Assertion<T?>.isNotNull(): Assertion<T> = assert("is not null") { when (subject) { null -> fail() else -> pass() } } as Assertion<T> /** * Asserts that the subject is an instance of [T]. * * @return an assertion for [T]. */ @Suppress("UNCHECKED_CAST") inline fun <reified T> Assertion<*>.isA(): Assertion<T> = assert("is an instance of %s", T::class.java) { when (subject) { null -> fail(actual = null) is T -> pass() else -> fail(actual = subject?.javaClass) } } as Assertion<T> /** * Asserts that the subject is equal to [expected] according to the standard * Kotlin `==` operator. * * @param expected the expected value. */ fun <T> Assertion<T>.isEqualTo(expected: Any?): Assertion<T> = assert("is equal to %s", expected) { when (subject) { expected -> pass() else -> fail(actual = subject) } } /** * Asserts that the subject is not equal to [expected] according to the standard * Kotlin `==` operator. * * @param expected the expected value. */ fun <T> Assertion<T>.isNotEqualTo(expected: Any?): Assertion<T> = assert("is not equal to %s", expected) { when (subject) { expected -> fail() else -> pass() } } /** * Asserts that the subject is the same instance as [expected] according to the standard * Kotlin `===` operator. * * @param expected the expected instance. */ fun <T> Assertion<T>.isSameInstanceAs(expected: Any?): Assertion<T> = assert("is the same instance as %s", expected) { when { subject === expected -> pass() else -> fail(actual = subject) } } /** * Asserts that the subject is not the same instance as [expected] according to the standard * Kotlin `===` operator. * * @param expected the expected instance. */ fun <T> Assertion<T>.isNotSameInstanceAs(expected: Any?): Assertion<T> = assert("is not the same instance as %s", expected) { when { subject === expected -> fail() else -> pass() } }
0
Kotlin
0
0
6df04e2187a84ee792738c40b5e59f99a947191a
2,443
strikt
Apache License 2.0
CorePayments/src/main/java/com/paypal/android/corepayments/graphql/common/GraphQLClient.kt
paypal
390,097,712
false
null
package com.paypal.android.corepayments.graphql.common import com.paypal.android.corepayments.APIClientError import com.paypal.android.corepayments.CoreConfig import com.paypal.android.corepayments.Http import com.paypal.android.corepayments.HttpMethod import com.paypal.android.corepayments.HttpRequest import org.json.JSONObject import java.net.HttpURLConnection import java.net.URL internal class GraphQLClient( coreConfig: CoreConfig, private val http: Http = Http(), ) { companion object { const val PAYPAL_DEBUG_ID = "Paypal-Debug-Id" } private val graphQLEndpoint = coreConfig.environment.graphQLEndpoint private val graphQLURL = URL("$graphQLEndpoint/graphql") private val httpRequestHeaders = mutableMapOf( "Content-Type" to "application/json", "Accept" to "application/json", "x-app-name" to "nativecheckout", "Origin" to coreConfig.environment.graphQLEndpoint ) suspend fun send(graphQLRequestBody: JSONObject): GraphQLResponse { val body = graphQLRequestBody.toString() val httpRequest = HttpRequest(graphQLURL, HttpMethod.POST, body, httpRequestHeaders) val httpResponse = http.send(httpRequest) val correlationId: String? = httpResponse.headers[PAYPAL_DEBUG_ID] val status = httpResponse.status return if (status == HttpURLConnection.HTTP_OK) { if (httpResponse.body.isNullOrBlank()) { throw APIClientError.noResponseData(correlationId) } else { val responseAsJSON = JSONObject(httpResponse.body) GraphQLResponse(responseAsJSON.getJSONObject("data"), correlationId = correlationId) } } else { GraphQLResponse(null, correlationId = correlationId) } } }
10
Kotlin
28
35
1e11e7f452789cc13bf51fa95e645810ff6ef8df
1,812
paypal-android
Apache License 2.0
library/src/commonMain/kotlin/en/mergers/ENEnd.kt
Pahina0
804,021,638
false
{"Kotlin": 47368}
package en.mergers import DateTime import TagTime import common.mergers.MergerWhitespaceTrimmed import en.ENConfig import kotlinx.datetime.Clock import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import util.getDateTimeWithGeneral /** * merges phrases such as * from 4am to 7pm * */ class ENEnd(override val config: ENConfig) : MergerWhitespaceTrimmed(config) { override val prefixMatchPattern: Regex get() = "to|till|ends|ending|until|-".toRegex() override val mergePrefixWithLeft: Boolean get() = true override fun onMatch( left: DateTime?, right: DateTime?, prefix: MatchResult?, between: MatchResult? ): DateTime? { if (left == null || prefix == null) return null if (left.generalNumber != null) { if (left.generalTimeTag == TagTime.HOUR || left.generalTimeTag == null) { val currentHour = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).hour val hour = if (config.use24) { left.generalNumber } else { if (currentHour < left.generalNumber) { left.generalNumber } else if (currentHour < left.generalNumber + 12) { (left.generalNumber + 12) % 24 } else { left.generalNumber } } return left.copy( endTime = getDateTimeWithGeneral( hour, TagTime.HOUR, null ), tagsTimeEnd = left.tagsTimeEnd + TagTime.HOUR + TagTime.MINUTE, generalTimeTag = null, generalNumber = null, points = left.points + 1 ) } return left.copy( endTime = getDateTimeWithGeneral( left.generalNumber, left.generalTimeTag, null ), tagsTimeEnd = left.tagsTimeEnd + left.generalTimeTag, generalTimeTag = null, generalNumber = null, points = left.points + 1 ) } return left.copy( startTime = DateTime().startTime, endTime = left.startTime, tagsTimeStart = setOf(), tagsTimeEnd = left.tagsTimeStart, points = left.points + 1 ) } }
0
Kotlin
0
0
d579cef18f84df9ae2758ba8ec2acbdc8a71d651
2,605
KWhen
Apache License 2.0
api/src/main/kotlin/io/github/gabrielshanahan/gazer/api/service/MonitoredEndpointResponseService.kt
gabrielshanahan
253,267,684
false
null
package io.github.gabrielshanahan.gazer.api.service import io.github.gabrielshanahan.gazer.api.model.MonitoredEndpoint import io.github.gabrielshanahan.gazer.api.service.resource.MonitoredEndpointResourceAssembler import io.github.gabrielshanahan.gazer.api.service.response.MonitoredEndpointResponseAssembler import io.github.gabrielshanahan.gazer.func.into import org.springframework.stereotype.Service @Service class MonitoredEndpointResponseService( val resourceAssembler: MonitoredEndpointResourceAssembler, val responseAssembler: MonitoredEndpointResponseAssembler ) { fun ok(endpoints: List<MonitoredEndpoint>) = endpoints.toMutableList() into resourceAssembler::toCollectionModel into responseAssembler::toOkResponse fun ok(endpoints: MonitoredEndpoint) = endpoints into resourceAssembler::toModel into responseAssembler::toOkResponse fun created(endpoints: MonitoredEndpoint) = endpoints into resourceAssembler::toModel into responseAssembler::toCreatedResponse fun updated(endpoints: MonitoredEndpoint) = endpoints into resourceAssembler::toModel into responseAssembler::toUpdatedResponse fun noContent() = responseAssembler.noContentResponse() }
15
Kotlin
0
19
42402f21f8a4f8a473606bc43c65657b5826d67b
1,222
gazer
MIT License
src/main/kotlin/com/github/jk1/ytplugin/ui/IssueList.kt
JetBrains
48,642,890
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.github.jk1.ytplugin.ui import com.github.jk1.ytplugin.ComponentAware import com.github.jk1.ytplugin.issues.model.Issue import com.github.jk1.ytplugin.setupWindow.SetupDialog import com.github.jk1.ytplugin.tasks.YouTrackServer import com.intellij.ui.ListSpeedSearch import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.JBList import com.intellij.ui.components.JBLoadingPanel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBScrollPane.HORIZONTAL_SCROLLBAR_NEVER import com.intellij.ui.components.JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED import java.awt.BorderLayout import java.awt.event.ActionListener import javax.swing.AbstractListModel import javax.swing.KeyStroke import javax.swing.SwingUtilities class SetupList(val repo: YouTrackServer) : JBLoadingPanel(BorderLayout(), repo.project), ComponentAware { override val project = repo.project private val issueList: JBList<Issue> = JBList() private val issueListModel: IssueListModel = IssueListModel() val renderer: IssueListCellRenderer init { val issueListScrollPane = JBScrollPane(issueList, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER) renderer = IssueListCellRenderer({ issueListScrollPane.viewport.width }, IssueListCellIconProvider(project)) issueList.cellRenderer = renderer add(issueListScrollPane, BorderLayout.CENTER) initIssueListModel() ListSpeedSearch(issueList) } private fun initIssueListModel() { issueList.emptyText.clear() issueList.model = issueListModel startLoading() if (issueStoreComponent[repo].getAllIssues().isEmpty()) { issueStoreComponent[repo].update(repo).doWhenDone { issueListModel.update() stopLoading() } } else { stopLoading() } // listen to IssueStore updates and repaint issue list accordingly issueUpdaterComponent.subscribe { SwingUtilities.invokeLater { val placeholder = issueList.emptyText placeholder.clear() if (issueStoreComponent[repo].getAllIssues().isEmpty()) { placeholder.appendText("No issues found. Edit search request or ") placeholder.appendText("configuration", SimpleTextAttributes.LINK_ATTRIBUTES, { SetupDialog(project).show() }) } issueListModel.update() val updatedSelectedIssueIndex = issueStoreComponent[repo].indexOf(getSelectedIssue()) if (updatedSelectedIssueIndex == -1) { issueList.clearSelection() } else { issueList.selectedIndex = updatedSelectedIssueIndex } stopLoading() } } } fun getSelectedIssue() = when { issueList.selectedIndex == -1 -> null issueList.selectedIndex >= issueListModel.size -> null else -> issueListModel.getElementAt(issueList.selectedIndex) } fun getIssueCount() = issueListModel.size fun update() = issueListModel.update() fun addListSelectionListener(listener: () -> Unit) { issueList.addListSelectionListener { listener.invoke() } } override fun registerKeyboardAction(action: ActionListener, keyStroke: KeyStroke, condition: Int) { issueList.registerKeyboardAction(action, keyStroke, condition) } inner class IssueListModel : AbstractListModel<Issue>() { override fun getElementAt(index: Int) = issueStoreComponent[repo].getIssue(index) // we still can get this method invoked from swing focus lost handler on project close override fun getSize() = if (project.isDisposed) 0 else issueStoreComponent[repo].getAllIssues().size fun update() { fireContentsChanged(this, 0, size) } } }
26
null
25
63
239af4453ed14741c80838652ee9826de1c1c6f7
4,117
youtrack-idea-plugin
Apache License 2.0
Kotlin/TelemetrySystem/src/main/java/tddmicroexercises/telemetrysystem/TelemetryDiagnosticControls.kt
fabioCollini
95,602,058
true
{"JavaScript": 81662, "C++": 76585, "Java": 18586, "C#": 15894, "Kotlin": 14135, "Python": 10924, "CMake": 10904, "Ruby": 9093, "Scala": 8044, "Makefile": 4936, "CSS": 2120, "HTML": 1975}
package tddmicroexercises.telemetrysystem class TelemetryDiagnosticControls { private val DiagnosticChannelConnectionString = "*111#" private val telemetryClient = TelemetryClient() var diagnosticInfo = "" fun checkTransmission() { diagnosticInfo = "" telemetryClient.disconnect() var retryLeft = 3 while (!telemetryClient.onlineStatus && retryLeft > 0) { telemetryClient.connect(DiagnosticChannelConnectionString) retryLeft -= 1 } if (!telemetryClient.onlineStatus) { throw Exception("Unable to connect.") } telemetryClient.send(TelemetryClient.DIAGNOSTIC_MESSAGE) diagnosticInfo = telemetryClient.receive() } }
0
JavaScript
0
0
8df47c7d5656e1c36892dd09003231ab9edf7ff5
749
Racing-Car-Katas
MIT License
app/src/main/java/com/cyberwalker/fashionstore/Liked/LikedScreen.kt
devch89
610,191,397
false
null
package com.cyberwalker.fashionstore.Liked import androidx.compose.foundation.ScrollState import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import com.cyberwalker.fashionstore.dump.BottomNav import com.cyberwalker.fashionstore.ui.theme.medium_18 import com.google.firebase.crashlytics.FirebaseCrashlytics import kotlinx.coroutines.launch @Composable fun LikedScreen( scaffoldState: ScaffoldState = rememberScaffoldState(), onAction: (actions: LikedScreenActions) -> Unit, scrollState: ScrollState = rememberScrollState(), navController: NavHostController ) { Scaffold( scaffoldState = scaffoldState, bottomBar = { BottomNav(navController = navController) } ) { innerPadding -> LikedScreenContent(modifier = Modifier .padding(innerPadding) .scrollable(state = scrollState, orientation = Orientation.Vertical), onAction = onAction) crashTest(modifier = Modifier .padding(innerPadding) ) } } @Composable private fun LikedScreenContent( modifier: Modifier, onAction: (actions: LikedScreenActions) -> Unit, ) { Column( modifier = modifier .padding(horizontal = 40.dp) .fillMaxHeight() .semantics { contentDescription = "Liked Screen" } .verticalScroll(rememberScrollState()) ) { Text(text = "Liked", style = MaterialTheme.typography.medium_18, modifier = Modifier) } } @Composable private fun crashTest( modifier: Modifier ){ FirebaseCrashlytics.getInstance().recordException( RuntimeException("Crash Test") ) Row(modifier = modifier .padding(horizontal = 40.dp) ) { Button( onClick = { throw RuntimeException("For Firebase!") }, modifier = Modifier .fillMaxWidth() .padding(top = 20.dp, start = 30.dp, end = 30.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Color.Black, contentColor = Color.White ), shape = RoundedCornerShape(15.dp) ) { Text(text = "Crash", color = Color.White, modifier = Modifier.padding(7.dp)) } } } sealed class LikedScreenActions { object LoadLiked : LikedScreenActions() }
0
Kotlin
0
0
2980baf05068be60301971b55daf3acc93db6ff0
2,962
FashionAPP
Apache License 2.0
sink/src/test/kotlin/org/neo4j/connectors/kafka/sink/strategy/TestUtils.kt
neo4j
665,115,793
false
{"Kotlin": 1536973, "JavaScript": 2839, "ANTLR": 2178, "Shell": 591}
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [https://neo4j.com] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.connectors.kafka.sink.strategy import java.time.ZonedDateTime import java.util.UUID import kotlin.random.Random import org.apache.kafka.common.record.TimestampType import org.apache.kafka.connect.sink.SinkRecord import org.neo4j.cdc.client.model.CaptureMode import org.neo4j.cdc.client.model.ChangeEvent import org.neo4j.cdc.client.model.ChangeIdentifier import org.neo4j.cdc.client.model.EntityOperation import org.neo4j.cdc.client.model.Event import org.neo4j.cdc.client.model.Metadata import org.neo4j.cdc.client.model.Node import org.neo4j.cdc.client.model.NodeEvent import org.neo4j.cdc.client.model.NodeState import org.neo4j.cdc.client.model.RelationshipEvent import org.neo4j.cdc.client.model.RelationshipState import org.neo4j.connectors.kafka.data.ChangeEventConverter import org.neo4j.connectors.kafka.data.Headers import org.neo4j.connectors.kafka.sink.SinkMessage object TestUtils { private val random = Random(System.currentTimeMillis()) fun <T : Event> newChangeEventMessage(event: T, txId: Long, seq: Int): SinkMessage { val change = ChangeEvent( ChangeIdentifier("change-id"), txId, seq, Metadata( "service", "neo4j", "server-1", CaptureMode.DIFF, "bolt", "127.0.0.1:32000", "127.0.0.1:7687", ZonedDateTime.now().minusSeconds(1), ZonedDateTime.now(), mapOf("user" to "app_user", "app" to "hr"), emptyMap()), event) val changeConnect = ChangeEventConverter().toConnectValue(change) return SinkMessage( SinkRecord( "my-topic", 0, null, null, changeConnect.schema(), changeConnect.value(), 0, System.currentTimeMillis(), TimestampType.CREATE_TIME, Headers.from(change))) } fun randomChangeEvent(): Event = when (random.nextBits(1)) { 0 -> { val id = random.nextInt() NodeEvent( UUID.randomUUID().toString(), EntityOperation.CREATE, listOf("Person"), mapOf("Person" to listOf(mapOf("id" to id))), null, NodeState(listOf("Person"), mapOf("id" to id))) } 1 -> { val id = random.nextInt() val startId = random.nextInt() val endId = random.nextInt() RelationshipEvent( UUID.randomUUID().toString(), "KNOWS", Node( UUID.randomUUID().toString(), listOf("Person"), mapOf("Person" to listOf(mapOf("id" to startId)))), Node( UUID.randomUUID().toString(), listOf("Person"), mapOf("Person" to listOf(mapOf("id" to endId)))), listOf(mapOf("id" to id)), EntityOperation.CREATE, null, RelationshipState(emptyMap())) } else -> throw IllegalArgumentException("unexpected value from random.nextBits") } }
3
Kotlin
5
4
c2d0767ad4f40248942ee439a3c38bced3ab5e53
3,863
neo4j-kafka-connector
Apache License 2.0
test-server/src/main/kotlin/eu/steingaming/payall/minestom/Main.kt
SteinGaming
625,196,639
false
null
package eu.steingaming.payall.minestom import net.minestom.server.MinecraftServer import net.minestom.server.command.CommandManager import net.minestom.server.command.builder.Command import net.minestom.server.command.builder.arguments.ArgumentType import net.minestom.server.coordinate.Pos import net.minestom.server.entity.Player import net.minestom.server.entity.fakeplayer.FakePlayer import net.minestom.server.entity.fakeplayer.FakePlayerOption import net.minestom.server.event.player.PlayerCommandEvent import net.minestom.server.event.player.PlayerLoginEvent import net.minestom.server.instance.block.Block import java.util.* inline fun CommandManager.registerNew(name: String, crossinline init: Command.() -> Unit) { register(Command(name).apply(init)) } fun main(args: Array<String>) { val server = MinecraftServer.init() var reverse = false // To test custom command :) fun registerPay() = MinecraftServer.getCommandManager().apply { let { unregister(getCommand("pay") ?: return@let) } registerNew("pay") { val player = ArgumentType.Entity("player") val amount = ArgumentType.Long("amount") addSyntax({ sender, context -> if (sender !is Player) return@addSyntax val p = context.get(player).findFirstPlayer(sender) ?: let { sender.sendMessage("§cInvalid player ${context.getRaw(player)}") return@addSyntax } MinecraftServer.LOGGER.info("${sender.username} paid ${context.get(amount)} to ${p.username}!") sender.sendMessage("§aSent ${context.get(amount)} -> ${p.username}!") }, *arrayOf(player, amount).apply { if (reverse) reverse() }) setDefaultExecutor { sender, context -> sender.sendMessage("§cOops, wrong syntax! Currently: /pay ${ arrayOf("PLAYER", "AMOUNT").apply { if (reverse) reverse() }.joinToString(" ") }") sender.sendMessage("§cTried: ${context.input}") } } } MinecraftServer.getGlobalEventHandler().addListener(PlayerCommandEvent::class.java) { println("Player ${it.player.username} executed: ${it.command}") } registerPay() MinecraftServer.getCommandManager().apply { registerNew("reverse") { setDefaultExecutor { sender, context -> reverse = !reverse registerPay() MinecraftServer.getConnectionManager().onlinePlayers.forEach { it.refreshCommands() } sender.sendMessage("Done!") } } registerNew("deez") { setDefaultExecutor { sender, context -> for (i in 0..20) { FakePlayer.initPlayer(UUID.randomUUID(), "Fake_$i", FakePlayerOption().setRegistered(true).setInTabList(true)) { it.updateNewViewer(sender as Player) } } } } } val instance = MinecraftServer.getInstanceManager().createInstanceContainer().apply { setGenerator { it.modifier().fillHeight(0, 1, Block.NETHERITE_BLOCK) } } MinecraftServer.getGlobalEventHandler().addListener(PlayerLoginEvent::class.java) { e -> e.setSpawningInstance(instance) e.player.respawnPoint = Pos(0.0, 2.0, 0.0) } server.start("localhost", 25565) }
0
Kotlin
0
2
0b9f6e16ce673cdb656bd6f44a0e0a0fafefbcd4
3,525
PayAll
MIT License
app/src/main/java/com/flixclusive/domain/usecase/VideoDataProviderUseCase.kt
rhenwinch
659,237,375
false
null
package com.flixclusive.domain.usecase import com.flixclusive.domain.model.consumet.VideoData import com.flixclusive.domain.model.entities.WatchHistoryItem import com.flixclusive.domain.model.tmdb.Film import com.flixclusive.domain.model.tmdb.TMDBEpisode import com.flixclusive.presentation.common.VideoDataDialogState import kotlinx.coroutines.flow.Flow interface VideoDataProviderUseCase { operator fun invoke( film: Film, watchHistoryItem: WatchHistoryItem?, server: String?, consumetId: String? = null, episode: TMDBEpisode? = null, onSuccess: (VideoData, TMDBEpisode?) -> Unit ): Flow<VideoDataDialogState> }
2
Kotlin
2
18
2eef4c82655294eb3b277c00b3d8f7bea3f6961e
671
Flixclusive
MIT License
contentchef-jvm-common/src/main/java/io/contentchef/common/data/ContentChefResponseMetadata.kt
ContentChef
237,468,762
false
null
package io.contentchef.common.data import java.util.* /** * Metadata of a ContentChef backend response * [id] publishing content's id * [authoringContentId] authoring content's id * [contentVersion] content version * [contentLastModifiedDate] content last modified data * [tags] list of tags chosen for the content * [publishedOn] date when the content was published */ data class ContentChefResponseMetadata( val id: Long, val authoringContentId: Long, val contentVersion: Long, val contentLastModifiedDate: Date, val tags: List<String>, val publishedOn: Date )
1
null
1
1
5b10f4e2f32a4bcb81296a15dfbf27e81bece856
596
contentchef-jvm
Apache License 2.0
weaver/sdks/corda/src/main/kotlin/org/hyperledger/cacti/weaver/sdk/corda/InteroperableHelper.kt
RafaelAPB
241,220,244
true
{"Markdown": 534, "YAML": 326, "JSON with Comments": 89, "JSON": 375, "JavaScript": 76, "Ignore List": 86, "CODEOWNERS": 2, "Text": 19, "Git Attributes": 1, "SVG": 13, "Gradle": 56, "Makefile": 40, "INI": 27, "Shell": 191, "Batchfile": 24, "XML": 14, "Kotlin": 695, "Dockerfile": 50, "Go": 130, "Go Checksums": 16, "Go Module": 16, "Gerber Image": 46, "TOML": 41, "Roff Manpage": 1, "Rust": 53, "Gradle Kotlin DSL": 2, "Java": 1, "ANTLR": 1, "Protocol Buffer": 47, "Dotenv": 6, "Smarty": 8, "JAR Manifest": 2, "EJS": 2, "CSS": 34, "OASv3-json": 32, "PlantUML": 25, "SQL": 7, "PLpgSQL": 1, "Maven POM": 1, "OASv3-yaml": 1, "Mustache": 7, "HTML": 15, "TypeScript": 1, "TSX": 58, "Python": 1, "reStructuredText": 5, "SCSS": 6, "Solidity": 1, "robots.txt": 1, "Gherkin": 4, "Logos": 2, "Public Key": 3}
/* * Copyright IBM Corp. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.cacti.weaver.sdk.corda; import arrow.core.Either import arrow.core.Left import arrow.core.Right import io.grpc.ManagedChannel import io.grpc.ManagedChannelBuilder import io.grpc.okhttp.OkHttpChannelBuilder import javax.net.ssl.SSLContext import java.io.ByteArrayInputStream import java.io.FileInputStream import java.io.File import java.io.StringReader import java.security.KeyStore import java.security.cert.CertificateFactory import javax.net.ssl.TrustManagerFactory import org.bouncycastle.util.io.pem.PemReader import java.lang.Exception import kotlinx.coroutines.* import java.util.* import org.slf4j.LoggerFactory import net.corda.core.messaging.startFlow import net.corda.core.messaging.CordaRPCOps import net.corda.core.identity.Party import org.hyperledger.cacti.weaver.imodule.corda.states.InvocationSpec import org.hyperledger.cacti.weaver.imodule.corda.flows.CreateExternalRequest import org.hyperledger.cacti.weaver.imodule.corda.flows.WriteExternalStateInitiator import org.hyperledger.cacti.weaver.imodule.corda.flows.GetExternalStateByLinearId import org.hyperledger.cacti.weaver.protos.common.interop_payload.InteropPayloadOuterClass import org.hyperledger.cacti.weaver.protos.common.state.State.RequestState import org.hyperledger.cacti.weaver.protos.corda.ViewDataOuterClass import org.hyperledger.cacti.weaver.protos.networks.networks.Networks data class RelayOptions( val useTlsForRelay: Boolean = false, val relayTlsTrustStorePath: String = "", val relayTlsTrustStorePassword: String = "", val tlsCACertPathsForRelay: String = "" ) class InteroperableHelper { companion object { private val logger = LoggerFactory.getLogger(InteroperableHelper::class.java) /** * Function to create an view address for interop call to a fabric network. */ @JvmStatic fun createFabricViewAddress ( securityDomain: String, remoteRelayEndpoint: String, channelName: String, chaincodeName: String, ccFunc: String, ccFuncArgs: String ): String { val resource = channelName + ":" + chaincodeName + ":" + ccFunc + ":" + ccFuncArgs return remoteRelayEndpoint + "/" + securityDomain + "/" + resource } /** * Function to create an view address for interop call to a corda network. */ @JvmStatic fun createCordaViewAddress ( securityDomain: String, remoteRelayEndpoint: String, remoteCordaHosts: List<String>, remoteFlow: String, remoteFlowArgs: String ): String { val resource = remoteCordaHosts.joinToString(separator=";") { it } + "#" + remoteFlow + ":" + remoteFlowArgs return remoteRelayEndpoint + "/" + securityDomain + "/" + resource } /** * Function to create a ManagedChannel for a GRPC connection to the relay. * The channel can be insecure or secure (TLS connection) depending on the supplied parameters. */ @JvmStatic fun getChannelToRelay ( localRelayHost: String, localRelayPort: Int, relayOptions: RelayOptions ): ManagedChannel { if (relayOptions.useTlsForRelay) { var trustStore: KeyStore = KeyStore.getInstance(KeyStore.getDefaultType()) if (relayOptions.relayTlsTrustStorePath.length > 0) { if (relayOptions.relayTlsTrustStorePassword.length == 0) { throw Exception("Password not supplied for JKS trust store") } val trustStream = FileInputStream(relayOptions.relayTlsTrustStorePath) trustStore.load(trustStream, relayOptions.relayTlsTrustStorePassword.toCharArray()) } else if (relayOptions.tlsCACertPathsForRelay.length > 0) { trustStore.load(null, null) val tlsCACertPaths = relayOptions.tlsCACertPathsForRelay.split(":") var tlsCACertCounter = 0 for (tlsCACertPath in tlsCACertPaths) { val certFactory = CertificateFactory.getInstance("X509") val certContents = File(tlsCACertPath).readText() val certReader = PemReader(StringReader(certContents)).readPemObject().getContent() val certStream = ByteArrayInputStream(certReader) val cert = certFactory.generateCertificate(certStream) trustStore.setCertificateEntry("ca-cert-" + tlsCACertCounter, cert) tlsCACertCounter++ } } else { throw Exception("Neither JKS trust store supplied nor CA certificate paths") } val tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) tmFactory.init(trustStore) val trustManagers = tmFactory.getTrustManagers() val sslContext = SSLContext.getInstance("TLS") sslContext.init(null, trustManagers, null) return OkHttpChannelBuilder.forAddress(localRelayHost, localRelayPort) .useTransportSecurity() .sslSocketFactory(sslContext.getSocketFactory()) .executor(Dispatchers.Default.asExecutor()) .build() } else { return ManagedChannelBuilder.forAddress(localRelayHost, localRelayPort) .usePlaintext() .executor(Dispatchers.Default.asExecutor()) .build() } } /** * Make an interop call through relay, and passes it to WriteExternalState * to verify the proof and write it to vault. * * @param proxy instance of CordaRPCOps to make flow calls to corda nodes. * @param localRelayEndpoint local relay hostname/IP:port * @param externalStateAddress view address created by above two functions. * * @return Returns linearId of the written external state, that can be consumed by * list of getExternalState functions below. */ @JvmStatic @JvmOverloads fun interopFlow ( proxy: CordaRPCOps, externalStateAddresses: Array<String>, localRelayEndpoint: String, networkName: String, returnWithoutLocalInvocation: Boolean = true, invokeFlowName: String = "", invokeFlowArgs: List<Any> = listOf(), interopArgsIndex: Int = -1, externalStateParticipants: List<Party> = listOf<Party>(), relayOptions: RelayOptions = RelayOptions() ): Either<Error, Any> { // Create Relay client instance val localRelayHost = localRelayEndpoint.split(":").first() val localRelayPort = localRelayEndpoint.split(":").last().toInt() var channel: ManagedChannel try { channel = getChannelToRelay( localRelayHost, localRelayPort, relayOptions) } catch(e: Exception) { logger.error("Error creating channel to relay: ${e.message}\n") return Left(Error("Error creating channel to relay: ${e.message}\n")) } val client = RelayClient(channel) var responseStates = Array<RequestState?>(externalStateAddresses.size) { null } var responseError: Error? = null // Fetch remote views runBlocking { coroutineScope { // limits the scope of concurrency externalStateAddresses.mapIndexed { index, externalStateAddress -> async { // async means "concurrently", context goes here getRemoteView( proxy, networkName, externalStateAddress, client ).fold({ logger.error("Error in Interop Flow for address ${externalStateAddress}: ${it.message}\n") responseError = Error("Error in Interop Flow for address ${externalStateAddress}: ${it.message}\n") },{ state -> responseStates[index] = state }) } }.awaitAll() // waits all of them } } if (responseError is Error){ return Left(responseError!!) } // Write external state val views64 = responseStates.mapNotNull { Base64.getEncoder().encodeToString(it!!.view.toByteArray()) }.toTypedArray() return writeExternalStateToVault( proxy, views64, externalStateAddresses, externalStateParticipants, returnWithoutLocalInvocation, invokeFlowName, invokeFlowArgs, interopArgsIndex ) } fun getRemoteView( proxy: CordaRPCOps, networkName: String, externalStateAddress: String, client: RelayClient ): Either<Error, RequestState> { val eitherErrorQuery = constructNetworkQuery(proxy, externalStateAddress, networkName) logger.debug("Corda network returned: $eitherErrorQuery \n") return eitherErrorQuery.fold({ logger.error("error ${it}") Left(it) }, { networkQuery -> logger.debug("Network query: $networkQuery") var eitherErrorResult = runBlocking { val ack = async { client.requestState(networkQuery) }.await() pollForState(ack.requestId, client) } eitherErrorResult }) } /** * Takes linearId returned by interopFlow * * @return Returns protobuf `ViewDataOuterClass.ViewData`, * that stores the interop flow result. */ @JvmStatic fun getExternalStateView( proxy: CordaRPCOps, externalStateLinearId: String ): ViewDataOuterClass.ViewData { val response = proxy.startFlow(::GetExternalStateByLinearId, externalStateLinearId) .returnValue.get() return ViewDataOuterClass.ViewData.parseFrom(response) } /** * Takes linearId returned by interopFlow, and returns interop payload string. */ @JvmStatic fun getExternalStatePayloadString( proxy: CordaRPCOps, externalStateLinearId: String ): String { val responseView = getExternalStateView(proxy, externalStateLinearId) val interopPayload = InteropPayloadOuterClass.InteropPayload.parseFrom(responseView.notarizedPayloadsList[0].payload) return interopPayload.payload.toStringUtf8() } /** * Takes linearId returned by interopFlow, and returns list of signatories in proof. */ @JvmStatic fun getExternalStateSignatories( proxy: CordaRPCOps, externalStateLinearId: String ): List<String> { val responseView = getExternalStateView(proxy, externalStateLinearId) var result: List<String> = listOf() for (notarization in responseView.notarizedPayloadsList) { val id = notarization.id result += id } return result } /** * Takes linearId returned by interopFlow and signatory Id, * and returns it's signature that is part of the proof. */ @JvmStatic fun getExternalStateSignature( proxy: CordaRPCOps, externalStateLinearId: String, signerId: String ): String { val responseView = getExternalStateView(proxy, externalStateLinearId) for (notarization in responseView.notarizedPayloadsList) { val id = notarization.id if (id == signerId) { return notarization.signature } } return "" } /** * Takes linearId returned by interopFlow and signatory Id, * and returns it's certificate that can be used to verify the signature. */ @JvmStatic fun getExternalStateSignatoryCertificate( proxy: CordaRPCOps, externalStateLinearId: String, signerId: String ): String { val responseView = getExternalStateView(proxy, externalStateLinearId) for (notarization in responseView.notarizedPayloadsList) { val id = notarization.id if (id == signerId) { return notarization.certificate } } return "" } /** * The constructNetworkQuery function passes the address provided by the user to the interoperation CorDapp * to get the external network's endorsement policy, and to provide a signature and certificate for the * external network to authenticate the request. * * @property address The address of the view provided by the user. * @property host The hostname of the Corda node. * @property port The port of the Corda node. * @property rpc The Corda node RPC connection. * @property proxy The proxy to the Corda node RPC connection. * @return Returns an Either with an error if the RPC connection failed or the interop flow failed, or a NetworkQuery. */ fun constructNetworkQuery( proxy: CordaRPCOps, address: String, requestingNetwork: String ): Either<Error, Networks.NetworkQuery> { logger.debug("Getting query information for foreign network from Corda network") return try { val eitherErrorRequest = runCatching { proxy.startFlow(::CreateExternalRequest, address) .returnValue.get().map { Networks.NetworkQuery.newBuilder() .addAllPolicy(it.policy) .setAddress(address) .setRequestingRelay("") .setRequestingNetwork(requestingNetwork) .setCertificate(it.certificate) .setRequestorSignature(it.signature) .setRequestingOrg(it.requestingOrg) .setNonce(it.nonce) .build() } }.getOrThrow() if (eitherErrorRequest.isLeft()) { Left(Error("Corda Network Error: ${eitherErrorRequest}")) } else { eitherErrorRequest } } catch (e: Exception) { Left(Error("Corda Network Error: ${e.message}")) } } /** * pollForState is used to poll the local relay for the requested state. This is a recursive function that continues * to poll if the returned state is "PENDING" or "PENDING_ACK" or returns the "COMPLETED" or "ERROR" state. * * @property requestId The requestId for the original request. * @property client The gRPC client for the relay. * @property requestState The state response from the relay. * Will have status "PENDING", "PENDING_ACK", "COMPLETED" or "ERROR". * @return Returns the request state when it has status "COMPLETED" or "ERROR". */ suspend fun pollForState(requestId: String, client: RelayClient, retryCount: Int = 0): Either<Error, RequestState> = coroutineScope { val timeout = 30 val delayTime = 500L val num = 30*1000/delayTime if (retryCount > num) { Left(Error("Error: Timeout, remote network took longer than $timeout seconds to respond")) } else { delay(delayTime) val requestState = async { client.getState(requestId) }.await() logger.debug("Response from getState: $requestState") when (requestState.status.toString()) { "COMPLETED" -> Right(requestState) "PENDING" -> async { pollForState(requestId, client, retryCount + 1) }.await() "PENDING_ACK" -> async { pollForState(requestId, client, retryCount + 1) }.await() "ERROR" -> { logger.error("Error returned from the remote network: $requestState") Left(Error("Error returned from remote network $requestState")) } else -> Left(Error("Unexpected status returned in RequestState")) } } } /** * writeExternalStateToVault is used to trigger the interoperation CorDapp to store the requested state in the ledger. * * @property requestState The state that is returned by the external network. * @property host The host of the Corda node to connect to. * @property port The port of the Corda node to connect to. * @property rpc The Corda node RPC connection. * @property stateId The linearId of the state stored in the Corda ledger. * @property proxy The proxy to the Corda node RPC connection. * @return Returns an Either with an error if the RPC connection failed or the Corda network returned an error, else * the unique identifier of the stored state. */ fun writeExternalStateToVault( proxy: CordaRPCOps, views64: Array<String>, addresses: Array<String>, externalStateParticipants: List<Party> = listOf<Party>(), returnWithoutLocalInvocation: Boolean = true, invokeFlowName: String = "", invokeFlowArgs: List<Any> = listOf(), interopArgsIndex: Int = -1 ): Either<Error, Any> { return try { logger.debug("Sending response to Corda for view verification.\n") val invokeObject = InvocationSpec( disableInvocation = returnWithoutLocalInvocation, invokeFlowName = invokeFlowName, invokeFlowArgs = invokeFlowArgs, interopArgsIndex = interopArgsIndex ) logger.debug("Invoke Object: ${invokeObject}") val stateId: Either<Error, Any> = runCatching { proxy.startFlow(::WriteExternalStateInitiator, views64, addresses, invokeObject, externalStateParticipants ).returnValue.get() }.fold({ it.fold({ logger.error("WriteExternalState flow error: ${it.message}\n") Left(Error("WriteExternalState flow error: ${it.message}\n")) }, { result: Any -> if (returnWithoutLocalInvocation) { logger.debug("Verification was successful and external-state was stored with array of linearIds $result.\n") Right(result) } else { logger.debug("Verification was successful and called flow: $invokeFlowName with result: $result.\n") Right(result) } }) }, { logger.error("Corda Network Error: Error running WriteExternalState flow: ${it.message}\n") Left(Error("Corda Network Error: Error running WriteExternalState flow: ${it.message}\n")) }) stateId } catch (e: Exception) { logger.error("Error writing state to Corda network: ${e.message}\n") Left(Error("Error writing state to Corda network: ${e.message}")) } } } }
50
TypeScript
3
6
4c94bf21ee570349995c61204fe60a2dc6a35766
21,276
blockchain-integration-framework
Apache License 2.0
kgit/src/commonMain/kotlin/me/saket/kgit/GitConfig.kt
saket
201,701,386
false
null
package me.saket.kgit import me.saket.kgit.GitConfig.Section data class GitConfig(val sections: List<Section>) { data class Section(val name: String, val values: List<Pair<String, String>>) } /** * Example usage: * * ``` * GitConfig("diff" to listOf("renames" to "true")) * ``` */ @Suppress("FunctionName") fun GitConfig(vararg sections: Pair<String, List<Pair<String, String>>>) = GitConfig(sections.map { (name, values) -> Section(name, values) }) fun GitConfig.author(): GitIdentity { return this["author"].let { GitIdentity(it["name"], it["email"]) } } fun GitConfig.committer(): GitIdentity { return this["committer"].let { GitIdentity(it["name"], it["email"]) } } private operator fun GitConfig.get(section: String): Section { return sections.single { it.name == section } } private operator fun Section.get(key: String): String { for ((k, v) in values) { if (k == key) { return v } } error("$key doesn't exist in $values") }
13
Kotlin
110
1,849
5f64350ec51402f3e6aeff145cbc35438780a03c
975
press
Apache License 2.0
jcv-core/src/main/kotlin/com/ekino/oss/jcv/core/comparator/EndsWithComparator.kt
ekino
163,856,313
false
{"Kotlin": 91322, "Java": 13695, "Mustache": 746}
/* * Copyright (c) 2019 ekino (https://www.ekino.com/) */ package com.ekino.oss.jcv.core.comparator import com.ekino.oss.jcv.core.JsonValueComparator import org.skyscreamer.jsonassert.ValueMatcherException /** * A endsWith comparator on text. * * @author <NAME> * * @see String.endsWith */ class EndsWithComparator( /** * Init comparator with the value to search for. * * @param value the value to search for */ private val value: String ) : JsonValueComparator<String> { override fun hasCorrectValue(actual: String?, expected: String?): Boolean { if (actual != null && actual.endsWith(value)) { return true } throw ValueMatcherException("Value should end with '$value'", expected, actual) } }
2
Kotlin
0
21
b97778ecb73a9e018f2d366d56ac98f9379419d8
743
jcv
MIT License
app/src/main/kotlin/com/kneelawk/ledcontroller1/Widgets.kt
Kneelawk
407,745,166
false
{"Kotlin": 33625}
package com.kneelawk.ledcontroller1 import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.kneelawk.ledcontroller1.ui.theme.LEDController1Theme private data class Wrapper<T>(var value: T) @Composable fun Spinner( value: Int, onValueChange: (Int) -> Unit, minValue: Int, maxValue: Int, enabled: Boolean = true ) { val keepValues = remember { Wrapper(false) } var curValue by remember { mutableStateOf(value) } var curText by remember { mutableStateOf(value.toString()) } if (keepValues.value) { keepValues.value = false } else { curValue = value curText = value.toString() } Row(modifier = Modifier.height(IntrinsicSize.Min)) { TextField( value = curText, onValueChange = { // Changing curText causes a recompose but we don't want to recalculate curText keepValues.value = true curText = it }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions { var newValue = curValue try { newValue = curText.toInt() } catch (e: NumberFormatException) { } curValue = newValue.coerceIn(minValue, maxValue) curText = curValue.toString() onValueChange(curValue) }, shape = RectangleShape, enabled = enabled, modifier = Modifier.fillMaxWidth(0.75F), singleLine = true, colors = TextFieldDefaults.textFieldColors( focusedIndicatorColor = MaterialTheme.colors.secondary, disabledIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent ) ) Column( modifier = Modifier .fillMaxHeight() .fillMaxWidth() .weight(0.5f) ) { SmallButton( onClick = { curValue = (curValue + 1).coerceAtMost(maxValue) curText = curValue.toString() onValueChange(curValue) }, contentPadding = PaddingValues(0.dp), shape = RectangleShape, modifier = Modifier .fillMaxHeight() .weight(0.5f), colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary), enabled = enabled ) { Text("+1") } SmallButton( onClick = { curValue = (curValue - 1).coerceAtLeast(minValue) curText = curValue.toString() onValueChange(curValue) }, contentPadding = PaddingValues(0.dp), shape = RectangleShape, modifier = Modifier .fillMaxHeight() .weight(0.5f), colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary), enabled = enabled ) { Text("-1") } } Column( modifier = Modifier .fillMaxHeight() .fillMaxWidth() .weight(0.5f) ) { SmallButton( onClick = { curValue = (curValue + 10).coerceAtMost(maxValue) curText = curValue.toString() onValueChange(curValue) }, contentPadding = PaddingValues(0.dp), shape = RectangleShape, modifier = Modifier .fillMaxHeight() .weight(0.5f), colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary), enabled = enabled ) { Text("+10") } SmallButton( onClick = { curValue = (curValue - 10).coerceAtLeast(minValue) curText = curValue.toString() onValueChange(curValue) }, contentPadding = PaddingValues(0.dp), shape = RectangleShape, modifier = Modifier .fillMaxHeight() .weight(0.5f), colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary), enabled = enabled ) { Text("-10") } } } } @OptIn(ExperimentalMaterialApi::class) @Composable fun SmallButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, elevation: ButtonElevation? = ButtonDefaults.elevation(), shape: Shape = MaterialTheme.shapes.small, border: BorderStroke? = null, colors: ButtonColors = ButtonDefaults.buttonColors(), contentPadding: PaddingValues = ButtonDefaults.ContentPadding, content: @Composable RowScope.() -> Unit ) { val contentColor by colors.contentColor(enabled) Surface( modifier = modifier, shape = shape, color = colors.backgroundColor(enabled).value, contentColor = contentColor.copy(alpha = 1f), border = border, elevation = elevation?.elevation(enabled, interactionSource)?.value ?: 0.dp, onClick = onClick, enabled = enabled, role = Role.Button, interactionSource = interactionSource, indication = rememberRipple() ) { CompositionLocalProvider(LocalContentAlpha provides contentColor.alpha) { ProvideTextStyle( value = MaterialTheme.typography.button ) { Row( Modifier .defaultMinSize( minWidth = ButtonDefaults.MinWidth ) .padding(contentPadding), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content ) } } } } @Composable @Preview(showBackground = true) fun SpinnerPreview() { LEDController1Theme { Spinner(value = 20, onValueChange = {}, 5, 10000) } }
0
Kotlin
0
0
29c0010b1c8f04e0af6a1eb54d37be679554441f
7,475
LEDController1-Android
MIT License
app/src/main/java/com/example/mark/colorpicker/Color.kt
mhuntin1
187,730,472
false
null
package com.example.mark.colorpicker /** * Created by Mark on 2/27/2018. */ class Color{ var Red : Int = 0 var Green: Int = 0 var Blue: Int = 0 }
0
Kotlin
0
0
427aef1d9a7ddbb3cb06cc3f18737c7be649288f
164
ColorPicker
Apache License 2.0
test/GameAnswerTest.kt
ginestra
125,407,258
false
{"Kotlin": 11700}
import org.junit.Test import kotlin.test.assertEquals class GameAnswerTest { @Test fun answerToString() { val answer = GameAnswer( GamePeg.valueOf("R"), GamePeg.valueOf("G"), GamePeg.valueOf("Y"), GamePeg.valueOf("B") ) assertEquals(answer.toString(), "RGYB") } }
3
Kotlin
0
1
d90bfc6f52ce2c4ccafe7ba728fad898a1af9b6c
350
sdp-mastermind
MIT License
common/src/main/kotlin/com/yod/common/helper/DisposeHelper.kt
luketang3
117,669,049
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Kotlin": 34, "XML": 21, "Java": 4}
package com.yod.common.helper import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable /** * composite Disposable * Created by tangJ on 2017/11/13 */ class DisposeHelper { val compositeDispose = CompositeDisposable() private val mapDispose = mutableMapOf<String, Disposable>() /** * 移除所有 */ fun removeAll() { compositeDispose.clear() mapDispose.clear() } fun add(disposable: Disposable) { compositeDispose.add(disposable) } fun add(tag: String, disposable: Disposable) { mapDispose[tag]?.let { if (!it.isDisposed) it.dispose() } mapDispose.put(tag, disposable) } fun remove(disposable: Disposable) { compositeDispose.remove(disposable) } fun remove(tag: String) { mapDispose[tag]?.let { if (!it.isDisposed) it.dispose() mapDispose.remove(tag) } } fun find(tag: String): Disposable? = mapDispose[tag] }
1
null
1
1
1cb0ad9aac66107163484c31bf9745b2617eb468
940
yodLib
Apache License 2.0
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/redis/op/SortOptions.kt
tsegismont
136,018,012
false
null
package io.vertx.kotlin.redis.op import io.vertx.redis.op.SortOptions /** * A function providing a DSL for building [io.vertx.redis.op.SortOptions] objects. * * * @param alpha * @param by * @param descending * @param gets * @param store * * <p/> * NOTE: This function has been automatically generated from the [io.vertx.redis.op.SortOptions original] using Vert.x codegen. */ fun SortOptions( alpha: Boolean? = null, by: String? = null, descending: Boolean? = null, gets: Iterable<String>? = null, store: String? = null): SortOptions = io.vertx.redis.op.SortOptions().apply { if (alpha != null) { this.setAlpha(alpha) } if (by != null) { this.setBy(by) } if (descending != null) { this.setDescending(descending) } if (gets != null) { for (item in gets) { this.addGet(item) } } if (store != null) { this.setStore(store) } }
1
null
1
1
5bed3976c3e3a08efad73123dcf024e067825c98
904
vertx-redis-client
Apache License 2.0
battery/src/main/java/com/domker/doctor/battery/BatteryFragment.kt
MaisonWan
330,649,879
false
{"Kotlin": 424567, "Java": 274179}
package com.domker.app.doctor.battery import android.os.BatteryManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.domker.app.doctor.battery.databinding.BatteryFragmentLayoutBinding /** * 电池展示信息的界面 */ class BatteryFragment : Fragment() { private lateinit var binding: BatteryFragmentLayoutBinding private lateinit var batteryWatcher: BatteryWatcher override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) batteryWatcher = BatteryWatcher(requireContext()) } override fun onResume() { super.onResume() batteryWatcher.register(this) { battery -> binding.batteryChargeView.charge = battery.level * 100 / battery.scale updateBatteryState(battery) updateBatteryDetail(battery) println(battery) } } override fun onStop() { super.onStop() batteryWatcher.unregister(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = BatteryFragmentLayoutBinding.inflate(inflater, container, false) return binding.root } /** * 更新电池的状态信息 */ private fun updateBatteryState(batteryInfo: BatteryInfo) { val id = when (batteryInfo.status) { BatteryManager.BATTERY_STATUS_CHARGING -> R.string.battery_charging BatteryManager.BATTERY_STATUS_DISCHARGING, BatteryManager.BATTERY_STATUS_NOT_CHARGING -> R.string.battery_discharging BatteryManager.BATTERY_STATUS_FULL -> R.string.battery_charging_full else -> R.string.battery_charging_unknown } binding.textViewState.setText(id) } /** * 更新电池的详情 */ private fun updateBatteryDetail(batteryInfo: BatteryInfo) { // 充电类型 val type = when (batteryInfo.plugged) { BatteryManager.BATTERY_PLUGGED_USB -> R.string.battery_plugged_usb BatteryManager.BATTERY_PLUGGED_AC -> R.string.battery_plugged_ac BatteryManager.BATTERY_PLUGGED_WIRELESS -> R.string.battery_plugged_wireless else -> R.string.battery_discharging } binding.textViewPlugged.setText(type) // 温度 binding.textViewTemperature.text = getString(R.string.battery_temperature_format, batteryInfo.temperature / 10f) // 电池容量 binding.textViewVoltage.text = getString(R.string.battery_voltage_format, batteryInfo.voltage) // 健康度 val healthResId = when (batteryInfo.health) { BatteryManager.BATTERY_HEALTH_GOOD -> R.string.battery_health_good BatteryManager.BATTERY_HEALTH_OVERHEAT -> R.string.battery_health_overheat BatteryManager.BATTERY_HEALTH_DEAD -> R.string.battery_health_dead BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE -> R.string.battery_health_over_voltage BatteryManager.BATTERY_HEALTH_COLD -> R.string.battery_health_cold else -> R.string.battery_health_unknown } binding.textViewHealth.setText(healthResId) } }
0
Kotlin
0
0
f9c15d7cb4d595a9d9b52f48cb06168565ce50dd
3,271
AppDoctor
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/activities/CreateActivityRequest.kt
ministryofjustice
444,895,409
false
null
package uk.gov.justice.digital.hmpps.nomisprisonerapi.activities import com.fasterxml.jackson.annotation.JsonInclude import io.swagger.v3.oas.annotations.media.Schema import java.math.BigDecimal import java.time.LocalDate @JsonInclude(JsonInclude.Include.NON_NULL) @Schema(description = "Course activity creation request") data class CreateActivityRequest( @Schema(description = "Code generated from the activity and schedule ids and mapped", required = true) val code: String, @Schema(description = "Activity start date", required = true, example = "2022-08-12") val startDate: LocalDate, @Schema(description = "Activity end date", example = "2022-08-12") val endDate: LocalDate?, @Schema(description = "Prison where the activity is to occur", required = true) val prisonId: String, @Schema(description = "Room where the activity is to occur (from activity schedule)") val internalLocationId: Long?, @Schema(description = "Capacity of activity (from activity schedule)", required = true) val capacity: Int, @Schema(description = "Pay rates", required = true) val payRates: List<PayRateRequest>, @Schema(description = "Description from concatenated activity and activity schedule", required = true) val description: String, @Schema(description = "Minimum Incentive Level") val minimumIncentiveLevelCode: String? = null, @Schema(description = "Program Service code (from activity category)", required = true) val programCode: String, @Schema(description = "Half or Full day (H or F)", required = true, example = "H") val payPerSession: String, ) @JsonInclude(JsonInclude.Include.NON_NULL) @Schema(description = "Course activity creation request pay rates") data class PayRateRequest( @Schema(description = "The incentive level", example = "BAS", required = true) val incentiveLevel: String, @Schema(description = "The pay band (1 TO 10)", example = "4", required = true) val payBand: String, @Schema(description = "The half day rate", example = "0.50", required = true) val rate: BigDecimal, ) /* "prisonCode": "PVI", "attendanceRequired": false, -- ignore "summary": "Maths level 1", -- ignore "description": "A basic maths course suitable for introduction to the subject", "categoryId": 0, program service code *** "tierId": 1, --- ignore "eligibilityRuleIds": [ -- course_activity_profiles TBC ], "pay": [ { "incentiveLevel": "Basic", -- desc not code "payBand": "A", -- 1 to 10 = nomis "rate": 150, *** half day rate "pieceRate": 150, -- ignore or might be a slot in nomis "pieceRateItems": 10 -- ignore } ], "riskLevel": "High", -- ignore "minimumIncentiveLevel": "Basic", "startDate": "2022-12-23", "endDate": "2022-12-23" NOTE slots being refactored out of the activity schedule. schedule = { "id": 123456, "description": "Monday AM Houseblock 3", "suspensions": [ { "suspendedFrom": "2022-12-23", "suspendedUntil": "2022-12-23" } ], "startTime": "9:00", "endTime": "11:30", "internalLocation": 98877667, "capacity": 10, "activity": { "id": 123456, "prisonCode": "PVI", "attendanceRequired": false, "summary": "Maths level 1", "description": "A basic maths course suitable for introduction to the subject", "category": { "id": 1, "code": "LEISURE_SOCIAL", "name": "Leisure and social", "description": "Such as association, library time and social clubs, like music or art" }, "riskLevel": "High", "minimumIncentiveLevel": "Basic" } } */
0
Kotlin
0
0
879c3e84dd7995376607479a503e99ce32993500
3,594
hmpps-nomis-prisoner-api
MIT License
glance_app_widget/src/main/java/dev/vengateshm/glance_app_widget/network/LiveScoreApiService.kt
vengateshm
670,054,614
false
{"Kotlin": 2044992, "Java": 55066}
package dev.vengateshm.glance_widget.network import com.google.gson.GsonBuilder import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object LiveScoreApiService { private val retrofit: Retrofit by lazy { Retrofit.Builder() .baseUrl(LiveScoreApi.BASE_URL) .addConverterFactory( GsonConverterFactory.create( GsonBuilder().setPrettyPrinting().create() ) ) .build() } fun getLiveScoreApi(): LiveScoreApi { return retrofit.create(LiveScoreApi::class.java) } }
0
Kotlin
0
1
5c1898b8c48a5ceac6d6b78b4267e1bdce7f5e9a
614
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
LeftScrollBar/src/main/kotlin/example/App.kt
aterai
158,348,575
false
null
package example import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* fun makeUI(): Component { val cl = Thread.currentThread().contextClassLoader val name = "example/CRW_3857_JFR.jpg" val label = object : JLabel(ImageIcon(cl.getResource(name))) { @Transient private var listener: MouseAdapter? = null override fun updateUI() { removeMouseMotionListener(listener) removeMouseListener(listener) super.updateUI() listener = DragScrollListener() addMouseMotionListener(listener) addMouseListener(listener) } } val scroll = JScrollPane(label) scroll.componentOrientation = ComponentOrientation.RIGHT_TO_LEFT val barWidth = scroll.verticalScrollBar.preferredSize.width val p = JPanel(BorderLayout()) p.add(Box.createHorizontalStrut(barWidth), BorderLayout.WEST) p.add(scroll.horizontalScrollBar) return JPanel(BorderLayout()).also { it.add(p, BorderLayout.NORTH) it.add(scroll) it.preferredSize = Dimension(320, 240) } } private class DragScrollListener : MouseAdapter() { private val defCursor = Cursor.getDefaultCursor() private val hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) private val pp = Point() override fun mouseDragged(e: MouseEvent) { val c = e.component val viewPort = SwingUtilities.getUnwrappedParent(c) if (viewPort is JViewport) { val cp = SwingUtilities.convertPoint(c, e.point, viewPort) val vp = viewPort.viewPosition vp.translate(pp.x - cp.x, pp.y - cp.y) (c as? JComponent)?.scrollRectToVisible(Rectangle(vp, viewPort.size)) pp.location = cp } } override fun mousePressed(e: MouseEvent) { val c = e.component c.cursor = hndCursor val p = SwingUtilities.getUnwrappedParent(c) if (p is JViewport) { val cp = SwingUtilities.convertPoint(c, e.point, p) pp.location = cp } } override fun mouseReleased(e: MouseEvent) { e.component.cursor = defCursor } } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) pack() setLocationRelativeTo(null) isVisible = true } } }
0
null
6
9
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
2,447
kotlin-swing-tips
MIT License
src/test/kotlin/ch/sourcemotion/vertx/gradle/hermes/plugin/HermesPluginTest.kt
wem
394,379,123
false
null
package ch.sourcemotion.vertx.gradle.hermes.plugin import ch.sourcemotion.vertx.gradle.hermes.AbstractProjectSupportTest import ch.sourcemotion.vertx.gradle.hermes.getDtoGenerationTask import ch.sourcemotion.vertx.gradle.hermes.getMessageCodecGenerationTask import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldEndWith import io.kotest.matchers.string.shouldStartWith import org.gradle.api.Project import org.gradle.api.plugins.JavaPlugin import org.junit.jupiter.api.Test internal class HermesPluginTest : AbstractProjectSupportTest() { }
2
Kotlin
0
0
1a65a5e7754272b361a4c23e63801b464cc87309
563
vertx-hermes-gradle-plugin
MIT License
android/app/src/main/kotlin/io/ceroy/moneysavvy/MainActivity.kt
ceroy-ak
279,751,872
false
{"Dart": 55067, "Java": 796, "Kotlin": 130}
package io.ceroy.moneysavvy import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
9efce01eb69ca0b4a34f23763e39e40090fc35e6
124
Money_Savvy
MIT License
TheDialer/app/src/main/java/com/cedricbahirwe/dialer/screens/ContactsSearchField.kt
cedricbahirwe
413,185,334
false
{"Kotlin": 156762}
package com.cedricbahirwe.dialer.screens import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TextFieldDefaults import androidx.compose.material.TextFieldDefaults.TextFieldDecorationBox import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Clear import androidx.compose.material.icons.filled.Search import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState 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.focus.FocusManager import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.focus.onFocusEvent import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.cedricbahirwe.dialer.R import com.cedricbahirwe.dialer.ui.theme.AccentBlue import com.cedricbahirwe.dialer.ui.theme.DialerTheme @Composable fun SearchField( searchQuery: String, isEditing: MutableState<Boolean>, onSearch: (String) -> Unit, onClearField: () -> Unit, focusManager: FocusManager, focusRequester: FocusRequester, modifier: Modifier = Modifier, hint: String = "Search by name or phone" ) { val interactionSource = remember { MutableInteractionSource() } fun endEditing() { onClearField() focusManager.clearFocus(force = true) isEditing.value = false } // // BackHandler { // focusManager.clearFocus() // isEditing.value = false // } Row( modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp) ) { MainField( text = searchQuery, onSearch = onSearch, isEditing = isEditing, interactionSource = interactionSource, focusManager = focusManager, focusRequester = focusRequester, placeholder = { Text( hint, style = MaterialTheme.typography.caption, maxLines = 1, overflow = TextOverflow.Ellipsis ) }, leadingIcon = { Icon( imageVector = Icons.Filled.Search, contentDescription = "Search", tint = Color.LightGray, ) }, trailingIcon = { AnimatedVisibility(visible = isEditing.value) { Icon( imageVector = Icons.Filled.Clear, contentDescription = "Clear", tint = MaterialTheme.colors.background, modifier = Modifier .background( Color.Gray, shape = RoundedCornerShape(10.dp) ) .size(18.dp) .padding(3.dp) .clickable { if (searchQuery.isEmpty()) { endEditing() } else { onClearField() } } ) } }, modifier = Modifier.weight(1f) ) AnimatedVisibility( visible = isEditing.value, // enter = fadeIn() + slideInHorizontally(), // exit = fadeOut() + slideOutHorizontally(), ) { Text( text = "Cancel", color = AccentBlue, modifier = Modifier .clickable { endEditing() } ) } } } @Preview(showBackground = true) @Composable fun PreviewSearchField() { var searchQuery by remember { mutableStateOf("") } val isEditing = remember { mutableStateOf(false) } DialerTheme(darkTheme = true) { Box(Modifier.background(Color.Black)) { SearchField( modifier = Modifier.padding(20.dp), searchQuery = searchQuery, isEditing = isEditing, onSearch = { searchQuery = it }, onClearField = {}, focusManager = LocalFocusManager.current, focusRequester = FocusRequester() ) } } } @OptIn(ExperimentalMaterialApi::class) @Composable fun MainField( text: String, placeholder: (@Composable () -> Unit), leadingIcon: (@Composable () -> Unit), trailingIcon: (@Composable () -> Unit), onSearch: (String) -> Unit, isEditing: MutableState<Boolean>, interactionSource: MutableInteractionSource, focusManager: FocusManager, focusRequester: FocusRequester, modifier: Modifier ) { BasicTextField( value = text, onValueChange = { newText -> onSearch(newText) }, interactionSource = interactionSource, singleLine = true, textStyle = MaterialTheme.typography.body2.copy( color = MaterialTheme.colors.primary, ), keyboardOptions = KeyboardOptions( autoCorrectEnabled = false, imeAction = ImeAction.Search ), keyboardActions = KeyboardActions( onSearch = { focusManager.clearFocus(true) isEditing.value = false } ), cursorBrush = SolidColor(AccentBlue), modifier = modifier .background( colorResource(R.color.offBackground), RoundedCornerShape(6.dp) ) .focusRequester(focusRequester) .onFocusEvent { isEditing.value = it.hasFocus } .onFocusChanged { isEditing.value = it.isFocused } ) { innerTextField -> TextFieldDecorationBox( enabled = true, singleLine = true, value = text, interactionSource = interactionSource, innerTextField = innerTextField, visualTransformation = VisualTransformation.None, placeholder = placeholder, leadingIcon = leadingIcon, trailingIcon = trailingIcon, colors = TextFieldDefaults.textFieldColors( textColor = Color.Green, disabledTextColor = Color.Transparent, backgroundColor = Color.Red, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, disabledIndicatorColor = Color.Transparent, placeholderColor = Color.Gray ), contentPadding = TextFieldDefaults.textFieldWithoutLabelPadding(0.dp) ) } }
6
Kotlin
1
5
e3853d4a3efa0a30ce2e35aa877fd866be7ec150
8,455
dialer-android
MIT License
src/test/kotlin/tornadofx/testapps/TodoTestApp.kt
bvolkmer
86,238,861
false
null
package tornadofx.testapps import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import tornadofx.* class TodoItem(text: String? = null) { val textProperty = SimpleStringProperty(text) var text by textProperty val completedProperty = SimpleBooleanProperty(false) var completed by completedProperty override fun toString() = "[${if (completed) "X" else " "}] $text" } class TodoList : View("Todo List") { val todos = FXCollections.observableArrayList(TodoItem("Item 1"), TodoItem("item 2")) override val root = tableview(todos) { setPrefSize(300.0, 200.0) column("Completed", TodoItem::completedProperty).useCheckbox() column("Text", TodoItem::textProperty).makeEditable() } override fun onDock() { with(workspace) { button("Print todos").action { println(todos.joinToString("\n")) } } } } class TodoTestApp : WorkspaceApp(TodoList::class)
1
null
1
1
7a050dd014512e0258de0ed8311107d174ae12cf
1,059
tornadofx
Apache License 2.0
src/test/kotlin/tornadofx/testapps/TodoTestApp.kt
bvolkmer
86,238,861
false
null
package tornadofx.testapps import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import tornadofx.* class TodoItem(text: String? = null) { val textProperty = SimpleStringProperty(text) var text by textProperty val completedProperty = SimpleBooleanProperty(false) var completed by completedProperty override fun toString() = "[${if (completed) "X" else " "}] $text" } class TodoList : View("Todo List") { val todos = FXCollections.observableArrayList(TodoItem("Item 1"), TodoItem("item 2")) override val root = tableview(todos) { setPrefSize(300.0, 200.0) column("Completed", TodoItem::completedProperty).useCheckbox() column("Text", TodoItem::textProperty).makeEditable() } override fun onDock() { with(workspace) { button("Print todos").action { println(todos.joinToString("\n")) } } } } class TodoTestApp : WorkspaceApp(TodoList::class)
1
null
1
1
7a050dd014512e0258de0ed8311107d174ae12cf
1,059
tornadofx
Apache License 2.0
data/RF00577/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF00577" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 2 to 8 77 to 83 } value = "#6794e8" } color { location { 9 to 76 } value = "#8f0976" } color { location { 1 to 1 } value = "#972885" } color { location { 84 to 84 } value = "#7b5eb4" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
779
Rfam-for-RNArtist
MIT License
app/src/main/java/com/dedio/russianroulette/base/ViewModelActivity.kt
PawelDedio
112,599,698
false
null
package com.dedio.russianroulette.base import android.databinding.ObservableField import android.os.Bundle import com.dedio.russianroulette.main.User abstract class ViewModelActivity<ViewModel : BaseViewModel> : BaseActivity() { protected lateinit var viewModel: ViewModel lateinit var user: ObservableField<User> abstract fun prepareActivityComponent() abstract fun createViewModel() : ViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) prepareActivityComponent() viewModel = createViewModel() } }
0
Kotlin
0
1
75ebc18fd332e6c7a4f6c6d969bb1b8a37d6f7a3
599
Russian-Roulette-Android
Apache License 2.0
app/src/main/java/com/artf/chatapp/view/SplashActivity.kt
QArtur99
198,841,223
false
{"Kotlin": 139186, "JavaScript": 2363}
package com.artf.chatapp.view import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import androidx.annotation.NonNull import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat.checkSelfPermission import com.artf.chatapp.utils.Utility class SplashActivity : AppCompatActivity() { companion object { private const val INITIAL_REQUEST = 1337 private val INITIAL_PERMS = mutableListOf<String>().apply { add(Manifest.permission.RECORD_AUDIO) add(Manifest.permission.CAMERA) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { add(Manifest.permission.READ_MEDIA_IMAGES) add(Manifest.permission.READ_MEDIA_VIDEO) add(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { add(Manifest.permission.READ_MEDIA_IMAGES) add(Manifest.permission.READ_MEDIA_VIDEO) } else { add(Manifest.permission.READ_EXTERNAL_STORAGE) add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } }.toTypedArray() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) checkPermissions() } private fun startApp() { startActivity(Intent(this@SplashActivity, MainActivity::class.java)) finish() } private fun checkPermissions() { if (checkHasPermissions().not()) { ActivityCompat.requestPermissions(this, INITIAL_PERMS, INITIAL_REQUEST) } else { startApp() } } private fun checkHasPermissions(): Boolean { var result = false for (i in INITIAL_PERMS) { result = if (isPermissionGranted(i)) true else return false } return result } private fun isPermissionGranted(i: String): Boolean { return checkSelfPermission(this, i) == PackageManager.PERMISSION_GRANTED } override fun onRequestPermissionsResult( requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { INITIAL_REQUEST -> if (checkHasPermissions()) { startApp() } else { Utility.makeText(this, "Permissions are necessary") Handler(Looper.getMainLooper()).postDelayed( { checkPermissions() }, 1500 ) } } } }
1
Kotlin
31
127
47c69e404707c2e20d55bebb267fbc994a5d2970
2,875
ChatApp
Apache License 2.0
src/main/kotlin/com/github/nenadjakic/eav/dto/EntityAddRequest.kt
nenadjakic
782,709,579
false
{"Kotlin": 108772}
package com.github.nenadjakic.eav.dto import jakarta.validation.constraints.NotNull class EntityAddRequest { @NotNull var entityTypeId: Long? = null }
1
Kotlin
0
1
44e1545be59ba3efaeb417a00ad691aa98dc5250
160
eav-platform
MIT License
app/src/main/java/com/chenguang/pokedex/db/model/PokemonStat.kt
lcgforever
367,496,752
false
null
package com.chenguang.pokedex.db.model import androidx.room.ColumnInfo import androidx.room.Entity import com.chenguang.pokedex.R @Entity(tableName = "pokemon_stat_table", primaryKeys = ["statId", "ownerId"]) data class PokemonStat( val statId: String, val ownerId: String, @ColumnInfo(name = "value") val value: Int, @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "url") val url: String ) { /** * We only want to display some stats not all of them */ fun isVisible(): Boolean { return "1236".contains(statId) } fun getColor(): Int { return when (statId) { "1" -> R.color.hp "2" -> R.color.attack "3" -> R.color.defense "6" -> R.color.speed else -> R.color.other } } fun getProgress(): Int { return value * 100 / 250 } }
0
Kotlin
0
0
05eace1a97fe1ff0e2614004ff7fa1dacd7338aa
893
Pokedex
Apache License 2.0
Estrutura_Sequencial/exercicio_007.kt
AlvesTSA
627,567,518
false
{"Kotlin": 57525}
//Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário. fun main(){ val lado: Float val area: Float println("Informe a medida de um dos lados do quadrado: ") lado = readLine()!!.toFloat() area = lado*lado*2 println("O dobro da área é: $area") }
0
Kotlin
0
0
f7dc5b77657f2e2afc01d0f37a985c7e256c7e98
329
Exercicios_Kotlin
MIT License
app/src/main/java/com/example/indiannotesapp/Note.kt
Nikhilkumarmishra
810,776,645
false
{"Kotlin": 9846}
package com.example.indiannotesapp data class Note(val id:Int, val title:String, val content:String)
0
Kotlin
0
1
274e71068ab3789ee0894e4eb8677b2e6c5c382e
102
Indian-Notes-App-Kotlin-Android-app
MIT License
app/src/androidTest/java/com/wei/amazingtalker/ui/robot/LoginEndToEndRobot.kt
azrael8576
584,299,514
false
null
package com.wei.amazingtalker.ui.robot import androidx.annotation.StringRes import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.semantics.getOrNull import androidx.compose.ui.test.SemanticsMatcher import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.hasContentDescription import androidx.compose.ui.test.junit4.AndroidComposeTestRule import androidx.compose.ui.test.performClick import androidx.test.ext.junit.rules.ActivityScenarioRule import com.wei.amazingtalker.MainActivity import kotlin.properties.ReadOnlyProperty import com.wei.amazingtalker.feature.login.R as FeatureLoginR /** * Screen Robot for End To End Test. * * 遵循此模型,找到測試使用者介面元素、檢查其屬性、和透過測試規則執行動作: * composeTestRule{.finder}{.assertion}{.action} * * Testing cheatsheet: * https://developer.android.com/jetpack/compose/testing-cheatsheet */ internal fun loginEndToEndRobot( composeTestRule: AndroidComposeTestRule<ActivityScenarioRule<MainActivity>, MainActivity>, func: LoginEndToEndRobotRobot.() -> Unit, ) = LoginEndToEndRobotRobot(composeTestRule).apply(func) internal open class LoginEndToEndRobotRobot( private val composeTestRule: AndroidComposeTestRule<ActivityScenarioRule<MainActivity>, MainActivity>, ) { private fun AndroidComposeTestRule<*, *>.stringResource(@StringRes resId: Int) = ReadOnlyProperty<Any?, String> { _, _ -> activity.getString(resId) } private fun withRole(role: Role) = SemanticsMatcher("${SemanticsProperties.Role.name} contains '$role'") { val roleProperty = it.config.getOrNull(SemanticsProperties.Role) ?: false roleProperty == role } // The strings used for matching in these tests private val loginDescription by composeTestRule.stringResource(FeatureLoginR.string.content_description_login) private val loginButton by lazy { composeTestRule.onNode( withRole(Role.Button) .and(hasContentDescription(loginDescription)), ) } private fun verifyLoginButtonDisplayed() { loginButton.assertExists().assertIsDisplayed() } fun isLoginButtonDisplayed(): Boolean { return try { verifyLoginButtonDisplayed() true } catch (e: AssertionError) { false } } infix fun login(func: ScheduleEndToEndRobot.() -> Unit): ScheduleEndToEndRobot { loginButton.performClick() return scheduleEndToEndRobot(composeTestRule) { // 等待任何動畫完成 composeTestRule.waitUntil(3_000) { isScheduleTopAppBarDisplayed() } func() } } }
8
null
1
9
a35d73bbf4c86339615b2828643babcdabfd0350
2,674
amazing-talker
Apache License 2.0
FirstApp/app/src/main/java/com/example/firstapp/MainActivity.kt
NicolasNobrega
607,452,286
false
null
package com.example.firstapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.firstapp.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var viewBinding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivityMainBinding.inflate(layoutInflater) val view = viewBinding.root setContentView(view) viewBinding.title.text = "Aqui está o Nicolas" } }
0
Kotlin
0
0
ab1d95c8aa014bcb2d47e94c3f371be43caf1acf
560
Kotlin
MIT License
src/ie/murph/objects/Inheritance/Banjo.kt
Mur3ph
65,215,707
false
null
package ie.murph.objects.inheritance /** * Created by Paul on 9/20/2016. */ interface Banjo { fun banjo() { println("I can play Banjo") } }
0
Kotlin
0
0
9b7bdfe33b1a05aa79c625c9d46cfc19fa99c2d6
162
Kotlin101
Apache License 2.0
app/src/main/java/com/zoop/sdk/taponphone/sample/PaymentViewModel.kt
getzoop
738,101,227
false
null
package com.zoop.sdk.taponphone.sample import android.app.Application import android.content.Context import androidx.lifecycle.AndroidViewModel import com.zoop.sdk.plugin.taponphone.api.InitializationRequest import com.zoop.sdk.plugin.taponphone.api.PaymentApprovedResponse import com.zoop.sdk.plugin.taponphone.api.PaymentErrorResponse import com.zoop.sdk.plugin.taponphone.api.PaymentRequest import com.zoop.sdk.plugin.taponphone.api.PaymentType import com.zoop.sdk.plugin.taponphone.api.TapOnPhone import com.zoop.sdk.plugin.taponphone.api.TapOnPhoneError import com.zoop.sdk.plugin.taponphone.api.TapOnPhoneTheme import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import java.util.UUID class PaymentViewModel(app: Application) : AndroidViewModel(app) { private val _uiState = MutableStateFlow(UiState( paymentStatus = PaymentStatus.Processing )) val uiState = _uiState.asStateFlow() data class UiState( val paymentStatus: PaymentStatus, val errorMessage: String? = null, val transactionId: String? = null ) private val tapOnPhone = TapOnPhone() fun initialize(context: Context, theme: TapOnPhoneTheme, onError:(TapOnPhoneError) -> Unit, onSuccess:() -> Unit ) { val credentials = InitializationRequest.Credentials( clientId = BuildConfig.CLIENT_ID.ifEmpty { "" }, clientSecret = BuildConfig.CLIENT_SECRET.ifEmpty { "" }, marketplace = BuildConfig.MARKETPLACE.ifEmpty { "" }, seller = BuildConfig.SELLER.ifEmpty { "" }, accessKey = BuildConfig.API_KEY.ifEmpty { "" }, scope = BuildConfig.SCOPE.ifEmpty { "" } ) val initializationRequest = InitializationRequest( context = context, theme = theme, credentials = credentials ) tapOnPhone.initialize( request = initializationRequest, onSuccess = onSuccess, onError = onError, ) } fun pay( amount: Long, paymentType: PaymentType, installments: Int? ) { tapOnPhone.pay( payRequest = PaymentRequest( referenceId = UUID.randomUUID().toString(), amount = amount, paymentType = paymentType, installments = installments ), onApproved = { response -> onPaymentSuccess(response) }, onError = { error -> onPaymentError(error) } ) } private fun onPaymentSuccess(response: PaymentApprovedResponse) { _uiState.update { it.copy( paymentStatus = PaymentStatus.Success, transactionId = response.transactionId, errorMessage = null ) } } private fun onPaymentError(error: PaymentErrorResponse) { _uiState.update { it.copy( paymentStatus = PaymentStatus.Fail, errorMessage = "Erro: ${error.message}\nCódigo: ${error.code}\nDescrição: ${error.description}", transactionId = error.transactionId ) } } }
0
null
2
2
664135f77fd9adc70d55b3d5c93786c9387d9138
3,347
zoop-sample-taponphone-android
MIT License
app/src/main/java/com/krossovochkin/fiberyunofficial/di/applist/AppListComponent.kt
krossovochkin
221,648,261
false
{"Kotlin": 493412, "Python": 2433, "Shell": 369}
/* Copyright 2020 Vasya Drobushkov 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.krossovochkin.fiberyunofficial.di.applist import com.krossovochkin.fiberyunofficial.GlobalDependencies import com.krossovochkin.fiberyunofficial.applist.presentation.AppListViewModelFactory import dagger.Component import javax.inject.Scope interface AppListParentComponent : GlobalDependencies @AppList @Component( modules = [ AppListDataModule::class, AppListDomainModule::class, AppListPresentationModule::class ], dependencies = [AppListParentComponent::class] ) interface AppListComponent { fun viewModelFactoryProducer(): () -> AppListViewModelFactory @Component.Factory interface Factory { fun create( appListParentComponent: AppListParentComponent ): AppListComponent } } @Scope @Retention annotation class AppList
0
Kotlin
0
15
1574dbccbcd5f3f99064b0f1fcba81285d8c1a09
1,416
FiberyUnofficial
Apache License 2.0
ok-deskshare-be-common/src/main/kotlin/com/deskshare/common/models/error/CommonError.kt
otuskotlin
378,049,296
false
null
package com.deskshare.common.models.error import com.deskshare.common.exception.NotFoundReservationException class CommonError( override val field: String = "", override val code: ErrorCode, override val level: ErrorLevel, override val message: String ) : ErrorInterface { companion object { fun fromThrowable(e: Throwable) = when (e) { is NotFoundReservationException -> fromNotFound(e.message.toString()) else -> fromRuntime(e.message.toString()) } fun fromNotFound(message: String) = CommonError(code = ErrorCode.NotFound, message = message, level = ErrorLevel.ERROR) fun fromValidation(field: String = "", message: String) = CommonError(code = ErrorCode.Validation, message = message, level = ErrorLevel.ERROR, field = "") fun fromAuth(message: String) = CommonError(code = ErrorCode.Authentication, message = message, level = ErrorLevel.ERROR) fun fromRuntime(message: String) = CommonError(code = ErrorCode.Runtime, message = message, level = ErrorLevel.ERROR) } }
1
Kotlin
0
1
baa39cc2b6c54bfd735992a91906817dd99082b0
1,122
ok-202105-deskshare-gl
MIT License
app/src/main/java/co/tiagoaguiar/course/instagram/register/RegisterNamePassword.kt
Felipe-Borba
751,564,839
false
{"Kotlin": 149355}
package co.tiagoaguiar.course.instagram.register import androidx.annotation.StringRes import co.tiagoaguiar.course.instagram.common.base.BasePresenter import co.tiagoaguiar.course.instagram.common.base.BaseView interface RegisterNamePassword { interface View : BaseView<Presenter> { fun showProgress(enabled: Boolean) fun displayNameFailure(@StringRes error: Int?) fun displayPasswordFailure(@StringRes error: Int?) fun displayConfirmFailure(@StringRes error: Int?) fun onCreateFailure(message: String) fun onCreateSuccess(name: String) } interface Presenter : BasePresenter { fun create(email: String, name: String, password: String, confirm: String) } }
0
Kotlin
0
0
58a795ec85a7f530917005cbaeded94d0aebbe76
731
InstagramCopy
MIT License
ktor-swagger-ui/src/main/kotlin/io/github/smiley4/ktorswaggerui/dsl/routes/OpenApiRequest.kt
SMILEY4
526,907,299
false
null
package io.github.smiley4.ktorswaggerui.dsl.routes import io.github.smiley4.ktorswaggerui.data.KTypeDescriptor import io.github.smiley4.ktorswaggerui.data.OpenApiRequestData import io.github.smiley4.ktorswaggerui.data.ParameterLocation import io.github.smiley4.ktorswaggerui.data.SwaggerTypeDescriptor import io.github.smiley4.ktorswaggerui.data.TypeDescriptor import io.github.smiley4.ktorswaggerui.dsl.OpenApiDslMarker import io.swagger.v3.oas.models.media.Schema import kotlin.reflect.KType import kotlin.reflect.typeOf /** * Describes a single request. */ @OpenApiDslMarker class OpenApiRequest { /** * A list of parameters that are applicable for this operation */ val parameters = mutableListOf<OpenApiRequestParameter>() /** * A path parameters that is applicable for this operation */ fun parameter(location: ParameterLocation, name: String, type: TypeDescriptor, block: OpenApiRequestParameter.() -> Unit = {}) { parameters.add(OpenApiRequestParameter(name, type, location).apply(block)) } /** * A path parameters that is applicable for this operation */ fun pathParameter(name: String, type: TypeDescriptor, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.PATH, name, type, block) /** * A path parameters that is applicable for this operation */ fun pathParameter(name: String, type: Schema<*>, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.PATH, name, SwaggerTypeDescriptor(type), block) /** * A path parameters that is applicable for this operation */ fun pathParameter(name: String, type: KType, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.PATH, name, KTypeDescriptor(type), block) /** * A path parameters that is applicable for this operation */ inline fun <reified T> pathParameter(name: String, noinline block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.PATH, name, KTypeDescriptor(typeOf<T>()), block) /** * A query parameters that is applicable for this operation */ fun queryParameter(name: String, type: TypeDescriptor, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.QUERY, name, type, block) /** * A query parameters that is applicable for this operation */ fun queryParameter(name: String, type: Schema<*>, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.QUERY, name, SwaggerTypeDescriptor(type), block) /** * A query parameters that is applicable for this operation */ fun queryParameter(name: String, type: KType, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.QUERY, name, KTypeDescriptor(type), block) /** * A query parameters that is applicable for this operation */ inline fun <reified T> queryParameter(name: String, noinline block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.QUERY, name, KTypeDescriptor(typeOf<T>()), block) /** * A header parameters that is applicable for this operation */ fun headerParameter(name: String, type: TypeDescriptor, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.HEADER, name, type, block) /** * A header parameters that is applicable for this operation */ fun headerParameter(name: String, type: Schema<*>, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.HEADER, name, SwaggerTypeDescriptor(type), block) /** * A header parameters that is applicable for this operation */ fun headerParameter(name: String, type: KType, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.HEADER, name, KTypeDescriptor(type), block) /** * A header parameters that is applicable for this operation */ inline fun <reified T> headerParameter(name: String, noinline block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.HEADER, name, KTypeDescriptor(typeOf<T>()), block) /** * A cookie parameters that is applicable for this operation */ fun cookieParameter(name: String, type: TypeDescriptor, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.COOKIE, name, type, block) /** * A cookie parameters that is applicable for this operation */ fun cookieParameter(name: String, type: Schema<*>, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.COOKIE, name, SwaggerTypeDescriptor(type), block) /** * A cookie parameters that is applicable for this operation */ fun cookieParameter(name: String, type: KType, block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.COOKIE, name, KTypeDescriptor(type), block) /** * A cookie parameters that is applicable for this operation */ inline fun <reified T> cookieParameter(name: String, noinline block: OpenApiRequestParameter.() -> Unit = {}) = parameter(ParameterLocation.COOKIE, name, KTypeDescriptor(typeOf<T>()), block) private var body: OpenApiBaseBody? = null fun getBody() = body /** * The body returned with this request */ fun body(type: TypeDescriptor, block: OpenApiSimpleBody.() -> Unit = {}) { val result = OpenApiSimpleBody(type).apply(block) if (!result.isEmptyBody()) { body = result } } /** * The body returned with this request */ fun body(type: Schema<*>, block: OpenApiSimpleBody.() -> Unit = {}) = body(SwaggerTypeDescriptor(type), block) /** * The body returned with this request */ fun body(type: KType, block: OpenApiSimpleBody.() -> Unit = {}) = body(KTypeDescriptor(type), block) /** * The body returned with this request */ inline fun <reified T> body(noinline block: OpenApiSimpleBody.() -> Unit = {}) = body(KTypeDescriptor(typeOf<T>()), block) /** * The multipart-body returned with this request */ fun multipartBody(block: OpenApiMultipartBody.() -> Unit) { body = OpenApiMultipartBody().apply(block) } /** * Set the body of this request. Intended for internal use. */ fun setBody(body: OpenApiBaseBody?) { this.body = body } /** * Build the data object for this config. */ fun build() = OpenApiRequestData( parameters = parameters.map { it.build() }, body = body?.build() ) private fun OpenApiBaseBody.isEmptyBody(): Boolean { return when (this) { is OpenApiSimpleBody -> when (type) { is KTypeDescriptor -> type.type == typeOf<Unit>() else -> false } is OpenApiMultipartBody -> false } } }
6
null
33
172
d040a9738c3dbbf3008a776bf38e8fa68386a83d
7,066
ktor-swagger-ui
Apache License 2.0
libs/logging/src/unitTest/kotlin/batect/logging/LoggerFactorySpec.kt
batect
102,647,061
false
null
/* Copyright 2017-2019 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.logging import batect.Application import batect.testutils.on import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.sameInstance import com.nhaarman.mockitokotlin2.mock import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object LoggerFactorySpec : Spek({ describe("a logger factory") { describe("creating loggers") { on("creating the first logger for a class") { val logSink = mock<LogSink>() val loggerFactory = LoggerFactory(logSink) val logger = loggerFactory.createLoggerForClass(Application::class) it("returns a logger configured with the provided log sink") { assertThat(logger.destination, equalTo(logSink)) } it("returns a logger configured with the class' fully-qualified name") { assertThat(logger.sourceName, equalTo("batect.Application")) } } on("creating a second logger for a class") { val logSink = mock<LogSink>() val loggerFactory = LoggerFactory(logSink) val firstLogger = loggerFactory.createLoggerForClass(Application::class) val secondLogger = loggerFactory.createLoggerForClass(Application::class) it("returns the same logger instance both times") { assertThat(secondLogger, sameInstance(firstLogger)) } } } } })
4
null
47
687
67c942241c7d52b057c5268278d6252301c48087
2,198
batect
Apache License 2.0
lib/src/main/kotlin/app/cash/quiver/extensions/Result.kt
cashapp
610,098,851
false
null
package app.cash.quiver.extensions import app.cash.quiver.Failure import app.cash.quiver.Outcome import app.cash.quiver.Present import app.cash.quiver.asOutcome import app.cash.quiver.toOutcome import arrow.core.Either import arrow.core.Option import arrow.core.flatMap import arrow.core.getOrElse import arrow.core.identity import arrow.core.left import arrow.core.right /** * Transforms a `Result<T>` into an `ErrorOr<T>` */ fun <T> Result<T>.toEither(): ErrorOr<T> = this.map { Either.Right(it) }.getOrElse { Either.Left(it) } /** * Transforms a `Result<T>` into an `OutcomeOf<T>` */ fun <T> Result<T>.toOutcome(): OutcomeOf<T> = this.map { Either.Right(it) }.getOrElse { Either.Left(it) }.asOutcome() /** * Transforms a `Result<Option<T>>` to an `OutcomeOf<A>` */ fun <T> Result<Option<T>>.toOutcomeOf(): OutcomeOf<T> = this.toEither().toOutcome() /** * Make anything a Success. */ fun <T> T.success(): Result<T> = Result.success(this) /** * Make any exception a Failure. */ fun <A> Throwable.failure(): Result<A> = Result.failure(this) /** * Turns a nullable value into a [Result]. */ inline fun <A : Throwable, B> B?.toResult(error: () -> A): Result<B> = this?.let { Result.success(it) } ?: Result.failure(error()) /** * Turns an [Option] value into a [Result]. */ inline fun <A, B: Throwable> Option<A>.toResult(error: () -> B): Result<A> = this.getOrNull().toResult(error) /** * If a [Result] is a failure, maps the underlying [Throwable] to a new [Throwable]. */ inline fun <N : Throwable, T> Result<T>.mapFailure( f: (exception: Throwable) -> N ): Result<T> { return when (val exception = exceptionOrNull()) { null -> Result.success(getOrThrow()) else -> Result.failure(f(exception)) } } /** * Calls the specified function block and returns its encapsulated result if invocation was successful, catching any * non-fatal exceptions thrown from the block function execution and encapsulating them as failures. */ @JvmName("tryCatch") inline fun <R> Result.Companion.catch(f: () -> R): Result<R> = arrow.core.raise.catch({ success(f()) }) { failure(it) } /** * Retrieves the success of a Result, or throws the failure. Alias of `getOrThrow`, included for consistency with ErrorOr. */ fun <A> Result<A>.orThrow() = getOrThrow() /** * Flattens a `Result<Result<T>>` into a `Result<T>` */ fun <T> Result<Result<T>>.flatten(): Result<T> = flatMap(::identity) /** * Map success to Unit, included for consistency with Either. */ fun <T> Result<T>.unit() = map { } /** * Performs an effect over successes but maps the original value back into * the Result. */ inline fun <A, B> Result<A>.tap(f: (A) -> B): Result<A> = this.map { a -> f(a) a } /** * Performs an effect over successes but maps the original value back into * the Result. This is useful for mixing with validation functions. */ inline fun <A> Result<A>.flatTap(f: (A) -> Result<Any>): Result<A> = this.flatMap { a -> f(a).map { a } } /** * Returns false if Success or returns the result of the given predicate to the Failure value. */ inline fun <T> Result<T>.isFailure(predicate: (Throwable) -> Boolean): Boolean = fold(onFailure = predicate, onSuccess = { false }) /** * Returns false if Failure or returns the result of the given predicate to the Success value. */ inline fun <T> Result<T>.isSuccess(predicate: (T) -> Boolean): Boolean = fold(onFailure = { false }, onSuccess = predicate) /** * Recovers errors with a function from Throwable to Result. */ inline fun <T> Result<T>.handleFailureWith(f: (Throwable) -> Result<T>): Result<T> = recoverCatching { f(it).getOrThrow() }
8
null
7
115
963d4430ba0d25dda73eff5ac3bac423aaedbc7e
3,634
quiver
Apache License 2.0
product/appkit/src/main/kotlin/com/reown/appkit/ui/components/button/views/AccountButton.kt
reown-com
851,466,242
false
{"Kotlin": 2055654, "Java": 4294, "Shell": 1676}
package com.reown.appkit.ui.components.button.views import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.FrameLayout import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.navigation.findNavController import com.reown.appkit.R import com.reown.appkit.ui.components.button.AccountButton import com.reown.appkit.ui.components.button.rememberAppKitState import com.reown.appkit.utils.toAccountButtonType class AccountButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { init { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.AccountButton, 0, 0) val accountButtonType = typedArray.getInteger(R.styleable.AccountButton_account_button_type, 0).toAccountButtonType() typedArray.recycle() LayoutInflater.from(context) .inflate(R.layout.view_button, this, true) .findViewById<ComposeView>(R.id.root) .apply { setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { val appKitState = rememberAppKitState(navController = findNavController()) AccountButton( state = appKitState, accountButtonType = accountButtonType ) } } } }
6
Kotlin
1
8
893084b3df91b47daa77f8f964e37f84a02843b1
1,566
reown-kotlin
Apache License 2.0
app/src/main/java/com/bhoopathi/sony/network/API.kt
bhoopathik
417,763,206
false
null
package com.bhoopathi.sony.network import com.bhoopathi.sony.model.LanguageDictionary import com.bhoopathi.sony.model.LocalizationList import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path interface API { @GET("localization") suspend fun getLocalization(): Response<LocalizationList> @GET("/{path}") suspend fun getLanguageDictionary(@Path("path") path:String): Response<LanguageDictionary> }
0
Kotlin
0
0
9fcb67d90501c388f7de836ad30b1404a2918263
436
SonyLocalization
Apache License 2.0
util/src/main/kotlin/wumo/sim/util/Shape.kt
wumo
305,330,037
false
{"Maven POM": 11, "Text": 7, "Python": 54, "Kotlin": 262, "Protocol Buffer Text Format": 2, "Java": 14, "ANTLR": 1, "Shell": 3, "CMake": 2, "C++": 291, "C": 22, "Prolog": 1, "M4": 3, "TeX": 2, "X PixMap": 1}
@file:Suppress("NOTHING_TO_INLINE") package wumo.sim.util import java.util.* val scalarDimension = Shape(IntArray(0)) //infix fun Int.x(a: Int) = Shape(this, a) //infix fun Shape.x(a: Int) = run { // val dims = asIntArray() // if (dims == null) Shape() // else Shape(*dims, a) //} // operator fun Int.plus(shape: Shape) = run { val dims = shape.asIntArray() if (dims == null) Shape() else Shape(this, *dims) } // //infix fun Shape.x(shape: Shape) = run { // val dims1 = asIntArray() // val dims2 = shape.asIntArray() // if (dims1 == null || dims2 == null) Shape() // else Shape(*dims1, *dims2) //} /** Represents the shape of a tensor computed by an op. * * A [Shape] represents a possibly-partial shape specification for an op output. It may be one of the following: * * - Fully known shape: It has a known number of dimensions and a known size for each dimension. * - Partially known shape: It has a known number of dimensions and an unknown size for one or more dimension. * - Unknown shape: It has an unknown number of dimensions and an unknown size for all its dimensions. * * Unknown dimensions are represented as having a size of `-1` and two shapes are considered equal only if they are * fully known and all their dimension sizes match. * * If a tensor is produced by an op of type `"Foo"`, its shape may be inferred if there is a registered shape function * for `"Foo"`. See [https://www.tensorflow.org/extend/adding_an_op#shape_functions_in_c Shape Functions in C++] for * details on shape functions and how to register them. * * @see [tensorflow/python/framework/tensor_shape.py/TensorShape] */ class Shape(private val dims: IntArray? = null) : Iterable<Int> { constructor(elements: LongArray) : this(IntArray(elements.size) { elements[it].toInt() }) companion object { operator fun invoke(vararg d: Int) = Shape(d) operator fun invoke(d: Int, shape: Shape): Shape { val dims = shape.asIntArray() return if (dims == null) Shape(d) else Shape(d, *dims) } operator fun invoke(dims: Collection<Int>): Shape = Shape(dims.toIntArray()) fun unknown(rank: Int = -1): Shape = if (rank == -1) Shape() else Shape(IntArray(rank) { -1 }) } fun asLongArray() = if (dims == null) null else LongArray(dims.size) { dims[it].toLong() } fun asIntArray() = dims val rank = dims?.size ?: -1 val isFullyDefined: Boolean get() = dims?.all { it >= 0 } ?: false val isUnknown: Boolean get() = !isFullyDefined val isScalar = dims?.size == 0 fun numElements() = if (!isFullyDefined) -1 else { var size = 1 dims!!.forEach { size *= it } size } operator fun get(idx: Int) = if (idx < 0) dims!![dims.size + idx] else dims!![idx] operator fun get(idx: IntRange) = run { if (dims == null) Shape() else { val size = (idx.endInclusive - idx.start) / idx.step val iter = idx.iterator() Shape(IntArray(size) { this[iter.nextInt()] }) } } operator fun set(idx: Int, d: Int) { dims!![idx] = d } operator fun plus(d: Int): Shape = plus(Shape(d)) operator fun plus(shape: Shape): Shape = when { dims == null -> shape.copy() shape.dims == null -> copy() else -> Shape(*dims, *shape.dims) } @Suppress("NAME_SHADOWING") fun slice(start: Int, end: Int? = null, step: Int = 1): Shape = if (dims == null) Shape() else { var end = end ?: if (start >= 0) dims.size else 0 if (end < 0) end += dims.size val start = if (start < 0) start + dims.size else start val size = (end - start) / step val iter = (start until end step step).iterator() Shape(IntArray(size) { this[iter.nextInt()] }) } override fun iterator() = dims!!.iterator() override fun toString(): String { val sb = StringBuilder() sb.append("(") if (dims != null) for ((i, value) in dims!!.withIndex()) { sb.append(if (value == -1) "?" else value) if (i < dims.lastIndex) sb.append(", ") } else sb.append("unknow_rank:true") sb.append(")") return sb.toString() } fun isCompatibleWith(other: Shape) = run { when { rank == -1 || other.rank == -1 -> true rank != other.rank -> false else -> (0 until rank).all { compatible(this[it], other[it]) } } } inline fun compatible(d1: Int, d2: Int) = d1 == -1 || d2 == -1 || d1 == d2 fun mergeWith(other: Shape): Shape { return when { rank == -1 -> other other.rank == -1 -> this else -> { assertSameRank(other) assertIsCompatibleWith(other) Shape(this.dims!!.zip(other.dims!!).map { (_1, _2) -> when { _1 == -1 -> _2 _2 == -1 -> _1 else -> _1 } }.toIntArray()) } } } fun withRank(rank: Int): Shape = mergeWith(unknown(rank)) fun withRankAtLeast(rank: Int): Shape { assertRankAtLeast(rank) return this } fun assertSameRank(other: Shape) = errorIf(this.rank != other.rank) { "Shape '$this' must have the same rank as shape '$other'" } fun assertRankAtLeast(rank: Int) = errorIf(this.rank < rank) { "Shape '$this' must have rank at least $rank." } fun assertIsCompatibleWith(other: Shape) = errorIf(!isCompatibleWith(other)) { "Shape '$this' must be compatible with shape '$other'." } fun copy(): Shape = Shape(dims?.copyOf()) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Shape if (!Arrays.equals(dims, other.dims)) return false return true } override fun hashCode(): Int { return dims?.let { Arrays.hashCode(it) } ?: 0 } operator fun component1() = this[0] operator fun component2() = this[1] operator fun component3() = this[2] operator fun component4() = this[3] operator fun component5() = this[4] operator fun component6() = this[5] operator fun component7() = this[6] } fun Int.isCompatibleWith(other: Int): Boolean = this == -1 || other == -1 || this == other
1
null
1
1
2a3a5118239b27eeb268cd1e7bdbfe5f5604dab6
6,393
sim-world
MIT License
smash-ranks-android/app/src/main/java/com/garpr/android/features/settings/IdentityPreferenceView.kt
charlesmadere
41,832,700
true
null
package com.garpr.android.features.settings import android.content.Context import android.content.DialogInterface import android.util.AttributeSet import android.view.View.OnClickListener import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import com.garpr.android.R import com.garpr.android.data.models.FavoritePlayer import com.garpr.android.features.common.views.SimplePreferenceView class IdentityPreferenceView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : SimplePreferenceView(context, attrs), DialogInterface.OnClickListener { var listeners: Listeners? = null private val deleteIdentityClickListener = OnClickListener { AlertDialog.Builder(context) .setMessage(R.string.are_you_sure_you_want_to_delete_your_identity) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.yes, this) .show() } private val setIdentityClickListener = OnClickListener { listeners?.onSetIdentityClick(this) } interface Listeners { fun onDeleteIdentityClick(v: IdentityPreferenceView) fun onSetIdentityClick(v: IdentityPreferenceView) } init { setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_face_white_24dp)) setLoading() } override fun onClick(dialog: DialogInterface, which: Int) { listeners?.onDeleteIdentityClick(this) } fun setContent(identity: FavoritePlayer?) { isEnabled = true if (identity == null) { titleText = resources.getText(R.string.identity) descriptionText = resources.getText(R.string.easily_find_yourself_throughout_the_app) setOnClickListener(setIdentityClickListener) } else { titleText = resources.getText(R.string.delete_identity) descriptionText = resources.getString(R.string.name_region_format, identity.name, identity.region.displayName) setOnClickListener(deleteIdentityClickListener) } } fun setLoading() { isEnabled = false titleText = resources.getText(R.string.loading_identity_) descriptionText = resources.getText(R.string.please_wait_) } }
0
Kotlin
0
9
151b2a0f9b4d38be60c3f73344ca444f17810bfd
2,315
smash-ranks-android
The Unlicense