path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/thicapps/artbook/viewmodel/ArtViewModel.kt
cemaltuysuz
398,304,728
false
null
package com.thicapps.artbook.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.thicapps.artbook.model.ImageResponse import com.thicapps.artbook.repo.ArtRepositoryI import com.thicapps.artbook.room.Art import com.thicapps.artbook.util.Resource import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import retrofit2.Response import java.lang.Exception import javax.inject.Inject @HiltViewModel class ArtViewModel @Inject constructor(private val repositoryI: ArtRepositoryI) : ViewModel() { // Art Fragment val artist = repositoryI.getArt() // Image API Fragment private val images = MutableLiveData<Resource<ImageResponse>>() val imageList : LiveData<Resource<ImageResponse>> get() = images private val selectedImage = MutableLiveData<String>() val selectedUrl : LiveData<String> get() = selectedImage // Art Details private var insertArtMsg = MutableLiveData<Resource<Art>>() val insertArtMessage : LiveData<Resource<Art>> get() = insertArtMsg fun resetInsertArtMsg(){ insertArtMsg = MutableLiveData<Resource<Art>>() } fun setSelectedImage(url:String){ selectedImage.postValue(url) } fun deleteArt (art:Art) = viewModelScope.launch { repositoryI.deleteArt(art) } fun insertArt(art: Art) = viewModelScope.launch { repositoryI.insertArt(art) } fun makeArt(name:String, artistName:String, year:String){ if (name.isEmpty() || artistName.isEmpty() || year.isEmpty()){ insertArtMsg.value = Resource.error("Enter name, artist name, year",null) return } val yearInt = try { year.toInt() }catch (e:Exception){ insertArtMsg.value = Resource.error("Year field must be of numeric type. ${e.message}", null) return } val art = Art(name,artistName,yearInt,selectedImage.value ?:"") insertArt(art) selectedImage.value = "" insertArtMsg.postValue(Resource.success(art)) } fun searchForImage (searchString:String){ if (searchString.isEmpty()) return images.value = Resource.loading(null) viewModelScope.launch { val response = repositoryI.searchImage(searchString) images.value = response } } }
0
Kotlin
0
0
9d854b731cfe9973f3082a1e803f5f55e750283e
2,472
ArtBook-Lesson-Example
MIT License
js/js.translator/testFiles/simple/cases/postfixIntOperations.kt
chirino
3,596,099
false
null
package foo fun box(): Boolean { var a = 3; val b = a++; a--; a--; return (a++ == 2) && (b == 3) }
0
null
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
121
kotlin
Apache License 2.0
src/main/kotlin/days/Day17.kt
mstar95
317,305,289
false
null
package days class Day17 : Day(17) { override fun partOne(): Any { val input = countActiveAfter(1, 3, inputList) println(input) return input } override fun partTwo(): Any { val input = countActiveAfter(6, 4, inputList) return input } data class DimensionalCube(private val coordinates: List<Int>) { fun neighbors(): List<DimensionalCube> { return recurse(listOf()) } fun recurse(prefix: List<Int>): List<DimensionalCube> { val position = prefix.size if (position == coordinates.size) { if (prefix != coordinates) { // cube isn't a neighbor to itself return listOf(DimensionalCube(prefix)) } } else { return (coordinates[position] - 1..coordinates[position] + 1).flatMap { recurse(prefix + it) } } return listOf() } } fun countActiveAfter(rounds: Int, dimensions: Int, input: List<String>): Int { var prevActive: Set<DimensionalCube> = input.withIndex().flatMap { (y, line) -> line.toCharArray().withIndex().filter { it.value == '#' }.map { it.index } .map { x -> DimensionalCube(listOf(x, y, *Array(dimensions - 2) { 0 })) } }.toSet() repeat(rounds) { // Active cells remain active with 2 or 3 neighbors, inactive cells become active with 3 prevActive = prevActive.flatMap(DimensionalCube::neighbors).groupingBy { it }.eachCount() .filter { (cube, count) -> count == 3 || (count == 2 && cube in prevActive) }.keys } return prevActive.size } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
1,740
aoc-2020
Creative Commons Zero v1.0 Universal
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/parameters/misc/labeledReturns.kt
JetBrains
2,489,216
false
null
fun foo() { listOf(1, "a").mapNotNull { <selection>run { return@mapNotNull 1 }</selection> } } // IGNORE_K1
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
144
intellij-community
Apache License 2.0
skd_chips/src/main/java/com/artlite/skd/chips/impl/models/ChipSectionModel.kt
dlernatovich
696,519,433
false
{"Kotlin": 71908}
package com.artlite.skd.chips.impl.models import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.artlite.skd.chips.facade.models.Displayable import com.artlite.skd.chips.facade.models.Expandable import com.artlite.skd.chips.facade.models.Identifiable import com.artlite.skd.chips.facade.models.createId /** * Class which provide the chip section model. * @property id String id for section. * @property icon Int? value. * @property text Int value. * @property isExpanded Boolean if section is expanded. * @property chips Set<ChipModel> list of chips. * @constructor */ class ChipSectionModel( override val id: String, @DrawableRes override var icon: Int? = null, @StringRes override var text: Int, val chips: Set<ChipModel> ): Identifiable, Displayable, Expandable { override var isExpanded: Boolean = false /** * Constructor with parameters. * @param icon Int? value. * @param text Int value. * @param chips Set<ChipModel> array of the [ChipModel]. * @constructor */ constructor(icon: Int?, text: Int, chips: Set<ChipModel>) : this(Identifiable.createId(), icon, text, chips) /** * Method which provide the equals functional. * @param other Any? model. * @return Boolean if it the same. */ override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ChipSectionModel if (id != other.id) return false return true } /** * Method which provide the hash code functional. * @return Int hash code value. */ override fun hashCode(): Int { return id.hashCode() } } /** * Method which provide to clear selected items. * @receiver ChipSectionModel */ fun ChipSectionModel.clearSelected() = chips.forEach { it.isSelected = false } /** * Method which provide to get the selected count value. * @receiver ChipSectionModel receiver. * @return Int value of the selected count. */ fun ChipSectionModel.getSelectedCount(): Int = chips.count { it.isSelected }
0
Kotlin
0
0
843f6876fec50d5f4e72c64fd4ad07f7c5368232
2,151
SdkAndroidChips
Apache License 2.0
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/note_editor/view/SecretInputType.kt
aivanovski
95,774,290
false
null
package com.ivanovsky.passnotes.presentation.note_editor.view enum class SecretInputType { TEXT, DIGITS }
0
Kotlin
0
0
08df99c790087a252f05de76a75833ec538f6100
114
passnotes
Apache License 2.0
src/main/kotlin/com/budzilla/auth/JwtTokenFilter.kt
MrLys
544,570,195
false
null
package com.budzilla.auth import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders.AUTHORIZATION import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.stereotype.Component import org.springframework.web.filter.OncePerRequestFilter import java.util.* import javax.servlet.FilterChain import javax.servlet.http.Cookie import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @Component class JwtTokenFilter( private val jwtService: JwtService, private val userDetailsService: UserDetailsService, @Value("\${budzilla.jwt.token.name}") private val sessionCookieName: String, ) : OncePerRequestFilter() { override fun doFilterInternal( request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain ) { val jwt = getBearerToken(request) if (jwt == null) { val allCookies: Array<Cookie>? = request.cookies if (allCookies != null) { val session: Cookie? = Arrays.stream(allCookies).filter { x -> x.name.equals(sessionCookieName) } .findFirst().orElse(null) if (session != null) { val jwt = session.value if (jwt != null && jwtService.validate(jwt)) { val username : String = jwtService.getUsername(jwt) val userDetails = userDetailsService.loadUserByUsername(username) val auth = UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities) SecurityContextHolder.getContext().authentication = auth } } } } else if (jwtService.validate(jwt)) { val username : String = jwtService.getUsername(jwt) val userDetails = userDetailsService.loadUserByUsername(username) val auth = UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities) SecurityContextHolder.getContext().authentication = auth } filterChain.doFilter(request, response) } private fun getBearerToken(request: HttpServletRequest): String? { val authHeader : String? = request.getHeader(AUTHORIZATION) if (authHeader?.contains("Bearer ") == true) { return authHeader.substring(7, authHeader.length) } // more to come return authHeader } }
0
Kotlin
0
0
e8940dcf4b4f26bbadec7edc00e59eb73655a884
2,705
congenial-dollop
Apache License 2.0
battery/src/main/java/com/domker/doctor/battery/BatteryWatcher.kt
MaisonWan
330,649,879
false
null
package com.domker.app.doctor.battery import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Build import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider /** * 电池状态监听器 * Created by wanlipeng on 2021/10/28 11:38 上午 */ class BatteryWatcher(private val context: Context) { private val batteryInfo = BatteryInfo() private lateinit var batteryViewModel: BatteryViewModel // 广播接收器 private val receiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == Intent.ACTION_BATTERY_CHANGED) { parserBattery(intent) batteryViewModel.batteryInfo.postValue(batteryInfo) } } } /** * 初始化的接口 */ fun register(owner: Fragment, listener: (BatteryInfo) -> Unit) { // 注册广播 val intentFilter = IntentFilter() intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED) intentFilter.addAction(Intent.ACTION_BATTERY_LOW) context.registerReceiver(receiver, intentFilter) // 注册监听器 batteryViewModel = ViewModelProvider(owner).get(BatteryViewModel::class.java) batteryViewModel.batteryInfo.observe(owner) { listener(batteryInfo) } } /** * 反注册监听器 */ fun unregister(owner: Fragment) { context.unregisterReceiver(receiver) batteryViewModel.batteryInfo.removeObservers(owner) } /** * 解析电池信息内容 */ private fun parserBattery(intent: Intent) { batteryInfo.status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0) batteryInfo.health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0) batteryInfo.present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false) batteryInfo.level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0) batteryInfo.scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0) batteryInfo.iconSmall = intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL, 0) batteryInfo.plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) batteryInfo.voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) batteryInfo.temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) batteryInfo.technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY) ?: "" batteryInfo.technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY) ?: "" if (Build.VERSION.SDK_INT >= 28) { batteryInfo.batteryLow = intent.getBooleanExtra(BatteryManager.EXTRA_BATTERY_LOW, false) } } }
0
Kotlin
0
0
df13773545f278b8e2946a93bd0b30477e176120
2,802
AppDoctor
Apache License 2.0
battery/src/main/java/com/domker/doctor/battery/BatteryWatcher.kt
MaisonWan
330,649,879
false
null
package com.domker.app.doctor.battery import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Build import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider /** * 电池状态监听器 * Created by wanlipeng on 2021/10/28 11:38 上午 */ class BatteryWatcher(private val context: Context) { private val batteryInfo = BatteryInfo() private lateinit var batteryViewModel: BatteryViewModel // 广播接收器 private val receiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == Intent.ACTION_BATTERY_CHANGED) { parserBattery(intent) batteryViewModel.batteryInfo.postValue(batteryInfo) } } } /** * 初始化的接口 */ fun register(owner: Fragment, listener: (BatteryInfo) -> Unit) { // 注册广播 val intentFilter = IntentFilter() intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED) intentFilter.addAction(Intent.ACTION_BATTERY_LOW) context.registerReceiver(receiver, intentFilter) // 注册监听器 batteryViewModel = ViewModelProvider(owner).get(BatteryViewModel::class.java) batteryViewModel.batteryInfo.observe(owner) { listener(batteryInfo) } } /** * 反注册监听器 */ fun unregister(owner: Fragment) { context.unregisterReceiver(receiver) batteryViewModel.batteryInfo.removeObservers(owner) } /** * 解析电池信息内容 */ private fun parserBattery(intent: Intent) { batteryInfo.status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0) batteryInfo.health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0) batteryInfo.present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false) batteryInfo.level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0) batteryInfo.scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0) batteryInfo.iconSmall = intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL, 0) batteryInfo.plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) batteryInfo.voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) batteryInfo.temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) batteryInfo.technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY) ?: "" batteryInfo.technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY) ?: "" if (Build.VERSION.SDK_INT >= 28) { batteryInfo.batteryLow = intent.getBooleanExtra(BatteryManager.EXTRA_BATTERY_LOW, false) } } }
0
Kotlin
0
0
df13773545f278b8e2946a93bd0b30477e176120
2,802
AppDoctor
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/cassandra/CfnTablePropsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.cassandra import cloudshift.awscdk.common.CdkDslMarker import cloudshift.awscdk.dsl.CfnTagDsl import kotlin.Any import kotlin.Boolean import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.CfnTag import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.cassandra.CfnTable import software.amazon.awscdk.services.cassandra.CfnTableProps /** * Properties for defining a `CfnTable`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.cassandra.*; * CfnTableProps cfnTableProps = CfnTableProps.builder() * .keyspaceName("keyspaceName") * .partitionKeyColumns(List.of(ColumnProperty.builder() * .columnName("columnName") * .columnType("columnType") * .build())) * // the properties below are optional * .billingMode(BillingModeProperty.builder() * .mode("mode") * // the properties below are optional * .provisionedThroughput(ProvisionedThroughputProperty.builder() * .readCapacityUnits(123) * .writeCapacityUnits(123) * .build()) * .build()) * .clientSideTimestampsEnabled(false) * .clusteringKeyColumns(List.of(ClusteringKeyColumnProperty.builder() * .column(ColumnProperty.builder() * .columnName("columnName") * .columnType("columnType") * .build()) * // the properties below are optional * .orderBy("orderBy") * .build())) * .defaultTimeToLive(123) * .encryptionSpecification(EncryptionSpecificationProperty.builder() * .encryptionType("encryptionType") * // the properties below are optional * .kmsKeyIdentifier("kmsKeyIdentifier") * .build()) * .pointInTimeRecoveryEnabled(false) * .regularColumns(List.of(ColumnProperty.builder() * .columnName("columnName") * .columnType("columnType") * .build())) * .tableName("tableName") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cassandra-table.html) */ @CdkDslMarker public class CfnTablePropsDsl { private val cdkBuilder: CfnTableProps.Builder = CfnTableProps.builder() private val _clusteringKeyColumns: MutableList<Any> = mutableListOf() private val _partitionKeyColumns: MutableList<Any> = mutableListOf() private val _regularColumns: MutableList<Any> = mutableListOf() private val _tags: MutableList<CfnTag> = mutableListOf() /** * @param billingMode The billing mode for the table, which determines how you'll be charged for * reads and writes:. * * *On-demand mode* (default) - You pay based on the actual reads and writes your application * performs. * * *Provisioned mode* - Lets you specify the number of reads and writes per second that you need * for your application. * * If you don't specify a value for this property, then the table will use on-demand mode. */ public fun billingMode(billingMode: IResolvable) { cdkBuilder.billingMode(billingMode) } /** * @param billingMode The billing mode for the table, which determines how you'll be charged for * reads and writes:. * * *On-demand mode* (default) - You pay based on the actual reads and writes your application * performs. * * *Provisioned mode* - Lets you specify the number of reads and writes per second that you need * for your application. * * If you don't specify a value for this property, then the table will use on-demand mode. */ public fun billingMode(billingMode: CfnTable.BillingModeProperty) { cdkBuilder.billingMode(billingMode) } /** * @param clientSideTimestampsEnabled Enables client-side timestamps for the table. * By default, the setting is disabled. You can enable client-side timestamps with the following * option: * * * `status: "enabled"` * * After client-side timestamps are enabled for a table, you can't disable this setting. */ public fun clientSideTimestampsEnabled(clientSideTimestampsEnabled: Boolean) { cdkBuilder.clientSideTimestampsEnabled(clientSideTimestampsEnabled) } /** * @param clientSideTimestampsEnabled Enables client-side timestamps for the table. * By default, the setting is disabled. You can enable client-side timestamps with the following * option: * * * `status: "enabled"` * * After client-side timestamps are enabled for a table, you can't disable this setting. */ public fun clientSideTimestampsEnabled(clientSideTimestampsEnabled: IResolvable) { cdkBuilder.clientSideTimestampsEnabled(clientSideTimestampsEnabled) } /** * @param clusteringKeyColumns One or more columns that determine how the table data is sorted. */ public fun clusteringKeyColumns(vararg clusteringKeyColumns: Any) { _clusteringKeyColumns.addAll(listOf(*clusteringKeyColumns)) } /** * @param clusteringKeyColumns One or more columns that determine how the table data is sorted. */ public fun clusteringKeyColumns(clusteringKeyColumns: Collection<Any>) { _clusteringKeyColumns.addAll(clusteringKeyColumns) } /** * @param clusteringKeyColumns One or more columns that determine how the table data is sorted. */ public fun clusteringKeyColumns(clusteringKeyColumns: IResolvable) { cdkBuilder.clusteringKeyColumns(clusteringKeyColumns) } /** * @param defaultTimeToLive The default Time To Live (TTL) value for all rows in a table in * seconds. * The maximum configurable value is 630,720,000 seconds, which is the equivalent of 20 years. By * default, the TTL value for a table is 0, which means data does not expire. * * For more information, see [Setting the default TTL value for a * table](https://docs.aws.amazon.com/keyspaces/latest/devguide/TTL-how-it-works.html#ttl-howitworks_default_ttl) * in the *Amazon Keyspaces Developer Guide* . */ public fun defaultTimeToLive(defaultTimeToLive: Number) { cdkBuilder.defaultTimeToLive(defaultTimeToLive) } /** * @param encryptionSpecification The encryption at rest options for the table. * * *AWS owned key* (default) - The key is owned by Amazon Keyspaces. * * *Customer managed key* - The key is stored in your account and is created, owned, and managed * by you. * * * If you choose encryption with a customer managed key, you must specify a valid customer managed * KMS key with permissions granted to Amazon Keyspaces. * * * For more information, see [Encryption at rest in Amazon * Keyspaces](https://docs.aws.amazon.com/keyspaces/latest/devguide/EncryptionAtRest.html) in the * *Amazon Keyspaces Developer Guide* . */ public fun encryptionSpecification(encryptionSpecification: IResolvable) { cdkBuilder.encryptionSpecification(encryptionSpecification) } /** * @param encryptionSpecification The encryption at rest options for the table. * * *AWS owned key* (default) - The key is owned by Amazon Keyspaces. * * *Customer managed key* - The key is stored in your account and is created, owned, and managed * by you. * * * If you choose encryption with a customer managed key, you must specify a valid customer managed * KMS key with permissions granted to Amazon Keyspaces. * * * For more information, see [Encryption at rest in Amazon * Keyspaces](https://docs.aws.amazon.com/keyspaces/latest/devguide/EncryptionAtRest.html) in the * *Amazon Keyspaces Developer Guide* . */ public fun encryptionSpecification(encryptionSpecification: CfnTable.EncryptionSpecificationProperty) { cdkBuilder.encryptionSpecification(encryptionSpecification) } /** * @param keyspaceName The name of the keyspace to create the table in. * The keyspace must already exist. */ public fun keyspaceName(keyspaceName: String) { cdkBuilder.keyspaceName(keyspaceName) } /** * @param partitionKeyColumns One or more columns that uniquely identify every row in the table. * Every table must have a partition key. */ public fun partitionKeyColumns(vararg partitionKeyColumns: Any) { _partitionKeyColumns.addAll(listOf(*partitionKeyColumns)) } /** * @param partitionKeyColumns One or more columns that uniquely identify every row in the table. * Every table must have a partition key. */ public fun partitionKeyColumns(partitionKeyColumns: Collection<Any>) { _partitionKeyColumns.addAll(partitionKeyColumns) } /** * @param partitionKeyColumns One or more columns that uniquely identify every row in the table. * Every table must have a partition key. */ public fun partitionKeyColumns(partitionKeyColumns: IResolvable) { cdkBuilder.partitionKeyColumns(partitionKeyColumns) } /** * @param pointInTimeRecoveryEnabled Specifies if point-in-time recovery is enabled or disabled * for the table. * The options are `PointInTimeRecoveryEnabled=true` and `PointInTimeRecoveryEnabled=false` . If * not specified, the default is `PointInTimeRecoveryEnabled=false` . */ public fun pointInTimeRecoveryEnabled(pointInTimeRecoveryEnabled: Boolean) { cdkBuilder.pointInTimeRecoveryEnabled(pointInTimeRecoveryEnabled) } /** * @param pointInTimeRecoveryEnabled Specifies if point-in-time recovery is enabled or disabled * for the table. * The options are `PointInTimeRecoveryEnabled=true` and `PointInTimeRecoveryEnabled=false` . If * not specified, the default is `PointInTimeRecoveryEnabled=false` . */ public fun pointInTimeRecoveryEnabled(pointInTimeRecoveryEnabled: IResolvable) { cdkBuilder.pointInTimeRecoveryEnabled(pointInTimeRecoveryEnabled) } /** * @param regularColumns One or more columns that are not part of the primary key - that is, * columns that are *not* defined as partition key columns or clustering key columns. * You can add regular columns to existing tables by adding them to the template. */ public fun regularColumns(vararg regularColumns: Any) { _regularColumns.addAll(listOf(*regularColumns)) } /** * @param regularColumns One or more columns that are not part of the primary key - that is, * columns that are *not* defined as partition key columns or clustering key columns. * You can add regular columns to existing tables by adding them to the template. */ public fun regularColumns(regularColumns: Collection<Any>) { _regularColumns.addAll(regularColumns) } /** * @param regularColumns One or more columns that are not part of the primary key - that is, * columns that are *not* defined as partition key columns or clustering key columns. * You can add regular columns to existing tables by adding them to the template. */ public fun regularColumns(regularColumns: IResolvable) { cdkBuilder.regularColumns(regularColumns) } /** * @param tableName The name of the table to be created. * The table name is case sensitive. If you don't specify a name, AWS CloudFormation generates a * unique ID and uses that ID for the table name. For more information, see [Name * type](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html) . * * * If you specify a name, you can't perform updates that require replacing this resource. You can * perform updates that require no interruption or some interruption. If you must replace the * resource, specify a new name. * * * *Length constraints:* Minimum length of 3. Maximum length of 255. * * *Pattern:* `^[a-zA-Z0-9][a-zA-Z0-9_]{1,47}$` */ public fun tableName(tableName: String) { cdkBuilder.tableName(tableName) } /** * @param tags An array of key-value pairs to apply to this resource. * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ public fun tags(tags: CfnTagDsl.() -> Unit) { _tags.add(CfnTagDsl().apply(tags).build()) } /** * @param tags An array of key-value pairs to apply to this resource. * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ public fun tags(tags: Collection<CfnTag>) { _tags.addAll(tags) } public fun build(): CfnTableProps { if(_clusteringKeyColumns.isNotEmpty()) cdkBuilder.clusteringKeyColumns(_clusteringKeyColumns) if(_partitionKeyColumns.isNotEmpty()) cdkBuilder.partitionKeyColumns(_partitionKeyColumns) if(_regularColumns.isNotEmpty()) cdkBuilder.regularColumns(_regularColumns) if(_tags.isNotEmpty()) cdkBuilder.tags(_tags) return cdkBuilder.build() } }
3
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
13,004
awscdk-dsl-kotlin
Apache License 2.0
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/InnerClassesLowering.kt
arrow-kt
109,678,056
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.common.lower import org.jetbrains.kotlin.backend.common.BackendContext import org.jetbrains.kotlin.backend.common.BodyLoweringPass import org.jetbrains.kotlin.backend.common.ClassLoweringPass import org.jetbrains.kotlin.backend.common.makePhase import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrConstructor import org.jetbrains.kotlin.ir.declarations.IrField import org.jetbrains.kotlin.ir.declarations.IrValueParameter import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol import org.jetbrains.kotlin.ir.symbols.IrValueParameterSymbol import org.jetbrains.kotlin.ir.symbols.IrValueSymbol import org.jetbrains.kotlin.ir.types.classifierOrNull import org.jetbrains.kotlin.ir.util.defaultType import org.jetbrains.kotlin.ir.util.dump import org.jetbrains.kotlin.ir.util.patchDeclarationParents import org.jetbrains.kotlin.ir.util.transformDeclarationsFlat import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import java.util.* val InnerClassesPhase = makePhase( ::InnerClassesLowering, name = "InnerClasses", description = "Move inner classes to toplevel" ) class InnerClassesLowering(val context: BackendContext) : ClassLoweringPass { override fun lower(irClass: IrClass) { InnerClassTransformer(irClass).lowerInnerClass() } private inner class InnerClassTransformer(val irClass: IrClass) { lateinit var outerThisField: IrField val oldConstructorParameterToNew = HashMap<IrValueParameter, IrValueParameter>() fun lowerInnerClass() { if (!irClass.isInner) return createOuterThisField() lowerConstructors() lowerConstructorParameterUsages() lowerOuterThisReferences() } private fun createOuterThisField() { val field = context.declarationFactory.getOuterThisField(irClass) outerThisField = field irClass.declarations += field } private fun lowerConstructors() { irClass.transformDeclarationsFlat { irMember -> if (irMember is IrConstructor) listOf(lowerConstructor(irMember)) else null } } private fun lowerConstructor(irConstructor: IrConstructor): IrConstructor { val startOffset = irConstructor.startOffset val endOffset = irConstructor.endOffset val loweredConstructor = context.declarationFactory.getInnerClassConstructorWithOuterThisParameter(irConstructor) val outerThisValueParameter = loweredConstructor.valueParameters[0].symbol irConstructor.valueParameters.forEach { old -> oldConstructorParameterToNew[old] = loweredConstructor.valueParameters[old.index + 1] } val blockBody = irConstructor.body as? IrBlockBody ?: throw AssertionError("Unexpected constructor body: ${irConstructor.body}") val instanceInitializerIndex = blockBody.statements.indexOfFirst { it is IrInstanceInitializerCall } // Initializing constructor: initialize 'this.this$0' with '$outer' blockBody.statements.add( 0, IrSetFieldImpl( startOffset, endOffset, outerThisField.symbol, IrGetValueImpl(startOffset, endOffset, irClass.thisReceiver!!.symbol), IrGetValueImpl(startOffset, endOffset, outerThisValueParameter), context.irBuiltIns.unitType ) ) if (instanceInitializerIndex < 0) { // Delegating constructor: invoke old constructor with dispatch receiver '$outer' val delegatingConstructorCall = (blockBody.statements.find { it is IrDelegatingConstructorCall } ?: throw AssertionError("Delegating constructor call expected: ${irConstructor.dump()}") ) as IrDelegatingConstructorCall delegatingConstructorCall.dispatchReceiver = IrGetValueImpl( delegatingConstructorCall.startOffset, delegatingConstructorCall.endOffset, outerThisValueParameter ) } blockBody.patchDeclarationParents(loweredConstructor) loweredConstructor.body = blockBody return loweredConstructor } private fun lowerConstructorParameterUsages() { irClass.transformChildrenVoid(VariableRemapper(oldConstructorParameterToNew)) } private fun lowerOuterThisReferences() { irClass.transformChildrenVoid(object : IrElementTransformerVoid() { override fun visitClass(declaration: IrClass): IrStatement = //TODO: maybe add another transformer that skips specified elements declaration override fun visitGetValue(expression: IrGetValue): IrExpression { expression.transformChildrenVoid(this) val implicitThisClass = expression.symbol.getClassForImplicitThis() ?: return expression if (implicitThisClass == irClass) return expression val startOffset = expression.startOffset val endOffset = expression.endOffset val origin = expression.origin var irThis: IrExpression = IrGetValueImpl(startOffset, endOffset, irClass.thisReceiver!!.symbol, origin) var innerClass = irClass while (innerClass != implicitThisClass) { if (!innerClass.isInner) { // Captured 'this' unrelated to inner classes nesting hierarchy, leave it as is - // should be transformed by closures conversion. return expression } val outerThisField = context.declarationFactory.getOuterThisField(innerClass) irThis = IrGetFieldImpl( startOffset, endOffset, outerThisField.symbol, innerClass.defaultType, irThis, origin ) val outer = innerClass.parent innerClass = outer as? IrClass ?: throw AssertionError("Unexpected containing declaration for inner class $innerClass: $outer") } return irThis } }) } private fun IrValueSymbol.getClassForImplicitThis(): IrClass? { //TODO: is it correct way to get class if (this is IrValueParameterSymbol) { val declaration = owner if (declaration.index == -1) { // means value is either IMPLICIT or EXTENSION receiver if (declaration.name.isSpecial) { // whether name is <this> return owner.type.classifierOrNull?.owner as IrClass } } } return null } } } val InnerClassConstructorCallsPhase = makePhase( ::InnerClassConstructorCallsLowering, name = "InnerClassConstructorCalls", description = "Handle constructor calls for inner classes" ) class InnerClassConstructorCallsLowering(val context: BackendContext) : BodyLoweringPass { override fun lower(irBody: IrBody) { irBody.transformChildrenVoid(object : IrElementTransformerVoid() { override fun visitCall(expression: IrCall): IrExpression { expression.transformChildrenVoid(this) val dispatchReceiver = expression.dispatchReceiver ?: return expression val callee = expression.symbol as? IrConstructorSymbol ?: return expression val parent = callee.owner.parent as? IrClass ?: return expression if (!parent.isInner) return expression val newCallee = context.declarationFactory.getInnerClassConstructorWithOuterThisParameter(callee.owner) val newCall = IrCallImpl( expression.startOffset, expression.endOffset, expression.type, newCallee.symbol, newCallee.descriptor, 0, // TODO type arguments map expression.origin ) newCall.putValueArgument(0, dispatchReceiver) for (i in 1..newCallee.valueParameters.lastIndex) { newCall.putValueArgument(i, expression.getValueArgument(i - 1)) } return newCall } override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall): IrExpression { expression.transformChildrenVoid(this) val dispatchReceiver = expression.dispatchReceiver ?: return expression val classConstructor = expression.symbol.owner if (!(classConstructor.parent as IrClass).isInner) return expression val newCallee = context.declarationFactory.getInnerClassConstructorWithOuterThisParameter(classConstructor) val newCall = IrDelegatingConstructorCallImpl( expression.startOffset, expression.endOffset, context.irBuiltIns.unitType, newCallee.symbol, newCallee.descriptor, classConstructor.typeParameters.size ).apply { copyTypeArgumentsFrom(expression) } newCall.putValueArgument(0, dispatchReceiver) for (i in 1..newCallee.valueParameters.lastIndex) { newCall.putValueArgument(i, expression.getValueArgument(i - 1)) } return newCall } override fun visitFunctionReference(expression: IrFunctionReference): IrExpression { expression.transformChildrenVoid(this) val callee = expression.symbol as? IrConstructorSymbol ?: return expression val parent = callee.owner.parent as? IrClass ?: return expression if (!parent.isInner) return expression val newCallee = context.declarationFactory.getInnerClassConstructorWithOuterThisParameter(callee.owner) val newReference = expression.run { IrFunctionReferenceImpl( startOffset, endOffset, type, newCallee.symbol, newCallee.descriptor, typeArgumentsCount, origin ) } newReference.let { it.dispatchReceiver = expression.dispatchReceiver it.extensionReceiver = expression.extensionReceiver for (t in 0 until expression.typeArgumentsCount) { it.putTypeArgument(t, expression.getTypeArgument(t)) } for (v in 0 until expression.valueArgumentsCount) { it.putValueArgument(v, expression.getValueArgument(v)) } } return newReference } // TODO callable references? }) } }
2
null
2
43
d2a24985b602e5f708e199aa58ece652a4b0ea48
11,869
kotlin
Apache License 2.0
app/src/main/java/team/msg/hi_v2/HiApplication.kt
GSM-MSG
637,641,666
false
null
package team.msg.hi_v2 import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class HiApplication: Application()
0
Kotlin
0
9
bd251a1fcf7c9b81125204a34f4b6f899cd356be
148
Hi-v2-Android
MIT License
app/src/main/java/team/msg/hi_v2/HiApplication.kt
GSM-MSG
637,641,666
false
null
package team.msg.hi_v2 import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class HiApplication: Application()
0
Kotlin
0
9
bd251a1fcf7c9b81125204a34f4b6f899cd356be
148
Hi-v2-Android
MIT License
src/commonMain/kotlin/org/intellij/markdown/html/GeneratingProviders.kt
JetBrains
27,873,341
false
{"Kotlin": 1305157, "Lex": 29252, "Ruby": 691, "Shell": 104}
package org.intellij.markdown.html import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.ast.* import org.intellij.markdown.ast.impl.ListCompositeNode import org.intellij.markdown.ast.impl.ListItemCompositeNode import org.intellij.markdown.html.entities.EntityConverter import org.intellij.markdown.parser.LinkMap import java.net.URI import java.util.* import kotlin.text.Regex abstract class OpenCloseGeneratingProvider : GeneratingProvider { abstract fun openTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) abstract fun closeTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { openTag(visitor, text, node) node.acceptChildren(visitor) closeTag(visitor, text, node) } } abstract class InlineHolderGeneratingProvider : OpenCloseGeneratingProvider() { open fun childrenToRender(node: ASTNode): List<ASTNode> { return node.children } override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { openTag(visitor, text, node) for (child in childrenToRender(node)) { if (child is LeafASTNode) { visitor.visitLeaf(child) } else { child.accept(visitor) } } closeTag(visitor, text, node) } } open class SimpleTagProvider(val tagName: String) : OpenCloseGeneratingProvider() { override fun openTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { visitor.consumeTagOpen(node, tagName) } override fun closeTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { visitor.consumeTagClose(tagName) } } open class SimpleInlineTagProvider(val tagName: String, val renderFrom: Int = 0, val renderTo: Int = 0) : InlineHolderGeneratingProvider() { override fun openTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { visitor.consumeTagOpen(node, tagName) } override fun closeTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { visitor.consumeTagClose(tagName) } override fun childrenToRender(node: ASTNode): List<ASTNode> { return node.children.subList(renderFrom, node.children.size + renderTo) } } open class TransparentInlineHolderProvider(renderFrom: Int = 0, renderTo: Int = 0) : SimpleInlineTagProvider("", renderFrom, renderTo) { override fun openTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { } override fun closeTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { } } open class TrimmingInlineHolderProvider() : InlineHolderGeneratingProvider() { override fun openTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { } override fun closeTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { } override fun childrenToRender(node: ASTNode): List<ASTNode> { val children = node.children var from = 0 while (from < children.size && children[from].type == MarkdownTokenTypes.WHITE_SPACE) { from++ } var to = children.size while (to > from && children[to - 1].type == MarkdownTokenTypes.WHITE_SPACE) { to-- } return children.subList(from, to) } } internal class ListItemGeneratingProvider : SimpleTagProvider("li") { override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { assert(node is ListItemCompositeNode) openTag(visitor, text, node) val listNode = node.parent assert(listNode is ListCompositeNode) val isLoose = (listNode as ListCompositeNode).loose for (child in node.children) { if (child.type == MarkdownElementTypes.PARAGRAPH && !isLoose) { SilentParagraphGeneratingProvider.processNode(visitor, text, child) } else { child.accept(visitor) } } closeTag(visitor, text, node) } object SilentParagraphGeneratingProvider : InlineHolderGeneratingProvider() { override fun openTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { } override fun closeTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { } } } internal class HtmlBlockGeneratingProvider : GeneratingProvider { override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { for (child in node.children) { if (child.type in listOf(MarkdownTokenTypes.EOL, MarkdownTokenTypes.HTML_BLOCK_CONTENT)) { visitor.consumeHtml(child.getTextInNode(text)) } } visitor.consumeHtml("\n") } } internal class CodeFenceGeneratingProvider : GeneratingProvider { override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { val indentBefore = node.getTextInNode(text).commonPrefixWith(" ".repeat(10)).length visitor.consumeHtml("<pre>") var state = 0 var childrenToConsider = node.children if (childrenToConsider.last().type == MarkdownTokenTypes.CODE_FENCE_END) { childrenToConsider = childrenToConsider.subList(0, childrenToConsider.size - 1) } var lastChildWasContent = false val attributes = ArrayList<String>() for (child in childrenToConsider) { if (state == 1 && child.type in listOf(MarkdownTokenTypes.CODE_FENCE_CONTENT, MarkdownTokenTypes.EOL)) { visitor.consumeHtml(HtmlGenerator.trimIndents(HtmlGenerator.leafText(text, child, false), indentBefore)) lastChildWasContent = child.type == MarkdownTokenTypes.CODE_FENCE_CONTENT } if (state == 0 && child.type == MarkdownTokenTypes.FENCE_LANG) { attributes.add("class=\"language-${ HtmlGenerator.leafText(text, child).toString().trim().split(' ')[0] }\"") } if (state == 0 && child.type == MarkdownTokenTypes.EOL) { visitor.consumeTagOpen(node, "code", *attributes.toTypedArray()) state = 1 } } if (state == 0) { visitor.consumeTagOpen(node, "code", *attributes.toTypedArray()) } if (lastChildWasContent) { visitor.consumeHtml("\n") } visitor.consumeHtml("</code></pre>") } } internal abstract class LinkGeneratingProvider(protected val baseURI: URI?) : GeneratingProvider { override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { val info = getRenderInfo(text, node) ?: return fallbackProvider.processNode(visitor, text, node) renderLink(visitor, text, node, info) } protected fun makeAbsoluteUrl(destination : CharSequence) : CharSequence { if (destination.startsWith('#')) { return destination } try { return baseURI?.resolve(destination.toString())?.toString() ?: destination } catch (e : IllegalArgumentException) { return destination } } open fun renderLink(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode, info: RenderInfo) { visitor.consumeTagOpen(node, "a", "href=\"${makeAbsoluteUrl(info.destination)}\"", info.title?.let { "title=\"$it\"" }) labelProvider.processNode(visitor, text, info.label) visitor.consumeTagClose("a") } abstract fun getRenderInfo(text: String, node: ASTNode): RenderInfo? data class RenderInfo(val label: ASTNode, val destination: CharSequence, val title: CharSequence?) companion object { val fallbackProvider = TransparentInlineHolderProvider() val labelProvider = TransparentInlineHolderProvider(1, -1) } } internal class InlineLinkGeneratingProvider(baseURI: URI?) : LinkGeneratingProvider(baseURI) { override fun getRenderInfo(text: String, node: ASTNode): LinkGeneratingProvider.RenderInfo? { val label = node.findChildOfType(MarkdownElementTypes.LINK_TEXT) ?: return null return LinkGeneratingProvider.RenderInfo( label, node.findChildOfType(MarkdownElementTypes.LINK_DESTINATION)?.getTextInNode(text)?.let { LinkMap.normalizeDestination(it, true) } ?: "", node.findChildOfType(MarkdownElementTypes.LINK_TITLE)?.getTextInNode(text)?.let { LinkMap.normalizeTitle(it) } ) } } internal class ReferenceLinksGeneratingProvider(private val linkMap: LinkMap, baseURI: URI?) : LinkGeneratingProvider(baseURI) { override fun getRenderInfo(text: String, node: ASTNode): LinkGeneratingProvider.RenderInfo? { val label = node.children.firstOrNull({ it.type == MarkdownElementTypes.LINK_LABEL }) ?: return null val linkInfo = linkMap.getLinkInfo(label.getTextInNode(text)) ?: return null val linkTextNode = node.children.firstOrNull({ it.type == MarkdownElementTypes.LINK_TEXT }) return LinkGeneratingProvider.RenderInfo( linkTextNode ?: label, EntityConverter.replaceEntities(linkInfo.destination, true, true), linkInfo.title?.let { EntityConverter.replaceEntities(it, true, true) } ) } } internal class ImageGeneratingProvider(linkMap: LinkMap, baseURI: URI?) : LinkGeneratingProvider(baseURI) { val referenceLinkProvider = ReferenceLinksGeneratingProvider(linkMap, baseURI) val inlineLinkProvider = InlineLinkGeneratingProvider(baseURI) override fun getRenderInfo(text: String, node: ASTNode): LinkGeneratingProvider.RenderInfo? { node.findChildOfType(MarkdownElementTypes.INLINE_LINK)?.let { linkNode -> return inlineLinkProvider.getRenderInfo(text, linkNode) } (node.findChildOfType(MarkdownElementTypes.FULL_REFERENCE_LINK) ?: node.findChildOfType(MarkdownElementTypes.SHORT_REFERENCE_LINK)) ?.let { linkNode -> return referenceLinkProvider.getRenderInfo(text, linkNode) } return null } override fun renderLink(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode, info: LinkGeneratingProvider.RenderInfo) { visitor.consumeTagOpen(node, "img", "src=\"${makeAbsoluteUrl(info.destination)}\"", "alt=\"${getPlainTextFrom(info.label, text)}\"", info.title?.let { "title=\"$it\"" }, autoClose = true) } private fun getPlainTextFrom(node: ASTNode, text: String): CharSequence { return REGEX.replace(node.getTextInNode(text), "") } companion object { val REGEX = Regex("[^a-zA-Z0-9 ]") } }
56
Kotlin
75
661
43c06cb6a9d66caab8b431f738aba3c57aee559f
11,346
markdown
Apache License 2.0
src/main/java/org/tokend/sdk/utils/extentions/ReviewableRequestResource.kt
tokend
153,458,393
false
null
package org.tokend.sdk.utils.extentions import org.tokend.sdk.api.v3.model.generated.resources.BaseReviewableRequestDetailsResource import org.tokend.sdk.api.v3.model.generated.resources.ReviewableRequestResource /** * @return the result of an unchecked cast of [ReviewableRequestResource.requestDetails] to [T] */ fun <T : BaseReviewableRequestDetailsResource> ReviewableRequestResource.getTypedRequestDetails(): T { return this.requestDetails as T }
0
Kotlin
1
14
5252e7441be26091a45c8dc8a87913bb0ebd1606
459
kotlin-sdk
Apache License 2.0
ui/auth/src/main/kotlin/com/gnoemes/shimori/auth/AuthViewModel.kt
gnoemes
213,210,354
false
null
package com.gnoemes.shimori.auth import androidx.lifecycle.ViewModel import com.gnoemes.shikimori.ShikimoriAuthManager import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel internal class AuthViewModel @Inject constructor( shikimoriAuthManager: ShikimoriAuthManager, ) : ViewModel(), ShikimoriAuthManager by shikimoriAuthManager
0
Kotlin
0
9
4aad5d0bd2e1e70ca7f0c79df3fd35b37d9e0b72
373
Shimori
Apache License 2.0
app/src/main/java/de/uriegel/superfit/ui/views/Settings.kt
uriegel
132,307,614
false
{"Kotlin": 122918}
package de.uriegel.superfit.ui.views import android.app.Activity import android.content.Intent import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import androidx.preference.PreferenceManager import com.jamal.composeprefs3.ui.LocalPrefsDataStore import com.jamal.composeprefs3.ui.PrefsScreen import com.jamal.composeprefs3.ui.prefs.CheckBoxPref import com.jamal.composeprefs3.ui.prefs.TextPref import de.uriegel.superfit.R import de.uriegel.superfit.sensor.BikeSensor import de.uriegel.superfit.sensor.HeartRateSensor import de.uriegel.superfit.ui.EditTextPref import de.uriegel.superfit.ui.MainActivity.Companion.prefBikeSensor import de.uriegel.superfit.ui.MainActivity.Companion.prefBikeSupport import de.uriegel.superfit.ui.MainActivity.Companion.prefHeartBeat import de.uriegel.superfit.ui.MainActivity.Companion.prefHeartSensor import de.uriegel.superfit.ui.MainActivity.Companion.prefMaps import de.uriegel.superfit.ui.MainActivity.Companion.prefWheel import de.uriegel.superfit.ui.MainActivity.Companion.showControls import de.uriegel.superfit.ui.NavRoutes import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @Composable @OptIn(ExperimentalMaterial3Api::class) fun Settings(dataStore: DataStore<Preferences>, navController: NavHostController) { val settings = stringResource(R.string.settings) val context = LocalContext.current val scope = rememberCoroutineScope() var selectedMap by remember { mutableStateOf("") } var heartBeatEnabled by remember { mutableStateOf(false) } var heartBeatSensor: Device? by remember { mutableStateOf(null) } var bikeSensor: Device? by remember { mutableStateOf(null) } var bikeEnabled by remember { mutableStateOf(false) } val prefs by remember { dataStore.data }.collectAsState(initial = null) LaunchedEffect(Unit) { prefs?.get(prefMaps)?.also { selectedMap = it } prefs?.get(prefBikeSupport)?.also { showControls = it bikeEnabled = it } prefs?.get(prefHeartBeat)?.also { heartBeatEnabled = it } prefs?.get(prefHeartSensor)?.also { it .split('|') .let { Device(it.first(), it.last()) }.also { heartBeatSensor = it } } prefs?.get(prefBikeSensor)?.also { it .split('|') .let { Device(it.first(), it.last()) }.also { bikeSensor = it } } } LaunchedEffect(dataStore.data) { dataStore.data.collectLatest { pref -> pref[prefMaps]?.also { selectedMap = it } pref[prefBikeSupport]?.also { showControls = it bikeEnabled = it } pref[prefHeartBeat]?.also { heartBeatEnabled = it } pref[prefHeartSensor]?.also { it .split('|') .let { Device(it.first(), it.last()) }.also { heartBeatSensor = it } } pref[prefBikeSensor]?.also { it .split('|') .let { Device(it.first(), it.last()) }.also { bikeSensor = it } } } } val mapsLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == Activity.RESULT_OK) { it.data?.data?.also { uri -> context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) scope.launch { dataStore.edit { preferences -> preferences[prefMaps] = uri.toString() selectedMap = uri.toString() PreferenceManager .getDefaultSharedPreferences(context) .edit() .putString("PREF_MAP", uri.toString()) .apply() } } } } } Scaffold( topBar = { TopAppBar(title = { Text(stringResource(R.string.app_title)) })}, content = { PrefsScreen( modifier = Modifier.padding(it), dataStore = dataStore) { prefsGroup(title = settings) { prefsItem { CheckBoxPref( key = prefHeartBeat.name, title = stringResource(R.string.heartrate_sensor), summary = stringResource(R.string.heartrate_description)) } prefsItem { TextPref( title = stringResource(R.string.heartrate_sensor), summary = heartBeatSensor?.name, enabled = heartBeatEnabled, darkenOnDisable = true, onClick = { navController.navigate(NavRoutes.DevicesView.route + "/${prefHeartSensor.name}/${R.string.heartrate_sensor}/${HeartRateSensor.getUuid()}") } ) } prefsItem { CheckBoxPref( key = prefBikeSupport.name, title = stringResource(R.string.bike_support), summary = stringResource(R.string.bike_support_description)) } prefsItem { TextPref( title = stringResource(R.string.bike_sensor), enabled = bikeEnabled, darkenOnDisable = true, summary = bikeSensor?.name, onClick = { navController.navigate(NavRoutes.DevicesView.route + "/${prefBikeSensor.name}/${R.string.bike_sensor}/${BikeSensor.getUuid()}") } ) } prefsItem { EditTextPref( title = stringResource(R.string.bike_circumference), summary = stringResource(R.string.bike_circumference_description), dialogMessage = stringResource(R.string.bike_circumference_description), dialogTitle = stringResource(R.string.bike_circumference), key = prefWheel, enabled = bikeEnabled, numbers = true ) } } prefsGroup(title = "Navigation") { prefsItem { TextPref( title = stringResource(R.string.maps), summary = if (selectedMap.isNotEmpty()) selectedMap.getPath() else stringResource(R.string.maps_description), enabled = true, onClick = { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "*/*" } mapsLauncher.launch(intent) }) } } } } ) } fun String.getPath() = Uri.parse(this).path @Preview @Composable fun SettingsPreview() { Settings(LocalPrefsDataStore.current, rememberNavController()) }
0
Kotlin
1
1
53e1c418d96917938d0259a44669ff1bf0d14a46
9,278
SuperFit
MIT License
app/src/main/java/io/tokend/template/logic/credentials/providers/CredentialsProvider.kt
tokend
153,459,333
false
null
package io.tokend.template.logic.credentials.providers interface CredentialsProvider { fun hasCredentials(): Boolean fun getCredentials(): Pair<String, CharArray> }
1
null
9
24
297a2dd4b1017f49c37e7a23e4cea0e7682c99d4
173
android-client
Apache License 2.0
modules/core/arrow-core-data/src/main/kotlin/arrow/core/Id.kt
Krishan14sharma
183,217,828
false
null
package arrow.core import arrow.higherkind fun <A> IdOf<A>.value(): A = this.fix().value() @higherkind data class Id<out A>(private val value: A) : IdOf<A> { inline fun <B> map(f: (A) -> B): Id<B> = Id(f(value())) inline fun <B> flatMap(f: (A) -> IdOf<B>): Id<B> = f(value()).fix() fun <B> foldLeft(initial: B, operation: (B, A) -> B): B = operation(initial, value) fun <B> foldRight(initial: Eval<B>, operation: (A, Eval<B>) -> Eval<B>): Eval<B> = operation(value, initial) fun <B> coflatMap(f: (IdOf<A>) -> B): Id<B> = this.fix().map { f(this) } fun extract(): A = value fun value(): A = value fun <B> ap(ff: IdOf<(A) -> B>): Id<B> = ff.fix().flatMap { f -> map(f) }.fix() companion object { tailrec fun <A, B> tailRecM(a: A, f: (A) -> IdOf<Either<A, B>>): Id<B> { val x: Either<A, B> = f(a).value() return when (x) { is Either.Left -> tailRecM(x.a, f) is Either.Right -> Id(x.b) } } fun <A> just(a: A): Id<A> = Id(a) } override fun equals(other: Any?): Boolean = when (other) { is Id<*> -> other.value == value else -> other == value } override fun hashCode(): Int = value.hashCode() }
0
null
0
1
2b26976e1a8fbf29b7a3786074d56612440692a8
1,196
arrow
Apache License 2.0
app/src/main/java/com/example/west2_3/ChatAdapter.kt
Bngel
323,668,435
false
null
package com.example.west2_3 import android.content.Context import android.content.Intent import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView class ChatAdapter(val chatitems: List<Data_ChatItem>): BaseAdapter<Data_ChatItem>(chatitems) { override fun convert(holder: BaseViewHolder, position: Int) { val chatitem = chatitems[position] val chatImg = holder.getView<ImageView>(R.id.main_item_img) chatImg.setImageResource(chatitem.ChatImg) chatImg.setTag(chatitem.ChatImg) val chatTitle = holder.getView<TextView>(R.id.main_item_title) chatTitle.text = chatitem.ChatTitle val chatAuthor = holder.getView<TextView>(R.id.main_item_author) chatAuthor.text = chatitem.ChatAuthor } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { val holder = super.onCreateViewHolder(parent, viewType) holderSetting(parent.context,holder) return holder } private fun holderSetting(context: Context, holder: BaseViewHolder) { val img = holder.getView<ImageView>(R.id.main_item_img) val title = holder.getView<TextView>(R.id.main_item_title) val author = holder.getView<TextView>(R.id.main_item_author) holder.itemView.setOnClickListener { intentSetting(context,title.text.toString(),author.text.toString(),img.getTag() as Int) } } private fun intentSetting(context: Context, title: String, author: String, img: Int) { val main_intent_to_detail = Intent(context,DetailActivity::class.java) main_intent_to_detail.putExtra("detail_title",title) main_intent_to_detail.putExtra("detail_author",author) main_intent_to_detail.putExtra("detail_img", img) context.startActivity(main_intent_to_detail) } }
0
Kotlin
0
0
eb2a72064c374a29922657cf61ca7d974a97281a
1,866
West2_3
Apache License 2.0
src/main/kotlin/com/kryszak/gwatlin/api/pvp/model/stats/PvpStanding.kt
Kryszak
214,791,260
false
null
package com.kryszak.gwatlin.api.pvp.model.stats import com.google.gson.annotations.SerializedName /** * Data model for pvp standings object */ data class PvpStanding( val current: CurrentPvpStanding, val best: BestPvpStanding, @SerializedName("season_id") val seasonId: String )
10
Kotlin
0
3
e86b74305df2b4af8deda8c0a5d2929d8110e41d
307
gwatlin
MIT License
src/main/kotlin/com/amazon/opendistroforelasticsearch/indexmanagement/indexstatemanagement/model/managedindexmetadata/ActionProperties.kt
opendistro-for-elasticsearch
174,581,847
false
null
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.managedindexmetadata import org.opensearch.common.io.stream.StreamInput import org.opensearch.common.io.stream.StreamOutput import org.opensearch.common.io.stream.Writeable import org.opensearch.common.xcontent.ToXContent import org.opensearch.common.xcontent.ToXContentFragment import org.opensearch.common.xcontent.XContentBuilder import org.opensearch.common.xcontent.XContentParser import org.opensearch.common.xcontent.XContentParser.Token import org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken /** Properties that will persist across steps of a single Action. Will be stored in the [ActionMetaData]. */ // TODO: Create namespaces to group properties together data class ActionProperties( val maxNumSegments: Int? = null, val snapshotName: String? = null, val rollupId: String? = null, val hasRollupFailed: Boolean? = null ) : Writeable, ToXContentFragment { override fun writeTo(out: StreamOutput) { out.writeOptionalInt(maxNumSegments) out.writeOptionalString(snapshotName) out.writeOptionalString(rollupId) out.writeOptionalBoolean(hasRollupFailed) } override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder { if (maxNumSegments != null) builder.field(Properties.MAX_NUM_SEGMENTS.key, maxNumSegments) if (snapshotName != null) builder.field(Properties.SNAPSHOT_NAME.key, snapshotName) if (rollupId != null) builder.field(Properties.ROLLUP_ID.key, rollupId) if (hasRollupFailed != null) builder.field(Properties.HAS_ROLLUP_FAILED.key, hasRollupFailed) return builder } companion object { const val ACTION_PROPERTIES = "action_properties" fun fromStreamInput(si: StreamInput): ActionProperties { val maxNumSegments: Int? = si.readOptionalInt() val snapshotName: String? = si.readOptionalString() val rollupId: String? = si.readOptionalString() val hasRollupFailed: Boolean? = si.readOptionalBoolean() return ActionProperties(maxNumSegments, snapshotName, rollupId, hasRollupFailed) } fun parse(xcp: XContentParser): ActionProperties { var maxNumSegments: Int? = null var snapshotName: String? = null var rollupId: String? = null var hasRollupFailed: Boolean? = null ensureExpectedToken(Token.START_OBJECT, xcp.currentToken(), xcp) while (xcp.nextToken() != Token.END_OBJECT) { val fieldName = xcp.currentName() xcp.nextToken() when (fieldName) { Properties.MAX_NUM_SEGMENTS.key -> maxNumSegments = xcp.intValue() Properties.SNAPSHOT_NAME.key -> snapshotName = xcp.text() Properties.ROLLUP_ID.key -> rollupId = xcp.text() Properties.HAS_ROLLUP_FAILED.key -> hasRollupFailed = xcp.booleanValue() } } return ActionProperties(maxNumSegments, snapshotName, rollupId, hasRollupFailed) } } enum class Properties(val key: String) { MAX_NUM_SEGMENTS("max_num_segments"), SNAPSHOT_NAME("snapshot_name"), ROLLUP_ID("rollup_id"), HAS_ROLLUP_FAILED("has_rollup_failed") } }
51
null
46
117
cda0eda35fc5da3816c407ad7a929d746edaf179
4,310
index-management
Apache License 2.0
compiler/testData/codegen/box/strings/kt3571.kt
JakeWharton
99,388,807
false
null
class Thing(delegate: CharSequence) : CharSequence by delegate fun box(): String { val l = Thing("hello there").length return if (l == 11) "OK" else "Fail $l" }
182
null
5646
83
4383335168338df9bbbe2a63cb213a68d0858104
172
kotlin
Apache License 2.0
app/src/main/java/com/example/waiyan/mmhealthkotlin/data/vos/HealthCareInfoVO.kt
YeHtutAung
141,786,122
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 18, "XML": 19, "Java": 1}
package com.example.waiyan.mmhealthkotlin.data.vos import com.google.gson.annotations.SerializedName class HealthCareInfoVO { @SerializedName("id") val id: Int = 0 @SerializedName("title") val title: String = "" @SerializedName("image") val image: String = "" @SerializedName("author") val authorVO: AuthorVO?=null @SerializedName("short-description") val shortDescription: String = "" @SerializedName("published-date") val publishedDate: String = "" @SerializedName("complete-url") val completedUrl:String = "" @SerializedName("info-type") val infoType: String = "" }
0
Kotlin
0
0
ed19fbfa159ad84a37f33e454b9d320416fb44f7
643
MMHealthKotlin_WY
MIT License
subprojects/android-test/ui-testing-core-app/src/androidTest/kotlin/com/avito/android/ui/test/VisibilityScreen.kt
avito-tech
230,265,582
false
{"Kotlin": 3752627, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086}
package com.avito.android.ui.test import androidx.test.espresso.matcher.ViewMatchers import com.avito.android.test.page_object.SimpleScreen import com.avito.android.test.page_object.ViewElement import com.avito.android.ui.R class VisibilityScreen : SimpleScreen() { override val rootId: Int = R.id.visibility val label: ViewElement = element(ViewMatchers.withId(R.id.text)) }
10
Kotlin
50
414
4dc43d73134301c36793e49289305768e68e645b
388
avito-android
MIT License
plugin/src/main/java/com/edwardstock/cmakebuild/CMakeBuildConfig.kt
edwardstock
437,412,773
false
{"Kotlin": 21226, "Shell": 172}
package com.edwardstock.cmakebuild import org.gradle.api.tasks.InputDirectory import java.io.File abstract class CMakeBuildConfig : BaseBuildConfig() { /** * Represents current OS for developers needs. * You can access this variable in your project by using: * <code> * cmakeBuild.currentOs * </code> * OSType can detect only 3 basic OS types: * - Windows * - MacOS * - Linux * - Default - any os, used for internal needs */ val currentOs: OsCheck.OSType = OsCheck.operatingSystemType val isWindows = currentOs == OsCheck.OSType.Windows val isLinux = currentOs == OsCheck.OSType.Linux val isMacOS = currentOs == OsCheck.OSType.MacOS /** * Path to CMake binary. * Plugin will try to find it by itself, if cmake not installed you'll see error */ var cmakeBin: String? = null /** * CMake project directory * For example: ${project.projectDir}/path/to/myclibrary */ @InputDirectory var path: File? = null /** * CMake build directory. By default: ${project.buildDir}/cmake */ @InputDirectory var stagingPath: File? = null /** * List of ABIs to build. Now only supported system-only toolchain. Cross-compilation does not work yet */ var abis: MutableList<String> = mutableListOf() /** * CMake build type: Debug, Release or whatever */ var buildType: String = "Debug" /** * Prints extra information about build */ var debug: Boolean = true /** * Enable cmake project build, it can be switched off if you have pre-built binaries */ var enable: Boolean = true /** * Configuration for all OS */ fun allOS(acceptor: OsSpecificOpts.() -> Unit) { osSpecificOpts[OsCheck.OSType.Default] = OsSpecificOpts().apply(acceptor) } /** * Configuration for windows */ fun windows(acceptor: OsSpecificOpts.() -> Unit) { osSpecificOpts[OsCheck.OSType.Windows] = OsSpecificOpts().apply(acceptor) } /** * Configuration for MacOS */ fun macos(acceptor: OsSpecificOpts.() -> Unit) { osSpecificOpts[OsCheck.OSType.MacOS] = OsSpecificOpts().apply(acceptor) } /** * Configuration for any Linux */ fun linux(acceptor: OsSpecificOpts.() -> Unit) { osSpecificOpts[OsCheck.OSType.Linux] = OsSpecificOpts().apply(acceptor) } }
0
Kotlin
2
2
eecfe4991f2463cfec716c5b8de8eb7205e19a42
2,443
gradle-cmakebuild
MIT License
formula-test/src/main/java/com/instacart/formula/test/CountingInspector.kt
instacart
171,923,573
false
null
package com.instacart.formula.test import com.instacart.formula.DeferredAction import com.instacart.formula.Inspector import com.instacart.formula.Transition import java.lang.AssertionError import kotlin.reflect.KClass class CountingInspector : Inspector { private var runCount = 0 private val evaluatedList = mutableListOf<Class<*>>() private val actionsStarted = mutableListOf<Class<*>>() private val stateTransitions = mutableListOf<Class<*>>() override fun onEvaluateFinished(formulaType: KClass<*>, output: Any?, evaluated: Boolean) { if (evaluated) { evaluatedList.add(formulaType.java) } } override fun onRunStarted(evaluate: Boolean) { runCount += 1 } override fun onActionStarted(formulaType: KClass<*>, action: DeferredAction<*>) { actionsStarted.add(formulaType.java) } override fun onTransition( formulaType: KClass<*>, result: Transition.Result<*>, evaluate: Boolean ) { if (result is Transition.Result.Stateful) { stateTransitions.add(formulaType.java) } } fun assertEvaluationCount(expected: Int) = apply { val evaluationCount = evaluatedList.size if (evaluationCount != expected) { throw AssertionError("Evaluation count does not match - count: $evaluationCount, expected: $expected") } } fun assertEvaluationCount(formulaType: KClass<*>, expected: Int) = apply { val evaluationCount = evaluatedList.filter { it == formulaType.java }.size if (evaluationCount != expected) { throw AssertionError("Evaluation count does not match - count: $evaluationCount, expected: $expected, list: $evaluatedList") } } fun assertRunCount(expected: Int) = apply { if (runCount != expected) { throw AssertionError("Run count does not match - count: $runCount, expected: $expected") } } fun assertActionsStarted(expected: Int) = apply { val actionsStartedCount = actionsStarted.size if (actionsStartedCount != expected) { throw AssertionError("Actions started count does not match - count: $actionsStartedCount, expected: $expected") } } fun assertStateTransitions(formulaType: KClass<*>, expected: Int) = apply { val stateTransitionCount = stateTransitions.filter { it == formulaType.java }.size if (stateTransitionCount != expected) { throw AssertionError("State transition count does not match - count: $stateTransitionCount, expected: $expected, list: $stateTransitions") } } }
10
Kotlin
14
145
7a7140f11fab9e07541b0e36d70a76c8340bcfee
2,649
formula
BSD 3-Clause Clear License
bye-bye-dead-code/src/main/java/com/dipien/byebyedeadcode/commons/ExtendedExecResult.kt
dipien
282,313,164
false
{"Kotlin": 43726, "Groovy": 14054, "Shell": 2559, "HTML": 1637}
package com.releaseshub.gradle.plugin.common import org.gradle.process.ExecResult import org.gradle.process.internal.ExecException import java.io.ByteArrayOutputStream class ExtendedExecResult( private val execResult: ExecResult, private val standardOutputStream: ByteArrayOutputStream, private val errorOutputStream: ByteArrayOutputStream ) : ExecResult { fun isSuccessful(): Boolean { return exitValue == 0 } fun getStandardOutput(): String { return standardOutputStream.toString() } fun getErrorOutput(): String { return errorOutputStream.toString() } override fun getExitValue(): Int { return execResult.exitValue } @Throws(ExecException::class) override fun assertNormalExitValue(): ExecResult { return execResult.assertNormalExitValue() } @Throws(ExecException::class) override fun rethrowFailure(): ExecResult { return execResult.rethrowFailure() } }
7
Kotlin
7
7
51be68322402c28a02a844235c5a42af7eba044c
983
bye-bye-dead-code
Apache License 2.0
09_MyAnimation/StartingPoint/MyAnimation/app/src/main/java/com/example/myanimation/sample/07AnimateContentSizeView.kt
emboss369
764,072,610
false
{"Kotlin": 232668}
package com.example.myanimation.sample import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.myanimation.ui.theme.MyAnimationTheme @Composable fun AnimateContentSizeView() { var flag by remember { mutableStateOf(true) } Column( Modifier.width(300.dp) ) { Box( modifier = Modifier .background(Color.LightGray) .animateContentSize() ) { Text(text = if (flag) "Hello" else "Hello Compose Happy Kotlin coding") } Box( modifier = Modifier.background(Color.LightGray) ) { Text(text = if (flag) "Hello" else "Hello Compose Happy Kotlin coding") } Button(onClick = { flag = !flag }) { Text(text = "add message Compose") } } } @Preview(showBackground = true) @Composable fun AnimateContentSizeViewPreview() { MyAnimationTheme { AnimateContentSizeView() } }
0
Kotlin
0
0
cecbe3fc6f4a744314853a83e25b995e6406ec42
1,507
android-compose-book
The Unlicense
android/src/main/java/me/uport/rnsigner/RNUportSignerPackage.kt
uport-project
154,713,148
false
null
@file:Suppress("unused") package me.uport.rnsigner import com.facebook.react.ReactPackage import com.facebook.react.bridge.JavaScriptModule import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager import java.util.* /** * package class as required by react native integration. * * This adds abilities to create, import and use private keys for signing, * either directly or by derivation from * seed phrases and a Hierarchically Deterministic algorithm. * * See [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). */ class RNUportSignerPackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { val modules = ArrayList<NativeModule>() modules.add(RNUportSignerModule(reactContext)) modules.add(RNUportHDSignerModule(reactContext)) return modules } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList() } }
4
null
5
8
bfbd890fc431e6341b748be918be94a4592ea4ee
1,115
react-native-uport-signer
Apache License 2.0
app/src/main/java/org/listenbrainz/android/ui/screens/profile/listens/TrackProgressBar.kt
metabrainz
550,726,972
false
null
package com.spotify.sdk.demo import android.os.Handler import android.widget.SeekBar class TrackProgressBar(private val seekBar: SeekBar, private val seekStopListener: (Long) -> Unit) { private val handler: Handler private val seekBarChangeListener = object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {} override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) { seekStopListener.invoke(seekBar.progress.toLong()) } } init { seekBar.setOnSeekBarChangeListener(seekBarChangeListener) handler = Handler() } private val seekUpdateRunnable = object : Runnable { override fun run() { val progress = seekBar.progress seekBar.progress = progress + LOOP_DURATION handler.postDelayed(this, LOOP_DURATION.toLong()) } } fun setDuration(duration: Long) { seekBar.max = duration.toInt() } fun update(progress: Long) { seekBar.progress = progress.toInt() } fun pause() { handler.removeCallbacks(seekUpdateRunnable) } fun unpause() { handler.removeCallbacks(seekUpdateRunnable) handler.postDelayed(seekUpdateRunnable, LOOP_DURATION.toLong()) } companion object { private const val LOOP_DURATION = 500 } }
5
null
31
99
573ab0ec6c5b87ea963f013174159ddfcd123976
1,454
listenbrainz-android
Apache License 2.0
app/src/main/java/com/octaedges/advanceandroid/model/CountriesService.kt
Farhad2015
440,224,698
false
{"Kotlin": 9538}
package com.octaedges.advanceandroid.model import com.octaedges.advanceandroid.DI.DaggerApiComponet import io.reactivex.rxjava3.core.Single import javax.inject.Inject class CountriesService { @Inject lateinit var api: CountriesApi init { DaggerApiComponet.create().inject(this) } fun getCountries(): Single<List<Country>> { return api.getCountries() } }
0
Kotlin
0
0
3e3916afec492bab76b8be7d7f8dac9f134f2c5f
398
RxWithDragger
Apache License 2.0
src_old/main/kotlin/glm/internals/simd natives.kt
FauxKiwi
315,724,386
false
null
package glm.internals internal external fun n_f32_plusAssign(a0: FloatArray, i0: Int, a1: FloatArray, i1: Int, n: Int): FloatArray internal external fun n_f32_minusAssign(a0: FloatArray, i0: Int, a1: FloatArray, i1: Int, n: Int): FloatArray internal external fun n_f32_timesAssign(a0: FloatArray, i0: Int, a1: FloatArray, i1: Int, n: Int): FloatArray
0
Kotlin
0
2
b384f2a430c0f714237e07621a01f094d9f5ee75
353
Pumpkin-Engine
Apache License 2.0
src/main/kotlin/org/hildan/minecraft/mining/optimizer/patterns/DiggingPattern.kt
joffrey-bion
48,772,914
false
{"Kotlin": 73321}
package org.hildan.minecraft.mining.optimizer.patterns import org.hildan.minecraft.mining.optimizer.blocks.Sample /** * Represents a way to dig into the stone in 3 dimensions. */ interface DiggingPattern { /** * Digs this pattern into the given [sample]. This method must take care of stopping at the edge of the given sample. */ fun digInto(sample: Sample) /** * Digs this pattern into the given [sample], and then digs every visible ore recursively until no more ore is * directly visible. This is supposed to represent what a real user will do while digging the pattern. */ fun digAndFollowOres(sample: Sample) { digInto(sample) sample.digVisibleOresRecursively() } }
2
Kotlin
0
0
fba62c181d2cb75f266e630ddc0690d958f3a443
737
mc-mining-optimizer
MIT License
src/main/kotlin/org/move/ide/navigation/goto/MvSymbolNavigationContributor.kt
pontem-network
279,299,159
false
{"Kotlin": 2175494, "Move": 38620, "Lex": 5509, "HTML": 2114, "Java": 1275}
package org.move.ide.navigation import com.intellij.navigation.ChooseByNameContributorEx import com.intellij.navigation.NavigationItem import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.Processor import com.intellij.util.indexing.FindSymbolParameters import com.intellij.util.indexing.IdFilter import org.move.lang.core.psi.MvNamedElement import org.move.lang.core.psi.MvStruct import org.move.openapiext.allMoveFiles class MvStructNavigationContributor : ChooseByNameContributorEx { override fun processNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?) { // get all names val project = scope.project ?: return val visitor = object : MvNamedElementsVisitor() { override fun processNamedElement(element: MvNamedElement) { if (element is MvStruct) { val elementName = element.name ?: return processor.process(elementName) } } } project.allMoveFiles().map { it.accept(visitor) } } override fun processElementsWithName( name: String, processor: Processor<in NavigationItem>, parameters: FindSymbolParameters ) { val project = parameters.project val visitor = object : MvNamedElementsVisitor() { override fun processNamedElement(element: MvNamedElement) { if (element is MvStruct) { val elementName = element.name ?: return if (elementName == name) processor.process(element) } } } project.allMoveFiles().map { it.accept(visitor) } } }
9
Kotlin
4
69
51a5703d064a4b016ff2a19c2f00fe8f8407d473
1,699
intellij-move
MIT License
common/common-ui/src/main/java/com/duckduckgo/common/ui/store/ThemingSharedPreferences.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2021 DuckDuckGo * * 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.duckduckgo.mobile.android.ui.store import android.content.Context import android.content.SharedPreferences import androidx.core.content.edit import com.duckduckgo.mobile.android.ui.DuckDuckGoTheme import javax.inject.Inject class ThemingSharedPreferences @Inject constructor(private val context: Context) : ThemingDataStore { private val themePrefMapper = ThemePrefsMapper() override var theme: DuckDuckGoTheme get() = selectedThemeSavedValue() set(theme) = preferences.edit { putString(KEY_THEME, themePrefMapper.prefValue(theme)) } override fun isCurrentlySelected(theme: DuckDuckGoTheme): Boolean { return selectedThemeSavedValue() == theme } private fun selectedThemeSavedValue(): DuckDuckGoTheme { val savedValue = preferences.getString(KEY_THEME, null) return themePrefMapper.themeFrom(savedValue, DuckDuckGoTheme.LIGHT) } private val preferences: SharedPreferences get() = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE) private class ThemePrefsMapper { companion object { private const val THEME_LIGHT = "LIGHT" private const val THEME_DARK = "DARK" private const val THEME_SYSTEM_DEFAULT = "SYSTEM_DEFAULT" } fun prefValue(theme: DuckDuckGoTheme) = when (theme) { DuckDuckGoTheme.SYSTEM_DEFAULT -> THEME_SYSTEM_DEFAULT DuckDuckGoTheme.LIGHT -> THEME_LIGHT DuckDuckGoTheme.DARK -> THEME_DARK } fun themeFrom( value: String?, defValue: DuckDuckGoTheme ) = when (value) { THEME_LIGHT -> DuckDuckGoTheme.LIGHT THEME_DARK -> DuckDuckGoTheme.DARK THEME_SYSTEM_DEFAULT -> DuckDuckGoTheme.SYSTEM_DEFAULT else -> defValue } } companion object { const val FILENAME = "com.duckduckgo.app.settings_activity.settings" const val KEY_THEME = "THEME" } }
67
null
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
2,656
Android
Apache License 2.0
src/main/kotlin/com/ort/lastwolf/api/body/validator/VillageRegisterBodyValidator.kt
h-orito
288,476,085
false
{"Kotlin": 934120, "Batchfile": 522, "Shell": 454}
package com.ort.lastwolf.api.body.validator import com.ort.lastwolf.api.body.VillageRegisterBody import com.ort.lastwolf.domain.model.skill.Skill import com.ort.lastwolf.fw.LastwolfDateUtil import org.springframework.stereotype.Component import org.springframework.validation.Errors import org.springframework.validation.Validator @Component class VillageRegisterBodyValidator : Validator { override fun supports(clazz: Class<*>): Boolean { return VillageRegisterBody::class.java.isAssignableFrom(clazz) } override fun validate(target: Any, errors: Errors) { if (errors.hasErrors()) return val body = target as VillageRegisterBody // 開始日時 if (body.setting!!.time!!.startDatetime!!.isBefore(LastwolfDateUtil.currentLocalDateTime())) { errors.reject("", "開始日時に過去日は指定できません") return } // 編成 validateOrganization(body, errors) } private fun validateOrganization(body: VillageRegisterBody, errors: Errors) { val organizationList = body.setting!!.organization!!.organization!!.replace("\r\n", "\n").split("\n") val min = organizationList.map { it.length }.min() ?: 0 val max = organizationList.map { it.length }.max() ?: 0 // 歯抜け if ((min..max).any { personNum -> organizationList.none { it.length == personNum } }) { errors.reject("", "最小人数から定員までの全ての人数に対する編成が必要です") return } // 重複 if ((min..max).any { personNum -> organizationList.count { it.length == personNum } > 1 }) { errors.reject("", "同一人数に対する編成が複数存在しています") return } // 存在しない役職がいる if (organizationList.any { org -> org.toCharArray().any { Skill.skillByShortName(it.toString()) == null } }) { errors.reject("", "存在しない役職があります") return } // 役欠けありだが噛まれることができる役職が存在しない val isAvailableDummySkill = body.setting.rule!!.availableDummySkill!! if (isAvailableDummySkill && organizationList.any { org -> org.toCharArray().map { it.toString() }.none { val cdefSkill = Skill.skillByShortName(it)!!.toCdef() !cdefSkill.isNoDeadByAttack && !cdefSkill.isNotSelectableAttack } } ) { errors.reject("", "役欠けありの場合噛まれて死亡する役職を含めてください") return } // 人狼がいない if (organizationList.any { org -> org.toCharArray().map { it.toString() }.none { Skill.skillByShortName(it)!!.toCdef().isHasAttackAbility } }) { errors.reject("", "襲撃役職が必要です") return } // 人狼が半数以上 if (organizationList.any { org -> val personCount = org.length val wolfCount = org.toCharArray().map { it.toString() }.count { Skill.skillByShortName(it)!!.toCdef().isHasAttackAbility } wolfCount >= personCount / 2 } ) { errors.reject("", "襲撃役職は半分以下にしてください") return } } }
5
Kotlin
0
0
a86e0b7a55dbe616bfd390b69ea368c990aee99f
3,147
lastwolf-api
MIT License
nebulosa-platesolver/src/main/kotlin/nebulosa/platesolver/PlateSolver.kt
tiagohm
568,578,345
false
{"Kotlin": 2747666, "TypeScript": 509060, "HTML": 243311, "JavaScript": 120539, "SCSS": 11332, "Python": 2817, "Makefile": 355}
package nebulosa.plate.solving import nebulosa.common.concurrency.cancel.CancellationToken import nebulosa.image.Image import nebulosa.math.Angle import java.nio.file.Path import java.time.Duration interface PlateSolver { fun solve( path: Path?, image: Image?, centerRA: Angle = 0.0, centerDEC: Angle = 0.0, radius: Angle = 0.0, downsampleFactor: Int = 0, timeout: Duration? = null, cancellationToken: CancellationToken = CancellationToken.NONE, ): PlateSolution }
4
Kotlin
2
4
e144290464c5e6e2e18ad23a036526800428e7f9
508
nebulosa
MIT License
core/android/src/main/kotlin/com/walletconnect/android/echo/network/EchoService.kt
WalletConnect
435,951,419
false
{"Kotlin": 1795667, "Java": 4358}
package com.walletconnect.android.echo.network import com.walletconnect.android.echo.network.model.EchoBody import com.walletconnect.android.echo.network.model.EchoResponse import retrofit2.Response import retrofit2.http.* interface EchoService { @POST("{projectId}/clients") suspend fun register(@Path("projectId") projectId: String, @Query("auth") clientID: String, @Body echoClientsBody: EchoBody): Response<EchoResponse> @DELETE("{projectId}/clients/{clientId}") suspend fun unregister(@Path("projectId") projectId: String, @Path("clientId") clientID: String): Response<EchoResponse> }
154
Kotlin
66
166
5158f90f2f241d318c7b0188047125ea789d9577
609
WalletConnectKotlinV2
Apache License 2.0
backend/src/main/kotlin/com/denchic45/studiversity/feature/membership/MembershipRouting.kt
denchic45
435,895,363
false
{"Kotlin": 2073955, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.feature.membership //import com.denchic45.studiversity.config //import com.denchic45.studiversity.feature.membership.usecase.FindMembershipByScopeUseCase //import com.denchic45.studiversity.feature.membership.usecase.RemoveMemberFromScopeUseCase //import com.denchic45.studiversity.feature.membership.usecase.RemoveSelfMemberFromScopeUseCase //import com.denchic45.studiversity.feature.role.RoleErrors //import com.denchic45.studiversity.feature.role.usecase.* //import com.denchic45.studiversity.ktor.* //import com.denchic45.studiversity.util.hasNotDuplicates //import com.denchic45.studiversity.validation.buildValidationResult //import com.denchic45.stuiversity.api.membership.MembershipErrors //import com.denchic45.stuiversity.api.membership.model.ManualJoinMemberRequest //import com.denchic45.stuiversity.api.role.model.Capability //import com.denchic45.stuiversity.api.role.model.UpdateUserRolesRequest //import com.denchic45.stuiversity.util.toUUID //import io.ktor.http.* //import io.ktor.server.application.* //import io.ktor.server.auth.* //import io.ktor.server.plugins.* //import io.ktor.server.plugins.requestvalidation.* //import io.ktor.server.request.* //import io.ktor.server.response.* //import io.ktor.server.routing.* //import io.ktor.server.util.* //import org.koin.ktor.ext.inject //import java.util.* // //fun Application.membershipRoutes(memberships: Map<UUID, ExternalMembership>) { // routing { // authenticate("auth-jwt") { // route("/scopes/{scopeId}") { // membersRoute() // route("/memberships") { // val findMembershipByScope: FindMembershipByScopeUseCase by inject() // get { // findMembershipByScope( // call.parameters["scopeId"]!!.toUUID(), // call.request.queryParameters["type"] // )?.let { membershipId -> call.respond(HttpStatusCode.OK, membershipId.toString()) } // ?: throw NotFoundException() // } // route("/{membershipId}") { // val requireCapability: RequireCapabilityUseCase by inject() // post("/sync") { // requireCapability( // call.currentUserId(), // Capability.WriteMembership, // config.organizationId // ) // memberships[call.parameters.getOrFail("membershipId").toUUID()] // ?.forceSync() // ?: throw NotFoundException() // call.respond(HttpStatusCode.Accepted) // } // } // } // } // } // } //} // //fun Route.membersRoute() { // route("/members") { // val requireCapability: RequireCapabilityUseCase by inject() // val requireAvailableRolesInScope: RequireAvailableRolesInScopeUseCase by inject() // val requirePermissionToAssignRoles: RequirePermissionToAssignRolesUseCase by inject() // val findMembersInScope: FindMembersInScopeUseCase by inject() // val existMemberInScopeUseCase: ExistMemberInScopeUseCase by inject() // val membershipService: MembershipService by inject() // // get { // val scopeId = call.parameters.getUuidOrFail("scopeId") // val currentUserId = call.currentUserId() // // // if (!existMemberInScopeUseCase(currentUserId, scopeId)) // requireCapability(currentUserId, Capability.ReadMembers, scopeId) // // findMembersInScope(scopeId).apply { // call.respond(HttpStatusCode.OK, this) // } // } // post { // val currentUserId = call.currentUserId() // val scopeId = call.parameters["scopeId"]!!.toUUID() // // val result = when (call.request.queryParameters["action"]!!) { // "manual" -> { // val body = call.receive<ManualJoinMemberRequest>() // // requireCapability(currentUserId, Capability.WriteMembers, scopeId) // // val assignableRoles = body.roleIds // requireAvailableRolesInScope(assignableRoles, scopeId) // requirePermissionToAssignRoles(currentUserId, assignableRoles, scopeId) // // membershipService.getMembershipByTypeAndScopeId<ManualMembership>("manual", scopeId) // .joinMember(body) // } // // else -> throw BadRequestException(MembershipErrors.UNKNOWN_MEMBERSHIP_ACTION) // } // call.respond(HttpStatusCode.Created, result) // } // memberByIdRoute() // } //} // //private fun Route.memberByIdRoute() { // route("/{memberId}") { // install(RequestValidation) { // validate<UpdateUserRolesRequest> { // buildValidationResult { // condition(it.roleIds.isNotEmpty(), RoleErrors.NO_ROLE_ASSIGNMENT) // condition(it.roleIds.hasNotDuplicates(), RoleErrors.ROLES_DUPLICATION) // } // } // } // // val requireCapability: RequireCapabilityUseCase by inject() // val removeMemberFromScope: RemoveMemberFromScopeUseCase by inject() // val removeSelfMemberFromScope: RemoveSelfMemberFromScopeUseCase by inject() // // get { // val currentUserId = call.currentUserId() // val scopeId = call.parameters.getOrFail("scopeId").toUUID() // val memberId = call.parameters.getOrFail("memberId").toUUID() // // TODO get one member by scope id and member id // } // // delete { // val currentUserId = call.currentUserId() // val scopeId = call.parameters.getOrFail("scopeId").toUUID() // val memberId = call.parameters.getOrFail("memberId").toUUID() // when (call.request.queryParameters.getOrFail("action")) { // "manual" -> { // requireCapability(currentUserId, Capability.WriteMembers, scopeId) // removeMemberFromScope(memberId, scopeId) // } // // "self" -> { // if (currentUserId != memberId) // removeSelfMemberFromScope(memberId, scopeId) // else throw ForbiddenException() // } // // else -> throw BadRequestException("UNKNOWN_MEMBERSHIP_ACTION") // } // call.respond(HttpStatusCode.NoContent) // } // } //}
0
Kotlin
0
7
9d1744ffd9e1652e93af711951e924b739e96dcc
6,824
Studiversity
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[399]除法求值.kt
maoqitian
175,940,000
false
{"Text": 1, "Ignore List": 2, "Markdown": 1, "Java": 254, "Gradle": 2, "INI": 1, "Shell": 1, "Batchfile": 1, "Java Properties": 1, "Kotlin": 189, "JSON": 2, "C++": 1}
import java.util.* //给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [Ai, Bi] 和 values //[i] 共同表示等式 Ai / Bi = values[i] 。每个 Ai 或 Bi 是一个表示单个变量的字符串。 // // 另有一些以数组 queries 表示的问题,其中 queries[j] = [Cj, Dj] 表示第 j 个问题,请你根据已知条件找出 Cj / Dj = // ? 的结果作为答案。 // // 返回 所有问题的答案 。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。 // // // // 注意:输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。 // // // // 示例 1: // // //输入:equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"] //,["b","a"],["a","e"],["a","a"],["x","x"]] //输出:[6.00000,0.50000,-1.00000,1.00000,-1.00000] //解释: //条件:a / b = 2.0, b / c = 3.0 //问题:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? //结果:[6.0, 0.5, -1.0, 1.0, -1.0 ] // // // 示例 2: // // //输入:equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], quer //ies = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]] //输出:[3.75000,0.40000,5.00000,0.20000] // // // 示例 3: // // //输入:equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a //","c"],["x","y"]] //输出:[0.50000,2.00000,-1.00000,-1.00000] // // // // // 提示: // // // 1 <= equations.length <= 20 // equations[i].length == 2 // 1 <= Ai.length, Bi.length <= 5 // values.length == equations.length // 0.0 < values[i] <= 20.0 // 1 <= queries.length <= 20 // queries[i].length == 2 // 1 <= Cj.length, Dj.length <= 5 // Ai, Bi, Cj, Dj 由小写英文字母与数字组成 // // Related Topics 并查集 图 // 👍 385 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray { var count = 0 //统计出现的所有字符,并赋予对应的index val map: MutableMap<String, Int> = HashMap() for (list in equations) { for (s in list) { if (!map.containsKey(s)) { map[s] = count++ } } } //构建一个矩阵来代替图结构 val graph = Array(count + 1) { DoubleArray(count + 1) } //初始化 for (s in map.keys) { val x = map[s]!!!! graph[x][x] = 1.0 } var index = 0 for (list in equations) { val a = list[0] val b = list[1] val aa = map[a]!!!! val bb = map[b]!!!! val value = values[index++] graph[aa][bb] = value graph[bb][aa] = 1 / value } //通过Floyd算法进行运算 //通过Floyd算法进行运算 val n = count + 1 for (i in 0 until n) { for (j in 0 until n) { for (k in 0 until n) { if (j == k || graph[j][k] != 0.toDouble()) continue if (graph[j][i] != 0.toDouble() && graph[i][k] != 0.toDouble()) { graph[j][k] = graph[j][i] * graph[i][k] } } } } //直接通过查询矩阵得到答案 //直接通过查询矩阵得到答案 val res = DoubleArray(queries.size) for (i in res.indices) { val q = queries[i] val a = q[0] val b = q[1] if (map.containsKey(a) && map.containsKey(b)) { val ans = graph[map[a]!!][map[b]!!] res[i] = if (ans == 0.0) -1.0 else ans } else { res[i] = -1.0 } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
3,430
MyLeetCode
Apache License 2.0
server/world/src/main/kotlin/net/js5/Js5Decoder.kt
Guthix
270,323,476
false
{"Kotlin": 667208}
/* * Copyright 2018-2021 Guthix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.guthix.oldscape.server.net.js5 import io.netty.buffer.ByteBuf import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.ByteToMessageDecoder import java.io.IOException class Js5Decoder : ByteToMessageDecoder() { override fun decode(ctx: ChannelHandlerContext, inc: ByteBuf, out: MutableList<Any>) { if (!inc.isReadable(4)) return when (val opcode = inc.readUnsignedByte().toInt()) { Js5Type.NORMAL_CONTAINER_REQUEST.opcode, Js5Type.URGENT_CONTAINER_REQUEST.opcode -> { val indexFileId = inc.readUnsignedByte().toInt() val containerId = inc.readUnsignedShort() out.add( Js5ContainerRequest( opcode == Js5Type.URGENT_CONTAINER_REQUEST.opcode, indexFileId, containerId ) ) } Js5Type.CLIENT_LOGGED_IN.opcode, Js5Type.CLIENT_LOGGED_OUT.opcode -> { val statusCode = inc.readUnsignedMedium() if (statusCode != 0) { throw IOException("Js5 client status code expected: 0 but was $statusCode.") } } Js5Type.ENCRYPTION_KEY_UPDATE.opcode -> { inc.skipBytes(3) } else -> throw IOException("Could not identify js5 request with opcode $opcode.") } } }
2
Kotlin
9
43
bbf40d18940a12155a33341a1c99ba47289b8e2a
2,036
OldScape
Apache License 2.0
src/me/anno/engine/ui/PrefabSaveableInput.kt
AntonioNoack
456,513,348
false
null
package me.anno.engine.ui import me.anno.ecs.prefab.PrefabSaveable import me.anno.language.translation.NameDesc import me.anno.studio.StudioBase.Companion.dragged import me.anno.ui.base.menu.Menu.msg import me.anno.ui.base.menu.Menu.openMenu import me.anno.ui.base.menu.MenuOption import me.anno.ui.base.text.TextPanel import me.anno.ui.style.Style import org.apache.logging.log4j.LogManager import kotlin.reflect.KClass // todo click, then open tree view to select it (?) /** * input panel for drag-dropping references to instances in the same scene * */ class PrefabSaveableInput<Type : PrefabSaveable>(val title: String, val clazz: KClass<*>, value0: Type?, style: Style) : TextPanel("$title: ${value0?.name}", style) { var value = value0 set(value) { field = value changeListener(value) update(value) } private var changeListener: (v: Type?) -> Unit = {} fun setChangeListener(changeListener: (v: Type?) -> Unit) { this.changeListener = changeListener } private var resetListener: () -> Type? = { value0 } fun setResetListener(resetListener: () -> Type?) { this.resetListener = resetListener } init { // right click to reset it addRightClickListener { openMenu(windowStack, listOf(MenuOption(NameDesc("Reset")) { value = resetListener() })) } } fun update(value0: Type?) { text = "$title: ${value0?.name}" invalidateDrawing() } override fun onPaste(x: Float, y: Float, data: String, type: String) { when (type) { "PrefabSaveable" -> { val instance = dragged!!.getOriginal() as? PrefabSaveable if (instance == null) { LOGGER.warn("Dragged instance was not PrefabSaveable") } else if (clazz.isInstance(instance)) { @Suppress("UNCHECKED_CAST") value = instance as Type } else { // check all children, if there is any match for (childType in instance.listChildTypes()) { for (child in instance.getChildListByType(childType)) { if (clazz.isInstance(child)) { @Suppress("UNCHECKED_CAST") value = child as Type return } } } msg( windowStack, NameDesc( "Incorrect type", "${instance.name} is not instance of $clazz, and none of its direct children is either", "" ) ) } } else -> super.onPaste(x, y, data, type) } } companion object { private val LOGGER = LogManager.getLogger(PrefabSaveableInput::class) } }
0
Kotlin
3
9
94bc7c74436aa567ec3c19f386dd67af0f1ced00
3,059
RemsEngine
Apache License 2.0
app/src/main/java/com/hadi/archives/presentation/screens/details/BookDetailsScreen.kt
unaisulhadi
499,780,070
false
{"Kotlin": 74268}
package com.hadi.archives.presentation.screens.details import android.widget.Toast import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Star import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.hadi.archives.R import com.hadi.archives.data.local.getAllBooks import com.hadi.archives.data.local.getManagementBooks import com.hadi.archives.data.model.Book import com.hadi.archives.ui.theme.BrutalBlue import com.hadi.archives.ui.theme.BrutalYellow import com.hadi.archives.utils.applyBrutalism @OptIn(ExperimentalCoilApi::class) @Composable fun BookDetailsScreen( navController: NavController, bookId: String ) { rememberSystemUiController().setStatusBarColor(Color.White) val scrollState = rememberScrollState() val book = getAllBooks().first { it.id == bookId } val painter = rememberImagePainter(data = book.imageUrl) { placeholder(R.drawable.ic_book_placeholder) error(R.drawable.ic_book_placeholder) } Box( modifier = Modifier .fillMaxSize(), ) { Column( modifier = Modifier .verticalScroll(scrollState) .fillMaxSize() .background(Color.White), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Top ) { Row( modifier = Modifier .fillMaxWidth() .padding(start = 12.dp, end = 12.dp, top = 12.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Box( modifier = Modifier .size(50.dp) .applyBrutalism( backgroundColor = BrutalYellow, borderWidth = 3.dp, ) .clickable { navController.popBackStack() }, contentAlignment = Alignment.Center ) { Icon( modifier = Modifier .size(36.dp) .padding(all = 6.dp), painter = painterResource(id = R.drawable.ic_left_arrow), contentDescription = "Notifications" ) } } //Book Cover Box( modifier = Modifier .width(250.dp) .height(360.dp) .padding(all = 12.dp) .applyBrutalism( backgroundColor = BrutalYellow, borderWidth = 3.dp, cornersRadius = 6.dp ), contentAlignment = Alignment.Center ) { Image( modifier = Modifier .fillMaxSize(), painter = painter, contentScale = ContentScale.Crop, contentDescription = "Notifications" ) } Text( modifier = Modifier.padding(start = 12.dp, end = 12.dp, top = 12.dp), text = book.title, style = MaterialTheme.typography.h4, color = Color.Black, textAlign = TextAlign.Center ) Spacer(modifier = Modifier.height(8.dp)) Text( text = book.author, style = MaterialTheme.typography.subtitle1, color = Color.Gray ) BookDetailsSection(book = book) //Synopsis Column( modifier = Modifier .fillMaxWidth() .padding(start = 12.dp, end = 12.dp, top = 8.dp), ) { Text( modifier = Modifier .padding(bottom = 8.dp), text = "Synopsis", style = MaterialTheme.typography.subtitle1, color = Color.Gray ) Text( text = book.description, style = MaterialTheme.typography.subtitle2, color = Color.DarkGray ) } //ClipToPadding Spacer( modifier = Modifier .fillMaxWidth() .height(80.dp) ) } //White Gradient at Bottom Spacer( modifier = Modifier .fillMaxWidth() .height(120.dp) .background( brush = Brush.verticalGradient( colors = listOf( Color.Transparent, Color.White ), ) ) .align(Alignment.BottomCenter) ) PrimaryBookActions( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .align(Alignment.BottomCenter) ) } } //Start Reading and Save Buttons @Composable fun PrimaryBookActions(modifier: Modifier = Modifier) { var saveBook by remember { mutableStateOf(false) } Row( modifier = modifier ) { Box( modifier = Modifier .width(70.dp) .height(80.dp) .padding(start = 12.dp, top = 12.dp, bottom = 12.dp) .applyBrutalism( backgroundColor = BrutalYellow, borderWidth = 3.dp, ) .clickable { saveBook = !saveBook }, contentAlignment = Alignment.Center ) { Icon( modifier = Modifier .size(36.dp) .padding(all = 6.dp), painter = painterResource(id = if (saveBook) R.drawable.ic_bookmark else R.drawable.ic_bookmark_outlined), contentDescription = "Notifications" ) } Box( modifier = Modifier .fillMaxWidth() .height(80.dp) .padding(all = 12.dp) .applyBrutalism( backgroundColor = BrutalBlue, borderWidth = 4.dp ), contentAlignment = Alignment.Center ) { Text( text = "Start Reading", style = MaterialTheme.typography.h6, color = Color.White ) } } } @Composable fun BookDetailsSection(modifier: Modifier = Modifier, book: Book) { Row( modifier = modifier .fillMaxWidth() .height(100.dp) .padding(horizontal = 12.dp, vertical = 12.dp) .background(Color.White) .border( width = 4.dp, color = Color.Black, shape = RoundedCornerShape(6.dp) ), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { BookFeature( modifier = Modifier.weight(1f), feature = "Released", value = "2022" ) Divider( modifier = Modifier .fillMaxHeight() .width(4.dp) .background(Color.Black) ) BookFeature( modifier = Modifier.weight(1f), feature = "Pages", value = book.pageCount.toString() ) Divider( modifier = Modifier .fillMaxHeight() .width(4.dp) .background(Color.Black) ) BookFeature( modifier = Modifier.weight(1f), feature = "Language", value = book.language ) Divider( modifier = Modifier .fillMaxHeight() .width(4.dp) .background(Color.Black) ) Column( modifier = Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( modifier = Modifier.padding(bottom = 4.dp), text = "Rating", style = MaterialTheme.typography.subtitle2, color = Color.Gray ) Row( verticalAlignment = Alignment.CenterVertically ) { Text( text = book.rating.toString(), style = MaterialTheme.typography.subtitle1, color = Color.DarkGray ) Spacer(modifier = Modifier.width(4.dp)) Icon( imageVector = Icons.Filled.Star, tint = BrutalYellow, contentDescription = null ) } } } } @Composable fun BookFeature(modifier: Modifier, feature: String, value: String) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( modifier = Modifier.padding(bottom = 4.dp), text = feature, style = MaterialTheme.typography.subtitle2, color = Color.Gray ) Text( text = value, style = MaterialTheme.typography.subtitle1, color = Color.DarkGray ) } } @Preview(showBackground = true) @Composable fun BookDetailsPreview() { BookDetailsScreen(navController = rememberNavController(), "1") }
0
Kotlin
3
42
866962abe3dadb362162e66feeb9e98764ae169d
11,028
Archives
MIT License
devops-boot-project/devops-boot-core/devops-schedule/devops-schedule-worker/src/main/kotlin/com/tencent/devops/schedule/hearbeat/Heartbeat.kt
bkdevops-projects
294,058,091
false
{"Kotlin": 488037, "JavaScript": 47413, "Vue": 36468, "SCSS": 7290, "HTML": 620, "Java": 559}
package com.tencent.devops.schedule.hearbeat import com.tencent.devops.schedule.enums.WorkerStatusEnum /** * 维持和调度中心的心跳,定时上报状态 */ interface Heartbeat { /** * @param status 自身状态 */ fun beat(status: WorkerStatusEnum) }
7
Kotlin
22
27
cbff03abe5d572b09cbd486830d87cddc91b938b
241
devops-framework
MIT License
pumping/src/test/kotlin/com/dpm/pumping/user/domain/UserTest.kt
depromeet
627,802,875
false
null
package com.dpm.pumping.user.domain import com.dpm.pumping.auth.domain.LoginPlatform import com.dpm.pumping.auth.domain.LoginType import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class UserTest { @Test fun `유저가 회원가입을 한 상태면 액세스 토큰을 발급한다`() { val platform = LoginPlatform(LoginType.APPLE, "appleId") val user = User("uid", "gc", Gender.MALE, "190", "90", platform, CharacterType.A, null) assertThat(user.isRegistered()).isTrue } @Test fun `유저 login정보를 제외한 가입 정보가 없는 상태면 등록된 상태가 아니다`() { val user = User.createWithOAuth(LoginPlatform(LoginType.APPLE, "appleId")) assertThat(user.isRegistered()).isFalse } }
3
Kotlin
0
2
366e951c11eafc9369aa0095337579ffb23f7ec6
709
pumping-server
Apache License 2.0
purchases/src/test/java/com/revenuecat/purchases/LogLevelTest.kt
RevenueCat
127,346,826
false
{"Kotlin": 3187935, "Java": 82657, "Ruby": 28079, "Shell": 443}
package com.revenuecat.purchases import androidx.test.ext.junit.runners.AndroidJUnit4 import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class LogLevelTest { @Test fun testLogLevelComparable() { assertThat(com.revenuecat.purchases.LogLevel.VERBOSE).isLessThan(com.revenuecat.purchases.LogLevel.DEBUG) assertThat(com.revenuecat.purchases.LogLevel.DEBUG).isLessThan(com.revenuecat.purchases.LogLevel.INFO) assertThat(com.revenuecat.purchases.LogLevel.INFO).isLessThan(com.revenuecat.purchases.LogLevel.WARN) assertThat(com.revenuecat.purchases.LogLevel.WARN).isLessThan(com.revenuecat.purchases.LogLevel.ERROR) assertThat(com.revenuecat.purchases.LogLevel.DEBUG).isGreaterThanOrEqualTo(com.revenuecat.purchases.LogLevel.VERBOSE) assertThat(com.revenuecat.purchases.LogLevel.INFO).isGreaterThanOrEqualTo(com.revenuecat.purchases.LogLevel.DEBUG) assertThat(com.revenuecat.purchases.LogLevel.WARN).isGreaterThanOrEqualTo(com.revenuecat.purchases.LogLevel.INFO) assertThat(com.revenuecat.purchases.LogLevel.ERROR).isGreaterThanOrEqualTo(com.revenuecat.purchases.LogLevel.WARN) } }
30
Kotlin
52
253
dad31133777389a224e9a570daec17f5c4c795ca
1,239
purchases-android
MIT License
components/ledger/ledger-utxo-flow/src/main/kotlin/net/corda/ledger/utxo/impl/token/selection/factories/ClaimReleaseParameters.kt
corda
346,070,752
false
{"Kotlin": 18843439, "Java": 318792, "Smarty": 101152, "Shell": 48766, "Groovy": 30378, "PowerShell": 6350, "TypeScript": 5826, "Solidity": 2024}
package net.corda.ledger.utxo.impl.token.selection.factories import net.corda.ledger.utxo.impl.token.selection.impl.PoolKey import net.corda.v5.ledger.utxo.StateRef data class ClaimReleaseParameters( val claimId: String, val poolKey: PoolKey, val usedTokens: List<StateRef> )
96
Kotlin
21
51
08c3e610a0e6ec20143c47d044e0516019ba6578
290
corda-runtime-os
Apache License 2.0
forstegangsbehandling/src/test/kotlin/FørstegangsbehandlingTest.kt
navikt
575,838,396
false
null
import no.nav.helse.Førstegangsbehandling import no.nav.helse.Søknad import no.nav.helse.februar import no.nav.helse.januar import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.time.LocalDate import java.time.LocalDateTime import java.util.UUID internal class FørstegangsbehandlingTest { companion object { internal fun lagSøknad( fom: LocalDate, tom: LocalDate, arbeidGjenopptatt: LocalDate?, hendelseId: UUID = UUID.randomUUID(), opprettet: LocalDateTime = LocalDateTime.now(), fnr: String = "12345678910", orgnr: String = "123456789", ) = Søknad( hendelseId, UUID.randomUUID(), UUID.randomUUID(), fnr, orgnr, fom, tom, arbeidGjenopptatt, opprettet ) } @Test fun `Første søknad mottatt er førstegangsbehandling`() { val fgb = Førstegangsbehandling() val søknad = lagSøknad(1.januar(2022), 31.januar(2022), 31.januar(2022)) fgb.motta(søknad) assertTrue(fgb.førstegangsbehandlinger()[0] == søknad.id) } @Test fun `Tilstøtende søknad er ikke førstegangsbehandling`() { val fgb = Førstegangsbehandling() val søknad = lagSøknad(1.januar(2022), 31.januar(2022), 31.januar(2022)) fgb.motta(søknad) fgb.motta(lagSøknad(1.februar(2022), 28.februar(2022), 28.februar(2022))) assertTrue(fgb.førstegangsbehandlinger().size == 1) assertTrue(fgb.førstegangsbehandlinger().contains(søknad.id)) } @Test fun `To søknader seprarert av helg er tilstøtende`() { val fgb = Førstegangsbehandling() val først = lagSøknad(3.januar(2022), 7.januar(2022), 7.januar(2022)) fgb.motta(først) fgb.motta(lagSøknad(10.januar(2022), 31.januar(2022), 31.januar(2022))) assertTrue(fgb.førstegangsbehandlinger().size == 1) assertTrue(fgb.førstegangsbehandlinger().contains(først.id)) } @Test fun `Arbeid gjennopptatt avkutter søknadsperioden`() { val fgb = Førstegangsbehandling() val først = lagSøknad(1.januar(2022), 31.januar(2022), 30.januar(2022)) val sist = lagSøknad(1.februar(2022), 28.februar(2022), 28.februar(2022)) fgb.motta(først) fgb.motta(sist) assertTrue(fgb.førstegangsbehandlinger().containsAll(listOf(først.id, sist.id))) } @Test fun `sist opprettede søknad telles`() { val fgb = Førstegangsbehandling() val opprettet = LocalDateTime.of(2022, 1, 1, 1, 0) val søknader = listOf( lagSøknad(1.januar(2022), 31.januar(2022), 30.januar(2022), UUID.randomUUID(), opprettet.plusDays(1)), lagSøknad(1.januar(2022), 31.januar(2022), 30.januar(2022), UUID.randomUUID(), opprettet), lagSøknad(1.januar(2022), 31.januar(2022), 30.januar(2022), UUID.randomUUID(), opprettet) ) søknader.forEach { fgb.motta(it) } val result = fgb.førstegangsbehandlinger() assertEquals(1, result.size) assertEquals(søknader[0].id, result.first()) } }
6
null
0
1
e57f5a3450eed4bd5dced16786ff06a017f62156
3,209
helse-dataprodukter
MIT License
app/src/main/java/com/github/malitsplus/shizurunotes/ui/clanbattledetails/ClanBattleBossSkillAdapter.kt
liar1573
242,482,699
true
{"Java": 779399, "Kotlin": 121731, "C++": 12688, "Starlark": 8903}
package com.github.malitsplus.shizurunotes.ui.clanbattledetails import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.github.malitsplus.shizurunotes.R import com.github.malitsplus.shizurunotes.data.Skill import com.github.malitsplus.shizurunotes.databinding.ListItemClanBattleBossSkillBinding class ClanBattleBossSkillAdapter ( private var skillList: List<Skill> ) : RecyclerView.Adapter<ClanBattleBossSkillAdapter.ClanBattleBossSkillHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): ClanBattleBossSkillHolder { val binding = DataBindingUtil.inflate<ListItemClanBattleBossSkillBinding>( LayoutInflater.from(parent.context), R.layout.list_item_clan_battle_boss_skill, parent, false ) return ClanBattleBossSkillHolder(binding) } override fun onBindViewHolder( holder: ClanBattleBossSkillHolder, position: Int ) { holder.binding.skill = skillList[position] holder.binding.executePendingBindings() } override fun getItemCount(): Int { return skillList.size } fun update(periodList: List<Skill>) { this.skillList = periodList notifyDataSetChanged() } class ClanBattleBossSkillHolder internal constructor(val binding: ListItemClanBattleBossSkillBinding) : RecyclerView.ViewHolder(binding.root) }
0
null
0
0
14af2059c37b754e125442381005998835119cb2
1,609
ShizuruNotes
Apache License 2.0
RefreshToken.kt
tanishq14developer
578,764,894
false
{"Kotlin": 2737}
import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import okhttp3.Authenticator import okhttp3.Request import okhttp3.Response import okhttp3.Route /** * Created by <NAME> on 15/12/22. */ class TokenAuthenticator( private val tokenManager: TokenManager ) : Authenticator { override fun authenticate(route: Route?, response: Response): Request { return runBlocking { val sessionData = if (isRefreshNeeded(response)) { getUpdatedSessionData() } else { getExistingSessionData() } response.request.newBuilder() .header(HeaderKeys.SESSION_ID, sessionData.sessionId) .header(HeaderKeys.REFRESH_ID, sessionData.refreshId) .build() } } private fun isRefreshNeeded(response: Response): Boolean { val oldSessionId = response.request.header(HeaderKeys.SESSION_ID) val oldRefreshId = response.request.header(HeaderKeys.REFRESH_ID) val updatedSessionId = tokenManager.getSessionId() val updatedRefreshId = tokenManager.getRefreshId() return (oldSessionId == updatedSessionId && oldRefreshId == updatedRefreshId) } private fun getExistingSessionData(): ApiResponse.SessionData { val updatedSessionId = tokenManager.getSessionId() val updatedRefreshId = tokenManager.getRefreshId() return ApiResponse.SessionData( sessionId = updatedSessionId, refreshId = updatedRefreshId ) } private suspend fun getUpdatedSessionData(): ApiResponse.SessionData { val refreshTokenRequest = ApiResponse.RefreshSessionRequest(tokenManager.getRefreshId()) return when (val result = getResult { userApiService().refreshSession(refreshTokenRequest) }) { is ApiResult.Success -> { val sessionData = result.data.data tokenManager.saveSessionId(sessionData.sessionId) tokenManager.saveRefreshId(sessionData.refreshId) delay(50) sessionData } is ApiResult.Error -> { MySdk.instance().mySdkListeners?.onSessionExpired() return ApiResponse.SessionData() } } } private class CustomNetworkStateChecker : NetworkStateChecker { override fun isNetworkAvailable() = true } private fun userApiService(): UserApiService { val retrofit = RetrofitHelper.provideRetrofit( RetrofitHelper.provideOkHttpClient(CustomNetworkStateChecker(), tokenManager) ) return retrofit.create(UserApiService::class.java) } }
0
Kotlin
0
0
0e52957fb5bd848c64c8f1732993522465245a82
2,729
RefreshToken
MIT License
eithernet/src/commonMain/kotlin/com/slack/eithernet/ApiResult.kt
slackhq
297,518,695
false
null
/* * Copyright (C) 2020 Slack Technologies, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.slack.eithernet import com.slack.eithernet.ApiResult.Failure import com.slack.eithernet.ApiResult.Failure.ApiFailure import com.slack.eithernet.ApiResult.Failure.HttpFailure import com.slack.eithernet.ApiResult.Failure.NetworkFailure import com.slack.eithernet.ApiResult.Failure.UnknownFailure import com.slack.eithernet.ApiResult.Success import kotlin.reflect.KClass import okio.IOException /** * Represents a result from a traditional HTTP API. [ApiResult] has two sealed subtypes: [Success] * and [Failure]. [Success] is typed to [T] with no error type and [Failure] is typed to [E] with no * success type. * * [Failure] in turn is represented by four sealed subtypes of its own: [Failure.NetworkFailure], * [Failure.ApiFailure], [Failure.HttpFailure], and [Failure.UnknownFailure]. This allows for simple * handling of results through a consistent, non-exceptional flow via sealed `when` branches. * * ``` * when (val result = myApi.someEndpoint()) { * is Success -> doSomethingWith(result.response) * is Failure -> when (result) { * is NetworkFailure -> showError(result.error) * is HttpFailure -> showError(result.code) * is ApiFailure -> showError(result.error) * is UnknownError -> showError(result.error) * } * } * ``` * * Usually, user code for this could just simply show a generic error message for a [Failure] case, * but a sealed class is exposed for more specific error messaging. */ public sealed interface ApiResult<out T : Any, out E : Any> { /** A successful result with the data available in [response]. */ public class Success<T : Any> @InternalEitherNetApi public constructor(public val value: T, tags: Map<KClass<*>, Any>) : ApiResult<T, Nothing> { /** Extra metadata associated with the result such as original requests, responses, etc. */ @InternalEitherNetApi public val tags: Map<KClass<*>, Any> = tags.toUnmodifiableMap() /** Returns a new copy of this with the given [tags]. */ public fun withTags(tags: Map<KClass<*>, Any>): Success<T> { return Success(value, tags) } } /** Represents a failure of some sort. */ public sealed interface Failure<E : Any> : ApiResult<Nothing, E> { /** * A network failure caused by a given [error]. This error is opaque, as the actual type could * be from a number of sources (connectivity, etc). This event is generally considered to be a * non-recoverable and should be used as signal or logging before attempting to gracefully * degrade or retry. */ public class NetworkFailure @InternalEitherNetApi public constructor(public val error: IOException, tags: Map<KClass<*>, Any>) : Failure<Nothing> { /** Extra metadata associated with the result such as original requests, responses, etc. */ internal val tags: Map<KClass<*>, Any> = tags.toUnmodifiableMap() /** Returns a new copy of this with the given [tags]. */ public fun withTags(tags: Map<KClass<*>, Any>): NetworkFailure { return NetworkFailure(error, tags.toUnmodifiableMap()) } } /** * An unknown failure caused by a given [error]. This error is opaque, as the actual type could * be from a number of sources (serialization issues, etc). This event is generally considered * to be a non-recoverable and should be used as signal or logging before attempting to * gracefully degrade or retry. */ public class UnknownFailure @InternalEitherNetApi public constructor(public val error: Throwable, tags: Map<KClass<*>, Any>) : Failure<Nothing> { /** Extra metadata associated with the result such as original requests, responses, etc. */ internal val tags: Map<KClass<*>, Any> = tags.toUnmodifiableMap() /** Returns a new copy of this with the given [tags]. */ public fun withTags(tags: Map<KClass<*>, Any>): UnknownFailure { return UnknownFailure(error, tags.toUnmodifiableMap()) } } /** * An HTTP failure. This indicates a 4xx or 5xx response. The [code] is available for reference. * * @property code The HTTP status code. * @property error An optional [error][E]. This would be from the error body of the response. */ public class HttpFailure<E : Any> @InternalEitherNetApi public constructor(public val code: Int, public val error: E?, tags: Map<KClass<*>, Any>) : Failure<E> { /** Extra metadata associated with the result such as original requests, responses, etc. */ internal val tags: Map<KClass<*>, Any> = tags.toUnmodifiableMap() /** Returns a new copy of this with the given [tags]. */ public fun withTags(tags: Map<KClass<*>, Any>): HttpFailure<E> { return HttpFailure(code, error, tags.toUnmodifiableMap()) } } /** * An API failure. This indicates a 2xx response where [ApiException] was thrown during response * body conversion. * * An [ApiException], the [error] property will be best-effort populated with the value of the * [ApiException.error] property. * * @property error An optional [error][E]. */ public class ApiFailure<E : Any> @InternalEitherNetApi public constructor(public val error: E?, tags: Map<KClass<*>, Any>) : Failure<E> { /** Extra metadata associated with the result such as original requests, responses, etc. */ internal val tags: Map<KClass<*>, Any> = tags.toUnmodifiableMap() /** Returns a new copy of this with the given [tags]. */ public fun withTags(tags: Map<KClass<*>, Any>): ApiFailure<E> { return ApiFailure(error, tags.toUnmodifiableMap()) } } } public companion object { private const val OK = 200 private val HTTP_SUCCESS_RANGE = OK..299 private val HTTP_FAILURE_RANGE = 400..599 /** Returns a new [Success] with given [value]. */ public fun <T : Any> success(value: T): Success<T> = Success(value, emptyMap()) /** Returns a new [HttpFailure] with given [code] and optional [error]. */ public fun <E : Any> httpFailure(code: Int): HttpFailure<E> { return httpFailure(code, null) } /** Returns a new [HttpFailure] with given [code] and optional [error]. */ public fun <E : Any> httpFailure(code: Int, error: E? = null): HttpFailure<E> { checkHttpFailureCode(code) return HttpFailure(code, error, emptyMap()) } /** Returns a new [ApiFailure] with given [error]. */ public fun <E : Any> apiFailure(): ApiFailure<E> = apiFailure(null) /** Returns a new [ApiFailure] with given [error]. */ public fun <E : Any> apiFailure(error: E? = null): ApiFailure<E> = ApiFailure(error, emptyMap()) /** Returns a new [NetworkFailure] with given [error]. */ public fun networkFailure(error: IOException): NetworkFailure = NetworkFailure(error, emptyMap()) /** Returns a new [UnknownFailure] with given [error]. */ public fun unknownFailure(error: Throwable): UnknownFailure = UnknownFailure(error, emptyMap()) internal fun checkHttpFailureCode(code: Int) { require(code !in HTTP_SUCCESS_RANGE) { "Status code '$code' is a successful HTTP response. If you mean to use a $OK code + error " + "string to indicate an API error, use the ApiResult.apiFailure() factory." } require(code in HTTP_FAILURE_RANGE) { "Status code '$code' is not a HTTP failure response. Must be a 4xx or 5xx code." } } } }
4
null
26
734
290aae1da9f8ab2b64e035f9b99840d97bc910f4
8,099
EitherNet
Apache License 2.0
app/src/main/java/com/zyr/apiclient/network/ApiErrorType.kt
ZYRzyr
102,813,716
false
null
/******************************************************************************* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.beacool.appnetwork.network import android.content.Context import android.support.annotation.StringRes enum class ApiErrorType(val code: Int, val message: String) { // INTERNAL_SERVER_ERROR(500, "服务器出错"), // BAD_GATEWAY(502, R.string.service_error), // NOT_FOUND(404, R.string.not_found), // CONNECTION_TIMEOUT(408, R.string.timeout), // NETWORK_NOT_CONNECT(499, R.string.network_wrong), // UNEXPECTED_ERROR(700, R.string.unexpected_error); // // private val DEFAULT_CODE = 1 // // fun getApiErrorModel(context: Context): ApiErrorModel { // return ApiErrorModel(DEFAULT_CODE, context.getString(messageId)) // } }
0
Kotlin
4
44
d02f7b400fb69b71f254b0f9812ca8b4c5249b63
1,403
ApiClient
Apache License 2.0
project/jimmer-sql-kotlin/src/test/kotlin/org/babyfish/jimmer/sql/kt/common/AbstractMutationTest.kt
babyfish-ct
488,154,823
false
null
package org.babyfish.jimmer.sql.kt.common import org.babyfish.jimmer.sql.kt.ast.KExecutable import org.babyfish.jimmer.sql.kt.ast.expression.value import org.babyfish.jimmer.sql.kt.ast.mutation.KBatchSaveResult import org.babyfish.jimmer.sql.kt.ast.mutation.KMutationResult import org.babyfish.jimmer.sql.kt.ast.mutation.KSimpleSaveResult import java.sql.Connection import java.util.* import javax.sql.DataSource import kotlin.reflect.KClass import kotlin.reflect.KProperty1 import kotlin.test.* abstract class AbstractMutationTest : AbstractTest() { protected fun executeAndExpectRowCount( executable: KExecutable<Int>, block: ExpectDSLWithRowCount.() -> Unit ) { executeAndExpectRowCount(null, executable, block) } protected fun executeAndExpectRowCount( rowCountBlock: (Connection) -> Int, block: ExpectDSLWithRowCount.() -> Unit ) { executeAndExpectRowCount(null, { con -> rowCountBlock(con) }, block) } protected fun executeAndExpectRowCount( dataSource: DataSource? = null, executable: KExecutable<Int>, block: ExpectDSLWithRowCount.() -> Unit ) { return executeAndExpectRowCount( dataSource, { con -> executable.execute(con) }, block ) } protected fun executeAndExpectRowCount( dataSource: DataSource? = null, rowCountBlock: (Connection) -> Int, block: ExpectDSLWithRowCount.() -> Unit ) { jdbc(dataSource, true) { con -> clearExecutions() var affectedRowCount = 0 var throwable: Throwable? = null try { affectedRowCount = rowCountBlock(con) } catch (ex: Throwable) { throwable = ex } assertRowCount(throwable, affectedRowCount, block) } } protected fun executeAndExpectResult( executeBlock: (Connection) -> KMutationResult, block: ExpectDSLWithResult.() -> Unit ) { executeAndExpectResult(null, executeBlock, block) } protected fun executeAndExpectResult( dataSource: DataSource?, executeBlock: (Connection) -> KMutationResult, block: ExpectDSLWithResult.() -> Unit ) { jdbc(dataSource, true) { con -> clearExecutions() var result: KMutationResult? var throwable: Throwable? = null try { result = executeBlock(con) } catch (ex: Throwable) { throwable = ex result = null } assertResult(throwable, result, block) } } protected fun <T> connectAndExpect( action: (Connection) -> T, block: ExpectDSLWithValue<T>.() -> Unit ) { jdbc(null, true) { con -> clearExecutions() var value: T? var throwable: Throwable? = null try { value = action(con) } catch (ex: Throwable) { throwable = ex value = null } val dsl = ExpectDSLWithValue(executions, throwable, value) block(dsl) dsl.close() } } private fun assertRowCount( throwable: Throwable?, rowCount: Int, block: ExpectDSLWithRowCount.() -> Unit ) { val dsl = ExpectDSLWithRowCount(executions, throwable, rowCount) block(dsl) dsl.close() } private fun assertResult( throwable: Throwable?, result: KMutationResult?, block: ExpectDSLWithResult.() -> Unit ) { val dsl = ExpectDSLWithResult(executions, throwable, result) block(dsl) dsl.close() } protected open class ExpectDSL( executions: List<Execution>, throwable: Throwable? ) { private val executions: List<Execution> protected var throwable: Throwable? private var statementCount = 0 private var throwableChecked = false init { this.executions = executions this.throwable = throwable } fun statement(block: StatementDSL.() -> Unit) { val index = statementCount++ if (index < executions.size) { block(StatementDSL(index, executions[index])) } else if (throwable != null) { throw throwable!! } else { fail("Two many statements, max statement count: " + executions.size) } } fun throwable(block: ThrowableDSL.() -> Unit) { assertNotNull(throwable, "No throwable.") block(ThrowableDSL(throwable)) throwableChecked = true } open fun close() { assertEquals( statementCount, executions.size, "Error statement count." ) if (throwable != null) { if (!throwableChecked) { throw throwable!! } } } } protected class ExpectDSLWithRowCount( executions: List<Execution>, throwable: Throwable?, private val rowCount: Int ) : ExpectDSL(executions, throwable) { fun rowCount(rowCount: Int) { if (throwable == null) { assertEquals(rowCount, this.rowCount, "bad row count") } } } protected class ExpectDSLWithResult( executions: List<Execution>, throwable: Throwable?, private val result: KMutationResult? ) : ExpectDSL(executions, throwable) { private var entityCount = 0 fun totalRowCount(totalRowCount: Int): ExpectDSLWithResult { assertNotNull(result) assertEquals(totalRowCount, result!!.totalAffectedRowCount) return this } fun rowCount(entityType: KClass<*>, rowCount: Int): ExpectDSLWithResult { assertNotNull(result) assertEquals( rowCount, result!!.affectedRowCount(entityType), "rowCountMap['$entityType']" ) return this } fun rowCount(prop: KProperty1<*, *>, rowCount: Int): ExpectDSLWithResult { assertNotNull(result) assertEquals( rowCount, result!!.affectedRowCount(prop), "rowCountMap['$prop']" ) return this } fun entity(block: EntityDSL.() -> Unit): ExpectDSLWithResult { if (throwable != null) { throw throwable!! } return entity(entityCount++, block) } private fun entity( index: Int, block: EntityDSL.() -> Unit ): ExpectDSLWithResult { val simpleSaveResult: KSimpleSaveResult<*> = if (index == 0) { if (result is KSimpleSaveResult<*>) { result } else { (result as KBatchSaveResult<*>).simpleResults[0] } } else { (result as KBatchSaveResult<*>).simpleResults[index] } block(EntityDSL(index, simpleSaveResult)) return this } override fun close() { super.close() val actualEntityCount: Int = if (result is KSimpleSaveResult<*>) { 1 } else if (result is KBatchSaveResult<*>) { result.simpleResults.size } else { 0 } assertEquals( entityCount, actualEntityCount, "entity.count" ) } } protected class ExpectDSLWithValue<T>( executions: List<Execution>, throwable: Throwable?, private val value: T? ) : ExpectDSL(executions, throwable) { private var entityCount = 0 fun value(value: String): ExpectDSLWithValue<T> { assertContentEquals( value, this.value?.toString() ?: "" ) return this } override fun close() { super.close() assertTrue( value != null, "value" ) } } protected class StatementDSL internal constructor( private val index: Int, private val execution: Execution ) { fun sql(value: String) { contentEquals( value, execution.sql, "statements[$index].sql" ) } fun variables(vararg values: Any?) { assertEquals( values.size, execution.variables.size, "statements[$index].variables.size." ) for (i in values.indices) { val exp = values[i] val act: Any = execution.variables[i] if (exp is ByteArray) { assertTrue( Arrays.equals(exp as ByteArray?, act as ByteArray), "statements[$index].variables[$i]." ) } else { assertEquals( exp, act, "statements[$index].variables[$i]." ) } } } fun unorderedVariables(vararg values: Any?) { assertEquals( values.toSet(), execution.variables.toSet(), "statements[$index].variables." ) } fun variables(block: List<Any?>.() -> Unit) { block(execution.variables) } } protected class ThrowableDSL internal constructor(private val throwable: Throwable?) { fun type(type: Class<out Throwable?>?) { assertSame(type, throwable!!.javaClass) } fun message(message: String?) { assertEquals(message, throwable!!.message) } fun detail(block: Throwable.() -> Unit) { block(throwable!!) } } protected class EntityDSL internal constructor( private val index: Int, private val result: KSimpleSaveResult<*> ) { fun original(json: String) { contentEquals( json, result.originalEntity.toString(), "originalEntities[$index]" ) } fun modified(json: String) { contentEquals( json, result.modifiedEntity.toString(), "modifiedEntities[$index]" ) } } }
18
null
72
725
873f8405a268d95d0b2e0ff796e2d0925ced21e7
10,829
jimmer
Apache License 2.0
SqlObjectMapper/src/main/kotlin/com/qualifiedcactus/sqlObjectMapper/fromRs/ResultSetParser.kt
qualified-cactus
546,189,129
false
null
/* * MIT License * * Copyright (c) 2023 qualified-cactus * * 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. * */ @file:Suppress("UNCHECKED_CAST") @file:JvmName("ResultSetParser") package com.qualifiedcactus.sqlObjectMapper.fromRs import com.qualifiedcactus.sqlObjectMapper.MappingProvider import com.qualifiedcactus.sqlObjectMapper.SqlObjectMapperException import com.qualifiedcactus.sqlObjectMapper.fromRs.IdMapping.* import com.qualifiedcactus.sqlObjectMapper.fromRs.RowParser.* import java.sql.ResultSet import java.util.* import kotlin.reflect.KClass import java.sql.SQLException import kotlin.collections.ArrayList /** * Get columns' values of all rows as a list of DTOs of type [clazz], then close [ResultSet] * @throws SqlObjectMapperException on invalid mapping * @throws SQLException from JDBC */ @JvmOverloads fun <T : Any> parseToList(resultSet: ResultSet, clazz: Class<T>, initialArraySize: Int = 0): List<T> = resultSet.toList(clazz.kotlin, initialArraySize) /** * Get columns' values of the first row as a DTO of type [clazz], then close [ResultSet] * @return null if there is no rows * @throws SqlObjectMapperException on invalid mapping * @throws SQLException from JDBC */ fun <T : Any> parseToObject(resultSet: ResultSet, clazz: Class<T>): T? = resultSet.toObject(clazz.kotlin) /** * Get value of the first column of the first row, then close [ResultSet] * @return null if there is no rows * @throws SQLException from JDBC */ fun <T : Any> parseToScalar(resultSet: ResultSet): T? { return resultSet.use { if (resultSet.next()) { resultSet.getObject(1) as T? } else { null } } } fun <T : Any> ResultSet.toScalar(): T? = parseToScalar(this) @JvmOverloads fun <T : Any> parseToScalarList(resultSet: ResultSet, initialArraySize: Int = 0): List<T?> { return resultSet.use { val output = ArrayList<T?>(initialArraySize) while (it.next()) { output.add(it.getObject(1) as T?) } output } } fun <T: Any> ResultSet.toScalarList(initialArraySize: Int = 0): List<T?> = parseToScalarList(this, initialArraySize) /** * Get columns' values of the first row as a DTO of type [clazz], then close [ResultSet] * @return null if there is no rows * @throws SqlObjectMapperException on invalid mapping * @throws SQLException from JDBC */ fun <T : Any> ResultSet.toObject(clazz: KClass<T>): T? { return this.use { if (!it.next()) { return@use null } val clazzMapping = MappingProvider.mapRsClass(clazz) val rowParser = RowParser(it) if (clazzMapping.isSimple) { return@use rowParser.simpleParse(clazzMapping) as T } else { return@use rowParser.parseWithNested(clazzMapping).value as T } } } /** * Get columns' values of all rows as a list of DTOs of type [clazz], then close [ResultSet] * @throws SqlObjectMapperException on invalid mapping * @throws SQLException from JDBC */ fun <T : Any> ResultSet.toList(clazz: KClass<T>, initialArraySize: Int = 0): List<T> { return this.use { val clazzMapping = MappingProvider.mapRsClass(clazz) val outputList = ArrayList<Any>(initialArraySize) val rowParser = RowParser(it) if (clazzMapping.isSimple) { while (it.next()) { outputList.add(rowParser.simpleParse(clazzMapping)) } } else if (clazzMapping.toManyList.isEmpty()) { while (it.next()) { outputList.add(rowParser.parseWithNested(clazzMapping).value) } } else { val relationalTracker = RelationalTracker(clazzMapping) fun tempF(curMapping: RsTopClassMapping, parent: Pair<IdValue, RsTopClassMapping>?) { if (curMapping.idMapping.noId) { throw SqlObjectMapperException( "${curMapping.rootMapping.clazz} doesn't have id column(s)" ) } val curId = curMapping.idMapping.fromResultSet(it) if (curId == null) { return } if (!relationalTracker.objectExists( curMapping.rootMapping.clazz, curId)) { val parsingResult = rowParser.parseWithNested(curMapping) relationalTracker.registerObject( curMapping.rootMapping.clazz, curId, parsingResult ) if (parent == null) { outputList.add(parsingResult.value) } } if (parent != null) { val (parentId, parentMapping) = parent relationalTracker.addToParent( ObjectInfo(parentMapping.rootMapping.clazz, parentId), ObjectInfo(curMapping.rootMapping.clazz, curId) ) } curMapping.toManyList.forEach { tempF(it.elementMapping, Pair(curId, curMapping)) } } while (it.next()) { tempF(clazzMapping, null) } } outputList as List<T> } } private class ObjectInfo( val clazz: KClass<*>, val idValue: IdValue ) private class AddedObject( val value: Any, val collectionsDict: Map<KClass<*>, Pair<MutableSet<IdValue>, ParsedCollection>> ) private class RelationalTracker( val topClassMapping: RsTopClassMapping, ) { private val dict: Map<KClass<*>, MutableMap<IdValue, AddedObject>> init { dict = HashMap() initDict(dict, topClassMapping) } fun initDict( dict: HashMap<KClass<*>, MutableMap<IdValue, AddedObject>>, curClazz: RsTopClassMapping ) { dict[curClazz.rootMapping.clazz] = HashMap() curClazz.toManyList.forEach { initDict(dict, it.elementMapping) } } fun objectExists(objectType: KClass<*>, objectId: IdValue): Boolean { return dict[objectType]!!.containsKey(objectId) } fun registerObject(clazz: KClass<*>, idValue: IdValue, parsedInfo: ParseWithNestedResult) { dict[clazz]!![idValue] = AddedObject( parsedInfo.value, parsedInfo.toManyCollectionList.let { collectionsList -> val map = HashMap< KClass<*>, Pair<MutableSet<IdValue>, ParsedCollection> >(collectionsList.size) collectionsList.forEach { collection -> map[ collection.info.elementMapping .rootMapping.clazz ] = Pair(HashSet(), collection) } map } ) } /** * Parent object and child object must be already added */ fun addToParent(parentInfo: ObjectInfo, objectInfo: ObjectInfo) { val parent = dict[parentInfo.clazz]!![parentInfo.idValue]!! val (idSet, parsedCollection) = parent.collectionsDict[objectInfo.clazz]!! if (!idSet.contains(objectInfo.idValue)) { idSet.add(objectInfo.idValue) val childObject = dict[objectInfo.clazz]!![objectInfo.idValue]!!.value parsedCollection.collection.add( parsedCollection.info.valueConverter.convert( childObject, parsedCollection.info.elementMapping.rootMapping.clazz ) ) } } } ///** // * An object used to convert [ResultSet] to desired objects // */ //@Suppress("UNCHECKED_CAST") //object ResultSetParser { // // //}
0
Kotlin
0
2
1027e4f634ec7b6db7a9fb1dbdf025a7d93536e5
8,819
SqlObjectMapper
MIT License
app/src/main/java/sgtmelon/adventofcode/year15/day7/Year15Day7ViewModel.kt
SerjantArbuz
559,224,296
false
{"Kotlin": 152755}
package sgtmelon.adventofcode.year15.day7 import sgtmelon.adventofcode.app.domain.SplitTextUseCase import sgtmelon.adventofcode.app.presentation.screen.parent.solution.TextSolutionViewModelImpl import sgtmelon.adventofcode.year15.day7.model.Command import sgtmelon.adventofcode.year15.day7.useCase.CalculateWiresUseCase import sgtmelon.adventofcode.year15.day7.useCase.GetCommandUseCase class Year15Day7ViewModel( private val input: String, private val splitText: SplitTextUseCase, private val getCommand: GetCommandUseCase, private val calculateWires: CalculateWiresUseCase ) : TextSolutionViewModelImpl() { override suspend fun calculatePuzzle() { val commandList = splitText(input).map { getCommand(it) } val firstResult = calculateWires(commandList) firstValue.postValue(firstResult.aValue()) val secondResult = calculateWires(getSecondCommandList(commandList, firstResult.aValue())) secondValue.postValue(secondResult.aValue()) } private fun getSecondCommandList( commandList: List<Command>, firstResult: String ): List<Command> { val newCommandList = commandList.toMutableList() val bIndex = newCommandList.indexOfFirst { it is Command.Set && it.to == "b" } newCommandList[bIndex] = Command.Set(firstResult, to = "b") return newCommandList } private fun Map<String, Int>.aValue(): String { return this["a"]?.toString() ?: throw NullPointerException("Didn't found `a` value!") } }
0
Kotlin
0
0
26a57b8431c03e2d09071f7302d6360ba91bfd2f
1,532
AdventOfCode
Apache License 2.0
app/src/main/java/sgtmelon/adventofcode/year15/day7/Year15Day7ViewModel.kt
SerjantArbuz
559,224,296
false
{"Kotlin": 152755}
package sgtmelon.adventofcode.year15.day7 import sgtmelon.adventofcode.app.domain.SplitTextUseCase import sgtmelon.adventofcode.app.presentation.screen.parent.solution.TextSolutionViewModelImpl import sgtmelon.adventofcode.year15.day7.model.Command import sgtmelon.adventofcode.year15.day7.useCase.CalculateWiresUseCase import sgtmelon.adventofcode.year15.day7.useCase.GetCommandUseCase class Year15Day7ViewModel( private val input: String, private val splitText: SplitTextUseCase, private val getCommand: GetCommandUseCase, private val calculateWires: CalculateWiresUseCase ) : TextSolutionViewModelImpl() { override suspend fun calculatePuzzle() { val commandList = splitText(input).map { getCommand(it) } val firstResult = calculateWires(commandList) firstValue.postValue(firstResult.aValue()) val secondResult = calculateWires(getSecondCommandList(commandList, firstResult.aValue())) secondValue.postValue(secondResult.aValue()) } private fun getSecondCommandList( commandList: List<Command>, firstResult: String ): List<Command> { val newCommandList = commandList.toMutableList() val bIndex = newCommandList.indexOfFirst { it is Command.Set && it.to == "b" } newCommandList[bIndex] = Command.Set(firstResult, to = "b") return newCommandList } private fun Map<String, Int>.aValue(): String { return this["a"]?.toString() ?: throw NullPointerException("Didn't found `a` value!") } }
0
Kotlin
0
0
26a57b8431c03e2d09071f7302d6360ba91bfd2f
1,532
AdventOfCode
Apache License 2.0
app/src/main/java/com/simbiri/equityjamii/adapters/TaskAdapter.kt
SimbaSimbiri
706,250,529
false
{"Kotlin": 451132}
package com.example.app.adapters import android.content.Context import android.os.Handler import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.cardview.widget.CardView import androidx.navigation.findNavController import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.google.android.material.progressindicator.LinearProgressIndicator import com.google.firebase.firestore.FirebaseFirestore import com.simbiri.equityjamii.R import com.simbiri.equityjamii.constants.TASK_SUB_COLLECTION import com.simbiri.equityjamii.constants.WORKSPACE_COLLECTION import com.simbiri.equityjamii.data.objects.AuthUtils import com.simbiri.equityjamii.data.model.Task import com.simbiri.equityjamii.ui.main_activity.workspace_page.AddTaskFragment import com.simbiri.equityjamii.ui.main_activity.workspace_page.MainWorkspFragmentDirections import com.simbiri.equityjamii.ui.main_activity.workspace_page.ViewTaskFragment import com.simbiri.equityjamii.ui.main_activity.workspace_page.ViewTaskFragmentDirections import com.simbiri.equityjamii.ui.main_activity.workspace_page.ViewWorkspFragmentDirections class TaskAdapter( var context: Context, var taskList: MutableList<Task>, val workspaceId: String, val canEdit: Boolean ) : RecyclerView.Adapter<TaskAdapter.TaskViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.adapter_tasks_item, parent, false) return TaskViewHolder(view) } override fun onBindViewHolder(holder: TaskViewHolder, position: Int) { val task = taskList[position] holder.bind(task) } override fun getItemCount(): Int { return taskList.size } inner class TaskViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val textTaskMentionView: TextView = itemView.findViewById(R.id.textTaskMentionView) private val progressMilestoneTv: TextView = itemView.findViewById(R.id.progressMilestoneTv) private val progressTask: LinearProgressIndicator = itemView.findViewById(R.id.progressTask) private val imageMyProfile: ImageView = itemView.findViewById(R.id.imageMyProfile) private var cardViewHolder: CardView = itemView.findViewById(R.id.cardViewMyProfile) private var taskAssignorTv: TextView = itemView.findViewById(R.id.assignorTaskTv) fun bind(task: Task) { adjustHolderSize() textTaskMentionView.text = task.title textTaskMentionView.setOnClickListener { val action = ViewWorkspFragmentDirections.actionOpenTask(task, workspaceId) (context as AppCompatActivity).findNavController(R.id.worksp_frag_container) .navigate(action) } progressMilestoneTv.text = if (task.milestonesTask.isNotEmpty()) { "${task.milestonesTask.count { it.complete }}/ ${task.milestonesTask.size} milestones" } else { "" } progressTask.progress = if (task.milestonesTask.isNotEmpty()) { if (task.complete) 100 else task.milestonesTask.count { it.complete } * 100 / task.milestonesTask.size } else { 0 } val currentUserId = AuthUtils.getCurrentUserId() val assigneeIdToShow = if (task.assigneeListIds.contains(currentUserId)) { currentUserId } else { task.assigneeListIds.firstOrNull() } if (task.assignorId.contentEquals(AuthUtils.getCurrentUserId())) { taskAssignorTv.text = "assigned by me" } else { AuthUtils.getCurrentPerson(task.assignorId) { person -> taskAssignorTv.text = "assigned by ${person?.name}" } } if (assigneeIdToShow != null) { AuthUtils.getCurrentPerson(assigneeIdToShow) { person -> person?.let { Glide.with(itemView.context) .load(it.profileUri) .placeholder(R.drawable.account_box) .into(imageMyProfile) } } } else { imageMyProfile.setImageResource(R.drawable.account_box) } } private fun adjustHolderSize() { val layoutParamsHolder = cardViewHolder.layoutParams val displayMetrics = DisplayMetrics() val windowManager = itemView.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager windowManager.defaultDisplay.getMetrics(displayMetrics) val screenWidth = displayMetrics.widthPixels layoutParamsHolder.width = (screenWidth / 5.5).toInt() layoutParamsHolder.height = (screenWidth / 5.5).toInt() cardViewHolder.layoutParams = layoutParamsHolder } } }
0
Kotlin
0
0
8f20edd903d6616cb3dbeaa426bbd9a054cdd674
5,400
EquiJamii
Apache License 2.0
gradle-declarative-lang/src/com/android/tools/idea/gradle/dcl/ide/DeclarativePairedBraceMatcher.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.gradle.declarative import com.android.tools.idea.gradle.declarative.parser.DeclarativeElementTypeHolder import com.intellij.lang.BracePair import com.intellij.lang.PairedBraceMatcher import com.intellij.psi.PsiFile import com.intellij.psi.tree.IElementType class DeclarativePairedBraceMatcher : PairedBraceMatcher { override fun getPairs(): Array<BracePair> = parenPair override fun isPairedBracesAllowedBeforeType(lbraceType: IElementType, contextType: IElementType?): Boolean = true override fun getCodeConstructStart(file: PsiFile?, openingBraceOffset: Int): Int = openingBraceOffset } private val parenPair = arrayOf( BracePair(DeclarativeElementTypeHolder.OP_LBRACE, DeclarativeElementTypeHolder.OP_RBRACE, true), BracePair(DeclarativeElementTypeHolder.OP_LPAREN, DeclarativeElementTypeHolder.OP_RPAREN, true) )
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,486
android
Apache License 2.0
cli/src/main/kotlin/com/malinskiy/marathon/cli/args/FileVendorConfiguration.kt
badoo
251,365,845
false
{"Gradle Kotlin DSL": 24, "CODEOWNERS": 1, "INI": 8, "YAML": 20, "Shell": 11, "Text": 1, "Ignore List": 4, "Batchfile": 4, "EditorConfig": 1, "Markdown": 1, "Gradle": 3, "XML": 33, "Kotlin": 476, "Java": 8, "OpenStep Property List": 11, "Swift": 18, "JSON": 18, "JavaScript": 15, "JSON with Comments": 1, "HTML": 9, "SCSS": 12, "Public Key": 1, "CSS": 2}
package com.malinskiy.marathon.cli.args interface FileVendorConfiguration { }
1
null
6
1
e07de46f42f42e7b0a335bc1f81682deaa769288
79
marathon
Apache License 2.0
app/src/main/java/com/willowtree/vocable/presets/IPresetsRepository.kt
willowtreeapps
188,443,410
false
{"Kotlin": 261197}
package com.willowtree.vocable.presets import com.willowtree.vocable.room.CategoryDto import com.willowtree.vocable.room.PhraseDto import kotlinx.coroutines.flow.Flow //TODO: PK - Rename this once we make the jump to rename [PresetsRepository] -> "RoomPresetsRepository" interface IPresetsRepository { suspend fun getPhrasesForCategory(categoryId: String): List<PhraseDto> /** * Return all categories, sorted by [CategoryDto.sortOrder] */ fun getAllCategoriesFlow(): Flow<List<CategoryDto>> /** * Return all categories, sorted by [CategoryDto.sortOrder] */ suspend fun getAllCategories(): List<CategoryDto> suspend fun deletePhrase(phraseId: Long) suspend fun updateCategories(categories: List<CategoryDto>) suspend fun updateCategory(category: CategoryDto) suspend fun addCategory(category: CategoryDto) suspend fun getCategoryById(categoryId: String): CategoryDto suspend fun deleteCategory(categoryId: String) suspend fun getRecentPhrases(): List<PhraseDto> suspend fun updatePhraseLastSpoken(phraseId: Long, lastSpokenDate: Long) suspend fun updatePhrase(phrase: PhraseDto) suspend fun addPhrase(phrase: PhraseDto) }
63
Kotlin
12
96
fdf4a76a016314f4d982c0a6bd2cf41cf888d84d
1,204
vocable-android
MIT License
data/RF00614/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF00614" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 2 to 8 58 to 64 } value = "#4ea9ab" } color { location { 19 to 27 45 to 53 } value = "#efbcbc" } color { location { 28 to 30 41 to 43 } value = "#32743d" } color { location { 77 to 80 134 to 137 } value = "#966346" } color { location { 85 to 87 125 to 127 } value = "#058f7b" } color { location { 90 to 91 122 to 123 } value = "#c09b4f" } color { location { 93 to 95 114 to 116 } value = "#b5ebb3" } color { location { 97 to 101 106 to 110 } value = "#e2c60f" } color { location { 9 to 18 54 to 57 } value = "#448d89" } color { location { 28 to 27 44 to 44 } value = "#7ad7b9" } color { location { 31 to 40 } value = "#f73af4" } color { location { 81 to 84 128 to 133 } value = "#20d90f" } color { location { 88 to 89 124 to 124 } value = "#816ff1" } color { location { 92 to 92 117 to 121 } value = "#85c053" } color { location { 96 to 96 111 to 113 } value = "#11bf0f" } color { location { 102 to 105 } value = "#f91322" } color { location { 1 to 1 } value = "#e3844a" } color { location { 65 to 76 } value = "#646efb" } color { location { 138 to 144 } value = "#248ba5" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
2,927
Rfam-for-RNArtist
MIT License
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/LongParameterList.kt
niraj8
355,162,546
true
{"Kotlin": 1852830, "HTML": 4183, "Groovy": 2423}
package io.gitlab.arturbosch.detekt.rules.complexity import io.gitlab.arturbosch.detekt.api.AnnotationExcluder import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Metric import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell import io.gitlab.arturbosch.detekt.rules.isOverride import io.gitlab.arturbosch.detekt.rules.valueOrDefaultCommaSeparated import org.jetbrains.kotlin.psi.KtAnnotated import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtParameterList import org.jetbrains.kotlin.psi.KtPrimaryConstructor import org.jetbrains.kotlin.psi.KtSecondaryConstructor import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject /** * Reports functions and constructors which have more parameters than a certain threshold. * * @configuration threshold - number of parameters required to trigger the rule (default: `6`) * (deprecated: "Use `functionThreshold` and `constructorThreshold` instead") * @configuration functionThreshold - number of function parameters required to trigger the rule (default: `6`) * @configuration constructorThreshold - number of constructor parameters required to trigger the rule (default: `7`) * @configuration ignoreDefaultParameters - ignore parameters that have a default value (default: `false`) * @configuration ignoreDataClasses - ignore long constructor parameters list for data classes (default: `true`) * @configuration ignoreAnnotated - ignore long parameters list for constructors or functions in the context of these * annotation class names (default: `[]`) * * @active since v1.0.0 */ class LongParameterList( config: Config = Config.empty ) : Rule(config) { override val issue = Issue("LongParameterList", Severity.Maintainability, "The more parameters a function has the more complex it is. Long parameter lists are often " + "used to control complex algorithms and violate the Single Responsibility Principle. " + "Prefer functions with short parameter lists.", Debt.TWENTY_MINS) private val functionThreshold: Int = valueOrDefault(FUNCTION_THRESHOLD, valueOrDefault(THRESHOLD, DEFAULT_FUNCTION_THRESHOLD)) private val constructorThreshold: Int = valueOrDefault(CONSTRUCTOR_THRESHOLD, valueOrDefault(THRESHOLD, DEFAULT_CONSTRUCTOR_THRESHOLD)) private val ignoreDefaultParameters = valueOrDefault(IGNORE_DEFAULT_PARAMETERS, false) private val ignoreDataClasses = valueOrDefault(IGNORE_DATA_CLASSES, true) private val ignoreAnnotated = valueOrDefaultCommaSeparated(IGNORE_ANNOTATED, emptyList()) .map { it.removePrefix("*").removeSuffix("*") } private lateinit var annotationExcluder: AnnotationExcluder override fun visitKtFile(file: KtFile) { annotationExcluder = AnnotationExcluder(file, ignoreAnnotated) super.visitKtFile(file) } override fun visitNamedFunction(function: KtNamedFunction) { val owner = function.containingClassOrObject if (owner is KtClass && owner.isIgnored()) { return } validateFunction(function, functionThreshold) } override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) { validateConstructor(constructor) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { validateConstructor(constructor) } private fun KtAnnotated.isIgnored(): Boolean { return annotationExcluder.shouldExclude(annotationEntries) } private fun validateConstructor(constructor: KtConstructor<*>) { val owner = constructor.getContainingClassOrObject() if (owner is KtClass && owner.isDataClassOrIgnored()) { return } validateFunction(constructor, constructorThreshold) } private fun KtClass.isDataClassOrIgnored() = isIgnored() || ignoreDataClasses && isData() private fun validateFunction(function: KtFunction, threshold: Int) { if (function.isOverride() || function.isIgnored() || function.containingKtFile.isIgnored()) return val parameterList = function.valueParameterList val parameters = parameterList?.parameterCount() if (parameters != null && parameters >= threshold) { report(ThresholdedCodeSmell(issue, Entity.from(parameterList), Metric("SIZE", parameters, threshold), "The function ${function.nameAsSafeName} has too many parameters. The current threshold" + " is set to $threshold.")) } } private fun KtParameterList.parameterCount(): Int { return if (ignoreDefaultParameters) { parameters.filter { !it.hasDefaultValue() }.size } else { parameters.size } } companion object { const val THRESHOLD = "threshold" const val FUNCTION_THRESHOLD = "functionThreshold" const val CONSTRUCTOR_THRESHOLD = "constructorThreshold" const val IGNORE_DEFAULT_PARAMETERS = "ignoreDefaultParameters" const val IGNORE_DATA_CLASSES = "ignoreDataClasses" const val IGNORE_ANNOTATED = "ignoreAnnotated" const val DEFAULT_FUNCTION_THRESHOLD = 6 const val DEFAULT_CONSTRUCTOR_THRESHOLD = 7 } }
4
Kotlin
0
1
e1d7272886b46ba4ba79059b9e3c0772589b62e1
5,751
detekt
Apache License 2.0
src/main/kotlin/no/nav/familie/ba/sak/kjerne/autovedtak/fødselshendelse/VelgFagSystemService.kt
navikt
224,639,942
false
null
package no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse import io.micrometer.core.instrument.Counter import io.micrometer.core.instrument.Metrics import no.nav.familie.ba.sak.config.FeatureToggleConfig import no.nav.familie.ba.sak.config.FeatureToggleService import no.nav.familie.ba.sak.integrasjoner.infotrygd.InfotrygdService import no.nav.familie.ba.sak.integrasjoner.pdl.PersonopplysningerService import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemRegelVurdering.SEND_TIL_BA import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemRegelVurdering.SEND_TIL_INFOTRYGD import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemUtfall.DAGLIG_KVOTE import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemUtfall.FAGSAK_UTEN_IVERKSATTE_BEHANDLINGER_I_BA_SAK import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemUtfall.IVERKSATTE_BEHANDLINGER_I_BA_SAK import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemUtfall.LØPENDE_SAK_I_INFOTRYGD import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemUtfall.MOR_IKKE_NORSK_STATSBORGER import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemUtfall.SAKER_I_INFOTRYGD_MEN_IKKE_LØPENDE_UTBETALINGER import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemUtfall.STANDARDUTFALL_INFOTRYGD import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.FagsystemUtfall.values import no.nav.familie.ba.sak.kjerne.behandling.BehandlingService import no.nav.familie.ba.sak.kjerne.behandling.NyBehandlingHendelse import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingStatus import no.nav.familie.ba.sak.kjerne.fagsak.Fagsak import no.nav.familie.ba.sak.kjerne.fagsak.FagsakService import no.nav.familie.ba.sak.kjerne.personident.Aktør import no.nav.familie.ba.sak.kjerne.personident.PersonidentService import org.slf4j.LoggerFactory import org.springframework.stereotype.Service private const val INFOTRYGD_NULLDATO = "000000" @Service class VelgFagSystemService( private val fagsakService: FagsakService, private val infotrygdService: InfotrygdService, private val personidentService: PersonidentService, private val behandlingService: BehandlingService, private val personopplysningerService: PersonopplysningerService, private val featureToggleService: FeatureToggleService ) { val utfallForValgAvFagsystem = mutableMapOf<FagsystemUtfall, Counter>() init { values().forEach { utfallForValgAvFagsystem[it] = Metrics.counter( "familie.ba.sak.velgfagsystem", "navn", it.name, "beskrivelse", it.beskrivelse ) } } internal fun morHarLøpendeEllerTidligereUtbetalinger(fagsak: Fagsak?): Boolean { return if (fagsak == null) false else if (behandlingService.hentBehandlinger(fagsakId = fagsak.id) .any { it.status == BehandlingStatus.UTREDES } ) true else behandlingService.hentSisteBehandlingSomErIverksatt(fagsakId = fagsak.id) != null } internal fun morHarSakerMenIkkeLøpendeIInfotrygd(morsIdent: String): Boolean { val stønader = infotrygdService.hentInfotrygdstønaderForSøker(morsIdent, historikk = true).bruker if (stønader.any { it.opphørtFom == INFOTRYGD_NULLDATO }) throw IllegalStateException("Mor har løpende stønad i Infotrygd") return stønader.isNotEmpty() } internal fun morEllerBarnHarLøpendeSakIInfotrygd(morsIdent: String, barnasIdenter: List<String>): Boolean { val morsIdenter = personidentService.hentIdenter(personIdent = morsIdent, historikk = false) .filter { it.gruppe == "FOLKEREGISTERIDENT" } .map { it.ident } val alleBarnasIdenter = barnasIdenter.flatMap { personidentService.hentIdenter(personIdent = it, historikk = false) .filter { identinfo -> identinfo.gruppe == "FOLKEREGISTERIDENT" } .map { identinfo -> identinfo.ident } } return infotrygdService.harLøpendeSakIInfotrygd(morsIdenter, alleBarnasIdenter) } internal fun harMorGyldigNorskstatsborger(morsAktør: Aktør): Boolean { val gjeldendeStatsborgerskap = personopplysningerService.hentGjeldendeStatsborgerskap(morsAktør) secureLogger.info("Gjeldende statsborgerskap for ${morsAktør.aktivFødselsnummer()}=(${gjeldendeStatsborgerskap.land}, bekreftelsesdato=${gjeldendeStatsborgerskap.bekreftelsesdato}, gyldigFom=${gjeldendeStatsborgerskap.gyldigFraOgMed}, gyldigTom=${gjeldendeStatsborgerskap.gyldigTilOgMed})") return gjeldendeStatsborgerskap.land == "NOR" } fun velgFagsystem(nyBehandlingHendelse: NyBehandlingHendelse): FagsystemRegelVurdering { val morsAktør = personidentService.hentOgLagreAktør(nyBehandlingHendelse.morsIdent) val fagsak = fagsakService.hent(morsAktør) val (fagsystemUtfall: FagsystemUtfall, fagsystem: FagsystemRegelVurdering) = when { morHarLøpendeEllerTidligereUtbetalinger(fagsak) -> Pair( IVERKSATTE_BEHANDLINGER_I_BA_SAK, SEND_TIL_BA ) morEllerBarnHarLøpendeSakIInfotrygd( nyBehandlingHendelse.morsIdent, nyBehandlingHendelse.barnasIdenter ) -> Pair( LØPENDE_SAK_I_INFOTRYGD, SEND_TIL_INFOTRYGD ) fagsak != null -> Pair( FAGSAK_UTEN_IVERKSATTE_BEHANDLINGER_I_BA_SAK, SEND_TIL_BA ) morHarSakerMenIkkeLøpendeIInfotrygd(nyBehandlingHendelse.morsIdent) -> Pair( SAKER_I_INFOTRYGD_MEN_IKKE_LØPENDE_UTBETALINGER, SEND_TIL_INFOTRYGD ) !harMorGyldigNorskstatsborger(morsAktør) -> Pair( MOR_IKKE_NORSK_STATSBORGER, SEND_TIL_INFOTRYGD ) kanBehandleINyttSystem() -> Pair( DAGLIG_KVOTE, SEND_TIL_BA ) else -> Pair(STANDARDUTFALL_INFOTRYGD, SEND_TIL_INFOTRYGD) } secureLogger.info("Sender fødselshendelse for ${nyBehandlingHendelse.morsIdent} til $fagsystem med utfall $fagsystemUtfall") utfallForValgAvFagsystem[fagsystemUtfall]?.increment() return fagsystem } private fun kanBehandleINyttSystem(): Boolean { val gradualRolloutFødselshendelser = featureToggleService.isEnabled(FeatureToggleConfig.AUTOMATISK_FØDSELSHENDELSE_GRADUAL_ROLLOUT) logger.info("Toggle for gradvis utrulling er $gradualRolloutFødselshendelser") return gradualRolloutFødselshendelser } companion object { val secureLogger = LoggerFactory.getLogger("secureLogger") val logger = LoggerFactory.getLogger(VelgFagSystemService::class.java) } } enum class FagsystemRegelVurdering { SEND_TIL_BA, SEND_TIL_INFOTRYGD } enum class FagsystemUtfall(val beskrivelse: String) { IVERKSATTE_BEHANDLINGER_I_BA_SAK("Mor har fagsak med tidligere eller løpende utbetalinger i ba-sak"), LØPENDE_SAK_I_INFOTRYGD("Mor har løpende sak i infotrygd"), FAGSAK_UTEN_IVERKSATTE_BEHANDLINGER_I_BA_SAK("Mor har fagsak uten iverksatte behandlinger"), SAKER_I_INFOTRYGD_MEN_IKKE_LØPENDE_UTBETALINGER("Mor har saker i infotrygd, men ikke løpende utbetalinger"), MOR_IKKE_NORSK_STATSBORGER("Mor har ikke gyldig norsk statsborgerskap"), DAGLIG_KVOTE("Daglig kvote er ikke nådd"), STANDARDUTFALL_INFOTRYGD("Ingen av de tidligere reglene slo til, sender til Infotrygd") }
8
Kotlin
0
7
d4a7ef6bc7ba6f0dfdbea1e0d7c7413a97891d55
7,669
familie-ba-sak
MIT License
gradle/build-infra/src/main/kotlin/dev/elide/infra/gradle/catalogs/VersionCatalogMergeTask.kt
elide-dev
646,018,864
false
{"Kotlin": 257243, "TOML": 52866, "Gradle": 42054, "YAML": 21793, "Dockerfile": 7754, "Java": 2273}
package dev.elide.infra.gradle.catalogs import org.gradle.api.DefaultTask import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.tasks.* import org.tomlj.Toml import org.tomlj.TomlArray import org.tomlj.TomlParseResult import org.tomlj.TomlTable import java.nio.charset.StandardCharsets import java.nio.file.Path import java.util.SortedMap import java.util.SortedSet import java.util.TreeMap import java.util.TreeSet import java.util.function.Supplier import javax.inject.Inject // Retrieve a top-level catalog table. private fun TomlParseResult.table(file: Path, name: String): TomlTable = requireNotNull(getTable(name)) { "Failed to resolve required `$name` section in catalog: '$file'" } // Append a TOML snippet for a version spec. private fun StringBuilder.appendVersionSpec(spec: VersionCatalogMergeTask.VersionSpec) { val (ref, version) = when (val v = spec) { is VersionCatalogMergeTask.StringLiteralVersion -> false to v.version is VersionCatalogMergeTask.VersionReference -> true to v.ref } append(if (ref) { "version.ref = \"$version\"" } else { "version = \"$version\"" }) } /** * # Task: Merge Version Catalogs * * Accepts multiple version catalogs as inputs, and deep-merges them, with later inputs overriding (so long as overrides * have been allowlisted). */ public abstract class VersionCatalogMergeTask @Inject constructor () : DefaultTask() { private object Constants { const val SECTION_VERSIONS: String = "versions" const val SECTION_LIBRARIES: String = "libraries" const val SECTION_PLUGINS: String = "plugins" const val SECTION_BUNDLES: String = "bundles" } // Version specification; either by reference or literal. internal sealed class VersionSpec (private val versionMap: Map<String, String>) { /** * Resolve the version provided by this version spec * * @param versions Version mappings * @return Supplier of the version */ abstract fun resolve(versions: Map<String, String>): Supplier<String> /** * Resolve the version referenced by this object */ val version: String get() = requireNotNull(resolve(versionMap).get()) { "Failed to resolve version reference" } companion object { @JvmStatic fun of(versionMap: Map<String, String>, key: String, value: Any?): VersionSpec = when (value) { null -> error("No version declared for target $key") is String -> StringLiteralVersion(versionMap, value) is TomlTable -> VersionReference(versionMap, requireNotNull(value["ref"] as? String)) else -> error("Unrecognized type for version spec parse: '$value'") } } } // String literal version implementation. internal class StringLiteralVersion(map: Map<String, String>, private val literal: String) : VersionSpec(map) { override fun resolve(versions: Map<String, String>): Supplier<String> = Supplier { literal } } // Version reference implementation. internal class VersionReference(map: Map<String, String>, val ref: String): VersionSpec(map) { override fun resolve(versions: Map<String, String>): Supplier<String> = Supplier { requireNotNull(versions[ref]) { "Failed to resolve version reference $ref" } } } internal sealed interface CatalogEphemera { val key: String } // Version catalog entry for a library. internal data class LibraryMapping( override val key: String, @JvmField var module: String? = null, @JvmField var group: String? = null, @JvmField var name: String? = null, @JvmField var version: VersionSpec? = null, ) : CatalogEphemera { companion object { @JvmStatic fun from( versionMap: Map< String, String>, key: String, value: TomlTable, ): LibraryMapping = LibraryMapping( key = key, module = value["module"] as? String, group = value["group"] as? String, name = value["name"] as? String, version = VersionSpec.of(versionMap, key, value["version"]), ).also { require ( it.module?.ifBlank { null } != null || (it.group?.ifBlank { null } != null && it.name?.ifBlank { null } != null) ) { "One of `module` or `name` and `group` must be specified for library `$key`" } } } override fun toString(): String = StringBuilder().apply { append("$key = { ") when { !module?.ifBlank { null }.isNullOrBlank() -> { val mod = requireNotNull(module) append("module = \"$mod\", ") } !group?.ifBlank { null }.isNullOrBlank() -> { val group = requireNotNull(group) val name = requireNotNull(name) append("group = \"$group\", name = \"$name\", ") } } appendVersionSpec(requireNotNull(version)) append(" }") }.toString() } // Version catalog entry for a plugin. internal data class PluginMapping( override val key: String, @JvmField var id: String? = null, @JvmField var version: VersionSpec? = null, ) : CatalogEphemera { companion object { @JvmStatic fun from( versionMap: Map<String, String>, key: String, value: TomlTable, ): PluginMapping = PluginMapping( key = key, id = requireNotNull(value["id"] as? String) { "No ID for plugin '$key'" }, version = VersionSpec.of(versionMap, key, value["version"]), ) } override fun toString(): String = StringBuilder().apply { append("$key = { ") append("id = \"$id\", ") appendVersionSpec(requireNotNull(version)) append(" }") }.toString() } // Version catalog entry for a bundle. internal data class BundleMapping( override val key: String, @JvmField var libraries: SortedSet<String> = sortedSetOf(), ) : CatalogEphemera { companion object { @JvmStatic fun from(key: String, value: TomlArray): BundleMapping = BundleMapping( key = key, libraries = value.size().let { TreeSet<String>().apply { for (i in 0 until it) { add(value.getString(i)) } } }, ) } override fun toString(): String = StringBuilder().apply { append("$key = [") append(libraries.joinToString(", ") { "\"$it\"" }) append("]") }.toString() } // De-serialized Gradle Version Catalog file. internal data class VersionCatalog( @JvmField val path: Path? = null, @JvmField val versions: SortedMap<String, String> = sortedMapOf(), @JvmField val libraries: SortedMap<String, LibraryMapping> = sortedMapOf(), @JvmField val plugins: SortedMap<String, PluginMapping> = sortedMapOf(), @JvmField val bundles: SortedMap<String, BundleMapping> = sortedMapOf(), ) { companion object { @JvmStatic fun parseFrom(file: Path): VersionCatalog { val toml: TomlParseResult = Toml.parse(file) val versions = toml.table(file, Constants.SECTION_VERSIONS) val libraries = toml.table(file, Constants.SECTION_LIBRARIES) val plugins = toml.table(file, Constants.SECTION_PLUGINS) val bundles = toml.getTable(Constants.SECTION_BUNDLES) val versionsMap = TreeMap(versions.toMap().map { it.key to it.value as String }.toMap()) return VersionCatalog( path = file, versions = versionsMap, libraries = TreeMap(libraries.toMap().map { it.key to LibraryMapping.from(versionsMap, it.key, it.value as TomlTable) }.toMap()), plugins = TreeMap(plugins.toMap().map { it.key to PluginMapping.from(versionsMap, it.key, it.value as TomlTable) }.toMap()), bundles = bundles?.let { TreeMap(it.toMap().map { pair -> pair.key to BundleMapping.from(pair.key, pair.value as TomlArray) }.toMap()) } ?: sortedMapOf(), ) } } } // Holds a merged version catalog; each is merged into this object, applying settings as we go. internal inner class MergedVersionCatalog( private val base: VersionCatalog = VersionCatalog(), private val overrideTokens: SortedSet<String> = overrides.get().toSortedSet(), ) { // Check if the provided `key` is eligible to be overridden. private fun eligibleForOverride(key: String): Boolean = key.lowercase().trim().let { candidate -> overrideTokens.any { key in candidate } } // Check if the provided `key` is eligible to be overridden. private fun eligibleForOverride(key: String, op: () -> String) { require(eligibleForOverride(key)) { op.invoke() } } // Require that a merged value is either not present in the authoritative map, or eligible for overrides. private fun requireNotPresentOrEligible(section: String, map: Map<String, *>, key: String) { if (key in map) eligibleForOverride(key) { val tokens = overrideTokens.joinToString(",") "Key '$key' in section '$section' is duplicate, and not eligible for overrides (\"$tokens\")" } } // Merge the provided version value into the catalog. private fun mergeVersion(key: String, version: String) { requireNotPresentOrEligible(Constants.SECTION_VERSIONS, base.versions, key) base.versions[key] = version } // Merge the provided library mapping into the catalog. private fun mergeLibrary(key: String, lib: LibraryMapping) { requireNotPresentOrEligible(Constants.SECTION_LIBRARIES, base.libraries, key) base.libraries[key] = when (val existing = base.libraries[key]) { null -> lib else -> existing.copy( module = lib.module ?: existing.module, group = lib.group ?: existing.group, name = lib.name ?: existing.name, version = lib.version ?: existing.version, ) } } // Merge the provided plugin mapping into the catalog. private fun mergePlugin(key: String, plugin: PluginMapping) { requireNotPresentOrEligible(Constants.SECTION_PLUGINS, base.plugins, key) base.plugins[key] = when (val existing = base.plugins[key]) { null -> plugin else -> existing.copy( id = plugin.id ?: existing.id, version = plugin.version ?: existing.version, ) } } // Merge the provided bundle mapping into the catalog. private fun mergeBundle(key: String, bundle: BundleMapping) { requireNotPresentOrEligible(Constants.SECTION_BUNDLES, base.bundles, key) base.bundles[key] = when (val existing = base.bundles[key]) { null -> bundle else -> existing.copy( libraries = existing.libraries.plus(bundle.libraries).toSortedSet(), ) } } operator fun plusAssign(other: VersionCatalog) { other.versions.map { mergeVersion(it.key, it.value) } other.libraries.map { mergeLibrary(it.key, it.value) } other.plugins.map { mergePlugin(it.key, it.value) } other.bundles.map { mergeBundle(it.key, it.value) } } // Render the merged TOML file to a string builder. fun toToml() = StringBuilder().apply { appendLine("[versions]") base.versions.forEach { appendLine("${it.key} = \"${it.value}\"") } appendLine() appendLine("[plugins]") base.plugins.forEach { appendLine(it.value.toString()) } appendLine() appendLine("[libraries]") base.libraries.forEach { appendLine(it.value.toString()) } appendLine() appendLine("[bundles]") base.bundles.forEach { appendLine(it.value.toString()) } } } /** * ## Catalogs * * Version catalogs to use as inputs to the merge operation */ @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) public abstract val catalogs: ConfigurableFileCollection /** * ## Destination File * * Target file, where the merged catalog should be written to */ @get:OutputFile public abstract val destinationFile: RegularFileProperty /** * ## Overrides * * Strings to allowlist for overrides; when collisions are encountered, they are checked for any of these substrings. * Matches allow the override, failures halt the build. */ @get:Input public abstract val overrides: ListProperty<String> @TaskAction internal fun merge() { val files = catalogs.files val parseErrors = ArrayList<Throwable>() val catalogs = ArrayList<VersionCatalog>(files.size) files.map { try { logger.info("Parsing catalog '${it.toPath()}'") VersionCatalog.parseFrom(it.toPath()) } catch (err: Throwable) { parseErrors.add(err) null } }.filter { it != null }.forEach { catalogs.add(it!!) } // check parse errors if (parseErrors.isNotEmpty()) { val first = parseErrors.first() throw IllegalStateException("Failed to parse one or more input version catalogs: ${first.message}", first) } // with no parse errors, we can begin merging val merged = MergedVersionCatalog() catalogs.forEach { logger.info("Merging catalog '${it.path ?: "in_memory"}'") merged += it } // open the destination file and write the merged catalog val targetFile = destinationFile.get().asFile try { targetFile.parentFile.mkdirs() targetFile.outputStream().bufferedWriter(StandardCharsets.UTF_8).use { it.write(merged.toToml().toString()) } } catch (err: Throwable) { logger.error("Failed to write merged version catalog: $err", err) } } }
6
Kotlin
2
2
ac58e3bbd8e88868d8104dccceb2affb967389af
13,690
build-infra
MIT License
src/test/kotlin/no/nav/syfo/util/GetDateTests.kt
navikt
192,538,863
false
{"Kotlin": 164579, "Dockerfile": 278}
package no.nav.syfo.util import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import java.time.LocalDateTime internal class GetDateTests { @Test internal fun `Convert without offset`() { val it = "2021-02-02T12:00:00" val localDateTime = getLocalDateTime(it) Assertions.assertEquals(LocalDateTime.parse("2021-02-02T11:00:00"), localDateTime) } @Test internal fun `Convert with offset pluss 01 00`() { val it = "2021-02-02T12:00:00+01:00" val localDateTime = getLocalDateTime(it) Assertions.assertEquals(LocalDateTime.parse("2021-02-02T11:00:00"), localDateTime) } @Test internal fun `Convert with offset pluss 02 00`() { val it = "2021-02-02T12:00:00+02:00" val localDateTime = getLocalDateTime(it) Assertions.assertEquals(LocalDateTime.parse("2021-02-02T10:00:00"), localDateTime) } @Test internal fun `Convert with Z offset`() { val it = "2021-02-02T12:00:00Z" val localDateTime = getLocalDateTime(it) Assertions.assertEquals(LocalDateTime.parse("2021-02-02T12:00:00"), localDateTime) } }
4
Kotlin
1
0
f65517a241fd06ac2b161f438325296022d1affc
1,162
syfosmmottak
MIT License
src/main/kotlin/ArrayGrid.kt
acmi
91,500,714
false
null
class ArrayGrid<T>(override val width: Int, override val height: Int, initializer: (x: Int, y: Int) -> T) : Grid<T> { private val data = ArrayList((0..(width * height - 1)).map { initializer(it % width, it / width) }) override operator fun get(x: Int, y: Int) = object : Cell<T> { override val x: Int get() = x override val y: Int get() = y override fun invoke(): T { return data[x + y * width] } override fun invoke(v: T) { data[x + y * width] = v } override fun toString() = "Cell[$x,$y]=${invoke()}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ArrayGrid<*>) return false if (width != other.width) return false if (height != other.height) return false if (data != other.data) return false return true } override fun hashCode(): Int { var result = width result = 31 * result + height result = 31 * result + data.hashCode() return result } }
0
Kotlin
0
0
ae0781d2b2d446688b0214c178f4099a9af6d791
1,149
SudokuSolver
Do What The F*ck You Want To Public License
app/src/main/java/com/rafaelds/russianhelper/home/MainActivityView.kt
themobilecoder
155,638,923
false
{"Kotlin": 35702}
package com.rafaelds.russianhelper.home import com.rafaelds.russianhelper.data.RussianWord interface MainActivityView { fun showAddWordDialog() fun showWordAddedSnackbar() fun updateWordList(results: ArrayList<RussianWord>) fun getWordIndex(id: String) : Int fun insertWord(word: RussianWord, index: Int) fun deleteWord(id: String) fun openDetailsScreen(russianWord: RussianWord) fun showWordDeletedSnackbar(russianWord: RussianWord, index: Int) }
0
Kotlin
0
0
d8782cee5cff030322699c4fce11afa16f11d469
481
Russian-Word-Helper
MIT License
src/org/jetbrains/r/roxygen/annotator/RoxygenAnnotator.kt
JetBrains
214,212,060
false
{"Kotlin": 2849847, "Java": 814635, "R": 36890, "CSS": 23692, "Lex": 14307, "HTML": 10063, "Rez": 245, "Rebol": 64}
/* * 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 org.jetbrains.r.roxygen.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.psi.PsiElement class RoxygenAnnotator : Annotator { override fun annotate(psiElement: PsiElement, holder: AnnotationHolder) { val visitor = RoxygenAnnotatorVisitor(holder) psiElement.accept(visitor) } }
2
Kotlin
12
62
a6454514e602c16474b0d25cbec5b11e70a5f686
526
Rplugin
Apache License 2.0
src/main/kotlin/no/nav/tiltakspenger/arena/felles/Mapper.kt
navikt
501,620,756
false
{"Kotlin": 135710, "Shell": 207, "Dockerfile": 135}
package no.nav.tiltakspenger.arena.felles import mu.KotlinLogging import java.text.ParseException import java.time.LocalDate import java.time.ZoneId import java.util.GregorianCalendar import javax.xml.datatype.DatatypeConfigurationException import javax.xml.datatype.DatatypeFactory import javax.xml.datatype.XMLGregorianCalendar private val LOG = KotlinLogging.logger {} private val SECURELOG = KotlinLogging.logger("tjenestekall") // TO DO: Er ikke sikker på om vi burde angi Europe/Oslo eller ikke. // (Gjelder både tilXmlGregorianCalenadar og toLocalDate..) fun LocalDate?.toXMLGregorian(): XMLGregorianCalendar? { return try { this?.atStartOfDay(ZoneId.systemDefault()) // ZoneId.of("Europe/Oslo") ?? ?.let { GregorianCalendar.from(it) } ?.let { DatatypeFactory.newInstance().newXMLGregorianCalendar(it) } } catch (exception: ParseException) { LOG.error("Feil logget til securelog") SECURELOG.error(exception) { "Noe feilet" } null } catch (exception: DatatypeConfigurationException) { LOG.error("Feil logget til securelog") SECURELOG.error(exception) { "Noe feilet" } null } } fun XMLGregorianCalendar?.toLocalDate(): LocalDate? = try { // https://codereview.stackexchange.com/questions/214711/xmlgregoriancalendar-to-localdatetime this?.toGregorianCalendar() ?.toZonedDateTime() // ?.withZoneSameInstant(ZoneId.of("Europe/Oslo")) ?.toLocalDate() } catch (exception: ParseException) { LOG.error("Feil logget til securelog") SECURELOG.error(exception) { "Noe feilet" } null } catch (exception: DatatypeConfigurationException) { LOG.error("Feil logget til securelog") SECURELOG.error(exception) { "Noe feilet" } null }
6
Kotlin
0
2
756057cefec20ba19ea92531e0978300ed86bb8d
1,841
tiltakspenger-arena
MIT License
src/main/kotlin/fr/zakaoai/coldlibrarybackend/infrastructure/implementation/NyaaTorrentServiceImpl.kt
zakaoai
344,490,461
false
{"Kotlin": 57777, "Dockerfile": 318}
package fr.zakaoai.coldlibrarybackend.infrastructure.implementation import de.kaysubs.tracker.nyaasi.NyaaSiApi import de.kaysubs.tracker.nyaasi.model.Category import de.kaysubs.tracker.nyaasi.model.SearchRequest import fr.zakaoai.coldlibrarybackend.infrastructure.NyaaTorrentService import fr.zakaoai.coldlibrarybackend.infrastructure.db.services.TrackedAnimeTorrentRepository import fr.zakaoai.coldlibrarybackend.model.dto.response.AnimeEpisodeTorrentDTO import fr.zakaoai.coldlibrarybackend.model.mapper.toAnimeEpisodeTorrentDTO import org.springframework.cache.annotation.CacheConfig import org.springframework.cache.annotation.Cacheable import org.springframework.stereotype.Service import reactor.core.publisher.Flux import reactor.core.publisher.Mono @Service @CacheConfig(cacheNames = ["torrents"]) class NyaaTorrentServiceImpl( private val nyaaSiApi: NyaaSiApi, private val trackedAnimeTorrentRepository: TrackedAnimeTorrentRepository ) : NyaaTorrentService{ @Cacheable override fun getAnimeSearch(searchTerm: String): SearchRequest { return SearchRequest() .setCategory(Category.Nyaa.anime) .setSortedBy(SearchRequest.Sort.SEEDERS) .setOrdering(SearchRequest.Ordering.DESCENDING) .setTerm(searchTerm) } @Cacheable override fun searchEpisodeTorrent(malId: Int, episodeNumber: Int): Flux<AnimeEpisodeTorrentDTO> { return trackedAnimeTorrentRepository.findByMalId(malId) .map { trackedAnime -> trackedAnime.searchWords } .map { searchWord -> when (episodeNumber) { 0 -> "VOSTFR $searchWord" else -> "VOSTFR $searchWord $episodeNumber" } } .map(this::getAnimeSearch) .map { search -> nyaaSiApi.search(search) } .flatMapMany { Flux.fromArray(it) } .map { it.toAnimeEpisodeTorrentDTO(malId,episodeNumber) } } override fun searchEpisodeTorrentById(torrentId: Int, malId: Int, episodeNumber: Int): Mono<AnimeEpisodeTorrentDTO> { return Mono.just(nyaaSiApi.getTorrentInfo(torrentId)) .map { it.toAnimeEpisodeTorrentDTO(torrentId, malId, episodeNumber) } } }
11
Kotlin
0
0
40aaf07e4464c3b6f4d4955bb6e94aefe1f35983
2,245
cold-library-backend
MIT License
app/src/main/java/com/yechy/dailypic/ui/home/MainViewModel.kt
houtengzhi
232,999,794
false
{"Kotlin": 58269}
package com.yechy.dailypic.ui.home import androidx.lifecycle.* import com.yechy.dailypic.ext.copyMap import com.yechy.dailypic.repository.DataRepos import com.yechy.dailypic.repository.SourceInfo import com.yechy.dailypic.ui.DataState import com.yechy.dailypic.vm.BaseViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import javax.inject.Inject /** * * Created by cloud on 2021/3/22. */ @HiltViewModel class MainViewModel @Inject constructor(val dataRepos: DataRepos): BaseViewModel() { private var _sourceList = MutableLiveData<DataState<List<SourceInfo>>>(DataState.inital()) val sourceList get() = _sourceList init { viewModelScope.launch { dataRepos.getPictureSourceList() .onStart { _sourceList.copyMap { it.copy(true,null,null) } } .catch { e -> _sourceList.copyMap { it.copy(false, null, e) } } .collect { infoList -> _sourceList.copyMap { it.copy(false, infoList,null) } } } } }
0
Kotlin
0
0
92f6c0cf8f4cf201089d320790684297fcd8a297
1,315
DailyPictures
Apache License 2.0
Flexsame/app/src/main/java/com/flexso/flexsame/ui/office/OfficeViewModel.kt
bertve
241,305,722
false
null
package com.flexso.flexsame.ui.office import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.flexso.flexsame.models.Address import com.flexso.flexsame.models.Office import com.flexso.flexsame.models.User import com.flexso.flexsame.repos.OfficeRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch class OfficeViewModel(private val officeRepository: OfficeRepository) : ViewModel() { //coroutines private val viewModelJob = SupervisorJob() private val viewModelScope = CoroutineScope(viewModelJob + Dispatchers.Main) lateinit var office: Office //checkedPersons private var _checkedPersons: MutableLiveData<MutableList<Long>> = MutableLiveData() val checkedPersons: LiveData<MutableList<Long>> get() = _checkedPersons //auth_persons private var _authorizedPersons: MutableLiveData<List<User>> = officeRepository.authorizedPersons val authorizedPersons: LiveData<List<User>> get() = _authorizedPersons //unauth_persons private var _unAuthorizedPersons: MutableLiveData<List<User>> = officeRepository.unAuthorizedPersons val unAuthorizedPersons: LiveData<List<User>> get() = _unAuthorizedPersons //add_succes private val _addSucces = MutableLiveData<Boolean>() val addSucces: LiveData<Boolean> get() = _addSucces //remove_succes private val _removeSucces = MutableLiveData<Boolean>() val removeSucces: LiveData<Boolean> get() = _removeSucces //edit_succes private val _editSucces = MutableLiveData<Boolean>() val editSucces: LiveData<Boolean> get() = _editSucces override fun onCleared() { super.onCleared() viewModelJob.cancel() } init { _checkedPersons.value = mutableListOf() } fun setCurrentOffice(currentOffice: Office) { this.office = currentOffice getAuthorizedPersons() getUnAuthorizedPersons() } fun getUnAuthorizedPersons() { viewModelScope.launch { officeRepository.getUnAuthorizedPersons(office.officeId) _unAuthorizedPersons = officeRepository.unAuthorizedPersons } } fun deAuthorizeUserFromOffice(userId: Long) { viewModelScope.launch { _removeSucces.postValue(officeRepository.deAuthorizePerson(office.officeId, userId)) getAuthorizedPersons() getUnAuthorizedPersons() } } fun addCheckedPersons() { this._checkedPersons.value!!.forEach { this.authorizePerson(it) } } fun authorizePerson(userId: Long) { viewModelScope.launch { _addSucces.postValue(officeRepository.authorizePerson(office.officeId, userId)) getAuthorizedPersons() getUnAuthorizedPersons() } } fun getAuthorizedPersons() { viewModelScope.launch { officeRepository.getAuthorizedPersons(office.officeId) _authorizedPersons = officeRepository.authorizedPersons } } fun editOfficeAddress(a: Address) { var helper = Office(office.officeId, office.company, a) viewModelScope.launch { if (officeRepository.updateOffice(helper)) { _editSucces.postValue(true) office.address = a } else { _editSucces.postValue(false) } } } fun removeFromCheckedList(userId: Long) { val res: MutableList<Long> = this._checkedPersons.value!! res.remove(userId) this._checkedPersons.value = res Log.i("checked_min", _checkedPersons.value.toString()) } fun addToCheckedList(userId: Long) { val res: MutableList<Long> = this._checkedPersons.value!! res.add(userId) this._checkedPersons.value = res Log.i("checked_plus", _checkedPersons.value.toString()) } fun resetCheckedList() { val res: MutableList<Long> = this._checkedPersons.value!! res.clear() this._checkedPersons.value = res Log.i("checked_reset", _checkedPersons.value.toString()) } }
0
Kotlin
0
0
d22c365b1dc9378caed4353fac21fd746674fbc9
4,265
AccesControlFlexso-frontend
MIT License
ExportAsDragOrExportToClipboard/src/main/kotlin/example/App.kt
aterai
158,348,575
false
null
package example import java.awt.* import java.awt.datatransfer.Clipboard import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.Transferable import java.awt.datatransfer.UnsupportedFlavorException import java.awt.event.InputEvent import javax.swing.* fun makeUI(): Component { val list = makeList(makeModel()) val check1 = JCheckBox("canExportAsDrag") check1.addActionListener { val b = check1.isSelected list.putClientProperty(check1.text, b) } val check2 = JCheckBox("canExportToClipboard") check2.addActionListener { val b = check2.isSelected list.putClientProperty(check2.text, b) } val check3 = JCheckBox("canImportFromClipboard") check3.addActionListener { val b = check3.isSelected list.putClientProperty(check3.text, b) } val box1 = Box.createHorizontalBox() box1.add(check1) val box2 = Box.createHorizontalBox() box2.add(check2) box2.add(check3) val p = JPanel(BorderLayout()) p.add(box1, BorderLayout.NORTH) p.add(box2, BorderLayout.SOUTH) return JPanel(BorderLayout()).also { it.add(p, BorderLayout.NORTH) it.add(JScrollPane(list)) it.border = BorderFactory.createEmptyBorder(5, 5, 5, 5) it.preferredSize = Dimension(320, 240) } } private fun makeModel() = DefaultListModel<Color>().also { it.addElement(Color.RED) it.addElement(Color.BLUE) it.addElement(Color.GREEN) it.addElement(Color.CYAN) it.addElement(Color.ORANGE) it.addElement(Color.PINK) it.addElement(Color.MAGENTA) } private fun makeList(model: ListModel<Color>): JList<Color> { return object : JList<Color>(model) { override fun updateUI() { selectionBackground = null // Nimbus cellRenderer = null super.updateUI() selectionModel.selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION dropMode = DropMode.INSERT dragEnabled = true val renderer = cellRenderer setCellRenderer { list, value, index, isSelected, cellHasFocus -> renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).also { it.foreground = value } } transferHandler = ListItemTransferHandler() componentPopupMenu = ListPopupMenu(this) } } } private class ListPopupMenu(list: JList<*>) : JPopupMenu() { private val cutItem: JMenuItem private val copyItem: JMenuItem init { val clipboard = Toolkit.getDefaultToolkit().systemClipboard val handler = list.transferHandler cutItem = add("cut") cutItem.addActionListener { handler.exportToClipboard(list, clipboard, TransferHandler.MOVE) } copyItem = add("copy") copyItem.addActionListener { handler.exportToClipboard(list, clipboard, TransferHandler.COPY) } add("paste").addActionListener { handler.importData(list, clipboard.getContents(null)) } addSeparator() add("clearSelection").addActionListener { list.clearSelection() } } override fun show( c: Component?, x: Int, y: Int, ) { if (c is JList<*>) { val isSelected = !c.isSelectionEmpty cutItem.isEnabled = isSelected copyItem.isEnabled = isSelected super.show(c, x, y) } } } private class ListItemTransferHandler : TransferHandler() { private val selectedIndices = mutableListOf<Int>() private var addIndex = -1 // Location where items were added private var addCount = 0 // Number of items added. override fun createTransferable(c: JComponent): Transferable { val source = (c as? JList<*>)?.also { s -> s.selectedIndices.forEach { selectedIndices.add(it) } } val selectedValues = source?.selectedValuesList return object : Transferable { override fun getTransferDataFlavors() = arrayOf(FLAVOR) override fun isDataFlavorSupported(flavor: DataFlavor) = FLAVOR == flavor @Throws(UnsupportedFlavorException::class) override fun getTransferData(flavor: DataFlavor): Any { return if (isDataFlavorSupported(flavor) && selectedValues != null) { selectedValues } else { throw UnsupportedFlavorException(flavor) } } } } override fun canImport(info: TransferSupport) = info.isDataFlavorSupported(FLAVOR) override fun getSourceActions(c: JComponent) = COPY_OR_MOVE override fun importData(info: TransferSupport): Boolean { // println("importData(TransferSupport)") val target = info.component as? JList<*> val v = target?.getClientProperty("canImportFromClipboard") val b = !info.isDrop && (v == null || v == false) if (target == null || b) { return false } var index = getIndex(info) addIndex = index val values = runCatching { info.transferable.getTransferData(FLAVOR) as? List<*> }.getOrNull().orEmpty() @Suppress("UNCHECKED_CAST") (target.model as? DefaultListModel<Any>)?.also { for (o in values) { val i = index++ it.add(i, o) target.addSelectionInterval(i, i) } } addCount = if (info.isDrop) values.size else 0 // target.requestFocusInWindow() return values.isNotEmpty() } override fun importData( c: JComponent?, t: Transferable?, ) = importData(TransferSupport(c, t)) override fun exportAsDrag( comp: JComponent, e: InputEvent?, action: Int, ) { // println("exportAsDrag") if (comp.getClientProperty("canExportAsDrag") == true) { super.exportAsDrag(comp, e, action) } } override fun exportToClipboard( comp: JComponent, clip: Clipboard?, action: Int, ) { // println("exportToClipboard") if (comp.getClientProperty("canExportToClipboard") == true) { super.exportToClipboard(comp, clip, action) } } override fun exportDone( c: JComponent, data: Transferable?, action: Int, ) { cleanup(c, action == MOVE) } private fun cleanup( c: JComponent, remove: Boolean, ) { if (remove && selectedIndices.isNotEmpty()) { val selectedList = if (addCount > 0) { selectedIndices.map { if (it >= addIndex) it + addCount else it } } else { selectedIndices.toList() } ((c as? JList<*>)?.model as? DefaultListModel<*>)?.also { model -> for (i in selectedList.reversed()) { model.remove(i) } } } selectedIndices.clear() addCount = 0 addIndex = -1 } private fun getIndex(info: TransferSupport): Int { val target = info.component as? JList<*> ?: return -1 var index = if (info.isDrop) { // Mouse Drag & Drop val tdl = info.dropLocation if (tdl is JList.DropLocation) { tdl.index } else { target.selectedIndex } } else { // Keyboard Copy & Paste target.selectedIndex } val max = (target.model as? DefaultListModel<*>)?.size ?: -1 index = if (index < 0) max else index index = index.coerceAtMost(max) return index } companion object { private val FLAVOR = DataFlavor(List::class.java, "List of items") } } 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
28
433dfe2513f1016eeb1fdc0c42551623a8cfaadf
7,469
kotlin-swing-tips
MIT License
src/main/kotlin/top/lanscarlos/vulpecula/bacikal/action/vector/ActionVectorRotateAxis.kt
Lanscarlos
517,897,387
false
{"Kotlin": 654453}
package top.lanscarlos.vulpecula.bacikal.action.vector /** * Vulpecula * top.lanscarlos.vulpecula.bacikal.action.vector * * @author Lanscarlos * @since 2023-03-22 15:54 */ object ActionVectorRotateAxis : ActionVector.Resolver { override val name: Array<String> = arrayOf("rotate-axis", "rotate-a") /** * vec rotate-axis &vec with/by &angle * */ override fun resolve(reader: ActionVector.Reader): ActionVector.Handler<out Any?> { return reader.transfer { combine( source(), trim("with", "by", then = vector(display = "vector axis")), double(0.0) ) { vector, axis, angle -> if (angle == 0.0) return@combine vector vector.rotateAroundAxis(axis, angle) } } } }
1
Kotlin
5
30
b07e79c505ebd953535b8c059144baa5482807d8
823
Vulpecula
MIT License
domain/src/main/java/com/jacekpietras/zoo/domain/feature/planner/interactor/AddAnimalToCurrentPlanUseCase.kt
JacekPietras
334,416,736
false
{"Kotlin": 752140, "Java": 21319}
package com.jacekpietras.zoo.domain.feature.planner.interactor import com.jacekpietras.zoo.domain.feature.animal.interactor.GetAnimalUseCase import com.jacekpietras.zoo.domain.feature.planner.model.PlanEntity import com.jacekpietras.zoo.domain.feature.planner.model.Stage import com.jacekpietras.zoo.domain.feature.planner.repository.PlanRepository import com.jacekpietras.zoo.domain.feature.animal.model.AnimalId import com.jacekpietras.zoo.domain.model.Region.AnimalRegion import com.jacekpietras.zoo.domain.model.RegionId class AddAnimalToCurrentPlanUseCase( private val planRepository: PlanRepository, private val getAnimalUseCase: GetAnimalUseCase, private val getOrCreateCurrentPlanUseCase: GetOrCreateCurrentPlanUseCase, ) { suspend fun run(animalId: AnimalId) { val plan = getOrCreateCurrentPlanUseCase.run() val regions = getAnimalUseCase.run(animalId).regionInZoo if (plan.containsRegions(regions)) return val newStages = plan.stages + Stage.InRegion(regions = regions.map(::AnimalRegion)) val newPlan = plan.copy(stages = newStages) planRepository.setPlan(newPlan) } private fun PlanEntity.containsRegions( regions: List<RegionId>, ) = when { regions.isEmpty() -> true regions.size == 1 -> singleRegionStages.any { it.region.id == regions.first() } else -> multipleRegionStages.any { it.alternatives == regions } } }
0
Kotlin
1
2
e6a689f442cc32d19ee3f51efc49bf49f9969ca8
1,446
ZOO
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/locations/LocationsToNomisIntTest.kt
ministryofjustice
445,140,246
false
{"Kotlin": 1551337, "Mustache": 1803, "Dockerfile": 1118}
package uk.gov.justice.digital.hmpps.prisonertonomisupdate.locations import com.github.tomakehurst.wiremock.client.WireMock.equalTo import com.github.tomakehurst.wiremock.client.WireMock.equalToJson import com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor import com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath import com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor import com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo import org.assertj.core.api.Assertions.assertThat import org.awaitility.kotlin.await import org.awaitility.kotlin.matches import org.awaitility.kotlin.untilAsserted import org.awaitility.kotlin.untilCallTo import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.isNull import org.mockito.kotlin.times import org.mockito.kotlin.verify import software.amazon.awssdk.services.sns.model.MessageAttributeValue import software.amazon.awssdk.services.sns.model.PublishRequest import uk.gov.justice.digital.hmpps.prisonertonomisupdate.integration.SqsIntegrationTestBase import uk.gov.justice.digital.hmpps.prisonertonomisupdate.wiremock.LocationsApiExtension.Companion.locationsApi import uk.gov.justice.digital.hmpps.prisonertonomisupdate.wiremock.MappingExtension.Companion.mappingServer import uk.gov.justice.digital.hmpps.prisonertonomisupdate.wiremock.NomisApiExtension.Companion.nomisApi import uk.gov.justice.hmpps.sqs.countAllMessagesOnQueue private const val DPS_ID = "57718979-573c-433a-9e51-2d83f887c11c" private const val PARENT_ID = "12345678-573c-433a-9e51-2d83f887c11c" private const val NOMIS_ID = 1234567L class LocationsToNomisIntTest : SqsIntegrationTestBase() { val locationApiResponse = """ { "id": "$DPS_ID", "prisonId": "MDI", "code": "001", "pathHierarchy": "A-1-001", "locationType": "CELL", "active": true, "localName": "<NAME>", "comments": "Not to be used", "capacity": { "maxCapacity": 2, "workingCapacity": 2 }, "certification": { "certified": true, "capacityOfCertifiedCell": 1 }, "attributes": [ "FEMALE_SEMI", "NON_SMOKER_CELL" ], "usage": [ { "usageType": "APPOINTMENT", "capacity": 3, "sequence": 1 }, { "usageType": "VISIT", "capacity": 3, "sequence": 2 }, { "usageType": "MOVEMENT", "sequence": 3 }, { "usageType": "OCCURRENCE", "sequence": 4 } ], "orderWithinParentLocation": 1, "topLevelId": "abcdef01-573c-433a-9e51-2d83f887c11c", "parentId": "$PARENT_ID", "key": "MDI-A-1-001", "isResidential": true } """.trimIndent() val locationMappingResponse = """ { "dpsLocationId": "$DPS_ID", "nomisLocationId": $NOMIS_ID, "mappingType": "LOCATION_CREATED" } """.trimIndent() val parentMappingResponse = """ { "dpsLocationId": "$PARENT_ID", "nomisLocationId": 12345678, "mappingType": "LOCATION_CREATED" } """.trimIndent() @Nested inner class Create { @Nested inner class WhenLocationHasBeenCreatedInDPS { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponse) nomisApi.stubLocationCreate("""{ "locationId": $NOMIS_ID }""") mappingServer.stubGetMappingGivenDpsLocationIdWithError(DPS_ID, 404) mappingServer.stubGetMappingGivenDpsLocationId(PARENT_ID, parentMappingResponse) mappingServer.stubCreateLocation() publishLocationDomainEvent("location.inside.prison.created") } @Test fun `will callback back to location service to get more details`() { waitForCreateProcessingToBeComplete() locationsApi.verify(getRequestedFor(urlEqualTo("/locations/$DPS_ID"))) } @Test fun `will create success telemetry`() { waitForCreateProcessingToBeComplete() verify(telemetryClient).trackEvent( eq("location-create-success"), org.mockito.kotlin.check { assertThat(it["dpsLocationId"]).isEqualTo(DPS_ID) assertThat(it["nomisLocationId"]).isEqualTo(NOMIS_ID.toString()) assertThat(it["key"]).isEqualTo("MDI-A-1-001") assertThat(it["prisonId"]).isEqualTo("MDI") }, isNull(), ) } @Test fun `will call nomis api to create the location`() { waitForCreateProcessingToBeComplete() nomisApi.verify( postRequestedFor(urlEqualTo("/locations")) .withRequestBody( equalToJson( """ { "certified" : true, "locationType" : "CELL", "prisonId" : "MDI", "locationCode" : "001", "description" : "MDI-A-1-001", "parentLocationId" : 12345678, "operationalCapacity" : 2, "cnaCapacity" : 1, "userDescription" : "Wing A", "unitType" : null, "capacity" : 2, "listSequence" : 1, "comment" : "Not to be used", "profiles" : [ { "profileType" : "SUP_LVL_TYPE", "profileCode" : "S" }, { "profileType" : "HOU_UNIT_ATT", "profileCode" : "NSMC" } ], "usages" : [ { "internalLocationUsageType": "APP", "usageLocationType" : null, "capacity": 3, "sequence": 1 }, { "internalLocationUsageType": "VISIT", "usageLocationType" : null, "capacity": 3, "sequence": 2 }, { "internalLocationUsageType": "MOVEMENT", "usageLocationType" : null, "capacity" : null, "sequence": 3 }, { "internalLocationUsageType": "OCCUR", "usageLocationType" : null, "capacity" : null, "sequence": 4 } ] } """.trimIndent(), ), ), ) } @Test fun `will create a mapping`() { waitForCreateProcessingToBeComplete() await untilAsserted { mappingServer.verify( postRequestedFor(urlEqualTo("/mapping/locations")) .withRequestBody(matchingJsonPath("dpsLocationId", equalTo(DPS_ID))) .withRequestBody(matchingJsonPath("nomisLocationId", equalTo(NOMIS_ID.toString()))), ) } await untilAsserted { verify(telemetryClient).trackEvent(any(), any(), isNull()) } } } @Nested inner class ValidationErrors { @Test fun `attribute is invalid`() { val locationApiResponse = """ { "id": "$DPS_ID", "prisonId": "MDI", "code": "001", "pathHierarchy": "A-1-001", "locationType": "CELL", "active": true, "topLevelId": "abcdef01-573c-433a-9e51-2d83f887c11c", "parentId": "$PARENT_ID", "key": "MDI-A-1-001", "isResidential": true, "attributes": [ "INVALID" ] } """.trimIndent() locationsApi.stubGetLocation(DPS_ID, locationApiResponse) publishLocationDomainEvent("location.inside.prison.created") await untilAsserted { verify(telemetryClient, times(3)).trackEvent( eq("location-create-failed"), org.mockito.kotlin.check { assertThat(it["dpsLocationId"]).isEqualTo(DPS_ID) assertThat(it["nomisLocationId"]).isNull() assertThat(it["key"]).isEqualTo("MDI-A-1-001") }, isNull(), ) } } @Test fun `usage is invalid`() { val locationApiResponse = """ { "id": "$DPS_ID", "prisonId": "MDI", "code": "001", "pathHierarchy": "A-1-001", "locationType": "CELL", "active": true, "topLevelId": "abcdef01-573c-433a-9e51-2d83f887c11c", "parentId": "$PARENT_ID", "key": "MDI-A-1-001", "isResidential": true, "usage": [{ "usageType": "INVALID", "capacity": 3, "sequence": 1 }] } """.trimIndent() locationsApi.stubGetLocation(DPS_ID, locationApiResponse) publishLocationDomainEvent("location.inside.prison.created") await untilAsserted { verify(telemetryClient, times(3)).trackEvent( eq("location-create-failed"), org.mockito.kotlin.check { assertThat(it["dpsLocationId"]).isEqualTo(DPS_ID) assertThat(it["nomisLocationId"]).isNull() assertThat(it["key"]).isEqualTo("MDI-A-1-001") }, isNull(), ) } } } @Nested inner class WhenMappingAlreadyCreatedForLocation { @BeforeEach fun setUp() { mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) publishLocationDomainEvent("location.inside.prison.created") } @Test fun `will not create an location in NOMIS`() { waitForCreateProcessingToBeComplete() verify(telemetryClient).trackEvent( eq("location-create-duplicate"), org.mockito.kotlin.check { assertThat(it["dpsLocationId"]).isEqualTo(DPS_ID) }, isNull(), ) nomisApi.verify( 0, postRequestedFor(urlEqualTo("/locations")), ) } } @Nested inner class WhenMappingServiceFailsOnce { @BeforeEach fun setUp() { mappingServer.stubGetMappingGivenDpsLocationIdWithError(DPS_ID, 404) mappingServer.stubGetMappingGivenDpsLocationId(PARENT_ID, parentMappingResponse) mappingServer.stubCreateLocationWithErrorFollowedBySlowSuccess() nomisApi.stubLocationCreate("""{ "locationId": $NOMIS_ID }""") locationsApi.stubGetLocation(DPS_ID, locationApiResponse) publishLocationDomainEvent("location.inside.prison.created") await untilCallTo { locationsApi.getCountFor("/locations/$DPS_ID") } matches { it == 1 } await untilCallTo { nomisApi.postCountFor("/locations") } matches { it == 1 } } @Test fun `should only create the NOMIS location once`() { await untilAsserted { verify(telemetryClient).trackEvent( eq("location-create-mapping-retry-success"), any(), isNull(), ) } nomisApi.verify( 1, postRequestedFor(urlEqualTo("/locations")), ) } @Test fun `will eventually create a mapping after NOMIS location is created`() { await untilAsserted { mappingServer.verify( 2, postRequestedFor(urlEqualTo("/mapping/locations")) .withRequestBody(matchingJsonPath("dpsLocationId", equalTo(DPS_ID))) .withRequestBody(matchingJsonPath("nomisLocationId", equalTo(NOMIS_ID.toString()))), ) } await untilAsserted { verify(telemetryClient).trackEvent( eq("location-create-mapping-retry-success"), any(), isNull(), ) } } } private fun waitForCreateProcessingToBeComplete() { await untilAsserted { verify(telemetryClient).trackEvent(any(), any(), isNull()) } } } @Nested inner class Update { @Nested inner class WhenLocationHasBeenUpdatedInDPS { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponse) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) mappingServer.stubGetMappingGivenDpsLocationId(PARENT_ID, parentMappingResponse) nomisApi.stubLocationUpdate("/locations/$NOMIS_ID") publishLocationDomainEvent("location.inside.prison.amended") } @Test fun `will callback back to location service to get more details`() { await untilAsserted { locationsApi.verify(getRequestedFor(urlEqualTo("/locations/$DPS_ID"))) } } @Test fun `will create success telemetry`() { await untilAsserted { verify(telemetryClient).trackEvent( eq("location-amend-success"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) assertThat(it["nomisId"]).isEqualTo(NOMIS_ID.toString()) assertThat(it["key"]).isEqualTo("MDI-A-1-001") }, isNull(), ) } } @Test fun `will call nomis api to update the location`() { await untilAsserted { nomisApi.verify(putRequestedFor(urlEqualTo("/locations/$NOMIS_ID"))) } } } @Nested inner class Exceptions { @Nested inner class WhenServiceFailsOnce { @BeforeEach fun setUp() { locationsApi.stubGetLocationWithErrorFollowedBySlowSuccess( id = DPS_ID, response = locationApiResponse, ) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) mappingServer.stubGetMappingGivenDpsLocationId(PARENT_ID, parentMappingResponse) nomisApi.stubLocationUpdate("/locations/$NOMIS_ID") publishLocationDomainEvent("location.inside.prison.amended") } @Test fun `will callback back to location service twice to get more details`() { await untilAsserted { locationsApi.verify(2, getRequestedFor(urlEqualTo("/locations/$DPS_ID"))) verify(telemetryClient).trackEvent(Mockito.eq("location-amend-success"), any(), isNull()) } } @Test fun `will eventually update the location in NOMIS`() { await untilAsserted { nomisApi.verify(1, putRequestedFor(urlEqualTo("/locations/$NOMIS_ID"))) verify(telemetryClient).trackEvent(Mockito.eq("location-amend-failed"), any(), isNull()) verify(telemetryClient).trackEvent(Mockito.eq("location-amend-success"), any(), isNull()) } } } @Nested inner class WhenServiceKeepsFailing { @BeforeEach fun setUp() { locationsApi.stubGetLocation(id = DPS_ID, response = locationApiResponse) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) mappingServer.stubGetMappingGivenDpsLocationId(PARENT_ID, parentMappingResponse) nomisApi.stubLocationUpdateWithError("/locations/$NOMIS_ID", 503) publishLocationDomainEvent("location.inside.prison.amended") } @Test fun `will callback back to location service 3 times before given up`() { await untilAsserted { locationsApi.verify(3, getRequestedFor(urlEqualTo("/locations/$DPS_ID"))) } } @Test fun `will create failure telemetry`() { await untilAsserted { verify(telemetryClient, times(3)).trackEvent( Mockito.eq("location-amend-failed"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) assertThat(it["nomisId"]).isEqualTo(NOMIS_ID.toString()) }, isNull(), ) } } @Test fun `will add message to dead letter queue`() { await untilCallTo { awsSqsLocationDlqClient!!.countAllMessagesOnQueue(locationDlqUrl!!).get() } matches { it == 1 } } } } } @Nested inner class Deactivate { val locationApiResponseDeactivated = """ { "id": "$DPS_ID", "prisonId": "MDI", "code": "001", "pathHierarchy": "A-1-001", "locationType": "CELL", "active": false, "orderWithinParentLocation": 1, "topLevelId": "abcdef01-573c-433a-9e51-2d83f887c11c", "key": "MDI-A-1-001", "isResidential": true, "deactivatedDate": "2024-02-01", "deactivatedReason": "CELL_RECLAIMS", "reactivatedDate": "2024-02-14" } """.trimIndent() @Nested inner class WhenLocationHasBeenDeactivatedInDPS { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponseDeactivated) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) nomisApi.stubLocationUpdate("/locations/$NOMIS_ID/deactivate") publishLocationDomainEvent("location.inside.prison.deactivated") } @Test fun `will create success telemetry`() { await untilAsserted { verify(telemetryClient).trackEvent( Mockito.eq("location-deactivate-success"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) assertThat(it["nomisId"]).isEqualTo(NOMIS_ID.toString()) }, isNull(), ) } } @Test fun `will call nomis api correctly to deactivate the location`() { await untilAsserted { nomisApi.verify( putRequestedFor(urlEqualTo("/locations/$NOMIS_ID/deactivate")) .withRequestBody(matchingJsonPath("reasonCode", equalTo("B"))) .withRequestBody(matchingJsonPath("reactivateDate", equalTo("2024-02-14"))) .withRequestBody(matchingJsonPath("deactivateDate", equalTo("2024-02-01"))), ) } } } @Nested inner class Exceptions { @Nested inner class WhenServiceFailsOnce { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponse) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) nomisApi.stubLocationUpdateWithErrorFollowedBySlowSuccess("/locations/$NOMIS_ID/deactivate") publishLocationDomainEvent("location.inside.prison.deactivated") } @Test fun `will eventually deactivate the location in NOMIS`() { await untilAsserted { nomisApi.verify(2, putRequestedFor(urlEqualTo("/locations/$NOMIS_ID/deactivate"))) verify(telemetryClient).trackEvent(Mockito.eq("location-deactivate-failed"), any(), isNull()) verify(telemetryClient).trackEvent(Mockito.eq("location-deactivate-success"), any(), isNull()) } } } @Nested inner class WhenNomisFails { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponse) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) nomisApi.stubLocationUpdateWithError("/locations/$NOMIS_ID/deactivate", 503) publishLocationDomainEvent("location.inside.prison.deactivated") } @Test fun `will create failure telemetry`() { await untilAsserted { verify(telemetryClient, times(3)).trackEvent( Mockito.eq("location-deactivate-failed"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) assertThat(it["nomisId"]).isEqualTo(NOMIS_ID.toString()) }, isNull(), ) } } } @Nested inner class WhenMappingNotFound { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponse) mappingServer.stubGetMappingGivenDpsLocationIdWithError(DPS_ID, 404) nomisApi.stubLocationUpdate("/locations/$NOMIS_ID/deactivate") publishLocationDomainEvent("location.inside.prison.deactivated") } @Test fun `will create failure telemetry and not call Nomis`() { await untilAsserted { verify(telemetryClient, times(3)).trackEvent( Mockito.eq("location-deactivate-failed"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) }, isNull(), ) } nomisApi.verify( 0, putRequestedFor(urlEqualTo("/locations/$NOMIS_ID/deactivate")), ) } } @Nested inner class WhenLocationApiFails { @BeforeEach fun setUp() { locationsApi.stubGetLocationWithError(DPS_ID, 404) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) nomisApi.stubLocationUpdate("/locations/$NOMIS_ID/deactivate") publishLocationDomainEvent("location.inside.prison.deactivated") } @Test fun `will create failure telemetry and not call Nomis`() { await untilAsserted { verify(telemetryClient, times(3)).trackEvent( Mockito.eq("location-deactivate-failed"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) }, isNull(), ) } nomisApi.verify( 0, putRequestedFor(urlEqualTo("/locations/$NOMIS_ID/deactivate")), ) } } } } @Nested inner class Reactivate { @Nested inner class WhenLocationHasBeenReactivatedInDPS { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponse) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) nomisApi.stubLocationUpdate("/locations/$NOMIS_ID/reactivate") publishLocationDomainEvent("location.inside.prison.reactivated") } @Test fun `will create success telemetry`() { await untilAsserted { verify(telemetryClient).trackEvent( Mockito.eq("location-reactivate-success"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) assertThat(it["nomisId"]).isEqualTo(NOMIS_ID.toString()) }, isNull(), ) } } @Test fun `will call nomis api to reactivate the location`() { await untilAsserted { nomisApi.verify(putRequestedFor(urlEqualTo("/locations/$NOMIS_ID/reactivate"))) } } } } @Nested inner class ChangeCapacity { @Nested inner class WhenCapacityHasBeenChangedInDPS { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponse) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) nomisApi.stubLocationUpdate("/locations/$NOMIS_ID/capacity") publishLocationDomainEvent("location.inside.prison.capacity.changed") } @Test fun `will create success telemetry`() { await untilAsserted { verify(telemetryClient).trackEvent( Mockito.eq("location-capacity-success"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) assertThat(it["nomisId"]).isEqualTo(NOMIS_ID.toString()) }, isNull(), ) } } @Test fun `will call nomis api to change the capacity`() { await untilAsserted { nomisApi.verify(putRequestedFor(urlEqualTo("/locations/$NOMIS_ID/capacity"))) } } } } @Nested inner class ChangeCertification { @Nested inner class WhenCertificationHasBeenChangedInDPS { @BeforeEach fun setUp() { locationsApi.stubGetLocation(DPS_ID, locationApiResponse) mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) nomisApi.stubLocationUpdate("/locations/$NOMIS_ID/certification") publishLocationDomainEvent("location.inside.prison.certification.changed") } @Test fun `will create success telemetry`() { await untilAsserted { verify(telemetryClient).trackEvent( Mockito.eq("location-certification-success"), org.mockito.kotlin.check { assertThat(it["dpsId"]).isEqualTo(DPS_ID) assertThat(it["nomisId"]).isEqualTo(NOMIS_ID.toString()) }, isNull(), ) } } @Test fun `will call nomis api to change the certification`() { await untilAsserted { nomisApi.verify(putRequestedFor(urlEqualTo("/locations/$NOMIS_ID/certification"))) } } } } @Nested inner class DeleteLocation { @Nested inner class WhenLocationHasJustBeenDeletedByLocationService { @BeforeEach fun setUp() { mappingServer.stubGetMappingGivenDpsLocationId(DPS_ID, locationMappingResponse) nomisApi.stubLocationDelete(NOMIS_ID) mappingServer.stubDeleteLocationMapping(DPS_ID) publishLocationDomainEvent("location.inside.prison.deleted") } @Test fun `will delete the location in NOMIS`() { await untilAsserted { nomisApi.verify(putRequestedFor(urlEqualTo("/locations/$NOMIS_ID/deactivate"))) } } @Test fun `will create success telemetry`() { await untilAsserted { verify(telemetryClient).trackEvent( Mockito.eq("location-delete-success"), org.mockito.kotlin.check { assertThat(it["dpsLocationId"]).isEqualTo(DPS_ID) assertThat(it["nomisLocationId"]).isEqualTo(NOMIS_ID.toString()) }, isNull(), ) } } } } private fun publishLocationDomainEvent(eventType: String) { awsSnsClient.publish( PublishRequest.builder().topicArn(topicArn) .message(locationMessagePayload(DPS_ID, eventType)) .messageAttributes( mapOf("eventType" to MessageAttributeValue.builder().dataType("String").stringValue(eventType).build()), ).build(), ).get() } private fun locationMessagePayload(id: String, eventType: String) = """{"eventType":"$eventType", "additionalInformation": {"id":"$id", "key":"MDI-A-1-001"}, "version": "1.0", "description": "description", "occurredAt": "2024-02-01T17:09:56.0"}""" }
2
Kotlin
0
2
e168c734a06480b70bd771581ef2692e83f4fc1b
26,612
hmpps-prisoner-to-nomis-update
MIT License
app/src/debug/java/com/appchamp/wordchunks/DebugApp.kt
luhongwu
144,697,733
false
null
/* * Copyright 2017 Julia Kozhukhovskaya * * 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.appchamp.wordchunks import android.app.Application import android.content.res.Configuration import com.appchamp.wordchunks.realmdb.utils.RealmFactory import com.appchamp.wordchunks.util.Constants.LANG_RU import com.appchamp.wordchunks.util.Constants.SUPPORTED_LOCALES import com.facebook.stetho.Stetho import com.franmontiel.localechanger.LocaleChanger import com.squareup.leakcanary.LeakCanary import com.uphyca.stetho_realm.RealmInspectorModulesProvider import io.realm.Realm import java.util.* /** * DebugApp initializes: * * LocaleChanger * LeakCanary * Stetho * Realm * */ class DebugApp : Application() { override fun onCreate() { super.onCreate() LocaleChanger.initialize(applicationContext, SUPPORTED_LOCALES) initLeakCanary() initStetho() when { // User's system language is Russian Locale.getDefault().language.contentEquals(LANG_RU) -> initRealm(SUPPORTED_LOCALES[1].displayLanguage) else -> initRealm(SUPPORTED_LOCALES[0].displayLanguage) } } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) LocaleChanger.onConfigurationChanged() } /** * Initialize with default users configurations. */ private fun initRealm(dbName: String) { Realm.init(this) val realmFactory: RealmFactory = RealmFactory() realmFactory.setRealmConfiguration(dbName) // For debugging only //Realm.deleteRealm(realmFactory.setRealmConfiguration(dbName)) } private fun initLeakCanary() { 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) } private fun initStetho() { Stetho.initialize( Stetho.newInitializerBuilder(this) .enableDumpapp(Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector( RealmInspectorModulesProvider.builder(this).build()) .build()) } }
1
Kotlin
9
1
fb56b3bb4da2008a99068f27d9e202d083725124
2,853
WordChunks
Apache License 2.0
test/src/test/kotlin/test/java/integration/core/compile/success/template/TemplateHandlerTest.kt
afezeria
456,986,646
false
null
package test.java.template import org.junit.Test import test.BaseTest import test.Person import test.errorMessages import test.java.template.handler.* import kotlin.test.assertContentEquals /** * * @author afezeria */ class TemplateHandlerTest : BaseTest() { @Test fun `access map without type argument`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<AccessMapDao>() val list = impl.query(mapOf("a" to 0)) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `access list without type argument`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<AccessListDao>() val list = impl.query(listOf(0, 0)) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `get list size`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<CompareListSizeDao>() val list = impl.query(emptyList()) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `get map size`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<CompareMapSizeDao>() val list = impl.query(emptyMap<Any, Any>()) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `cast object to map`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<CastObjectToMapDao>() val list = impl.query(mapOf("abc" to 0)) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `cast object to list`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<CastObjectToListDao>() val list = impl.query(listOf(0, 0)) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `reflect access bean property`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<ReflectAccessDao>() val a = ReflectAccessDao.A() a.a = "b" val list = impl.query(a) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `boxed primitive type parameter`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<BoxedPrimitiveTypeParameterDao>() val list = impl.query(0) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `boxed primitive type property`() { initData( Person(1, "a"), Person(2, "b") ) val impl = getJavaDaoInstance<BoxedPrimitiveTypePropertyDao>() val a = BoxedPrimitiveTypePropertyDao.A() a.id = -1.3 val list = impl.query(a) assert(list.size == 1) assertContentEquals(list.map { it.id }, listOf(1)) } @Test fun `error, duplicate property declared`() { compileFailure<DuplicatePropertyDeclaredBadDao> { assert( errorMessages.contains("Property 'i' already exists") ) } } @Test fun `error, property is not a map`(){ compileFailure<PropertyIsNotMapBadDao> { assert( errorMessages.contains("id is not a map") ) } } @Test fun `error, property is not a list`(){ compileFailure<PropertyIsNotListBadDao> { assert( errorMessages.contains("id is not a list") ) } } @Test fun `error, missing property`(){ compileFailure<MissingPropertyBadDao> { assert( errorMessages.contains("error expr:person.company, missing property:test.Person.company.") ) } } @Test fun `error, expr type cast error`(){ compileFailure<ExprTypeCastErrorBaoDao> { assert( errorMessages.contains("a.b is of type java.lang.String cannot assignable to java.lang.Integer") ) } } }
0
null
3
5
f52fb74f3805b0518b2f0fce4eb842dee9517a4f
4,560
freedao
Apache License 2.0
demo/src/main/java/com/mta/tehreer/demo/TextViewWidgetActivity.kt
Tehreer
68,520,755
false
null
/* * Copyright (C) 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mta.tehreer.demo import android.graphics.Color import android.os.Bundle import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.ForegroundColorSpan import android.util.TypedValue import android.view.Gravity import android.widget.SeekBar import androidx.appcompat.app.AppCompatActivity import com.mta.tehreer.graphics.TypefaceManager import org.json.JSONArray import org.json.JSONException import java.io.IOException import java.io.InputStreamReader import java.io.Reader private const val MIN_TEXT_SIZE = 20f private const val MAX_TEXT_SIZE = 56f class TextViewWidgetActivity : AppCompatActivity() { private lateinit var textView: QuranTextView private lateinit var textSizeBar: SeekBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_text_view_widget) supportActionBar?.setDisplayHomeAsUpEnabled(true) textSizeBar = findViewById(R.id.seek_bar_text_size) textSizeBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { } override fun onStartTrackingTouch(seekBar: SeekBar) { clearAyahHighlighting() } override fun onStopTrackingTouch(seekBar: SeekBar) { updateTextSize() } }) textView = findViewById(R.id.text_view) textView.apply { updateTextSize() setGravity(Gravity.CENTER_HORIZONTAL) typeface = TypefaceManager.getTypeface(R.id.typeface_noorehuda) spanned = parseSurah() lineHeightMultiplier = 0.80f isJustificationEnabled = true separatorColor = Color.GRAY highlightingColor = resources.getColor(R.color.colorHighlight) } } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } private fun parseSurah(): Spanned? { try { val stream = assets.open("AlKahf.json") val buffer = CharArray(1024) val out = StringBuilder() val `in`: Reader = InputStreamReader(stream) var length: Int while (`in`.read(buffer, 0, buffer.size).also { length = it } > 0) { out.append(buffer, 0, length) } val jsonString = out.toString() val surah = SpannableStringBuilder() val ayahsJson = JSONArray(jsonString) val ayahCount = ayahsJson.length() for (i in 0 until ayahCount) { val ayahJson = ayahsJson.getJSONObject(i) val ayahText = ayahJson.getString("text") val attrsJson = ayahJson.getJSONArray("attributes") val attrCount = attrsJson.length() val offset = surah.length surah.append(ayahText) surah.setSpan( QuranTextView.AyahSpan(), offset, surah.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) for (j in 0 until attrCount) { val attrJson = attrsJson.getJSONObject(j) val start = attrJson.getInt("start") val end = attrJson.getInt("end") val colorString = attrJson.getString("color") val color = Color.parseColor("#$colorString") surah.setSpan( ForegroundColorSpan(color), start + offset, end + offset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } surah.append(if (i == 0) "\n" else " ") } return surah } catch (e: IOException) { e.printStackTrace() } catch (e: JSONException) { e.printStackTrace() } return null } private fun spToPx(sp: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, resources.displayMetrics) private fun clearAyahHighlighting() { textView.clearAyahHighlighting() } private fun updateTextSize() { val ratio = (textSizeBar.progress.toFloat() / textSizeBar.max.toFloat()) val multiplier = MAX_TEXT_SIZE - MIN_TEXT_SIZE val sp = (ratio * multiplier) + MIN_TEXT_SIZE textView.textSize = spToPx(sp) } }
2
C
16
78
74aa7286b37efe058971e3bee427214bffbc5ad5
5,162
Tehreer-Android
Apache License 2.0
core/src/main/java/com/fibelatti/core/android/recyclerview/PagingRecyclerView.kt
fibelatti
165,537,939
false
null
package com.fibelatti.core.android.recyclerview import android.content.Context import android.util.AttributeSet import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlin.properties.Delegates class PagingRecyclerView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, ) : RecyclerView(context, attrs, defStyleAttr) { private val pagingHandler = PagingHandler() private var scrollListenerSet: Boolean by Delegates.vetoable(false) { _, oldValue, _ -> !oldValue } var onShouldRequestNextPage: (() -> Unit)? = null init { addOnScrollListener( object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) when (val lm = layoutManager) { is LinearLayoutManager -> { handlePaging(lm.itemCount, lm.findFirstCompletelyVisibleItemPosition()) } is GridLayoutManager -> { handlePaging(lm.itemCount, lm.findFirstCompletelyVisibleItemPosition()) } else -> { throw IllegalStateException("PagingRecyclerView supports only " + "LinearLayoutManager and GridLayoutManager") } } } } ) scrollListenerSet = true } private fun handlePaging(itemCount: Int, firstVisibleItemPosition: Int) { if (pagingHandler.shouldHandlePaging(itemCount, firstVisibleItemPosition)) { pagingHandler.setRequestingNextPage(true) onShouldRequestNextPage?.invoke() } } fun setPageSize(pageSize: Int) { pagingHandler.setPageSize(pageSize) } fun setMinDistanceToLastItem(minDistanceToLastItem: Int) { pagingHandler.setMinDistanceToLastItem(minDistanceToLastItem) } fun onRequestNextPageCompleted() { pagingHandler.setRequestingNextPage(false) } // region Unsupported RecyclerView overrides override fun addOnScrollListener(listener: OnScrollListener) { if (!scrollListenerSet) { super.addOnScrollListener(listener) } else { throw IllegalStateException("PagingRecyclerView doesn't support addOnScrollListener.") } } @Deprecated(message = "", replaceWith = ReplaceWith("addOnScrollListener")) override fun setOnScrollListener(listener: OnScrollListener?) { throw IllegalStateException("PagingRecyclerView doesn't support setOnScrollListener.") } override fun removeOnScrollListener(listener: OnScrollListener) { throw IllegalStateException("PagingRecyclerView doesn't support removeOnScrollListener.") } override fun clearOnScrollListeners() { throw IllegalStateException("PagingRecyclerView doesn't support clearOnScrollListeners.") } // endregion } class PagingHandler { private var requestingNextPage: Boolean = false private var pageSize: Int = 0 private var minDistanceToLastItem: Int = 0 fun setRequestingNextPage(requestingNextPage: Boolean) { this.requestingNextPage = requestingNextPage } fun setPageSize(pageSize: Int) { if (pageSize > 0) { this.pageSize = pageSize } } fun setMinDistanceToLastItem(minDistanceToLastItem: Int) { if (minDistanceToLastItem > 0) { this.minDistanceToLastItem = minDistanceToLastItem } } fun shouldHandlePaging(itemCount: Int, firstVisibleItemPosition: Int): Boolean { return pageSize > 0 && minDistanceToLastItem > 0 && itemCount != 0 && itemCount % pageSize == 0 && itemCount - firstVisibleItemPosition < minDistanceToLastItem && !isRequestingNextPage() } @Synchronized private fun isRequestingNextPage(): Boolean = requestingNextPage }
3
Kotlin
10
87
c96e7b709abeec4614df91168c4830ac44981ae5
4,229
pinboard-kotlin
Apache License 2.0
release/rapid/src/main/kotlin/com/expediagroup/sdk/rapid/models/Fees.kt
ExpediaGroup
527,522,338
false
{"Kotlin": 2001564, "Mustache": 51082, "Shell": 166, "Makefile": 73}
/* * Copyright (C) 2022 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.sdk.rapid.models /* * Copyright (C) 2022 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.fasterxml.jackson.annotation.JsonProperty import javax.validation.Valid /** * Information related to a property's fees. * @param mandatory Describes resort fees and other mandatory taxes or charges. May describe which services are covered by any fees, such as fitness centers or internet access. * @param optional Describes additional optional fees for items such as breakfast, wifi, parking, pets etc. */ data class Fees( // Describes resort fees and other mandatory taxes or charges. May describe which services are covered by any fees, such as fitness centers or internet access. @JsonProperty("mandatory") @field:Valid val mandatory: kotlin.String? = null, // Describes additional optional fees for items such as breakfast, wifi, parking, pets etc. @JsonProperty("optional") @field:Valid val optional: kotlin.String? = null ) { companion object { @JvmStatic fun builder() = Builder() } class Builder( private var mandatory: kotlin.String? = null, private var optional: kotlin.String? = null ) { fun mandatory(mandatory: kotlin.String) = apply { this.mandatory = mandatory } fun optional(optional: kotlin.String) = apply { this.optional = optional } fun build(): Fees { return Fees( mandatory = mandatory, optional = optional ) } } }
7
Kotlin
7
3
d91f62127859b50e806d2b858a1bcc04b47b6138
2,667
openworld-sdk-java
Apache License 2.0
app/src/main/java/cc/sovellus/vrcaa/ui/screen/group/UserGroupsScreenModel.kt
Nyabsi
745,635,224
false
{"Kotlin": 571062}
package cc.sovellus.vrcaa.ui.screen.group import cafe.adriel.voyager.core.model.StateScreenModel import cafe.adriel.voyager.core.model.screenModelScope import cc.sovellus.vrcaa.api.vrchat.models.UserGroups import cc.sovellus.vrcaa.manager.ApiManager.api import kotlinx.coroutines.launch sealed class UserGroupsState { data object Init : UserGroupsState() data object Loading : UserGroupsState() data class Result(val groups: ArrayList<UserGroups.Group>?) : UserGroupsState() } class UserGroupsScreenModel( private val userId: String ) : StateScreenModel<UserGroupsState>(UserGroupsState.Init) { private var groups: ArrayList<UserGroups.Group>? = null init { fetchGroups() } private fun fetchGroups() { mutableState.value = UserGroupsState.Loading screenModelScope.launch { groups = api.getUserGroups(userId) mutableState.value = UserGroupsState.Result(groups) } } }
1
Kotlin
3
35
46a1a0b7ec9a7dc068a132a5c6e4b03200009ec1
963
VRCAA
Apache License 2.0
app/src/main/java/com/fozechmoblive/fluidwallpaper/livefluid/ui/component/themes/adapter/WallpaperDiffUtil.kt
hoangvannhatanh
763,325,226
false
{"Kotlin": 228587, "Java": 183101, "GLSL": 66443}
package com.fozechmoblive.fluidwallpaper.livefluid.ui.component.themes.adapter import androidx.recyclerview.widget.DiffUtil import com.fozechmoblive.fluidwallpaper.livefluid.models.PresetModel class WallpaperDiffUtil( private val newList: List<PresetModel>, private val oldList: List<PresetModel> ) : DiffUtil.Callback() { override fun getOldListSize(): Int { return oldList.size } override fun getNewListSize(): Int { return newList.size } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition].typePresetModel == newList[newItemPosition].typePresetModel && oldList[oldItemPosition].isNew == newList[newItemPosition].isNew && oldList[oldItemPosition].isSelected == newList[newItemPosition].isSelected && oldList[oldItemPosition].imagePreset == newList[newItemPosition].imagePreset && oldList[oldItemPosition].isLock == newList[newItemPosition].isLock && oldList[oldItemPosition].name == newList[newItemPosition].name } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldList[oldItemPosition] == newList[newItemPosition] } }
0
Kotlin
0
0
c9e8296ab6640b4e9cc44fd347057bfe8c236c3d
1,292
fluid_wallpaper
MIT License
core/src/test/kotlin/com/expediagroup/sdk/domain/rapid/RapidHelpersTest.kt
ExpediaGroup
527,522,338
false
{"Kotlin": 2111465, "Mustache": 48416, "Shell": 715, "JavaScript": 606, "Makefile": 73}
/* * Copyright (C) 2022 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.sdk.domain.rapid import com.expediagroup.sdk.core.client.BaseRapidClient import com.expediagroup.sdk.core.configuration.RapidClientConfiguration import com.expediagroup.sdk.core.model.Response import io.ktor.client.statement.HttpResponse import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test class RapidHelpersTest { companion object { private val rapidClient = object : BaseRapidClient("dummy", RapidClientConfiguration()) { override suspend fun throwServiceException( response: HttpResponse, operationId: String ) { throw UnsupportedOperationException() } } val rapidHelpers = RapidHelpers(rapidClient) } @Nested inner class TestExtractToken { @Test fun `Verify extractToken returns token when present`() { assertEquals("12345", rapidHelpers.extractToken("https://www.example.com?token=12345")) } @Test fun `Verify extractToken returns null when no token is present`() { assertNull(rapidHelpers.extractToken("https://www.example.com")) } @Test fun `Verify extractToken returns an empty string when token is empty`() { assertEquals("", rapidHelpers.extractToken("https://www.example.com?token=")) } @Test fun `Verify extractToken returns token when it is not the first parameter`() { assertEquals("12345", rapidHelpers.extractToken("https://www.example.com?foo=bar&token=12345")) } @Test fun `Verify extractToken returns null when token is not provided but other parameters are`() { assertNull(rapidHelpers.extractToken("https://www.example.com?foo=bar")) } @Test fun `Verify extractToken returns null when token is not provided but multiple other parameters are`() { assertNull(rapidHelpers.extractToken("https://www.example.com?foo=bar&baz=qux")) } @Test fun `Verify extractToken returns it when token is not the last parameter`() { assertEquals("12345", rapidHelpers.extractToken("https://www.example.com?token=12345&foo=bar")) } @Test fun `extractToken should handle multiple parameters and return the correct token`() { assertEquals("xyz456", rapidHelpers.extractToken("https://example.com/page?param1=value1&token=xyz456&param2=value2")) } @Test fun `extractToken should handle URL-encoded characters in the token`() { assertEquals("abc%20456", rapidHelpers.extractToken("https://example.com/page?token=abc%20456&param=value")) } @Test fun `extractToken should handle different token parameter names`() { assertEquals("abcd1234", rapidHelpers.extractToken("https://example.com/page?access_token=abcd1234")) assertEquals("efgh5678", rapidHelpers.extractToken("https://example.com/page?api_token=efgh5678")) } @Test fun `extractToken should handle multiple tokens`() { assertEquals("abcd1234", rapidHelpers.extractToken("https://example.com/page?token=abcd1234&token=efgh5678")) assertEquals("efgh5678", rapidHelpers.extractToken("https://example.com/page?api_token=efgh5678&access_token=abcd1234")) } @Test fun `extractToken should get only the query param token`() { assertNull(rapidHelpers.extractToken("https://example.com/tokenPage?query=tokenValue")) } @Test fun `extractToken should return an empty string when token is empty and other parameters are present`() { assertEquals("", rapidHelpers.extractToken("https://www.example.com?foo=bar&token=")) } @Test fun `extractToken should return an empty string when token is empty in the middle of other parameters`() { assertEquals("", rapidHelpers.extractToken("https://www.example.com?foo=bar&token=&baz=qux")) } } @Nested inner class TestExtractRoomBookingId { @Test fun `Verify extractRoomBookingId returns roomId when present`() { assertEquals("abc-123-xyz", rapidHelpers.extractRoomBookingId("https://www.example.com/rooms/abc-123-xyz?token=abc")) } @Test fun `Verify extractRoomBookingId returns null when roomId is not present`() { assertNull(rapidHelpers.extractRoomBookingId("https://www.example.com?token=abc")) } } @Nested inner class TestExtractTransactionId { @Test fun `Verify extractTransactionId returns transactionId when present`() { Response<String>( 200, "body", mapOf("transaction-id" to listOf("abc-123-xyz")) ).let { assertEquals("abc-123-xyz", rapidHelpers.extractTransactionId(it)) } } @Test fun `Verify extractTransactionId returns null when transactionId is not present`() { Response<String>( 200, "body", mapOf("some-header" to listOf("some data")) ).let { assertNull(rapidHelpers.extractTransactionId(it)) } } } }
5
Kotlin
3
3
949c81113050e93ff71e1d5a4eefa3de8a4b504d
6,049
expediagroup-java-sdk
Apache License 2.0
request-filterer/request-filterer-api/src/main/java/com/duckduckgo/request/filterer/api/RequestFilterer.kt
hojat72elect
822,396,044
false
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.request.filterer.api import android.webkit.WebResourceRequest /** Public interface for the Request Filterer feature */ interface RequestFilterer { /** * This method takes a [request] and a [documentUrl] to calculate if the request should be filtered out or not. * @return `true` if the request should be filtered or `false` if it shouldn't */ fun shouldFilterOutRequest(request: WebResourceRequest, documentUrl: String?): Boolean /** * This method takes a [url] and registers it internally. This method must be used before using `shouldFilterOutRequest` * to correctly register the different page created events. */ fun registerOnPageCreated(url: String) }
0
Kotlin
0
0
54351d039b85138a85cbfc7fc3bd5bc53637559f
731
DuckDuckGo
Apache License 2.0
service/src/test/kotlin/fr/nihilus/music/service/TestBrowserTree.kt
thibseisel
80,150,620
false
null
/* * Copyright 2020 <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 fr.nihilus.music.service import android.net.Uri import fr.nihilus.music.core.media.MediaId import fr.nihilus.music.core.media.MediaId.Builder.CATEGORY_ALL import fr.nihilus.music.core.media.MediaId.Builder.TYPE_ALBUMS import fr.nihilus.music.core.media.MediaId.Builder.TYPE_TRACKS import fr.nihilus.music.core.test.stub import fr.nihilus.music.media.AudioTrack import fr.nihilus.music.media.MediaCategory import fr.nihilus.music.media.MediaContent import fr.nihilus.music.media.browser.BrowserTree import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map /** * A fake implementation of [BrowserTree] that provides static collections of children. */ internal object TestBrowserTree : BrowserTree { override fun getChildren(parentId: MediaId): Flow<List<MediaContent>> { val (type, category, track) = parentId return when { type == TYPE_TRACKS && category == CATEGORY_ALL -> provideAllTracksFlow() type == TYPE_ALBUMS -> when { category != null && track == null -> getAlbumChildrenFlow(category.toLong()) else -> getAlbumsFlow() } else -> noChildrenFlow() } } private fun provideAllTracksFlow() = periodicFlow(1000).map { longArrayOf(161, 309, 481, 48, 125, 294, 219, 75, 464, 477).map { trackId -> AudioTrack( id = MediaId(TYPE_TRACKS, CATEGORY_ALL, trackId), title = "Track #$trackId", artist = "", album = "", mediaUri = Uri.EMPTY, duration = 0L, disc = 0, number = 0 ) } } private fun getAlbumChildrenFlow(albumId: Long) = periodicFlow(500).map { listOf( AudioTrack( id = MediaId(TYPE_ALBUMS, albumId.toString(), albumId), title = "Track #$albumId", album = "Album #$albumId", artist = "sample_artist", mediaUri = Uri.EMPTY, disc = 0, number = 0, duration = 0 ) ) } private fun getAlbumsFlow() = periodicFlow(Long.MAX_VALUE).map { listOf( MediaCategory( id = MediaId(TYPE_ALBUMS, "42"), title = "Album #42" ) ) } private fun periodicFlow(period: Long) = flow { while (true) { emit(Unit) delay(period) } } private fun noChildrenFlow() = flow<Nothing> { throw NoSuchElementException() } override suspend fun getItem(itemId: MediaId): MediaContent = stub() }
23
null
8
67
f097bcda052665dc791bd3c26880adb0545514dc
3,364
android-odeon
Apache License 2.0
app/src/main/java/com/example/yanghuiwen/habittodoist/view/main_page/PagerAdapter.kt
kikiouo201
319,902,491
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Java": 2, "XML": 45, "Kotlin": 41}
package com.example.yanghuiwen.habittodoist.view.main_page import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import androidx.viewpager.widget.PagerAdapter class PagerAdapter(private val pageList : MutableList<RelativeLayout>) : PagerAdapter() { private var pageCount = 0 override fun getCount(): Int { return pageList.size } override fun isViewFromObject(view: View, o: Any): Boolean { return o === view } override fun instantiateItem(container: ViewGroup, position: Int): Any { // Log.i("PagerAdapter","i`m come in ${position}") container.addView(pageList[position]) //Log.i("PagerAdapter","position${position}") return pageList[position] } override fun destroyItem(container: ViewGroup, position: Int, o: Any) { container.removeView(o as View) } override fun getItemPosition(`object`: Any): Int { // 待研究 if (pageCount > 0) { pageCount-- return POSITION_NONE } return super.getItemPosition(`object`) } override fun notifyDataSetChanged() { pageCount = count super.notifyDataSetChanged() } }
0
Kotlin
0
0
5a58e75503064b0f1f2619ef04b21fec0f9308b9
1,243
habitToDoList
Apache License 2.0
idea/testData/codeInsight/overrideImplement/doNotOverrideFinal.kt
JakeWharton
99,388,807
false
null
open class A { fun a(){} fun b(){} } interface I { fun b() } abstract class B : A() { open fun f(){} abstract fun g() fun h(){} } class C : B(), I { <caret> }
0
null
30
83
4383335168338df9bbbe2a63cb213a68d0858104
190
kotlin
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/cloudfront/DistributionPropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.cloudfront import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.cloudfront.DistributionProps @Generated public fun buildDistributionProps(initializer: @AwsCdkDsl DistributionProps.Builder.() -> Unit): DistributionProps = DistributionProps.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
409
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/dania/productfinder/repository/PlpRepository.kt
daniachan
335,151,127
false
null
package com.dania.productfinder.repository import androidx.lifecycle.LiveData import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton import com.dania.productfinder.AppExecutors import com.dania.productfinder.api.ApiSuccessResponse import com.dania.productfinder.api.StoreService import com.dania.productfinder.api.SearchResponse import com.dania.productfinder.db.StoreDb import com.dania.productfinder.db.ProductDao import com.dania.productfinder.util.RateLimiter import com.dania.productfinder.vo.SearchResult import com.dania.productfinder.vo.Product import com.dania.productfinder.vo.Resource @Singleton //@OpenForTesting class PlpRepository @Inject constructor( private val appExecutors: AppExecutors, private val db: StoreDb, private val productDao: ProductDao, private val storeService: StoreService ) { private val repoListRateLimit = RateLimiter<String>(15, TimeUnit.MINUTES) fun getAllSugges() : LiveData<List<SearchResult>> { val allSuggest = db.productDao().getAllResults() return allSuggest } fun deleteItem(value: String) { db.productDao().deleteItemResult(value) } fun deleteAllItems() { db.productDao().deleteAllItems() } fun searchNextPage(search: String): LiveData<Resource<Boolean>> { val fetchNextSearchPageTask = FetchNextSearchPageTask( force = "true", search = search, itemsPerPage = 15, storeService = storeService, db = db ) appExecutors.networkIO().execute(fetchNextSearchPageTask) return fetchNextSearchPageTask.liveData } fun search(search: String): LiveData<Resource<List<Product>>> { return object : NetworkBoundResource<List<Product>, SearchResponse>(appExecutors) { override fun saveCallResult(item: SearchResponse) { val repoIds = item.plpResults.records.map { it.productID } val searchResult = SearchResult( query = search, totalCount = item.plpResults.plpState.totalNumRecs, next = item.plpResults.plpState.firstRecNum ) db.runInTransaction { productDao.insertProducts(item.plpResults.records) productDao.insert(searchResult) } } override fun shouldFetch(data: List<Product>?) = true override fun loadFromDb(): LiveData<List<Product>> { return productDao.load() } override fun cleanFromDb() { runBlocking(Dispatchers.Default) { productDao.deleteAll() } } override fun createCall() = storeService.searchPlp("true",search,1,10 ) override fun processResponse(response: ApiSuccessResponse<SearchResponse>) : SearchResponse { val body = response.body body.nextPage = response.nextPage return body } }.asLiveData() } }
0
Kotlin
0
0
a7cf8399e5c9e73b7ecadadc78b57b20dfae40c4
3,246
ProductFinder
MIT License
data/src/main/java/com/bottlerocketstudios/brarchitecture/data/model/BranchDto.kt
BottleRocketStudios
323,985,026
false
null
package com.bottlerocketstudios.brarchitecture.data.model import android.os.Parcelable import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import kotlinx.parcelize.Parcelize @JsonClass(generateAdapter = true) @Parcelize data class BranchDto( @Json(name = "name") val name: String?, @Json(name = "target") val target: TargetDto? ) : Parcelable, Dto
1
Kotlin
1
9
e3014001732516e9feab58c862e0d84de9911c83
373
Android-ArchitectureDemo
Apache License 2.0
android/engine/src/main/java/org/smartregister/fhircore/engine/data/remote/fhir/resource/FhirResourceService.kt
issyzac
420,960,297
true
{"Kotlin": 1058894}
/* * Copyright 2021 Ona Systems, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.smartregister.fhircore.engine.data.remote.fhir.resource import android.app.Application import ca.uhn.fhir.parser.IParser import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.logging.HttpLoggingInterceptor import org.hl7.fhir.r4.model.Bundle import org.hl7.fhir.r4.model.OperationOutcome import org.hl7.fhir.r4.model.Resource import org.smartregister.fhircore.engine.configuration.app.ConfigurableApplication import org.smartregister.fhircore.engine.data.remote.shared.interceptor.OAuthInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.PATCH import retrofit2.http.PUT import retrofit2.http.Path import retrofit2.http.Url /** [Retrofit] Service for communication with HAPI FHIR server. Used for querying FHIR Resources */ interface FhirResourceService { @GET suspend fun getResource(@Url url: String): Bundle @PUT("{type}/{id}") suspend fun insertResource( @Path("type") type: String, @Path("id") id: String, @Body body: RequestBody ): Resource @PATCH("{type}/{id}") suspend fun updateResource( @Path("type") type: String, @Path("id") id: String, @Body body: RequestBody ): OperationOutcome @DELETE("{type}/{id}") suspend fun deleteResource(@Path("type") type: String, @Path("id") id: String): OperationOutcome companion object { fun create(parser: IParser, application: Application): FhirResourceService { val logger = HttpLoggingInterceptor() logger.level = HttpLoggingInterceptor.Level.BODY val oauthInterceptor = OAuthInterceptor(application) val client = OkHttpClient.Builder().addInterceptor(oauthInterceptor).addInterceptor(logger).build() val applicationConfiguration = (application as ConfigurableApplication).applicationConfiguration return Retrofit.Builder() .baseUrl(applicationConfiguration.fhirServerBaseUrl) .client(client) .addConverterFactory(FhirConverterFactory(parser)) .addConverterFactory(GsonConverterFactory.create()) .build() .create(FhirResourceService::class.java) } } }
0
null
0
0
c4eb29dc58e6232dcee2431a77e082af7ed60421
2,835
fhircore
Apache License 2.0
data/src/main/java/com/andriawan/data/di/LocalModule.kt
andriawan24
491,750,250
false
{"Kotlin": 96002}
package com.andriawan.data.di import android.content.Context import androidx.room.Room import com.andriawan.common.Constants import com.andriawan.data.local.TemplateDatabase import com.andriawan.data.local.dao.GamesDAO import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object LocalModule { @Provides @Singleton fun providesDatabase( @ApplicationContext context: Context ): TemplateDatabase { return Room.databaseBuilder( context, TemplateDatabase::class.java, Constants.DATABASE_NAME ).build() } @Provides @Singleton fun providesGameDao(database: TemplateDatabase): GamesDAO { return database.gamesDao() } }
0
Kotlin
0
0
6459a6ecffd3835fb153db8a1b1cde577e598861
920
android-starter-template
MIT License
core/data/remote/src/main/java/com/fappslab/core/data/remote/network/HttpClient.kt
F4bioo
708,171,476
false
{"Kotlin": 210973}
package com.fappslab.core.data.remote.network interface HttpClient { fun <T> create(clazz: Class<T>): T }
0
Kotlin
0
1
104d22a398cc98a9f229c69a5e75273bca346c42
111
TMDBCompose
MIT License
app/src/main/java/com/homebooking/ui/home/houses/Rating.kt
MateeDevs
355,563,624
false
null
package com.homebooking.ui.home.houses import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.requiredSize import androidx.compose.material.Icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Star import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @Composable fun Rating(value: Int, modifier: Modifier = Modifier) { val starColor = Color(0xFFFFA235) Row(modifier) { repeat(5) { position -> Icon( Icons.Rounded.Star, "", tint = starColor, modifier = Modifier .requiredSize(22.dp) .alpha(if (position + 1 > value) 0.3f else 1f), ) } } }
0
Kotlin
1
0
886f9486523b1eaeda26e1ef9f6fe88175becc10
915
article-compose-basics-and
MIT License
idea/idea-completion/testData/handlers/keywords/ReturnInUnit.kt
JakeWharton
99,388,807
false
null
// ELEMENT: return object OtherTest { fun test() : Unit { retur<caret> } }
1
null
30
83
4383335168338df9bbbe2a63cb213a68d0858104
91
kotlin
Apache License 2.0
src/backend/nuget/api-nuget/src/main/kotlin/com/tencent/bkrepo/nuget/constant/NugetMessageCode.kt
TencentBlueKing
548,243,758
false
{"Kotlin": 13715127, "Vue": 1261493, "JavaScript": 683823, "Shell": 124343, "Lua": 101021, "SCSS": 34137, "Python": 25877, "CSS": 17382, "HTML": 13052, "Dockerfile": 4483, "Smarty": 3661, "Java": 423}
package com.tencent.bkrepo.nuget.constant import com.tencent.bkrepo.common.api.message.MessageCode enum class NugetMessageCode(private val key: String) : MessageCode { PACKAGE_CONTENT_INVALID("nuget.package.content.invalid"), VERSION_EXISTED("nuget.version.existed"), PACKAGE_VERSIONS_NOT_EXISTED("nuget.versions.not.existed"), PACKAGE_METADATA_LIST_NOT_FOUND("nuget.metadata.list.not.fount"), RESOURCE_FEED_NOT_FOUND("resource.feed.not.found") ; override fun getBusinessCode() = ordinal + 1 override fun getKey() = key override fun getModuleCode() = 11 }
383
Kotlin
38
70
817363204d5cb57fcd6d0cb520210fa7b33cd5d6
595
bk-repo
MIT License
buildSrc/src/main/kotlin/Configuration.kt
ThibaultBee
210,187,413
false
{"Kotlin": 254665, "C++": 113612, "CMake": 4052, "C": 3870}
object AndroidVersions { const val MIN_SDK = 19 const val TARGET_SDK = 34 const val COMPILE_SDK = 34 } object Publication { object Repository { val username: String? get() = Property.get(Property.SonatypeUsername) val password: String? get() = Property.get(Property.SonatypePassword) } object Pom { const val PACKAGING = "aar" const val URL = "https://github.com/ThibaultBee/srtdroid" object Scm { const val CONNECTION = "scm:git:git://github.com/ThibaultBee/srtdroid.git" const val DEVELOPER_CONNECTION = "scm:git:ssh://github.com/ThibaultBee/srtdroid.git" const val URL = "https://github.com/ThibaultBee/srtdroid" } object License { const val NAME = "Apache License, Version 2.0" const val URL = "https://www.apache.org/licenses/LICENSE-2.0.txt" const val DISTRIBUTION = "repo" } object Developer { const val URL = "https://github.com/ThibaultBee" const val NAME = "<NAME> } } object Signing { val hasKey: Boolean get() = key != null && keyId != null && password != null val key: String? get() = Property.get(Property.GpgKey) val password: String? get() = Property.get(Property.GpgPassword) val keyId: String? get() = Property.get(Property.GpgKeyId) } }
0
Kotlin
31
93
f6703268304f3416d1b6e79efbf06b4bdad47360
1,494
srtdroid
Apache License 2.0
video-editor/src/main/java/com/video/trimmer/view/TimeLineView.kt
tinybeanskids
275,830,814
false
null
package com.video.trimmer.view import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.media.MediaMetadataRetriever import android.net.Uri import android.util.AttributeSet import android.view.View import com.video.trimmer.R import com.video.trimmer.utils.BackgroundExecutor class TimeLineView @JvmOverloads constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) { private var mVideoUri: Uri? = null private var mHeightView: Int = 0 private var mBitmapList: MutableList<Bitmap> = mutableListOf() private var framesWidthTotal = 0f init { init() } private fun init() { mHeightView = context.resources.getDimensionPixelOffset(R.dimen.frames_video_height) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val minW = paddingLeft + paddingRight + suggestedMinimumWidth val w = resolveSizeAndState(minW, widthMeasureSpec, 1) val minH = paddingBottom + paddingTop + mHeightView val h = resolveSizeAndState(minH, heightMeasureSpec, 1) setMeasuredDimension(w, h) } override fun onSizeChanged(w: Int, h: Int, oldW: Int, oldH: Int) { super.onSizeChanged(w, h, oldW, oldH) if (w != oldW) getBitmap(w) } private fun getBitmap(viewWidth: Int) { BackgroundExecutor.execute(object : BackgroundExecutor.Task("", 0L, "") { override fun execute() { try { val threshold = 11 val mediaMetadataRetriever = MediaMetadataRetriever() mediaMetadataRetriever.setDataSource(context, mVideoUri) val videoLengthInMs = (Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) * 1000).toLong() val frameHeight = mHeightView //val initialBitmap = mediaMetadataRetriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC) val frameWidth = width / 6 // var numThumbs = ceil((viewWidth.toFloat() / frameWidth)).toInt() var numThumbs = 6 // if (numThumbs < threshold) numThumbs = threshold //val cropWidth = viewWidth / threshold var cropWidth = viewWidth / numThumbs val interval = videoLengthInMs / numThumbs for (i in 0 until numThumbs) { var bitmap = mediaMetadataRetriever.getFrameAtTime(i * interval, MediaMetadataRetriever.OPTION_CLOSEST_SYNC) if (bitmap != null) { try { bitmap = Bitmap.createScaledBitmap(bitmap, frameWidth, frameHeight, false) bitmap = Bitmap.createBitmap(bitmap, 0, 0, cropWidth, bitmap.height) mBitmapList.add(bitmap) invalidate() } catch (e: Exception) { e.printStackTrace() } } } mediaMetadataRetriever.release() } catch (e: Throwable) { Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e) } } }) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (!mBitmapList.isNullOrEmpty()) for (i in mBitmapList) { canvas.drawBitmap(i, framesWidthTotal, 0f, null) framesWidthTotal += i.width } framesWidthTotal = 0f } fun setVideo(data: Uri) { mVideoUri = data } }
0
Kotlin
0
0
0c5f1c0904d7bba75ed506f5edd59db3879b9ce6
3,875
VideoTrimmer
MIT License