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/kotlin/me/tmonteiro/kacn/playground/factory/MoshiFactory.kt
TiagoOlivMonteiro
199,861,969
false
null
package me.tmonteiro.kacn.playground.factory import com.squareup.moshi.Moshi object MoshiFactory { fun build(): Moshi { return Moshi.Builder().build() } }
0
Kotlin
0
0
9181da1430ab13b53a493ae7ce2ed3ef4755ce00
173
kotlin-architecture-component-navigation-playground
Apache License 2.0
src/main/kotlin/com/richodemus/test/kafka/aggregation/EventAggregationMain.kt
RichoDemus
105,287,979
false
null
package com.richodemus.test.kafka.aggregation import com.richodemus.test.kafka.StringProducer import org.apache.kafka.clients.consumer.ConsumerConfig import org.apache.kafka.common.serialization.Serdes import org.apache.kafka.streams.KafkaStreams import org.apache.kafka.streams.StreamsBuilder import org.apache.kafka.streams.StreamsConfig import org.apache.kafka.streams.kstream.TimeWindows import java.util.Properties import java.util.UUID import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.LongAdder import kotlin.concurrent.thread /** * ./bin/kafka-topics.sh --zookeeper localhost:2181 --create --topic events --replication-factor 1 --partitions 1 */ fun main(args: Array<String>) { val topic = "events" val config = Properties() config.put(StreamsConfig.APPLICATION_ID_CONFIG, "aggregate-test-${UUID.randomUUID()}") config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092") config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().javaClass) config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().javaClass) config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest") val totalNumberOfMessages = LongAdder() val gameroundMessages = LongAdder() val mergedMessages = LongAdder() val builder = StreamsBuilder() val events = builder.stream<String, String>(topic) events .peek { _, _ -> totalNumberOfMessages.increment() } .groupBy { _, value -> value.split(",")[0] } .windowedBy(TimeWindows.of(TimeUnit.DAYS.toMillis(1))) .aggregate({ "" }, { _, value, aggregate -> aggregate + value.split(",")[1] }) .toStream() .peek { _, _ -> mergedMessages.increment() } // .filter { _, value -> value.length > 2 } .foreach { key, value -> println("\nResult: ${key.key()}: $value") } // in reality we want to write it to a new topic, use .to to do that thread(isDaemon = true) { while (true) { if (mergedMessages.toLong() > 0) println("$totalNumberOfMessages messages, $gameroundMessages gameround messages, $mergedMessages merged, ${gameroundMessages.toDouble() / mergedMessages.toDouble()} ratio") else print(".") Thread.sleep(1000L) } } val streams = KafkaStreams(builder.build(), config) streams.start() Runtime.getRuntime().addShutdownHook(Thread(streams::close)) Thread.sleep(2000L) val firstId = UUID.randomUUID() StringProducer(topic).use { producer -> val secondId = UUID.randomUUID() val thirdId = UUID.randomUUID() producer.send("$secondId,h") producer.send("$firstId,h") producer.send("$firstId,e") producer.send("$firstId,l") producer.send("$thirdId,h") producer.send("$firstId,l") producer.send("$firstId,o") producer.send("$thirdId,o") producer.send("$secondId,i") } System.`in`.read() StringProducer(topic).use { producer -> producer.send("$firstId,!") } println("pong") System.`in`.read() streams.close() }
0
Kotlin
0
0
edf5ecbd4d874eebc2d5f91dbbe6928f2292214b
3,208
kafka-test
Apache License 2.0
android/app/src/main/java/com/example/togglutopia/data/model/Meta.kt
simonrozsival
226,355,253
false
null
package com.example.togglutopia.data.model data class Meta( val error: Boolean, val processing_request_took_ms: Int, val utc_server_time: String )
0
Rust
0
1
23a7ee33ae4d4237c97fe8c84470608676f1e222
159
toggl-utopia
MIT License
app/src/main/java/com/ikuzMirel/flick/domain/model/UserInfo.kt
IkuzItsuki
564,666,943
false
null
package com.ikuzMirel.flick.domain.model //Unused data class UserInfo( val username: String, val email: String, val id: String )
0
Kotlin
1
2
6dd85fb6a95fff25f4cd2e1cc7d9a9853b856f5f
142
FLICK
Apache License 2.0
app/src/main/java/com/breezeyellowbird/features/mylearning/apiCall/LMSApi.kt
DebashisINT
845,387,138
false
{"Kotlin": 15649699, "Java": 1026496}
package com.breezeyellowbird.features.mylearning.apiCall import com.breezeyellowbird.app.NetworkConstant import com.breezeyellowbird.base.BaseResponse import com.breezeyellowbird.features.addshop.model.AddQuestionSubmitRequestData import com.breezeyellowbird.features.login.api.opportunity.OpportunityListApi import com.breezeyellowbird.features.login.model.opportunitymodel.OpportunityStatusListResponseModel import com.breezeyellowbird.features.mylearning.CONTENT_WISE_QA_SAVE import com.breezeyellowbird.features.mylearning.ContentCountSave_Data import com.breezeyellowbird.features.mylearning.LMS_CONTENT_INFO import com.breezeyellowbird.features.mylearning.MyCommentListResponse import com.breezeyellowbird.features.mylearning.MyLarningListResponse import com.breezeyellowbird.features.mylearning.TopicListResponse import com.breezeyellowbird.features.mylearning.VideoTopicWiseResponse import io.reactivex.Observable import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST interface LMSApi { @FormUrlEncoded @POST("LMSInfoDetails/TopicLists") fun getTopics(@Field("user_id") user_id: String): Observable<TopicListResponse> @FormUrlEncoded @POST("LMSInfoDetails/TopicWiseLists") fun getTopicswiseVideoApi(@Field("user_id") user_id: String,@Field("topic_id") topic_id: String): Observable<VideoTopicWiseResponse> @POST("LMSInfoDetails/TopicContentDetailsSave") fun saveContentInfoApi(@Body lms_content_info: LMS_CONTENT_INFO?): Observable<BaseResponse> @FormUrlEncoded @POST("LMSInfoDetails/LearningContentLists") fun getMyLearningContentList(@Field("user_id") user_id: String): Observable<MyLarningListResponse> @FormUrlEncoded @POST("LMSInfoDetails/CommentLists") fun getCommentInfo(@Field("topic_id") topic_id: String , @Field("content_id") content_id: String): Observable<MyCommentListResponse> @POST("LMSInfoDetails/TopicContentWiseQASave") fun saveContentWiseQAApi(@Body mCONTENT_WISE_QA_SAVE: CONTENT_WISE_QA_SAVE): Observable<BaseResponse> @POST("LMSInfoDetails/ContentCountSave") fun saveContentCount(@Body mContentCountSave_Data: ContentCountSave_Data): Observable<BaseResponse> companion object Factory { fun create(): LMSApi { val retrofit = Retrofit.Builder() .client(NetworkConstant.setTimeOut()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(NetworkConstant.BASE_URL) .build() return retrofit.create(LMSApi::class.java) } } }
0
Kotlin
0
0
1e7cfe8e921e01b9411b1e8ee3c8b5b65d1c734c
2,829
YellowBird
Apache License 2.0
plugins/kotlin/idea/tests/testData/intentions/removeSingleArgumentName/range.kt
ingokegel
72,937,917
true
null
// AFTER-WARNING: Parameter 'b' is never used // AFTER-WARNING: Parameter 's' is never used fun foo(s: String, b: Boolean){} fun bar() { foo("", b = <caret>true) }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
168
intellij-community
Apache License 2.0
app/src/main/java/tech/bitcube/template/data/network/response/user/UserRegisterRequestDto.kt
RubenBez
223,260,073
false
null
package tech.bitcube.template.data.network.response.user data class UserRegisterRequestDto( val email: String, val password: String )
0
Kotlin
0
1
04736c77754b99f6e88799f92e149187b5957f75
142
android-template
MIT License
src/main/kotlin/utils/SetupRoles.kt
cracked-unc-club
853,847,314
false
{"Kotlin": 11918, "Dockerfile": 313}
package com.beradeep.utils import com.beradeep.constants.Constants.nameToColor import com.beradeep.constants.Constants.techRolesMap import com.beradeep.guild import kotlinx.coroutines.flow.toSet suspend fun setupRoles() { nameToColor.forEach { (name, color) -> if (guild.roles.toSet().none { it.name == name }) { createRole(guild, name, color) } } println("Color roles created") techRolesMap.values.forEach { roleName -> if (guild.roles.toSet().none { it.name == roleName }) { createRole(guild, roleName) } } println("Tech roles created") }
0
Kotlin
0
0
54510ec4d69420d40ee325caf0707c79b6a4b814
622
unccord-bot-kt
MIT License
gto-support-androidx-viewpager2/src/main/java/org/ccci/gto/android/common/androidx/viewpager2/widget/ViewPager2Utils.kt
CruGlobal
30,609,844
false
{"Gradle Kotlin DSL": 70, "Java Properties": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Proguard": 16, "EditorConfig": 1, "Text": 1, "Markdown": 1, "INI": 16, "Kotlin": 523, "Java": 74, "XML": 22, "TOML": 1, "Prolog": 1, "YAML": 4, "JSON": 1}
package org.ccci.gto.android.common.androidx.viewpager2.widget import android.view.ViewGroup import androidx.viewpager2.widget.ViewPager2 import androidx.viewpager2.widget.recyclerView fun ViewPager2.setHeightWrapContent() { with(recyclerView) { // update nested RecyclerView to have a wrap_content height layoutParams = layoutParams.apply { height = ViewGroup.LayoutParams.WRAP_CONTENT } // remove restriction that children should have match_parent for height and width // source: https://gist.github.com/safaorhan/1a541af729c7657426138d18b87d5bd4 clearOnChildAttachStateChangeListeners() } }
5
Kotlin
2
9
7506718d83c532edbdf84921338a26d86422bec6
645
android-gto-support
MIT License
app/src/main/java/com/github/v43d3rm4k4r/besthotels/domain/contracts/HotelsFetcher.kt
v43d3rm4k4r
624,895,645
false
null
package com.github.v43d3rm4k4r.besthotels.domain.contracts import android.graphics.Bitmap import com.github.v43d3rm4k4r.besthotels.data.models.Hotel import com.github.v43d3rm4k4r.besthotels.data.models.HotelDetailed import retrofit2.Response interface HotelsFetcher { suspend fun fetchHotelsList(): List<Hotel>? suspend fun fetchHotelDetails(id: Int): HotelDetailed? suspend fun fetchHotelImageBytes(imageName: String): Bitmap? }
0
Kotlin
0
0
06181d6a94e5580b683251f0138d92450c27b534
446
BestHotels
Apache License 2.0
app/src/main/java/com/pnuema/android/githubprviewer/diffviewer/viewmodel/DiffViewModel.kt
barnhill
185,720,710
false
{"Kotlin": 82327}
package com.pnuema.android.githubprviewer.diffviewer.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.ViewModel import com.pnuema.android.githubprviewer.diffviewer.repository.DiffRepository import com.pnuema.android.githubprviewer.pullrequests.ui.model.PullModel class DiffViewModel(val diffMetaData: PullModel): ViewModel() { val diffFile: LiveData<String> = MediatorLiveData() private val diffRepository: DiffRepository = DiffRepository() /** * Get diff file from the url provided */ fun getDiffFile() { val source = diffRepository.getDiffFile(diffMetaData.diffUrl) (diffFile as MediatorLiveData).addSource(source) { diffFile.postValue(it) diffFile.removeSource(source) } } }
0
Kotlin
0
0
1a7d6c960c71a000abb548d8c9048fcf32ec63c9
823
GithubPRViewer
Apache License 2.0
testapi/src/commonMain/kotlin/pers/shawxingkwok/center/api/WebSocketApi.kt
ShawxingKwok
702,423,277
false
{"Kotlin": 122297}
package pers.shawxingkwok.center.api import pers.shawxingkwok.phone.Phone @Phone.Api interface WebSocketApi { @Phone.Kind.WebSocket suspend fun getSignals(i: Int): Any? @Phone.Method.Post @Phone.Kind.WebSocket(true) suspend fun getChats(id: String?): Any? }
0
Kotlin
0
0
402c4c6c351bb743736a6fb50724a177be6dc95e
280
Phone
Apache License 2.0
MzaziConnectApplication/app/src/main/java/sakigake/mzaziconnect/mzaziconnectapplication/viewmodel/ShopsViewModel.kt
Florence-nyokabi
721,515,801
false
{"Kotlin": 146726}
package sakigake.mzaziconnect.mzaziconnectapplication.viewmodel import android.annotation.SuppressLint import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import sakigake.mzaziconnect.mzaziconnectapplication.model.Shops import sakigake.mzaziconnect.mzaziconnectapplication.repository.ShopRepository class ShopsViewModel:ViewModel() { var shopRepo = ShopRepository() val shopLiveData = MutableLiveData<List<Shops>>() val errorLiveData = MutableLiveData<String>() @SuppressLint("SuspiciousIndentation") fun fetchShops(){ viewModelScope.launch { val response = shopRepo.getShops() if (response.isSuccessful){ val shopLists =response.body()?: emptyList() shopLiveData.postValue(shopLists as List<Shops>) } else{ errorLiveData.postValue(response.errorBody()?.string()) } } } }
0
Kotlin
0
0
e4c7c167efb9b1373f2ecf231fd126ab6ff9675b
1,021
Sakigake-mobile
MIT License
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/Reorder.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36756847}
package compose.icons.cssggicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.CssGgIcons public val CssGgIcons.Reorder: ImageVector get() { if (_reorder != null) { return _reorder!! } _reorder = Builder(name = "Reorder", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 4.0f) curveTo(3.0f, 3.4477f, 3.4477f, 3.0f, 4.0f, 3.0f) horizontalLineTo(12.0f) curveTo(12.5523f, 3.0f, 13.0f, 3.4477f, 13.0f, 4.0f) curveTo(13.0f, 4.5523f, 12.5523f, 5.0f, 12.0f, 5.0f) horizontalLineTo(4.0f) curveTo(3.4477f, 5.0f, 3.0f, 4.5523f, 3.0f, 4.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 12.0f) curveTo(3.0f, 11.4477f, 3.4477f, 11.0f, 4.0f, 11.0f) horizontalLineTo(12.0f) curveTo(12.5523f, 11.0f, 13.0f, 11.4477f, 13.0f, 12.0f) curveTo(13.0f, 12.5523f, 12.5523f, 13.0f, 12.0f, 13.0f) horizontalLineTo(4.0f) curveTo(3.4477f, 13.0f, 3.0f, 12.5523f, 3.0f, 12.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 16.0f) curveTo(3.0f, 15.4477f, 3.4477f, 15.0f, 4.0f, 15.0f) horizontalLineTo(12.0f) curveTo(12.5523f, 15.0f, 13.0f, 15.4477f, 13.0f, 16.0f) curveTo(13.0f, 16.5523f, 12.5523f, 17.0f, 12.0f, 17.0f) horizontalLineTo(4.0f) curveTo(3.4477f, 17.0f, 3.0f, 16.5523f, 3.0f, 16.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 20.0f) curveTo(3.0f, 19.4477f, 3.4477f, 19.0f, 4.0f, 19.0f) horizontalLineTo(12.0f) curveTo(12.5523f, 19.0f, 13.0f, 19.4477f, 13.0f, 20.0f) curveTo(13.0f, 20.5523f, 12.5523f, 21.0f, 12.0f, 21.0f) horizontalLineTo(4.0f) curveTo(3.4477f, 21.0f, 3.0f, 20.5523f, 3.0f, 20.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(15.1707f, 9.0f) curveTo(15.5825f, 10.1652f, 16.6938f, 11.0f, 18.0f, 11.0f) curveTo(19.6569f, 11.0f, 21.0f, 9.6568f, 21.0f, 8.0f) curveTo(21.0f, 6.3432f, 19.6569f, 5.0f, 18.0f, 5.0f) curveTo(16.6938f, 5.0f, 15.5825f, 5.8348f, 15.1707f, 7.0f) horizontalLineTo(4.0f) curveTo(3.4477f, 7.0f, 3.0f, 7.4477f, 3.0f, 8.0f) curveTo(3.0f, 8.5523f, 3.4477f, 9.0f, 4.0f, 9.0f) horizontalLineTo(15.1707f) close() moveTo(19.0f, 8.0f) curveTo(19.0f, 8.5523f, 18.5523f, 9.0f, 18.0f, 9.0f) curveTo(17.4477f, 9.0f, 17.0f, 8.5523f, 17.0f, 8.0f) curveTo(17.0f, 7.4477f, 17.4477f, 7.0f, 18.0f, 7.0f) curveTo(18.5523f, 7.0f, 19.0f, 7.4477f, 19.0f, 8.0f) close() } } .build() return _reorder!! } private var _reorder: ImageVector? = null
15
Kotlin
20
460
651badc4ace0137c5541f859f61ffa91e5242b83
5,016
compose-icons
MIT License
libraries/arch/src/main/java/com/fappslab/mbchallenge/libraries/arch/extension/ContextExtension.kt
F4bioo
845,138,188
false
{"Kotlin": 242545}
package com.fappslab.mbchallenge.libraries.arch.extension import android.content.Context import android.content.Intent import android.net.Uri fun Context.openBrowser(url: String) { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(url) startActivity(intent) }
0
Kotlin
0
0
d81eff4b566578b5dc8596b7cbfcfb2e12e652b6
288
MBChallenge
MIT License
ui/src/androidMain/kotlin/kiwi/orbit/compose/ui/controls/SeatLegend.kt
kiwicom
289,355,053
false
null
package kiwi.orbit.compose.ui.controls import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import kiwi.orbit.compose.ui.OrbitTheme import kiwi.orbit.compose.ui.controls.internal.OrbitPreviews import kiwi.orbit.compose.ui.controls.internal.Preview import kiwi.orbit.compose.ui.foundation.ContentEmphasis import kiwi.orbit.compose.ui.foundation.LocalContentEmphasis import kiwi.orbit.compose.ui.foundation.LocalTextStyle @Composable public fun SeatLegendExtraLegroom( modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit, ) { SeatLegend( color = OrbitTheme.colors.info.normal.copy(alpha = 0.2f), // custom, missing theme color content = content, modifier = modifier, ) } @Composable public fun SeatLegendStandard( modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit, ) { SeatLegend( color = OrbitTheme.colors.primary.normal.copy(alpha = 0.2f), // custom, missing theme color content = content, modifier = modifier, ) } @Composable public fun SeatLegendUnavailable( modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit, ) { SeatLegend( color = OrbitTheme.colors.surface.strong.copy(alpha = 0.6f), // custom, missing theme color content = content, modifier = modifier, ) } @Composable private fun SeatLegend( color: Color, content: @Composable RowScope.() -> Unit, modifier: Modifier = Modifier, ) { Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically, ) { SeatLegendIcon(color) CompositionLocalProvider( LocalContentEmphasis provides ContentEmphasis.Minor, LocalTextStyle provides OrbitTheme.typography.bodyNormal, ) { content() } } } @Composable private fun SeatLegendIcon( color: Color, ) { Box( modifier = Modifier .padding(end = 8.dp) .width(16.dp) .height(20.dp) .clip( RoundedCornerShape( topStart = SeatTopRadius, topEnd = SeatTopRadius, bottomStart = SeatBottomRadius, bottomEnd = SeatBottomRadius, ), ) .background(color), ) } // Top radius of the legend icon private val SeatTopRadius = 3.dp // Bottom radius of the legend icon private val SeatBottomRadius = 1.dp @OrbitPreviews @Composable internal fun SeatLegendPreview() { Preview { SeatLegendStandard { Text("Standard") } SeatLegendExtraLegroom { Text("Extra Legroom") } SeatLegendUnavailable { Text("Unavailable") } } }
19
null
9
97
6d4026eef9fa059388c50cd9e9760d593c3ad6ac
3,365
orbit-compose
MIT License
mobile/src/main/java/ch/epfl/sdp/mobile/application/chess/engine/rules/AttackTowardsRules.kt
epfl-SDP
462,385,783
false
null
package ch.epfl.sdp.mobile.application.chess.engine.rules import ch.epfl.sdp.mobile.application.chess.engine.Color import ch.epfl.sdp.mobile.application.chess.engine.Delta import ch.epfl.sdp.mobile.application.chess.engine.Position /** * An implementation of [Rules] which attacks and moves towards a [List] of possible directions. * * @property directions the [List] of possible directions. */ abstract class AttackTowardsRules(private val directions: List<Delta>) : Rules { override fun AttackScope.attacks(color: Color, position: Position) { for (direction in directions) { attackTowards(direction, color, position) } } override fun ActionScope.actions(color: Color, position: Position) = likeAttacks(color, position) }
15
Kotlin
3
13
71f6e2a5978087205b35f82e89ed4005902d697e
751
android
MIT License
mobile/src/main/java/ch/epfl/sdp/mobile/application/chess/engine/rules/AttackTowardsRules.kt
epfl-SDP
462,385,783
false
null
package ch.epfl.sdp.mobile.application.chess.engine.rules import ch.epfl.sdp.mobile.application.chess.engine.Color import ch.epfl.sdp.mobile.application.chess.engine.Delta import ch.epfl.sdp.mobile.application.chess.engine.Position /** * An implementation of [Rules] which attacks and moves towards a [List] of possible directions. * * @property directions the [List] of possible directions. */ abstract class AttackTowardsRules(private val directions: List<Delta>) : Rules { override fun AttackScope.attacks(color: Color, position: Position) { for (direction in directions) { attackTowards(direction, color, position) } } override fun ActionScope.actions(color: Color, position: Position) = likeAttacks(color, position) }
15
Kotlin
3
13
71f6e2a5978087205b35f82e89ed4005902d697e
751
android
MIT License
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/small/FactorySmall.kt
SchweizerischeBundesbahnen
853,290,161
false
{"Kotlin": 6728512}
package ch.sbb.compose_mds.sbbicons.small import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import ch.sbb.compose_mds.sbbicons.SmallGroup public val SmallGroup.FactorySmall: ImageVector get() { if (_factorySmall != null) { return _factorySmall!! } _factorySmall = Builder(name = "FactorySmall", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(3.5f, 3.5f) horizontalLineToRelative(5.0f) verticalLineTo(11.0f) lineToRelative(3.2f, -2.4f) lineToRelative(0.8f, -0.6f) verticalLineToRelative(3.0f) lineToRelative(3.2f, -2.4f) lineToRelative(0.8f, -0.6f) verticalLineToRelative(3.0f) lineToRelative(3.2f, -2.4f) lineToRelative(0.8f, -0.6f) verticalLineToRelative(12.5f) horizontalLineToRelative(-17.0f) verticalLineToRelative(-17.0f) moveToRelative(1.0f, 1.0f) verticalLineToRelative(15.0f) horizontalLineToRelative(15.0f) verticalLineTo(10.0f) lineToRelative(-3.2f, 2.4f) lineToRelative(-0.8f, 0.6f) verticalLineToRelative(-3.0f) lineToRelative(-3.2f, 2.4f) lineToRelative(-0.8f, 0.6f) verticalLineToRelative(-3.0f) lineToRelative(-3.2f, 2.4f) lineToRelative(-0.8f, 0.6f) verticalLineTo(4.5f) close() } } .build() return _factorySmall!! } private var _factorySmall: ImageVector? = null
0
Kotlin
0
1
090a66a40e1e5a44d4da6209659287a68cae835d
2,452
mds-android-compose
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/DesktopSignal.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.DesktopSignal: ImageVector get() { if (_desktopSignal != null) { return _desktopSignal!! } _desktopSignal = fluentIcon(name = "Regular.DesktopSignal") { fluentPath { moveTo(15.0f, 1.5f) curveToRelative(-0.18f, 0.0f, -0.37f, 0.0f, -0.55f, 0.02f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f) curveTo(14.7f, 3.0f, 14.85f, 3.0f, 15.0f, 3.0f) arcToRelative(7.0f, 7.0f, 0.0f, false, true, 6.99f, 7.45f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.5f, 0.1f) lineToRelative(0.01f, -0.55f) curveToRelative(0.0f, -4.7f, -3.8f, -8.5f, -8.5f, -8.5f) close() moveTo(15.0f, 4.0f) curveToRelative(-0.2f, 0.0f, -0.38f, 0.0f, -0.57f, 0.03f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.14f, 1.49f) lineTo(15.0f, 5.5f) arcToRelative(4.5f, 4.5f, 0.0f, false, true, 4.48f, 4.93f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.5f, 0.14f) lineTo(21.0f, 10.0f) arcToRelative(6.0f, 6.0f, 0.0f, false, false, -6.0f, -6.0f) close() moveTo(15.0f, 6.5f) curveToRelative(-0.22f, 0.0f, -0.43f, 0.02f, -0.64f, 0.06f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.28f, 1.47f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.33f, 2.33f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.47f, 0.28f) arcTo(3.51f, 3.51f, 0.0f, false, false, 15.0f, 6.5f) close() moveTo(12.91f, 3.0f) lineTo(4.1f, 3.0f) arcTo(2.25f, 2.25f, 0.0f, false, false, 2.0f, 5.26f) verticalLineToRelative(10.66f) arcTo(2.25f, 2.25f, 0.0f, false, false, 4.26f, 18.0f) lineTo(8.5f, 18.0f) verticalLineToRelative(2.49f) lineTo(6.65f, 20.49f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f) horizontalLineToRelative(10.6f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.1f, -1.5f) lineTo(15.5f, 20.49f) lineTo(15.5f, 18.0f) horizontalLineToRelative(4.4f) arcToRelative(2.25f, 2.25f, 0.0f, false, false, 2.1f, -2.25f) lineTo(22.0f, 12.1f) curveToRelative(-0.2f, -0.1f, -0.37f, -0.22f, -0.52f, -0.37f) curveToRelative(-0.26f, 0.27f, -0.6f, 0.45f, -0.98f, 0.51f) verticalLineToRelative(3.62f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.75f, 0.65f) lineTo(4.15f, 16.51f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.65f, -0.75f) lineTo(3.5f, 5.15f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.65f) horizontalLineToRelative(8.52f) curveToRelative(0.06f, -0.38f, 0.24f, -0.72f, 0.5f, -0.98f) arcToRelative(1.75f, 1.75f, 0.0f, false, true, -0.36f, -0.52f) close() moveTo(14.0f, 18.0f) verticalLineToRelative(2.5f) horizontalLineToRelative(-4.0f) lineTo(10.0f, 18.0f) horizontalLineToRelative(4.0f) close() moveTo(16.0f, 10.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 2.0f, 0.0f) close() } } return _desktopSignal!! } private var _desktopSignal: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
4,070
compose-fluent-ui
Apache License 2.0
mobile-ui/src/main/java/org/dukecon/android/ui/features/networking/NetworkOfflineChecker.kt
Ary265
133,940,366
true
{"Kotlin": 160795, "Prolog": 293, "Shell": 256}
package org.dukecon.android.ui.features.networking import android.content.Context interface NetworkOfflineChecker { fun enable() fun disable() }
0
Kotlin
0
0
f83189da85ff55cd818018d807900964ea8fae75
157
dukecon_android
Apache License 2.0
src/calls/request/ta/presenter/TaCallRequestPresenter.kt
DiSSCo
517,633,705
false
null
package org.synthesis.calls.request.ta.presenter import org.synthesis.account.UserAccountFinder import org.synthesis.account.UserAccountId import org.synthesis.calls.request.CallRequestId import org.synthesis.calls.request.ta.TaCallRequest import org.synthesis.calls.request.ta.store.TaCallRequestFinder import org.synthesis.formbuilder.DynamicForm import org.synthesis.formbuilder.FieldWithValue import org.synthesis.institution.InstitutionStore class TaCallRequestPresenter( private val taCallRequestFinder: TaCallRequestFinder, private val institutionStore: InstitutionStore, private val userAccountFinder: UserAccountFinder ) { suspend fun find(id: CallRequestId): TaCallRequestResponse? = taCallRequestFinder.find(id)?.mapToDetails() private suspend fun TaCallRequest.mapToDetails(): TaCallRequestResponse { val institutions = content().institutions.values.map { TaCallRequestResponse.Institution( id = it.institutionId().grid.value, name = institutionStore.findById(it.institutionId())?.title() ?: "", status = it.status().name.lowercase(), fieldValues = it.content().mapToFieldValues() ) } val scoring = content().score.values.map { TaCallRequestResponse.Scoring( id = it.id() ) } return TaCallRequestResponse( id = id().uuid, callId = callId().uuid, status = status().name.lowercase(), fieldValues = content().general.mapToFieldValues(), institutions = institutions, scoreFormId = scoring, creatorData = userAccountFinder.find(UserAccountId(authorId().uuid))?.asTaCallRequesterData() ) } private fun DynamicForm.mapToFieldValues() = values .values .map { it.mapToFieldValue() } private fun FieldWithValue.mapToFieldValue() = TaCallRequestResponse.FieldValue( fieldId = field.toString(), value = value ) }
0
Kotlin
0
0
4b6387f85e9b8f006021e3de09e1246fbf13a8b2
2,043
elvis-backend
Apache License 2.0
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/ibmcloud.kt
fkorotkov
84,911,320
false
null
// GENERATED package com.fkorotkov.openshift import io.fabric8.openshift.api.model.IBMCloudPlatformSpec as model_IBMCloudPlatformSpec import io.fabric8.openshift.api.model.IBMCloudPlatformStatus as model_IBMCloudPlatformStatus import io.fabric8.openshift.api.model.PlatformSpec as model_PlatformSpec import io.fabric8.openshift.api.model.PlatformStatus as model_PlatformStatus fun model_PlatformSpec.`ibmcloud`(block: model_IBMCloudPlatformSpec.() -> Unit = {}) { if(this.`ibmcloud` == null) { this.`ibmcloud` = model_IBMCloudPlatformSpec() } this.`ibmcloud`.block() } fun model_PlatformStatus.`ibmcloud`(block: model_IBMCloudPlatformStatus.() -> Unit = {}) { if(this.`ibmcloud` == null) { this.`ibmcloud` = model_IBMCloudPlatformStatus() } this.`ibmcloud`.block() }
4
Kotlin
19
301
fa0b20b5a542cb332430fa85b1035456939a2ca6
797
k8s-kotlin-dsl
MIT License
billMan/src/main/kotlin/categories/CategoriesService.kt
adamWeesner
239,233,558
false
null
package categories import BaseService import auth.UsersService import diff import history.HistoryService import org.jetbrains.exposed.sql.Op import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.SqlExpressionBuilder import org.jetbrains.exposed.sql.leftJoin import org.jetbrains.exposed.sql.statements.UpdateBuilder import shared.billMan.Category class CategoriesService( private val usersService: UsersService, private val historyService: HistoryService ) : BaseService<CategoriesTable, Category>( CategoriesTable ) { override val CategoriesTable.connections get() = this.leftJoin(usersService.table, { ownerId }, { uuid }) override suspend fun update(item: Category, op: SqlExpressionBuilder.() -> Op<Boolean>): Int? { val oldItem = get { table.id eq item.id!! } ?: return null if (item.owner == null) return null oldItem.diff(item).updates(item.owner!!).forEach { historyService.add(it) } return super.update(item, op) } override suspend fun toItem(row: ResultRow) = Category( id = row[table.id], owner = row[table.ownerId]?.let { usersService.toItemRedacted(row) }, name = row[table.name], dateCreated = row[table.dateCreated], dateUpdated = row[table.dateUpdated] ).let { if (it.owner == null) return@let it val history = historyService.getFor<Category>(it.id, it.owner) return@let if (history == null) it else it.copy(history = history) } override fun UpdateBuilder<Int>.toRow(item: Category) { this[table.ownerId] = item.owner?.uuid this[table.name] = item.name } }
1
Kotlin
1
1
a04ad390fe844a7d89db2fa726599c23d3f796f6
1,825
weesnerDevelopment
MIT License
app/src/main/java/app/pokedex/common/data/remote/dto/GenerationVii.kt
tRexBruce
454,233,245
false
null
package app.pokedex.common.data.remote.dto import com.google.gson.annotations.SerializedName data class GenerationVii( val icons: Icons, @SerializedName("ultra-sun-ultra-moon") val ultraSunUltraMoon: UltraSunUltraMoon )
0
Kotlin
0
0
8be5f8681a89ab7b21852b86082944e1fddb31f3
229
Pokedex-App
The Unlicense
app/src/main/java/com/beeper/sms/app/App.kt
stumptownlabs
469,512,754
false
null
package com.beeper.sms.app import android.app.Application import android.util.Log import androidx.work.Configuration import com.beeper.sms.Bridge import com.beeper.sms.extensions.writeTo import timber.log.Timber import java.io.File class App : Application(), Configuration.Provider { override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) Bridge.INSTANCE.init(this) { val config = File(cacheDir, "config.yaml") assets.open("config.yaml").writeTo(config) config.absolutePath } Bridge.INSTANCE.start(this) } override fun getWorkManagerConfiguration(): Configuration = Configuration.Builder() .setMinimumLoggingLevel(if (BuildConfig.DEBUG) Log.DEBUG else Log.INFO) .build() }
0
Kotlin
0
0
2b128bab534c38e6a238e149a701370d9796c2a9
802
beeper-android-sms
Apache License 2.0
jb/src/main/kotlin/review/ReviewDiffRequestProducer.kt
TeamCodeStream
148,423,109
false
null
package com.codestream.review import com.codestream.agentService import com.codestream.protocols.agent.GetReviewContentsParams import com.codestream.protocols.agent.Review import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.requests.DiffRequest import com.intellij.diff.requests.ErrorDiffRequest import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.UserDataHolder import kotlinx.coroutines.runBlocking class ReviewDiffRequestProducer( val project: Project, val review: Review, val repoId: String, val path: String, val checkpoint: Int? ) : DiffRequestProducer { override fun getName(): String = "CodeStream Review" override fun process(context: UserDataHolder, indicator: ProgressIndicator): DiffRequest { var request: DiffRequest? = null val agent = project.agentService ?: return ErrorDiffRequest("Project already disposed") runBlocking { val response = agent.getReviewContents(GetReviewContentsParams(review.id, repoId, path, checkpoint)) val leftContent = createReviewDiffContent( project, response.repoRoot, review.id, checkpoint, repoId, ReviewDiffSide.LEFT, path, // response.leftPath, response.left ?: "" ) val rightContent = createReviewDiffContent( project, response.repoRoot, review.id, checkpoint, repoId, ReviewDiffSide.RIGHT, path, // response.rightPath, response.right ?: "" ) request = SimpleDiffRequest(review.title, leftContent, rightContent, response.leftPath, response.rightPath).also { it.putUserData(REPO_ID, repoId) it.putUserData(PATH, path) it.putUserData(REVIEW_DIFF, true) } } return request ?: ErrorDiffRequest("Something went wrong") } }
21
null
182
930
3989ca8f40ab33312f32887bf390262323676b5e
2,233
codestream
Apache License 2.0
src/main/kotlin/kotlinmud/io/service/RequestService.kt
danielmunro
241,230,796
false
null
package kotlinmud.io.service import kotlinmud.mob.model.PlayerMob import kotlinmud.mob.type.Disposition import kotlinmud.room.model.Room class RequestService(val mob: PlayerMob, val input: String) { val args: List<String> init { val setupArgs: MutableList<String> = mutableListOf() var buffer = "" var isOpen = false var escaped = false input.forEach { if (it == '\'' && !escaped) { if (isOpen) { setupArgs.add(buffer) } buffer = "" isOpen = !isOpen } else if (it == '\\') { escaped = true } else if (it == ' ' && !isOpen && buffer != "") { setupArgs.add(buffer) buffer = "" } else if (isOpen || it != ' ') { buffer += it escaped = false } } if (buffer != "") { setupArgs.add(buffer) } args = setupArgs } fun getRoom(): Room { return mob.room } fun getCommand(): String { return args[0] } fun getSubject(): String { return if (args.size > 1) args[1] else "" } fun getModifier(): String { return if (args.size > 2) args[2] else "" } fun getDisposition(): Disposition { return mob.disposition } }
0
Kotlin
1
9
b7ee0d21ae813990896b1b8c6703da9bd1f1fc5b
1,402
kotlinmud
MIT License
app/src/main/java/com/example/customlayoutflowrowmaxlines/ChipItem.kt
astamato
743,708,059
false
{"Kotlin": 9246}
package com.example.customlayoutflowrowmaxlines import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @Composable fun ChipItem( text: String, modifier: Modifier = Modifier, borderColor: Color = MaterialTheme.colors.primary, backgroundColor: Color = Color.Transparent, borderWidth: Int = 2, onClick: () -> Unit = {} ) { Box( modifier = modifier .background(backgroundColor, RoundedCornerShape(percent = 50)) .padding(8.dp) .border( width = borderWidth.dp, color = borderColor, shape = RoundedCornerShape(percent = 50) ) .clickable { onClick.invoke() } ) { Text( text = text, modifier = Modifier .padding(PaddingValues(vertical = 16.dp, horizontal = 8.dp)), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.body1 ) } }
0
Kotlin
0
0
c06b8ff338e39543d47ec569bfb6e7989bcf566d
1,578
custom-layout-flowrow-maxlines
MIT License
shared/src/commonMain/kotlin/com/presta/customer/ui/components/signAppSettings/SignSettingsComponent.kt
morgan4080
726,765,347
false
{"Kotlin": 2170913, "Swift": 2162, "Ruby": 382, "Shell": 228}
package com.presta.customer.ui.components.signAppSettings import com.presta.customer.ui.components.auth.store.AuthStore import com.presta.customer.ui.components.signAppHome.store.SignHomeStore import kotlinx.coroutines.flow.StateFlow interface SignSettingsComponent { fun onSelected(item: String) val authStore: AuthStore val authState: StateFlow<AuthStore.State> fun onAuthEvent(event: AuthStore.Intent) fun onEvent(event: SignHomeStore.Intent) val sigHomeStore: SignHomeStore val signHomeState: StateFlow<SignHomeStore.State> }
0
Kotlin
0
0
0850928853c87390a97953cfec2d21751904d3a9
560
kmp
Apache License 2.0
app/src/main/java/com/example/todoapp/domain/repositories/TaskRepository.kt
romzc
625,406,807
false
{"Kotlin": 14832}
package com.example.todoapp.domain.repositories import com.example.todoapp.domain.entities.Task interface TaskRepository { suspend fun getTasks(): List<Task> suspend fun createTask(task: Task): Unit suspend fun deleteTask(task: Task): Unit suspend fun updateTask(task: Task): Unit }
0
Kotlin
0
0
eb583c6f7578b6605869f46d8342d8259ec1d4e3
299
mvvm_todo_app
MIT License
app/src/androidTest/java/com/example/my_note/ExampleInstrumentedTest.kt
mahdihassani-dev
628,807,928
false
{"Kotlin": 21592}
package com.example.my_note import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.my_note", appContext.packageName) } }
0
Kotlin
1
2
3c796fd1fdbbd16612f9f0fd87a3f729b14c6584
665
SimpleNoteApp
MIT License
app/jvm/cli/src/main/java/cc/cryptopunks/crypton/format/CliExecute.kt
cryptopunkscc
202,181,919
false
{"Kotlin": 523158, "Shell": 6362}
package cc.cryptopunks.crypton.format import cc.cryptopunks.crypton.cliv2.Cli internal fun Cli.Execute.format(indent: String = INDENT): String = when (this) { is Cli.Commands -> "\n" + format(indent) is Cli.Command.Template -> format(indent) else -> toString() } private fun Cli.Commands.format(indent: String = INDENT): String = "\n" + (if (description == null) "" else "- $description\n\n") + (keyMap + matcherMap).map { (key: Any, value: Cli.Execute) -> "$indent$key ${value.format("$indent$INDENT")}" }.joinToString("\n") private const val INDENT = " " private fun Cli.Command.Template.format(indent: String = ""): String = (if (description == null) "" else "- $description") + params.format(indent) + "\n" private fun List<Cli.Param>.format(indent: String = ""): String = joinToString("") { it.format(indent) } fun Cli.Params.format() = list.format() fun Cli.Param.format(indent: String = "") = when (val type = type) { is Cli.Param.Type.Config -> ":${type.key}" is Cli.Param.Type.Positional -> "<$name>" is Cli.Param.Type.Named -> "${type.name}=<$name>" is Cli.Param.Type.Text -> "<$name...>" is Cli.Param.Type.Option -> type.on + if (type.off == null) "" else "|${type.off}" else -> null }?.let { param -> "\n$indent$param" + (description?.let { " - $it" } ?: "") } ?: ""
9
Kotlin
2
7
33dc96367c3a4eb869800b6a0ac84f302bd68502
1,346
crypton
MIT License
app/src/main/java/com/aowen/monolith/data/MatchDto.kt
heatcreep
677,508,642
false
{"Kotlin": 650523}
package com.aowen.monolith.data import com.google.gson.annotations.SerializedName data class MatchPlayerDto( val id: String, @SerializedName("display_name") val displayName: String, @SerializedName("is_ranked") val isRanked: Boolean, val mmr: Any?, @SerializedName("mmr_change") val mmrChange: Float, @SerializedName("rank_image") val rankImage: String?, val team: String, @SerializedName("hero_id") val heroId: Int, val role: String?, @SerializedName("performance_score") val performanceScore: Double, @SerializedName("performance_title") val performanceTitle: String, @SerializedName("minions_killed") val minionsKilled: Int, @SerializedName("lane_minions_killed") val laneMinionsKilled: Int, @SerializedName("neutral_minions_killed") val neutralMinionsKilled: Int, @SerializedName("neutral_minions_team_jungle") val neutralMinionsTeamJungle: Int, @SerializedName("neutral_minions_enemy_jungle") val neutralMinionsEnemyJungle: Int, val kills: Float, val deaths: Float, val assists: Float, @SerializedName("largest_killing_spree") val largestKillingSpree: Int, @SerializedName("largest_multi_kill") val largestMultiKill: Int, @SerializedName("total_damage_dealt") val totalDamageDealt: Int, @SerializedName("physical_damage_dealt") val physicalDamageDealt: Int, @SerializedName("magical_damage_dealt") val magicalDamageDealt: Int, @SerializedName("true_damage_dealt") val trueDamageDealt: Int, @SerializedName("largest_critical_strike") val largestCriticalStrike: Int, @SerializedName("total_damage_dealt_to_heroes") val totalDamageDealtToHeroes: Int, @SerializedName("physical_damage_dealt_to_heroes") val physicalDamageDealtToHeroes: Int, @SerializedName("magical_damage_dealt_to_heroes") val magicalDamageDealtToHeroes: Int, @SerializedName("true_damage_dealt_to_heroes") val trueDamageDealtToHeroes: Int, @SerializedName("total_damage_dealt_to_structures") val totalDamageDealtToStructures: Int, @SerializedName("total_damage_dealt_to_objectives") val totalDamageDealtToObjectives: Int, @SerializedName("total_damage_taken") val totalDamageTaken: Int, @SerializedName("physical_damage_taken") val physicalDamageTaken: Int, @SerializedName("magical_damage_taken") val magicalDamageTaken: Int, @SerializedName("true_damage_taken") val trueDamageTaken: Int, @SerializedName("total_damage_taken_from_heroes") val totalDamageTakenFromHeroes: Int, @SerializedName("physical_damage_taken_from_heroes") val physicalDamageTakenFromHeroes: Int, @SerializedName("magical_damage_taken_from_heroes") val magicalDamageTakenFromHeroes: Int, @SerializedName("true_damage_taken_from_heroes") val trueDamageTakenFromHeroes: Int, @SerializedName("total_damage_mitigated") val totalDamageMitigated: Int, @SerializedName("total_healing_done") val totalHealingDone: Int, @SerializedName("item_healing_done") val itemHealingDone: Int, @SerializedName("crest_healing_done") val crestHealingDone: Int, @SerializedName("utility_healing_done") val utilityHealingDone: Int, @SerializedName("total_shielding_received") val totalShieldingReceived: Int, @SerializedName("wards_placed") val wardsPlaced: Int, @SerializedName("wards_destroyed") val wardsDestroyed: Int, @SerializedName("gold_earned") val goldEarned: Int, @SerializedName("gold_spent") val goldSpent: Int, @SerializedName("inventory_data") val inventoryData: List<Int> ) data class TeamDto( @SerializedName("avg_mmr") val averageMmr: String?, val players: List<MatchPlayerDto> ) data class MatchDto( val id: String, @SerializedName("start_time") val startTime: String, @SerializedName("end_time") val endTime: String, @SerializedName("game_duration") val gameDuration: Int, val region: String, @SerializedName("winning_team") val winningTeam: String, @SerializedName("game_mode") val gameMode: String, val players: List<MatchPlayerDto> ) data class MatchesDto( val matches: List<MatchDto> )
11
Kotlin
0
2
44324f4bdef1e2bf9b0cad925ef7a90d9044d645
4,283
predecessor-monolith
MIT License
buildSrc/src/main/kotlin/Extensions.kt
jerryOkafor
332,439,368
false
{"Kotlin": 93159}
/** * Author: Jerry * Project: FairmoneyTest */ import org.gradle.api.artifacts.dsl.RepositoryHandler import org.gradle.kotlin.dsl.kotlin import org.gradle.plugin.use.PluginDependenciesSpec import org.gradle.plugin.use.PluginDependencySpec /**Apply Maven to a repository*/ fun RepositoryHandler.maven(url: String) { maven { setUrl(url) } } fun RepositoryHandler.applyDefault() { google() jcenter() mavenCentral() maven("https://jitpack.io") maven("https://plugins.gradle.org/m2/") maven("https://dl.bintray.com/kotlin/kotlin-eap") maven("https://oss.sonatype.org/content/repositories/snapshots/") } /**Plugin Extensions*/ //Apply Android val PluginDependenciesSpec.applyAndroidApplication: PluginDependencySpec get() = id("com.android.application") //Apply kotlin val PluginDependenciesSpec.applyKotlinAndroid: PluginDependencySpec get() = kotlin("android") //Apply Library val PluginDependenciesSpec.applyLibrary: PluginDependencySpec get() = id("com.android.library") //Apply Kotlin Library val PluginDependenciesSpec.applyKotlinLibrary: PluginDependencySpec get() = kotlin("library") //Apply dagger hilt val PluginDependenciesSpec.applyDaggerHilt: PluginDependencySpec get() = id("dagger.hilt.android.plugin") //Apply Benchmark val PluginDependenciesSpec.applyBenchmark: PluginDependencySpec get() = id("androidx.benchmark") //Apply nav safe args val PluginDependenciesSpec.applyNavSafeArgs: PluginDependencySpec get() = id("androidx.navigation.safeargs.kotlin") //Apply kotlin kapt plugin val PluginDependenciesSpec.applyKotlinKapt: PluginDependencySpec get() = kotlin("kapt")
0
Kotlin
0
1
5415b992db6d8c2519fddc46006a4c66097a8a75
1,672
fairmoney_test
MIT License
src/main/kotlin/com/github/jaytobi/service/UserService.kt
jayTobi
123,141,173
false
null
package com.github.jaytobi.service import com.github.jaytobi.model.User import java.util.* /** * Service interface for accessing [User]s. */ interface UserService { /** * Search a [User] by its unique id. * @return An Optional containing the possible user. */ fun find(id: Long): Optional<User>? /** * Search for all [User]s. * @return A list of [User]s OR an empty list. */ fun findAll(): List<User> /** * Save a [User]. * @return The saved user, sometimes with additional information, like an id if it was newly created. */ fun save(user: User): User? /** * Delete a [User]. */ fun delete(user: User) /** * Delete a [User] by its id (unique identifier). */ fun deleteById(id: Long) }
0
Kotlin
0
0
d17f32c8bb7f739e2789ecdf46e946bff3c776b7
798
kotlin-spring-microservice
Apache License 2.0
app/src/main/java/me/pblinux/tvmaze/ui/composables/common/TabBar.kt
pblinux
374,239,080
false
null
package me.pblinux.tvmaze.ui.composables.common import android.util.Log import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Row import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Search import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import me.pblinux.tvmaze.data.models.episode.Episode import me.pblinux.tvmaze.ui.screens.home.HomeTabs import me.pblinux.tvmaze.ui.screens.home.Tabs import me.pblinux.tvmaze.ui.theme.White @Preview @Composable private fun TVTabBarPreview() { TVTabBar(tabs = Tabs, selectedTab = 1, onSearchPressed = {}, onTabClicked = { Log.d("TVTabBar | Preview", it.toString()) } ) } @Composable fun TVTabBar( tabs: List<HomeTabs>, selectedTab: Int, onSearchPressed: () -> Unit, onTabClicked: (Int) -> Unit, modifier: Modifier = Modifier ) { val selectedColor = if (isSystemInDarkTheme()) White else MaterialTheme.colors.secondary val unselectedColor = if (isSystemInDarkTheme()) White.copy(alpha = 0.4f) else Color.Gray Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) { IconButton(onClick = onSearchPressed) { Icon( imageVector = Icons.Default.Search, contentDescription = "Search", tint = selectedColor ) } ScrollableTabRow( selectedTabIndex = selectedTab, backgroundColor = Color.Transparent, contentColor = Color.Transparent, divider = {}, edgePadding = 32.dp ) { tabs.forEach { val selected = selectedTab == tabs.indexOf(it) Tab( selected = selected, onClick = { onTabClicked(tabs.indexOf(it)) }, text = { Text( text = it.title, style = MaterialTheme.typography.h5.copy( color = if (selected) selectedColor else unselectedColor ) ) }, ) } } } } @Composable fun SeasonsTabBar( episodeInfo: Map<Int, List<Episode>>, selectedTab: Int, onTabClicked: (Int) -> Unit, ) { val selectedColor = if (isSystemInDarkTheme()) White else MaterialTheme.colors.secondary val unselectedColor = if (isSystemInDarkTheme()) White.copy(alpha = 0.4f) else Color.Gray ScrollableTabRow( selectedTabIndex = selectedTab, backgroundColor = Color.Transparent, contentColor = Color.Transparent, divider = {}, edgePadding = 8.dp ) { episodeInfo.onEachIndexed { index, entry -> val selected = index == selectedTab val title = if (entry.key > 100) "${entry.key}" else "Season ${entry.key}" Tab(selected = selected, onClick = { onTabClicked(index) }) { Text( title, style = MaterialTheme.typography.subtitle2.copy( color = if (selected) selectedColor else unselectedColor ) ) } } } }
0
Kotlin
0
0
4f5644cb8fce8f97992df0d9ef96424f8780cffc
3,478
tvmaze
MIT License
libs/crypto/merkle-impl/src/main/kotlin/net/corda/crypto/merkle/impl/MerkleProofFactoryImpl.kt
corda
346,070,752
false
{"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.crypto.merkle.impl import net.corda.crypto.cipher.suite.merkle.MerkleProofFactory import net.corda.sandbox.type.SandboxConstants.CORDA_MARKER_ONLY_SERVICE import net.corda.sandbox.type.UsedByFlow import net.corda.sandbox.type.UsedByPersistence import net.corda.v5.crypto.SecureHash import net.corda.v5.crypto.extensions.merkle.MerkleTreeHashDigestProvider import net.corda.v5.crypto.merkle.MerkleProof import net.corda.v5.crypto.merkle.MerkleProofType import net.corda.v5.serialization.SingletonSerializeAsToken import org.osgi.service.component.annotations.Activate import org.osgi.service.component.annotations.Component import org.osgi.service.component.annotations.ServiceScope @Component( service = [ MerkleProofFactory::class, UsedByFlow::class, UsedByPersistence::class ], property = [ CORDA_MARKER_ONLY_SERVICE ], scope = ServiceScope.PROTOTYPE ) class MerkleProofFactoryImpl @Activate constructor() : MerkleProofFactory, UsedByFlow, UsedByPersistence, SingletonSerializeAsToken { override fun createAuditMerkleProof( treeSize: Int, leavesIndexAndData: Map<Int, ByteArray>, hashes: List<SecureHash>, hashDigestProvider: MerkleTreeHashDigestProvider ): MerkleProof { return MerkleProofImpl( MerkleProofType.AUDIT, treeSize, leavesIndexAndData.map { (leafIndex, data) -> IndexedMerkleLeafImpl( leafIndex, hashDigestProvider.leafNonce(leafIndex), data ) }, hashes ) } }
11
Kotlin
27
69
d478e119ab288af663910f9a2df42a7a7b9f5bce
1,624
corda-runtime-os
Apache License 2.0
feature/navhost/src/main/java/com/summit/dynamicfeatures/navhost/NavHostViewState.kt
cesarwillymc
326,488,032
false
null
package com.summit.dynamicfeatures.navhost import com.summit.commons.ui.base.BaseViewState sealed class NavHostViewState : BaseViewState { object EmptyScreen : NavHostViewState() object FullScreen : NavHostViewState() object NavigationScreen : NavHostViewState() object AppBarScreen : NavHostViewState() fun isFullScreen() = this is FullScreen fun isEmptyScreen() = this is EmptyScreen fun isAppBar() = this is AppBarScreen fun isNavigationScreen() = this is NavigationScreen }
0
Kotlin
0
2
9583792cfc3832bdc5b76584ff90a741f4b87458
523
AddFast
Apache License 2.0
foosball/app/src/phone/java/com/instructure/androidfoosball/activities/BaseFireBaseActivity.kt
instructure
179,290,947
false
null
/* * Copyright (C) 2016 - present Instructure, 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.instructure.androidfoosball.activities import android.support.v7.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.instructure.androidfoosball.interfaces.FragmentCallbacks import com.instructure.androidfoosball.models.User abstract class BaseFireBaseActivity : AppCompatActivity(), FragmentCallbacks { override var mUser: User? = null override var mAuth: FirebaseAuth? = null override var mDatabase: DatabaseReference? = null protected abstract fun onAuthStateChange(firebaseAuth: FirebaseAuth) protected fun initFireBase() { mAuth = FirebaseAuth.getInstance() mDatabase = FirebaseDatabase.getInstance().reference } private val mAuthStateListener = FirebaseAuth.AuthStateListener { firebaseAuth -> onAuthStateChange(firebaseAuth) } override fun onStop() { super.onStop() mAuth?.removeAuthStateListener(mAuthStateListener) } override fun onStart() { super.onStart() mAuth?.addAuthStateListener(mAuthStateListener) } }
2
Kotlin
85
99
1bac9958504306c03960bdce7fbb87cc63bc6845
1,789
canvas-android
Apache License 2.0
app/src/main/java/com/zdm/net_disk_app_21/response/UserInfoResponse.kt
dandycheung
524,896,587
false
null
package com.zdm.net_disk_app_21.response import com.zdm.net_disk_app_21.entity.UserInfo class UserInfoResponse(msg: String, responseCode: Int, val userInfo : UserInfo) : BaseResponse(msg, responseCode) { }
0
null
0
0
958ead5f9b3886d2fe19cc3da195b2e2d86829f6
208
netdiskapp21
MIT License
feature-staking-impl/src/main/java/jp/co/soramitsu/feature_staking_impl/domain/validators/current/CurrentValidatorsInteractor.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.feature_staking_impl.domain.validators.current import jp.co.soramitsu.common.list.GroupedList import jp.co.soramitsu.common.list.emptyGroupedList import jp.co.soramitsu.common.utils.networkType import jp.co.soramitsu.fearless_utils.extensions.toHexString import jp.co.soramitsu.feature_staking_api.domain.api.StakingRepository import jp.co.soramitsu.feature_staking_api.domain.api.getActiveElectedValidatorsExposures import jp.co.soramitsu.feature_staking_api.domain.model.IndividualExposure import jp.co.soramitsu.feature_staking_api.domain.model.NominatedValidator import jp.co.soramitsu.feature_staking_api.domain.model.NominatedValidator.Status import jp.co.soramitsu.feature_staking_api.domain.model.StakingState import jp.co.soramitsu.feature_staking_impl.data.repository.StakingConstantsRepository import jp.co.soramitsu.feature_staking_impl.domain.common.isWaiting import jp.co.soramitsu.feature_staking_impl.domain.validators.ValidatorProvider import jp.co.soramitsu.feature_staking_impl.domain.validators.ValidatorSource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlin.reflect.KClass class CurrentValidatorsInteractor( private val stakingRepository: StakingRepository, private val stakingConstantsRepository: StakingConstantsRepository, private val validatorProvider: ValidatorProvider, ) { suspend fun nominatedValidatorsFlow( nominatorState: StakingState.Stash, ): Flow<GroupedList<Status.Group, NominatedValidator>> { if (nominatorState !is StakingState.Stash.Nominator) { return flowOf(emptyGroupedList()) } val networkType = nominatorState.accountAddress.networkType() return stakingRepository.observeActiveEraIndex(networkType).map { activeEra -> val stashId = nominatorState.stashId val exposures = stakingRepository.getActiveElectedValidatorsExposures() val activeNominations = exposures.mapValues { (_, exposure) -> exposure.others.firstOrNull { it.who.contentEquals(stashId) } } val nominatedValidatorIds = nominatorState.nominations.targets.mapTo(mutableSetOf(), ByteArray::toHexString) val isWaitingForNextEra = nominatorState.nominations.isWaiting(activeEra) val maxRewardedNominators = stakingConstantsRepository.maxRewardedNominatorPerValidator() val groupedByStatusClass = validatorProvider.getValidators( ValidatorSource.Custom(nominatedValidatorIds.toList()), cachedExposures = exposures ) .map { validator -> val userIndividualExposure = activeNominations[validator.accountIdHex] val status = when { userIndividualExposure != null -> { // safe to !! here since non null nomination means that validator is elected val userNominationIndex = validator.electedInfo!!.nominatorStakes .sortedByDescending(IndividualExposure::value) .indexOfFirst { it.who.contentEquals(stashId) } val userNominationRank = userNominationIndex + 1 val willBeRewarded = userNominationRank < maxRewardedNominators Status.Active(nomination = userIndividualExposure.value, willUserBeRewarded = willBeRewarded) } isWaitingForNextEra -> Status.WaitingForNextEra exposures[validator.accountIdHex] != null -> Status.Elected else -> Status.Inactive } NominatedValidator(validator, status) } .groupBy { it.status::class } val totalElectiveCount = with(groupedByStatusClass) { groupSize(Status.Active::class) + groupSize(Status.Elected::class) } val electedGroup = Status.Group.Active(totalElectiveCount) val waitingForNextEraGroup = Status.Group.WaitingForNextEra( maxValidatorsPerNominator = stakingConstantsRepository.maxValidatorsPerNominator(), numberOfValidators = groupedByStatusClass.groupSize(Status.WaitingForNextEra::class) ) groupedByStatusClass.mapKeys { (statusClass, validators) -> when (statusClass) { Status.Active::class -> electedGroup Status.Elected::class -> Status.Group.Elected(validators.size) Status.Inactive::class -> Status.Group.Inactive(validators.size) Status.WaitingForNextEra::class -> waitingForNextEraGroup else -> throw IllegalArgumentException("Unknown status class: $statusClass") } } .toSortedMap(Status.Group.COMPARATOR) } } private fun Map<KClass<out Status>, List<NominatedValidator>>.groupSize(statusClass: KClass<out Status>): Int { return get(statusClass)?.size ?: 0 } }
3
null
15
55
756c1fea772274ad421de1b215a12bf4e2798d12
5,186
fearless-Android
Apache License 2.0
src/main/kotlin/CFigureManager.kt
argcc
777,572,651
false
{"Kotlin": 866115}
package org.example import java.nio.ByteBuffer import java.nio.ByteOrder val MenuRectangles = MutableList(11) { RECT() } class CFigureManager : CBaseResourceManager() { var hash_map = mutableMapOf<String, ObjectModelData>() override fun ObjectsTypeName(): String = "figures" override fun Create(): Boolean { super.Create() AddMappedResource(ResourcesDir + "figures.res") AddMappedResource(ResourcesDir + "menus.res") GetMenuRects(MenuRectangles) return true } override fun GetTypeId(): ObjTypeId { return ObjTypeId.FIGURE_MANAGER_x28 } fun GetMenuRects(rects: MutableList<RECT>) { val reg = CFileRegistry() val data = OpenFile("menus.reg") if (data != null) { if (reg.OpenFromData(data)) { rects[0] = reg.FindRect("MainMenu", "NewGame") rects[1] = reg.FindRect("MainMenu", "LoadGame") rects[2] = reg.FindRect("MainMenu", "ExitGame") rects[3] = reg.FindRect("MainMenu", "Options") rects[4] = reg.FindRect("MainMenu", "Credits") rects[5] = reg.FindRect("MainMenu", "Multiplayer") rects[6] = reg.FindRect("EscMenu", "SaveGame") rects[7] = reg.FindRect("EscMenu", "LoadGame") rects[8] = reg.FindRect("EscMenu", "Options") rects[10] = reg.FindRect("EscMenu", "ResumeGame") rects[11] = reg.FindRect("EscMenu", "ExitMM") } } } override fun CreateInstant(id: InstanceTypeId): CBaseObject? { return when (id) { FigureInstanceTypeId.SKY_OBJECT_x44 -> CSkyObject() FigureInstanceTypeId.C_0073fbf0_x41 -> C_0073fbf0() FigureInstanceTypeId.C_0073c1c4_x42 -> C_0073c1c4() FigureInstanceTypeId.I3D_FIGURE_x43 -> CI3DFigure() FigureInstanceTypeId.ANIMATION_TRACK_x300b -> CAnimationTrack() FigureInstanceTypeId.ANIMATION_NODE_x300c -> CAnimationNode() FigureInstanceTypeId.ANIMATION_SYSTEM_x300d -> CAnimationSystem2() else -> null }?.also { it.instance_type_id = id } } override fun AddMappedResource(res_file_name: String): Boolean { if (mapped_resources.none { it.name === res_file_name }) { val res = ResPointer() res.resource = CMappedResourceW() res.name = res_file_name mapped_resources.add(res) res.resource?.OpenResource(res_file_name, 0) } return true } override fun RegisterInstant(type_id: InstanceTypeId, instance_id: Int): CBaseObject? { if ( type_id == FigureInstanceTypeId.C_0073fbf0_x41 || type_id == FigureInstanceTypeId.C_0073c1c4_x42 || type_id == FigureInstanceTypeId.I3D_FIGURE_x43 || type_id == FigureInstanceTypeId.SKY_OBJECT_x44 ) { return super.RegisterInstant(type_id, instance_id)?.also { val figSpec = CManagerContainer?.GetSpecificManager() ?.RegisterInstant(SpecificInstanceTypeId.FIGURE_x45, -1) as? CFigureSpecific (it as? CFigure)?.SetSpecific(figSpec) } } return super.RegisterInstant(type_id, instance_id) } fun GetModelData(template: String): ObjectModelData? { if (hash_map[template] == null) { val mod_file_data = OpenFile("$template.mod") val bon_file_data = OpenFile("$template.bon") val anm_file_data = OpenFile("$template.anm") if (mod_file_data != null) { val data = ObjectModelData() data.mod.FromMemoryArray(mod_file_data) if (bon_file_data != null) { data.bon.FromMemoryArray(bon_file_data) } if (anm_file_data != null) { data.anm.FromMemoryArray(anm_file_data) } hash_map[template] = data } } return hash_map[template] } fun LoadSkeleton(anim_system: CAnimationSystem2, template: String) { val model_data = GetModelData(template) val lnk_data = model_data?.mod?.OpenFile(template) ?: OpenFile("$template.lnk") if (lnk_data == null) { error("Can't load skeleton file for \"$template\"") } val lnk = ByteBuffer.wrap(lnk_data).order(ByteOrder.LITTLE_ENDIAN) val bones_count = lnk.getInt() for (i in 0..<bones_count) { val bone_name = ReadName(lnk) val bone_parent_name = ReadName(lnk) anim_system.AddBone(model_data, bone_name, bone_parent_name) } anim_system.DefineRootNode() if (model_data == null) { FreeFileData(lnk_data) } else { model_data.mod.FreeFileData(lnk_data) } } fun LoadAnimation(animation_system: CAnimationSystem2, template: String, animation_name: String?):Int { var ret = 0 if (animation_name == null) { ret = animation_system.clear() } else { val model_data = GetModelData(template) if (model_data == null) { error("Can't open model \"$template\"") } val animation = model_data.GetAnimation(animation_name) if (animation == null) { error("Can't open animation \"$animation_name\" for model \"$template\"") } ret = animation_system.LoadAnimation(animation, animation_name) } return ret } }
0
Kotlin
0
0
415f3190279236c8c1335a0f8556f3bb9eac5256
5,636
ei_reverse_consp
MIT License
app/src/main/java/com/nora/cinemoapp/data/model/MovieListEntity.kt
NoraHeithur
650,469,979
false
null
package com.nora.cinemoapp.data.model data class MovieListEntity( val movies: List<MovieEntity> )
0
Kotlin
0
0
bafdba8d8fc02fef3a1b49f28d7eda6bffb7856b
103
Cinemo
MIT License
src/test/kotlin/io/github/poeschl/bukkit/logcleaner/TestUtils.kt
Poeschl
58,483,032
false
null
package io.github.poeschl.bukkit.logcleaner import java.util.* /** * Created on 29.11.2016. */ fun Calendar.createDate(year: Int, month: Int, day: Int): Date { this.set(year, month, day) return this.time }
0
Kotlin
1
4
7fd9f95d233b7ec7cbab5b4a4e74b0d9eb5fd4c2
218
LogCleaner
MIT License
data/src/main/java/com/github/abhrp/cryptograph/data/mapper/ChartItemEntityMapper.kt
abhrp
154,935,698
false
null
package com.github.abhrp.cryptograph.data.mapper import com.github.abhrp.cryptograph.data.model.ChartItemEntity import com.github.abhrp.cryptograph.domain.model.ChartItem import javax.inject.Inject class ChartItemEntityMapper @Inject constructor() : EntityMapper<ChartItemEntity, ChartItem> { override fun mapToDomain(entity: ChartItemEntity): ChartItem = ChartItem(entity.datetime, entity.value) override fun mapToEntity(domain: ChartItem): ChartItemEntity = ChartItemEntity(domain.datetime, domain.value) }
1
null
1
1
1582562019efd270cb14b298caf3f1620d99548b
521
cryptograph
MIT License
app/src/main/java/com/android/virgilsecurity/virgilback4app/util/Utils.kt
VirgilSecurity
111,100,617
false
null
package com.android.virgilsecurity.virgilback4app.util import android.app.FragmentTransaction import android.content.Context import android.support.design.widget.TextInputLayout import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.util.Log import android.widget.EditText import android.widget.Toast import com.android.virgilsecurity.virgilback4app.R import com.parse.ParseException import com.virgilsecurity.sdk.client.exceptions.VirgilCardIsNotFoundException import com.virgilsecurity.sdk.client.exceptions.VirgilKeyIsAlreadyExistsException import com.virgilsecurity.sdk.client.exceptions.VirgilKeyIsNotFoundException import com.virgilsecurity.sdk.crypto.exceptions.KeyEntryNotFoundException import retrofit2.HttpException /** * Created by <NAME> on 11/17/17 at Virgil Security. * -__o */ object Utils { fun toast(context: Context, text: String) { Toast.makeText(context, text, Toast.LENGTH_SHORT).show() } fun toast(fragment: Fragment, text: String) { Toast.makeText(fragment.activity, text, Toast.LENGTH_SHORT).show() } fun toast(context: Context, stringResId: Int) { Toast.makeText(context, context.getString(stringResId), Toast.LENGTH_SHORT).show() } fun toast(fragment: Fragment, stringResId: Int) { Toast.makeText(fragment.activity, fragment.activity!!.getString(stringResId), Toast.LENGTH_SHORT).show() } fun log(tag: String, text: String) { Log.d(tag, text) } fun replaceFragmentNoTag(fm: FragmentManager, containerId: Int, fragment: Fragment) { fm.beginTransaction() .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .replace(containerId, fragment) .commit() } fun replaceFragmentNoBackStack(fm: FragmentManager, containerId: Int, fragment: Fragment, tag: String) { fm.beginTransaction() .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .replace(containerId, fragment, tag) .commit() } fun replaceFragment(fm: FragmentManager, containerId: Int, fragment: Fragment, tag: String) { fm.beginTransaction() .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .replace(containerId, fragment, tag) .addToBackStack(tag) .commit() } fun resolveError(t: Throwable): String { return when (t) { is HttpException -> when (t.code()) { Const.Http.BAD_REQUEST -> "Bad Request" Const.Http.UNAUTHORIZED -> "Unauthorized" Const.Http.FORBIDDEN -> "Forbidden" Const.Http.NOT_ACCEPTABLE -> "Not acceptable" Const.Http.UNPROCESSABLE_ENTITY -> "Unprocessable entity" Const.Http.SERVER_ERROR -> "Server error" else -> "Oops.. Something went wrong ):" } is ParseException -> when (t.code) { ParseException.USERNAME_TAKEN -> "Username is already registered.\nPlease, try another one. (Parse)" ParseException.OBJECT_NOT_FOUND -> "Username is not registered yet" 60042 -> t.message ?: "No exception message" // Custom exception in RxParse.class else -> "Oops.. Something went wrong ):" } is VirgilKeyIsNotFoundException -> "Username is not registered yet" is VirgilKeyIsAlreadyExistsException -> "Username is already registered. Please, try another one." is KeyEntryNotFoundException -> "Username is not found on this device. Maybe you deleted your private key" is VirgilCardIsNotFoundException -> "Virgil Card is not found.\nYou can not start chat with user without Virgil Card." else -> "Something went wrong" } } fun validateUi(til: TextInputLayout): Boolean { val text = til.editText!!.text.toString() val context = til.context return if (text.isEmpty()) { til.error = context.getString(R.string.username_empty) false } else { true } } fun validateUi(et: EditText): Boolean { val text = et.text.toString() val context = et.context return if (text.isEmpty()) { et.error = context.getString(R.string.username_empty) false } else { true } } }
1
null
20
25
66512e12f8919d37bea902a6af1981e51a7b51af
4,677
chat-back4app-android
Apache License 2.0
core/domain/src/main/java/com/muammarahlnn/learnyscape/core/domain/resourcecreate/CreateAssignmentUseCase.kt
muammarahlnn
663,132,195
false
{"Kotlin": 1077954}
package com.muammarahlnn.learnyscape.core.domain.resourcecreate import kotlinx.coroutines.flow.Flow import java.io.File import java.time.LocalDateTime /** * @Author <NAME> * @File CreateAssignmentUseCase, 16/01/2024 13.33 */ fun interface CreateAssignmentUseCase { operator fun invoke( classId: String, title: String, description: String, dueDate: LocalDateTime, attachments: List<File>, ): Flow<String> }
0
Kotlin
0
0
1a6aafc8a84cd2cbe54b7b64c6ec937c2c8c5580
459
Learnyscape
Apache License 2.0
app/src/main/java/com/volcaniccoder/spotty/main/MainViewModelFactory.kt
volsahin
144,414,847
false
null
package com.volcaniccoder.spotty.main import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider class MainViewModelFactory : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return MainViewModel() as T } }
0
Kotlin
9
33
7c204702b0a5eb54d1bb022a0610baa6b4613dd4
298
spotty-clone-app
Apache License 2.0
buildata-runtime/src/commonMain/kotlin/io/github/virelion/buildata/BuildataDSL.kt
Virelion
330,246,253
false
null
package io.github.virelion.buildata /** * DSL marker added to all builder methods */ @DslMarker annotation class BuildataDSL
9
Kotlin
0
6
7444a6b2c92f7ee8e82c4d0ae189833bac7a92d7
128
buildata
Apache License 2.0
app/src/test/java/com/example/cryptography/ExampleUnitTest.kt
emadabdalrahman
476,863,370
false
{"Kotlin": 39294}
package com.example.cryptography import com.example.crypto.Crypto import com.example.crypto.PersonEncrypted import com.example.crypto.wrapper.newInstanceOfPrimitiveCollection import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { val crypto = Crypto("ksdnvsdklvm") val person = Person() val container = PersonEncrypted() crypto.encryptObj(person,container) // val p = person.javaClass.declaredFields.forEach { val df = 0 // } } }
0
Kotlin
0
0
a87e46c20146106ad2a07c88f6ede038b758af45
691
crypto
MIT License
src/main/kotlin/day21/Day21.kt
jakubgwozdz
571,298,326
false
{"Kotlin": 85100}
@file:Suppress("SpellCheckingInspection") package day21 import execute import readAllText import wtf private val Long.monkey: NumMonkey get() = NumMonkey(this) fun part1(input: String) = input.lineSequence().filterNot { it.isBlank() } .map { parse(it) } .toMap() .let { it.mapValues { (_, desc) -> desc.build(it) } } .let { it["root"]!!.calc() } fun part2(input: String) = input.lineSequence().filterNot { it.isBlank() } .map { parse(it) } .toMap() .let { it + ("humn" to HumnDesc) } .let { it.mapValues { (_, desc) -> desc.build(it) } } .let { it["root"]!! as OpMonkey } .let { root -> var (l, r) = root.run { left.flatten() to right.flatten() } while (l !is HumnMonkey && r !is HumnMonkey) { val (l1, r1) = when { l is OpMonkey && r is NumMonkey -> l.inverseTo(r) l is NumMonkey && r is OpMonkey -> r.inverseTo(l) else -> wtf(l to r) } val l1f = l1.flatten() val r1f = r1.flatten() l = l1f r = r1f } if (l is HumnMonkey) r.calc() else if (r is HumnMonkey) l.calc() else wtf(l to r) } private sealed interface MonkeyDesc { fun build(map: Map<String, MonkeyDesc>): Monkey } private data class NumDesc(val v: Long) : MonkeyDesc { private var cached: Monkey? = null override fun build(map: Map<String, MonkeyDesc>) = cached ?: v.monkey.also { cached = it } } private data class OpDesc(val leftId: String, val op: String, val rightId: String) : MonkeyDesc { private var cached: Monkey? = null override fun build(map: Map<String, MonkeyDesc>) = cached ?: OpMonkey(map[leftId]!!.build(map), op, map[rightId]!!.build(map)).also { cached = it } } private object HumnDesc : MonkeyDesc { override fun build(map: Map<String, MonkeyDesc>) = HumnMonkey } sealed interface Monkey { fun calc(): Long fun flatten(): Monkey } private data class NumMonkey(val v: Long) : Monkey { override fun calc() = v override fun flatten(): Monkey = this override fun toString() = v.toString() } private object HumnMonkey : Monkey { override fun calc() = wtf("calc on $this") override fun flatten() = this override fun toString() = "X" } private data class OpMonkey(val left: Monkey, val op: String, val right: Monkey) : Monkey { var cached: Long? = null var cachedFlatten: Monkey? = null override fun calc(): Long { val leftCalc = left.calc() val rightCalc = right.calc() return cached ?: when (op) { "+" -> leftCalc + rightCalc "-" -> leftCalc - rightCalc "*" -> leftCalc * rightCalc "/" -> leftCalc / rightCalc else -> wtf(this.toString()) }.also { cached = it } } override fun flatten(): Monkey { val leftFlat = left.flatten() val rightFlat = right.flatten() return cachedFlatten ?: ( if (leftFlat is NumMonkey && rightFlat is NumMonkey) calc().monkey else OpMonkey(leftFlat, op, rightFlat)) .also { cachedFlatten = it } } override fun toString() = "($left$op$right)" fun inverseTo(other: NumMonkey): Pair<Monkey, Monkey> { val leftToCalc = left.flatten() !is NumMonkey val rightToCalc = right.flatten() !is NumMonkey return when { leftToCalc && op == "+" -> left to OpMonkey(other, "-", right) rightToCalc && op == "+" -> right to OpMonkey(other, "-", left) leftToCalc && op == "*" -> left to OpMonkey(other, "/", right) rightToCalc && op == "*" -> right to OpMonkey(other, "/", left) leftToCalc && op == "-" -> left to OpMonkey(other, "+", right) rightToCalc && op == "-" -> right to OpMonkey(left, "-", other) leftToCalc && op == "/" -> left to OpMonkey(other, "*", right) rightToCalc && op == "/" -> right to OpMonkey(left, "/", other) else -> wtf(this) } .let { (l, r) -> l to r } } } private fun parse(line: String): Pair<String, MonkeyDesc> { val (id, desc) = line.split(": ") val asNum = desc.toLongOrNull() if (asNum != null) return id to NumDesc(asNum) val (m1, op, m2) = desc.split(" ") return id to OpDesc(m1, op, m2) } fun main() { val input = readAllText("local/day21_input.txt") val test = """ root: pppw + sjmn dbpl: 5 cczh: sllz + lgvd zczc: 2 ptdq: humn - dvpt dvpt: 3 lfqf: 4 humn: 5 ljgn: 2 sjmn: drzm * dbpl sllz: 4 pppw: cczh / lfqf lgvd: ljgn * ptdq drzm: hmdt - zczc hmdt: 32 """.trimIndent() execute(::part1, test, 152) execute(::part1, input, 286698846151845) execute(::part2, test, 301) execute(::part2, input, 3759566892641) }
0
Kotlin
0
0
7589942906f9f524018c130b0be8976c824c4c2a
4,942
advent-of-code-2022
MIT License
app/src/main/java/com/tzion/jetpackmovies/ui/favoriteMovies/FavoriteMoviesScreen.kt
4mr0m3r0
156,536,164
false
{"Kotlin": 158808}
package com.tzion.jetpackmovies.ui.favoriteMovies import androidx.compose.foundation.layout.PaddingValues import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import com.tzion.jetpackmovies.R import com.tzion.jetpackmovies.presentation.favoritemovies.FavoriteMovieViewModel import com.tzion.jetpackmovies.uicomponent.appbar.MovieTopAppBar import com.tzion.jetpackmovies.uicomponent.button.ArrowBack @OptIn(ExperimentalMaterial3Api::class) @Composable fun FavoriteMoviesScreen(onBack: () -> Unit = {}) { Scaffold( topBar = { MovieTopAppBar( text = stringResource(id = R.string.favorites_movies), navigationIcon = { ArrowBack( onClick = onBack, contentDescription = stringResource(id = R.string.go_back) ) } ) }, content = { val favoriteMovieViewModel = hiltViewModel<FavoriteMovieViewModel>() FavoriteMoviesContent( favoriteMovieViewModel = favoriteMovieViewModel, paddingValues = it ) } ) } @Composable private fun FavoriteMoviesContent( favoriteMovieViewModel: FavoriteMovieViewModel, paddingValues: PaddingValues ) { }
4
Kotlin
4
14
d466c8d3b99af00985bd88f8ea3afa1fdf1603e3
1,493
movies-jetpack-sample
MIT License
android-lang/src/com/android/tools/idea/lang/proguardR8/ProguardR8SyntaxHighlighter.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2019 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.lang.proguardR8 import com.android.tools.idea.lang.proguardR8.parser.ProguardR8Lexer import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.ABSTRACT import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.AT_INTERFACE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.BOOLEAN import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.BYTE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.CHAR import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.CLASS import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.CLOSE_BRACE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.COMMA import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.DOUBLE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.DOUBLE_QUOTED_CLASS import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.DOUBLE_QUOTED_STRING import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.ENUM import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.EXTENDS import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.FILE_NAME import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.FINAL import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.FLAG import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.FLOAT import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.IMPLEMENTS import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.INT import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.INTERFACE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.JAVA_IDENTIFIER import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.JAVA_IDENTIFIER_WITH_WILDCARDS import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.LINE_CMT import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.LONG import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.LPAREN import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.NATIVE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.OPEN_BRACE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.PRIVATE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.PROTECTED import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.PUBLIC import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.RPAREN import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.SEMICOLON import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.SHORT import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.SINGLE_QUOTED_CLASS import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.SINGLE_QUOTED_STRING import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.STATIC import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.STRICTFP import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.SYNCHRONIZED import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.TRANSIENT import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.VOID import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes.VOLATILE import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes._CLINIT_ import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes._FIELDS_ import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes._INIT_ import com.android.tools.idea.lang.proguardR8.psi.ProguardR8PsiTypes._METHODS_ import com.intellij.lexer.Lexer import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.HighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.TokenType import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet val JAVA_KEY_WORDS = TokenSet.create(CLASS, INTERFACE, ENUM, EXTENDS, IMPLEMENTS, STATIC, ABSTRACT, PRIVATE, PROTECTED, PUBLIC, SYNCHRONIZED, STRICTFP, FINAL, NATIVE, VOLATILE, TRANSIENT, AT_INTERFACE) val JAVA_PRIMITIVE = TokenSet.create(BOOLEAN, BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE, VOID) val JAVA_IDENTIFIER_TOKENS = TokenSet.create(JAVA_IDENTIFIER, JAVA_IDENTIFIER_WITH_WILDCARDS, SINGLE_QUOTED_CLASS, DOUBLE_QUOTED_CLASS) val PATHS = TokenSet.create(FILE_NAME, SINGLE_QUOTED_STRING, DOUBLE_QUOTED_STRING) val METHOD_FIELD_WILDCARDS = TokenSet.create(_INIT_, _CLINIT_, _FIELDS_, _METHODS_) enum class ProguardR8TextAttributes(fallback: TextAttributesKey) { BAD_CHARACTER(HighlighterColors.BAD_CHARACTER), KEYWORD(DefaultLanguageHighlighterColors.KEYWORD), PARAMETER(DefaultLanguageHighlighterColors.INSTANCE_FIELD), BRACES(DefaultLanguageHighlighterColors.BRACES), PARENTHESES(DefaultLanguageHighlighterColors.PARENTHESES), STRING(DefaultLanguageHighlighterColors.STRING), METHOD_FIELD_WILDCARDS(DefaultLanguageHighlighterColors.STATIC_FIELD), LINE_COMMENT(DefaultLanguageHighlighterColors.LINE_COMMENT), COMMA(DefaultLanguageHighlighterColors.COMMA), SEMICOLON(DefaultLanguageHighlighterColors.SEMICOLON), FLAG(DefaultLanguageHighlighterColors.CONSTANT), IDENTIFIER(DefaultLanguageHighlighterColors.IDENTIFIER), ANNOTATION(DefaultLanguageHighlighterColors.METADATA) ; val key = TextAttributesKey.createTextAttributesKey("PROGUARD_R8_$name", fallback) val keys = arrayOf(key) } class ProguardR8SyntaxHighlighter : SyntaxHighlighterBase() { override fun getHighlightingLexer(): Lexer { return ProguardR8Lexer() } override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> { // Return the appropriate text attributes depending on the type of token. when (tokenType) { LINE_CMT -> return ProguardR8TextAttributes.LINE_COMMENT.keys TokenType.BAD_CHARACTER -> return ProguardR8TextAttributes.BAD_CHARACTER.keys in JAVA_IDENTIFIER_TOKENS -> return ProguardR8TextAttributes.IDENTIFIER.keys in METHOD_FIELD_WILDCARDS -> return ProguardR8TextAttributes.METHOD_FIELD_WILDCARDS.keys in PATHS -> return ProguardR8TextAttributes.STRING.keys LPAREN, RPAREN -> return ProguardR8TextAttributes.PARENTHESES.keys CLOSE_BRACE, OPEN_BRACE -> return ProguardR8TextAttributes.BRACES.keys SEMICOLON -> return ProguardR8TextAttributes.SEMICOLON.keys COMMA -> return ProguardR8TextAttributes.COMMA.keys FLAG -> return ProguardR8TextAttributes.FLAG.keys else -> return TextAttributesKey.EMPTY_ARRAY } } } class ProguardR8SyntaxHighlighterFactory : SyntaxHighlighterFactory() { override fun getSyntaxHighlighter(project: Project?, virtualFile: VirtualFile?): SyntaxHighlighter { return ProguardR8SyntaxHighlighter() } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
7,784
android
Apache License 2.0
waltid-libraries/waltid-did/src/commonMain/kotlin/id/walt/did/dids/document/models/verification/method/VerificationMaterialType.kt
walt-id
701,058,624
false
{"Kotlin": 3448224, "Vue": 474904, "TypeScript": 129086, "Swift": 40383, "JavaScript": 18819, "Ruby": 15159, "Dockerfile": 13118, "Python": 3114, "Shell": 1783, "Objective-C": 388, "CSS": 345, "C": 104}
package id.walt.did.dids.document.models.verification.method import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport /** * Enumerated type representing verification material types that are registered in the [Decentralized Identifier Extensions](https://www.w3.org/TR/2024/NOTE-did-spec-registries-20240830/#verification-method-properties) parameter registry. * Deprecated values, i.e., publicKeyHex, publicKeyBase58 and ethereumAddress are not supported. * Support for blockchainAccountId is not provided yet. */ @OptIn(ExperimentalJsExport::class) @JsExport @Serializable enum class VerificationMaterialType { @SerialName("publicKeyJwk") PublicKeyJwk, @SerialName("publicKeyMultibase") PublicKeyMultibase; override fun toString(): String { return when (this) { PublicKeyJwk -> "publicKeyJwk" PublicKeyMultibase -> "publicKeyMultibase" } } }
20
Kotlin
46
121
48c6b8cfef532e7e837db0bdb39ba64def985568
1,004
waltid-identity
Apache License 2.0
app-alpha/src/main/java/com/github/uragiristereo/mejiboard/presentation/posts/grid/PostsGrid.kt
uragiristereo
406,362,024
false
{"Kotlin": 395562}
package com.github.uragiristereo.mejiboard.presentation.posts.grid import androidx.compose.animation.Crossfade import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells import androidx.compose.foundation.lazy.staggeredgrid.items import androidx.compose.runtime.Composable import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import coil.annotation.ExperimentalCoilApi import com.github.uragiristereo.mejiboard.common.Constants import com.github.uragiristereo.mejiboard.domain.entity.provider.post.Post import com.github.uragiristereo.mejiboard.presentation.posts.grid.common.PostItem import com.github.uragiristereo.mejiboard.presentation.posts.grid.common.PostsProgress @OptIn(ExperimentalFoundationApi::class) @ExperimentalCoilApi @Composable fun PostsGrid( posts: SnapshotStateList<Post>, canLoadMore: Boolean, gridState: LazyStaggeredGridState, gridCount: Int, loading: Boolean, page: Int, topAppBarHeight: Dp, allowPostClick: Boolean, onNavigateImage: (Post) -> Unit, modifier: Modifier = Modifier, ) { val navigationBarsPadding = WindowInsets.navigationBars.asPaddingValues() Crossfade( targetState = loading && page == 0, modifier = modifier, ) { target -> if (!target) { LazyVerticalStaggeredGrid( state = gridState, columns = StaggeredGridCells.Fixed(count = gridCount), verticalArrangement = Arrangement.spacedBy(space = 8.dp), horizontalArrangement = Arrangement.spacedBy(space = 8.dp), contentPadding = PaddingValues( start = 8.dp, end = 8.dp, top = topAppBarHeight, bottom = navigationBarsPadding.calculateBottomPadding() + 56.dp + 8.dp, ), modifier = Modifier.fillMaxSize(), ) { items( items = posts, key = { item -> item.id }, ) { item -> PostItem( item = item, allowPostClick = allowPostClick, onNavigateImage = onNavigateImage, ) } if (posts.isNotEmpty() && (canLoadMore || loading)) { item( key = Constants.KEY_LOAD_MORE_PROGRESS, // span = { GridItemSpan(gridCount) }, ) { PostsProgress( modifier = Modifier .fillMaxHeight() .alpha(0f), ) } } } } else { PostsProgress(modifier = Modifier.fillMaxHeight()) } } }
2
Kotlin
3
72
6f23178dddf36ed4e9382aeef7bb56114903f443
3,666
Mejiboard
Apache License 2.0
cohort-core/src/main/kotlin/com/sksamuel/cohort/ldap/LdapHealthCheck.kt
sksamuel
342,731,382
false
null
package com.sksamuel.cohort.ldap import com.sksamuel.cohort.HealthCheck import com.sksamuel.cohort.HealthCheckResult import java.util.Hashtable import javax.naming.directory.InitialDirContext /** * A Cohort [HealthCheck] that checks for connectivity to an LDAP server. * * To use, pass an [environment] map that contains the connection details, eg * * val map = mapOf( * Context.INITIAL_CONTEXT_FACTORY to "com.sun.jndi.ldap.LdapCtxFactory" * Context.PROVIDER_URL to "ldap://localhost:10389" * ) */ class LdapHealthCheck( private val environment: Map<String, String>, override val name: String = "ldap", ) : HealthCheck { override suspend fun check(): HealthCheckResult = runCatching { val table = Hashtable<String, String>() environment.forEach { (key, value) -> table[key] = value } val context = InitialDirContext(table) context.close() HealthCheckResult.healthy("LDAP connection success") }.getOrElse { HealthCheckResult.unhealthy("LDAP Failure", it) } }
4
null
6
97
0e113858c6d7f924e5831ed40716988f187e355e
1,022
cohort
Apache License 2.0
stcspeechkit/src/main/java/ru/speechpro/stcspeechkit/domain/service/RecognizerService.kt
STC-VoiceKey
138,289,130
false
{"Kotlin": 129142, "Java": 13363}
package ru.speechpro.stcspeechkit.domain.service import com.speechpro.android.session.session_library.SessionClientFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import retrofit2.Response import ru.speechpro.stcspeechkit.data.network.RecognizeApi import ru.speechpro.stcspeechkit.domain.models.* /** * @author <NAME> */ @Suppress("EXPERIMENTAL_FEATURE_WARNING") class RecognizerService constructor( private val recognizerApi: RecognizeApi, sessionClient: SessionClientFactory.SessionClient ) : BaseService(sessionClient) { suspend fun getAllPackages(sessionId: String): Response<List<PackageResponse>> = withContext(Dispatchers.IO) { recognizerApi.getAllPackages(sessionId).await() } suspend fun loadPackage(sessionId: String, packageId: String): Response<Void> = withContext(Dispatchers.IO) { recognizerApi.loadPackage(sessionId, packageId).await() } suspend fun unloadPackage(sessionId: String, packageId: String): Response<Void> = withContext(Dispatchers.IO) { recognizerApi.unloadPackage(sessionId, packageId).await() } suspend fun sendVoiceToRecognize(sessionId: String, request: RecognizeRequest): Response<RecognizeResponse> = withContext(Dispatchers.IO) { recognizerApi.getSpeechRecognition(sessionId, request).await() } suspend fun openStream(sessionId: String, request: StreamRecognizeRequest): Response<StreamResponse> = withContext(Dispatchers.IO) { recognizerApi.startRecognitionStream(sessionId, request).await() } suspend fun closeStream(sessionId: String, transactionId: String): Response<RecognizeResponse> = withContext(Dispatchers.IO) { recognizerApi.closeRecognitionStream(sessionId, transactionId).await() } }
0
Kotlin
1
2
83eabbfe0d363226f9554ba7164d9e85a25b50d5
1,781
stc-speechkit-android
BSD 2-Clause FreeBSD License
backend/src/main/kotlin/com/example/challengeapifravega/controller/dto/UbicacionDTO.kt
cassa10
316,603,383
false
null
package com.example.challengeapifravega.controller.dto import com.example.challengeapifravega.model.Ubicacion import com.fasterxml.jackson.annotation.JsonIgnore import javax.validation.constraints.Pattern class UbicacionDTO( @field:Pattern(regexp = "-?[1-9][0-9]*(\\.[0-9]+)?", message = "{coord.invalida}") val latitude:String, @field:Pattern(regexp = "-?[1-9][0-9]*(\\.[0-9]+)?", message = "{coord.invalida}") val longitude:String ){ @JsonIgnore fun mapToUbicacion(): Ubicacion{ return Ubicacion(latitude, longitude) } data class Builder(val ubicacion: Ubicacion) { fun build() : UbicacionDTO { return UbicacionDTO(ubicacion.latitude, ubicacion.longitude) } } }
0
Kotlin
0
0
6732e199b44f025168815c2aef75626f45b89559
755
challenge-api-fravega
MIT License
permissions/src/main/java/com/piroworkz/composeandroidpermissions/PermissionLaunchedEffect.kt
piroworkz
802,955,723
false
{"Kotlin": 2705}
package com.piroworkz.composeandroidpermissions import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @Composable fun PermissionLaunchedEffect( permissionState: Permissions, vararg permissions: String, onGranted: () -> Unit ) { LaunchedEffect(key1 = permissionState.state) { when (permissionState.state) { PermissionsState.GRANTED -> { onGranted() } PermissionsState.DENIED -> { permissionState.launchRequestFor(permissions = permissions) } else -> { return@LaunchedEffect } } } }
0
Kotlin
0
1
3d8b4f47c24cfecf8c850b16a2be13b99f3ec5bc
676
ComposeAndroidPermissions
MIT License
lib/kafka-key-generator-client/src/main/kotlin/no/nav/paw/kafkakeygenerator/client/KafkaKeysClient.kt
navikt
794,875,530
false
null
package no.nav.paw.migrering.app.kafkakeys import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.http.ContentType import io.ktor.http.contentType import io.opentelemetry.instrumentation.annotations.WithSpan data class KafkaKeysResponse( val id: Long, val key: Long ) data class KafkaKeysRequest( val ident: String ) interface KafkaKeysClient { suspend fun getIdAndKey(identitetsnummer: String): KafkaKeysResponse } class StandardKafkaKeysClient( private val httpClient: HttpClient, private val kafkaKeysUrl: String, private val getAccessToken: () -> String ) : KafkaKeysClient { @WithSpan override suspend fun getIdAndKey(identitetsnummer: String): KafkaKeysResponse = httpClient.post(kafkaKeysUrl) { header("Authorization", "Bearer ${getAccessToken()}") contentType(ContentType.Application.Json) setBody(KafkaKeysRequest(identitetsnummer)) }.let { response -> if (response.status == io.ktor.http.HttpStatusCode.OK) { response.body<KafkaKeysResponse>() } else { throw Exception("Kunne ikke hente kafka key, http_status=${response.status}, melding=${response.body<String>()}") } } }
5
null
0
1
b1c3dfd591983dd071d94b6dbdc04120ba7c6688
1,387
paw-arbeidssoekerregisteret-utgang
MIT License
hexagon_benchmark/src/main/kotlin/com/hexagonkt/BenchmarkStorage.kt
xrd
105,823,553
true
{"Kotlin": 258896, "FreeMarker": 7796, "Groovy": 2154, "JavaScript": 1532, "CSS": 1072, "HTML": 1048}
package com.hexagonkt import com.hexagonkt.helpers.systemSetting import com.hexagonkt.settings.SettingsManager.setting import com.hexagonkt.store.MongoIdRepository import com.hexagonkt.store.mongoCollection import com.hexagonkt.store.mongoDatabase import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import java.sql.Connection import java.sql.ResultSet.CONCUR_READ_ONLY import java.sql.ResultSet.TYPE_FORWARD_ONLY import kotlin.reflect.KClass import kotlin.reflect.KProperty1 internal const val WORLD_ROWS = 10000 private val DB_HOST = systemSetting("DBHOST", "localhost") private val DB_NAME = setting("database", "hello_world") private val WORLD_NAME: String = setting("worldCollection", "world") private val FORTUNE_NAME: String = setting("fortuneCollection", "fortune") private val postgresqlUrl = "jdbc:postgresql://$DB_HOST/$DB_NAME?" + "jdbcCompliantTruncation=false&" + "elideSetAutoCommits=true&" + "useLocalSessionState=true&" + "cachePrepStmts=true&" + "cacheCallableStmts=true&" + "alwaysSendSetIsolation=false&" + "prepStmtCacheSize=4096&" + "cacheServerConfiguration=true&" + "prepStmtCacheSqlLimit=2048&" + "traceProtocol=false&" + "useUnbufferedInput=false&" + "useReadAheadInput=false&" + "maintainTimeStats=false&" + "useServerPrepStmts=true&" + "cacheRSMetadata=true" internal fun createStore(engine: String): Store = when (engine) { "mongodb" -> MongoDbStore() "postgresql" -> SqlStore(postgresqlUrl) else -> error("Unsupported database") } internal interface Store { fun findAllFortunes(): List<Fortune> fun findWorlds(count: Int): List<World> fun replaceWorlds(count: Int): List<World> fun close() } private class MongoDbStore : Store { private val database = mongoDatabase("mongodb://$DB_HOST/$DB_NAME") private val worldRepository = repository(WORLD_NAME, World::class, World::_id) private val fortuneRepository = repository(FORTUNE_NAME, Fortune::class, Fortune::_id) // TODO Find out why it fails when creating index '_id' with background: true private fun <T : Any> repository(name: String, type: KClass<T>, key: KProperty1<T, Int>) = MongoIdRepository(type, mongoCollection(name, database), key, indexOrder = null) override fun close() { /* Not needed */ } override fun findAllFortunes() = fortuneRepository.findObjects().toList() override fun findWorlds(count: Int) = (1..count).mapNotNull { worldRepository.find(randomWorld()) } override fun replaceWorlds(count: Int) = (1..count) .map { worldRepository.find(randomWorld())?.copy(randomNumber = randomWorld()) } .toList() .filterNotNull() .map { worldRepository.replaceObjects(it, bulk = true) it } } private class SqlStore(jdbcUrl: String) : Store { private val SELECT_WORLD = "select * from world where id = ?" private val UPDATE_WORLD = "update world set randomNumber = ? where id = ?" private val SELECT_ALL_FORTUNES = "select * from fortune" private val DATA_SOURCE: HikariDataSource init { val config = HikariConfig() config.jdbcUrl = jdbcUrl config.maximumPoolSize = setting("maximumPoolSize", 16) config.username = setting("databaseUsername", "benchmarkdbuser") config.password = setting("databasePassword", "benchmarkdbpass") DATA_SOURCE = HikariDataSource(config) } override fun close() { DATA_SOURCE.close() } override fun findAllFortunes(): List<Fortune> { var fortunes = listOf<Fortune>() DATA_SOURCE.connection.use { con: Connection -> val rs = con.prepareStatement(SELECT_ALL_FORTUNES).executeQuery() while (rs.next()) fortunes += Fortune(rs.getInt(1), rs.getString(2)) } return fortunes } override fun findWorlds(count: Int): List<World> { var worlds: List<World> = listOf() DATA_SOURCE.connection.use { con: Connection -> val stmtSelect = con.prepareStatement(SELECT_WORLD) for (ii in 0 until count) { stmtSelect.setInt(1, randomWorld()) val rs = stmtSelect.executeQuery() rs.next() val _id = rs.getInt(1) worlds += World(_id, _id, rs.getInt(2)) } } return worlds } override fun replaceWorlds(count: Int): List<World> { var worlds: List<World> = listOf() DATA_SOURCE.connection.use { con: Connection -> val stmtSelect = con.prepareStatement(SELECT_WORLD, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY) val stmtUpdate = con.prepareStatement(UPDATE_WORLD) for (ii in 0 until count) { stmtSelect.setInt(1, randomWorld()) val rs = stmtSelect.executeQuery() rs.next() val _id = rs.getInt(1) val world = World(_id, _id, rs.getInt(2)).copy(randomNumber = randomWorld()) worlds += world stmtUpdate.setInt(1, world.randomNumber) stmtUpdate.setInt(2, world.id) stmtUpdate.addBatch() if (ii % 25 == 0) stmtUpdate.executeBatch() } stmtUpdate.executeBatch() } return worlds } }
0
Kotlin
0
0
e84dbefa0d666fea07e3cac9163e2843584a79a6
5,424
hexagon
MIT License
api/src/main/kotlin/einsen/spikeysanju/dev/utils/Constants.kt
Spikeysanju
367,818,611
false
null
package einsen.spikeysanju.dev.utils const val ALGORITHM = "HmacSHA256"
5
Kotlin
74
858
e9e9e4277883ab91611e8699bb93da3dc51fc9d4
73
Einsen
Apache License 2.0
mvp/src/main/java/com/yww/mvp/core/MvpInternalDelegate.kt
wavening
180,977,597
false
{"Gradle": 14, "Java Properties": 4, "Shell": 1, "Text": 9, "Ignore List": 12, "Batchfile": 1, "Markdown": 1, "Proguard": 11, "XML": 65, "Kotlin": 113, "Java": 2, "JSON": 12, "SQL": 2, "Motorola 68K Assembly": 3, "Unix Assembly": 1}
package com.yww.mvp.core /** * @author WAVENING */ internal class MvpInternalDelegate<V : MvpView, P : MvpPresenter<V>>(private var callback: DelegateCallback<V, P>) { /** * 创建presenter */ fun createPresenter(): P = callback.getPresenter() /** * 绑定视图 */ fun attachView() { callback.getPresenter().attachView(callback.getMvpView()) } /** * 解绑视图 */ fun detachView(remainInstance: Boolean) { callback.getPresenter().detachView(remainInstance) } }
1
null
1
1
964e3eaa52e2aefdc10b883394910e61fdb2e467
528
KotlinLibs
Apache License 2.0
skiko/src/jvmMain/kotlin/org/jetbrains/skiko/Library.kt
5l1v3r1
293,228,548
true
{"Kotlin": 25856, "C++": 15136, "Objective-C": 5840}
package org.jetbrains.skiko import java.io.BufferedReader import java.io.InputStreamReader import java.io.File import java.nio.file.Files import java.nio.file.StandardCopyOption object Library { private var loaded = false private val cacheDir = "${System.getProperty("user.home")}/.skiko/" private fun loadOrGet(path: String, resource: String, isLibrary: Boolean) { File(cacheDir).mkdirs() val resourceName = if (isLibrary) System.mapLibraryName(resource) else resource val hash = Library::class.java.getResourceAsStream("$path$resourceName.sha256").use { BufferedReader(InputStreamReader(it)).lines().toArray()[0] as String } val fileName = if (isLibrary) System.mapLibraryName(hash) else resource val file = File(cacheDir, fileName) // TODO: small race change when multiple Compose apps are started first time, can handle with atomic rename. if (!file.exists()) { Library::class.java.getResourceAsStream("$path$resourceName").use { input -> Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING) } } if (isLibrary) { System.load(file.absolutePath) } } @Synchronized fun load(resourcePath: String, name: String) { if (loaded) return loadOrGet(resourcePath, name, true) val loadIcu = System.getProperty("os.name").toLowerCase().startsWith("win") if (loadIcu) { loadOrGet(resourcePath, "icudtl.dat", false) } loaded = true // we have to set this property to avoid render flickering. System.setProperty("sun.awt.noerasebackground", "true") } }
0
null
0
0
5c7a7ff6b2ab08ab53ebc8651df2b1a7fd6d8e56
1,729
skiko
Apache License 2.0
usvm-jvm/src/main/kotlin/org/usvm/machine/interpreter/JcVirtualInvokeResolver.kt
UnitTestBot
586,907,774
false
{"Kotlin": 2626055, "Java": 476812}
package org.usvm.machine.interpreter import io.ksmt.expr.KExpr import io.ksmt.sort.KBoolSort import io.ksmt.utils.asExpr import org.jacodb.api.JcClassOrInterface import org.jacodb.api.JcRefType import org.jacodb.api.JcType import org.jacodb.api.ext.enumValues import org.jacodb.api.ext.isEnum import org.jacodb.api.ext.toType import org.usvm.UBoolExpr import org.usvm.UConcreteHeapRef import org.usvm.UHeapRef import org.usvm.USymbolicHeapRef import org.usvm.api.evalTypeEquals import org.usvm.api.typeStreamOf import org.usvm.isAllocatedConcreteHeapRef import org.usvm.isStaticHeapRef import org.usvm.machine.JcConcreteMethodCallInst import org.usvm.machine.JcContext import org.usvm.machine.JcVirtualMethodCallInst import org.usvm.machine.interpreter.statics.JcStaticFieldLValue import org.usvm.machine.state.JcState import org.usvm.machine.state.newStmt import org.usvm.memory.foldHeapRef import org.usvm.model.UModelBase import org.usvm.types.UTypeStream import org.usvm.types.single import org.usvm.util.findMethod /** * Resolves a virtual [methodCall] with different strategies for forks, * depending on existence of any model in the current state. */ fun resolveVirtualInvoke( ctx: JcContext, methodCall: JcVirtualMethodCallInst, scope: JcStepScope, typeSelector: JcTypeSelector, forkOnRemainingTypes: Boolean, ) { val models = scope.calcOnState { models } if (models.isEmpty()) { resolveVirtualInvokeWithoutModel( ctx, methodCall, scope, typeSelector, forkOnRemainingTypes ) } else { resolveVirtualInvokeWithModel( ctx, methodCall, scope, models.first(), typeSelector, forkOnRemainingTypes ) } } private fun resolveVirtualInvokeWithModel( ctx: JcContext, methodCall: JcVirtualMethodCallInst, scope: JcStepScope, model: UModelBase<JcType>, typeSelector: JcTypeSelector, forkOnRemainingTypes: Boolean, ): Unit = with(methodCall) { val instance = arguments.first().asExpr(ctx.addressSort) val concreteRef = model.eval(instance) as UConcreteHeapRef if (isAllocatedConcreteHeapRef(concreteRef) || isStaticHeapRef(concreteRef)) { val callSite = findLambdaCallSite(methodCall, scope, concreteRef) if (callSite != null) { val lambdaCall = makeLambdaCallSiteCall(callSite) scope.doWithState { newStmt(lambdaCall) } } else { val concreteInvokes = prepareVirtualInvokeOnConcreteRef( scope, concreteRef, ctx, methodCall, instance, condition = ctx.trueExpr ) scope.forkMulti(concreteInvokes) } return } // Resolved lambda call site can't be an input ref val typeStream = model.typeStreamOf(concreteRef) val typeConstraintsWithBlockOnStates = makeConcreteCallsForPossibleTypes( scope, methodCall, typeStream, typeSelector, instance, ctx, ctx.trueExpr, forkOnRemainingTypes ) scope.forkMulti(typeConstraintsWithBlockOnStates) } private fun JcVirtualMethodCallInst.prepareVirtualInvokeOnConcreteRef( scope: JcStepScope, concreteRef: UConcreteHeapRef, ctx: JcContext, methodCall: JcVirtualMethodCallInst, instance: UHeapRef, condition: UBoolExpr, ): List<Pair<UBoolExpr, (JcState) -> Unit>> { // We have only one type for allocated and static heap refs val type = scope.calcOnState { memory.typeStreamOf(concreteRef) }.single() as JcRefType val superClass = type.jcClass.superClass if (superClass?.isEnum == true) { // We need to process abstract enums differently - make not type equality conditions // but ref equalities on enum constant refs return prepareVirtualInvokeOnAbstractEnum(superClass, ctx, scope, methodCall, instance, condition) } val state = { state: JcState -> val concreteCall = makeConcreteMethodCall(methodCall, type) state.newStmt(concreteCall) } return listOf(condition to state) } private fun JcVirtualMethodCallInst.prepareVirtualInvokeOnAbstractEnum( superClass: JcClassOrInterface, ctx: JcContext, scope: JcStepScope, methodCall: JcVirtualMethodCallInst, instance: UHeapRef, condition: UBoolExpr ): List<Pair<KExpr<KBoolSort>, (JcState) -> Unit>> { val superType = superClass.toType() // With enums, we need to fork on all enum types, in spite of type selector val enumConstantFields = superType.jcClass.enumValues ?: error("No enum constants found at enum type $superType") val curState = scope.calcOnState { this } val enumConstantRefs = enumConstantFields.map { val staticFieldLValue = JcStaticFieldLValue(it, ctx.addressSort) curState.memory.read(staticFieldLValue) } return enumConstantRefs.map { enumRef -> val enumConstantType = curState.memory.types.getTypeStream(enumRef).single() val enumConstantState = { state: JcState -> val concreteCall = makeConcreteMethodCall(methodCall, enumConstantType) state.newStmt(concreteCall) } with(ctx) { val equalToEnumRefCondition = mkHeapRefEq(instance, enumRef) mkAnd(condition, equalToEnumRefCondition) to enumConstantState } } } private fun resolveVirtualInvokeWithoutModel( ctx: JcContext, methodCall: JcVirtualMethodCallInst, scope: JcStepScope, typeSelector: JcTypeSelector, forkOnRemainingTypes: Boolean, ): Unit = with(methodCall) { val instance = arguments.first().asExpr(ctx.addressSort) val refsWithConditions = mutableListOf<Pair<UHeapRef, UBoolExpr>>() val lambdaCallSitesWithConditions = mutableListOf<Pair<JcLambdaCallSite, UBoolExpr>>() foldHeapRef( instance, Unit, initialGuard = ctx.trueExpr, ignoreNullRefs = true, collapseHeapRefs = false, blockOnConcrete = { _, (ref, condition) -> val lambdaCallSite = findLambdaCallSite(methodCall, scope, ref) if (lambdaCallSite != null) { lambdaCallSitesWithConditions += lambdaCallSite to condition } else { refsWithConditions += ref to condition } }, blockOnStatic = { _, (ref, condition) -> val lambdaCallSite = findLambdaCallSite(methodCall, scope, ref) if (lambdaCallSite != null) { lambdaCallSitesWithConditions += lambdaCallSite to condition } else { refsWithConditions += ref to condition } }, blockOnSymbolic = { _, (ref, condition) -> // Resolved lambda call site can't be a symbolic ref refsWithConditions.also { it += ref to condition } }, ) val conditionsWithBlocks = refsWithConditions.flatMapTo(mutableListOf()) { (ref, condition) -> when { isAllocatedConcreteHeapRef(ref) || isStaticHeapRef(ref) -> { prepareVirtualInvokeOnConcreteRef(scope, ref, ctx, methodCall, instance, condition) } ref is USymbolicHeapRef -> { val state = scope.calcOnState { this } val typeStream = state.pathConstraints .typeConstraints .getTypeStream(ref) // NOTE: this filter is required in case this state is actually unsat and/or // does not have type constraints for this symbolic ref .filterBySupertype(methodCall.method.enclosingClass.toType()) makeConcreteCallsForPossibleTypes( scope, methodCall, typeStream, typeSelector, instance, ctx, condition, forkOnRemainingTypes ) } else -> error("Unexpected ref $ref") } } lambdaCallSitesWithConditions.mapTo(conditionsWithBlocks) { (callSite, condition) -> val concreteCall = makeLambdaCallSiteCall(callSite) condition to { state: JcState -> state.newStmt(concreteCall) } } scope.forkMulti(conditionsWithBlocks) } private fun JcVirtualMethodCallInst.makeConcreteMethodCall( methodCall: JcVirtualMethodCallInst, type: JcType, ): JcConcreteMethodCallInst { val concreteMethod = type.findMethod(method) ?: error("Can't find method $method in type ${type.typeName}") return methodCall.toConcreteMethodCall(concreteMethod.method) } private fun JcVirtualMethodCallInst.makeConcreteCallsForPossibleTypes( scope: JcStepScope, methodCall: JcVirtualMethodCallInst, typeStream: UTypeStream<JcType>, typeSelector: JcTypeSelector, instance: UHeapRef, ctx: JcContext, condition: UBoolExpr, forkOnRemainingTypes: Boolean, ): MutableList<Pair<UBoolExpr, (JcState) -> Unit>> { val state = scope.calcOnState { this } val inheritors = typeSelector.choose(method, typeStream) val typeConstraints = inheritors.map { type -> state.memory.types.evalTypeEquals(instance, type) } val typeConstraintsWithBlockOnStates = mutableListOf<Pair<UBoolExpr, (JcState) -> Unit>>() inheritors.mapIndexedTo(typeConstraintsWithBlockOnStates) { idx, type -> val isExpr = typeConstraints[idx] val block = { newState: JcState -> val concreteMethod = type.findMethod(method) ?: error("Can't find method $method in type ${type.typeName}") val concreteCall = methodCall.toConcreteMethodCall(concreteMethod.method) newState.newStmt(concreteCall) } with(ctx) { (condition and isExpr) to block } } if (forkOnRemainingTypes) { val excludeAllTypesConstraint = ctx.mkAnd(typeConstraints.map { ctx.mkNot(it) }) typeConstraintsWithBlockOnStates += excludeAllTypesConstraint to { } // do nothing, just exclude types } return typeConstraintsWithBlockOnStates } private fun findLambdaCallSite( methodCall: JcVirtualMethodCallInst, scope: JcStepScope, ref: UConcreteHeapRef, ): JcLambdaCallSite? = with(methodCall) { val callSites = scope.calcOnState { memory.getRegion(ctx.lambdaCallSiteRegionId) as JcLambdaCallSiteMemoryRegion } val callSite = callSites.findCallSite(ref) ?: return null val lambdaMethodType = callSite.lambda.dynamicMethodType // Match function signature when { method.name != callSite.lambda.callSiteMethodName -> return null method.returnType != lambdaMethodType.returnType -> return null lambdaMethodType.argumentTypes != method.parameters.map { it.type } -> return null } return callSite } private fun JcVirtualMethodCallInst.makeLambdaCallSiteCall( callSite: JcLambdaCallSite, ): JcConcreteMethodCallInst { val lambdaMethod = callSite.lambda.actualMethod.method // Instance was already resolved to the call site val callArgsWithoutInstance = this.arguments.drop(1) val lambdaMethodArgs = callSite.callSiteArgs + callArgsWithoutInstance return JcConcreteMethodCallInst(location, lambdaMethod.method, lambdaMethodArgs, returnSite) }
40
Kotlin
6
9
819268c3c77c05d798891be826164bbede63fdfb
11,487
usvm
Apache License 2.0
core-ui/screens/auth/login-register/src/main/java/com/odogwudev/example/login_register/auth/Beagle.kt
odogwudev
592,877,753
false
null
package com.odogwudev.example.login_register.auth import com.pandulapeter.beagle.Beagle import com.pandulapeter.beagle.common.configuration.toText import com.pandulapeter.beagle.common.contracts.BeagleListItemContract import com.pandulapeter.beagle.modules.DividerModule import com.pandulapeter.beagle.modules.ItemListModule import com.pandulapeter.beagle.modules.TextModule internal fun createBeagleModules( onItemSelected: (user: User) -> Unit, ) = arrayOf( DividerModule(), TextModule(text = "Login", type = TextModule.Type.SECTION_HEADER), ItemListModule( items = listOf( User("<EMAIL>", "12345678"), User("<EMAIL>", "123456"), User("<EMAIL>", "123456"), ), isExpandedInitially = true, onItemSelected = { user -> onItemSelected(user) Beagle.hide() }, title = "Test Staging Login Credentials" ) ) internal data class User(val email: String, val password: String) : BeagleListItemContract { override val id = email override val title = email.substringBefore("@").toText() }
0
Kotlin
0
4
82791abdcf1554d2a2cd498a19cd93952f90e53e
1,114
CinephilesCompanion
MIT License
core/src/main/kotlin/cz/kotox/core/liveevent/LiveEvent.kt
kotoMJ
170,925,605
false
null
package cz.kotox.core.liveevent import androidx.annotation.MainThread import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import java.util.concurrent.atomic.AtomicBoolean /** * Rewritten to Kotlin from STRV Alfonz library (arch module): * https://github.com/petrnohejl/Alfonz/tree/master/alfonz-arch */ class LiveEvent<T> : MutableLiveData<T>() { private val mPending = AtomicBoolean(false) @MainThread fun observeEvents(lifecycleOwner: LifecycleOwner, observer: Observer<T>) { // observe the internal MutableLiveData super.observe(lifecycleOwner, Observer<T> { value -> if (mPending.compareAndSet(true, false)) { observer.onChanged(value) } }) } @MainThread override fun setValue(value: T?) { mPending.set(true) super.setValue(value) } @MainThread fun call() { value = null } }
2
Kotlin
0
0
9a1346e49802fec162f4c64f7e17448c12a716f5
885
kotox-android
MIT License
src/main/kotlin/io/foxcapades/lib/cli/builder/flag/CharFlag.fn.kt
Foxcapades
850,780,005
false
{"Kotlin": 253956}
package io.foxcapades.lib.cli.builder.flag import io.foxcapades.lib.cli.builder.arg.Argument import io.foxcapades.lib.cli.builder.flag.impl.CharFlagImpl import io.foxcapades.lib.cli.builder.flag.impl.UniversalFlagImpl @Suppress("NOTHING_TO_INLINE") inline fun charFlag(longForm: String, noinline action: FlagOptions<Char>.() -> Unit = {}) = charFlag { this.longForm = longForm; action() } @Suppress("NOTHING_TO_INLINE") inline fun charFlag(shortForm: Char, noinline action: FlagOptions<Char>.() -> Unit = {}) = charFlag { this.shortForm = shortForm; action() } fun charFlag(action: FlagOptions<Char>.() -> Unit = {}): CharFlag = CharFlagImpl(FlagOptions(Char::class).also(action)) fun nullableCharFlag(action: NullableFlagOptions<Char>.() -> Unit = {}): Flag<Argument<Char?>, Char?> = UniversalFlagImpl.of(NullableFlagOptions(Char::class).also(action))
8
Kotlin
0
0
457d895219666963b70ac10df70092a7b778ebea
867
lib-kt-cli-builder
MIT License
sync-script/src/main/kotlin/gui/GuiState.kt
FreshKernel
799,541,150
false
{"Kotlin": 391163}
package gui import config.models.ScriptConfig import constants.SharedConstants import passedArgs import java.awt.GraphicsEnvironment object GuiState { /** * By default, will load it from the program arguments by [SharedConstants.DISABLE_GUI_ARG_NAME] * the value can be overridden using [ScriptConfig.guiEnabled] when the [ScriptConfig] is initialized * */ var isGuiEnabled: Boolean = SharedConstants.GUI_ENABLED_WHEN_AVAILABLE_DEFAULT private set /** * A function to update the value of the [isGuiEnabled] based on [ScriptConfig.guiEnabled] and the [passedArgs] * if any of those changes, this function should be called * * */ fun updateIsGuiEnabled() { // Check if the user overrides the default value in the config file ScriptConfig.instance?.guiEnabled?.let { isGuiEnabled = it return } // Check if the user overrides the default value in the launch arguments val isDisableGuiArgumentPassed = passedArgs.isNotEmpty() && passedArgs[0] == SharedConstants.DISABLE_GUI_ARG_NAME if (isDisableGuiArgumentPassed) { isGuiEnabled = false return } // If the user didn't specify a value and GUI is not supported, make sure to disable the GUI mode as a default if (GraphicsEnvironment.isHeadless()) { isGuiEnabled = false return } } }
1
Kotlin
0
2
55d94d5d569d68c7a6447f6217b08cb3379ab279
1,446
kraft-sync
MIT License
core/domain/src/main/java/com/ahmetocak/domain/usecase/chat/AddMessageUseCase.kt
AhmetOcak
793,949,918
false
{"Kotlin": 406065}
package com.ahmetocak.domain.usecase.chat import com.ahmetocak.data.repository.chat.ChatRepository import com.ahmetocak.model.Message import javax.inject.Inject class AddMessageUseCase @Inject constructor(private val chatRepository: ChatRepository) { suspend operator fun invoke(message: Message) = chatRepository.addMessage(message) }
0
Kotlin
0
0
61d1fad8809e1420fd767c33806f994443062b6b
342
ChatApp
MIT License
jvm/src/test/kotlin/fr/xgouchet/elmyr/jvm/factories/UriForgeryFactoryTest.kt
xgouchet
92,030,208
false
null
package fr.xgouchet.elmyr.jvm.factories import fr.xgouchet.elmyr.annotation.Forgery import fr.xgouchet.elmyr.junit5.ForgeConfiguration import fr.xgouchet.elmyr.junit5.ForgeExtension import fr.xgouchet.elmyr.jvm.JvmConfigurator import java.net.URI import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(ForgeExtension::class) @ForgeConfiguration(JvmConfigurator::class) class UriForgeryFactoryTest { @Test fun `forges different values`( @Forgery uri1: URI, @Forgery uri2: URI ) { assertThat(uri1.toString()) .isNotEqualTo(uri2.toString()) } @Test fun `forge many URIs`(@Forgery uris: List<URI>) { // Do nothing } }
6
null
3
83
0ab6c3a673fd8771e9fc02f0676a3a886992a1ef
785
Elmyr
MIT License
nugu-android-helper/src/main/java/com/skt/nugu/sdk/platform/android/speechrecognizer/recorder/KeywordRecorder.kt
nugu-developers
214,067,023
false
{"Kotlin": 2748228, "Java": 1646, "Ruby": 1432}
package com.skt.nugu.sdk.platform.android.speechrecognizer.recorder interface KeywordRecorder { fun open(): Boolean fun write(buffer: ByteArray, offsetInBytes:Int, sizeInBytes: Int): Int fun close() }
0
Kotlin
18
18
e0570448bc5ec17b3af969b564f6a8aec85fd960
213
nugu-android
Apache License 2.0
src/test/java/de/fraunhofer/aisec/cpg/graph/QueryTest.kt
zsdlove
352,930,897
true
{"Shell": 2, "JSON": 10, "Markdown": 2, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Gradle Kotlin DSL": 1, "Java": 270, "Kotlin": 7, "C++": 63, "C": 4, "Go": 18, "Go Module": 2, "CMake": 1, "Go Checksums": 1, "Java Properties": 2, "YAML": 2, "XML": 1, "INI": 1}
package de.fraunhofer.aisec.cpg.graph import de.fraunhofer.aisec.cpg.ExperimentalGraph import de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration import de.fraunhofer.aisec.cpg.graph.declarations.ParamVariableDeclaration import de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge import de.fraunhofer.aisec.cpg.graph.types.UnknownType import de.fraunhofer.aisec.cpg.helpers.Benchmark import org.junit.jupiter.api.BeforeAll import org.opencypher.v9_0.ast.Query import org.opencypher.v9_0.parser.CypherParser import scala.Option import java.util.stream.Collector import java.util.stream.Collectors import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlin.time.ExperimentalTime import kotlin.time.milliseconds @ExperimentalGraph @ExperimentalTime class QueryTest { @Test fun testQueryExistenceOfEdge() { val query = parser.parse("MATCH (n:FunctionDeclaration)-[:PARAMETERS]->(m:ParamVariableDeclaration) RETURN n", null, null) as Query val nodes: List<Node> = db.executeQuery(query) assertEquals(2, nodes.size) } @Test fun testQueryExistenceOfEdgeOtherVar() { val query = parser.parse("MATCH (n:FunctionDeclaration)-[:PARAMETERS]->(m:ParamVariableDeclaration) RETURN m", null, null) as Query val nodes = db.executeQuery(query) assertEquals(2, nodes.size) } @Test fun testQueryExistenceOfEdgeWithEquals() { val query = parser.parse("MATCH (n:FunctionDeclaration)-[:PARAMETERS]->(m:ParamVariableDeclaration) WHERE m.name = 'paramB' RETURN n", null, null) as Query val nodes = db.executeQuery(query) assertEquals(1, nodes.size) assertEquals(func2, nodes[0]) } @Test fun testQueryWithSimpleProperty() { val query = parser.parse("MATCH (n:VariableDeclaration) WHERE n.name = 'myVar' RETURN n", null, null) as Query println(query) val nodes = db.executeQuery(query) assertEquals(1, nodes.size) } @Test fun testQueryAllNodes() { // should return all nodes val query = parser.parse("MATCH (n) RETURN n", null, null) as Query println(query) val nodes = db.executeQuery(query) assertEquals(db.size(), nodes.size) } @Test fun testQueryAllNodesWithEquals() { // should return all nodes val query = parser.parse("MATCH (n) WHERE 1=1 RETURN n", null, null) as Query println(query) val nodes = db.executeQuery(query) assertEquals(db.size(), nodes.size) } @Test fun testQueryLimit() { // should return all nodes val query = parser.parse("MATCH (n) RETURN n LIMIT 25", null, null) as Query println(query) val nodes = db.executeQuery(query) assertEquals(25, nodes.size) } @Test fun testQueryNoResult() { // should return no nodes val query = parser.parse("MATCH (n) WHERE 1='a' RETURN n", null, null) as Query println(query) val nodes = db.executeQuery(query) println(nodes) assertTrue(nodes.isEmpty()) } @Test fun testQueryLesser() { // should return no nodes val query = parser.parse("MATCH (n) WHERE 1<0 RETURN n", null, null) as Query println(query) val nodes = db.executeQuery(query) println(nodes) assertTrue(nodes.isEmpty()) } @Test fun testQueryGreaterThan() { // should return no nodes val query = parser.parse("MATCH (n) WHERE 0>1 RETURN n", null, null) as Query println(query) val nodes = db.executeQuery(query) println(nodes) assertTrue(nodes.isEmpty()) } companion object { lateinit var db: Graph val parser = CypherParser() lateinit var func1: FunctionDeclaration lateinit var func2: FunctionDeclaration lateinit var func3: FunctionDeclaration @ExperimentalGraph @BeforeAll @JvmStatic fun before() { db = Graph(mutableListOf()) db += NodeBuilder.newVariableDeclaration("myVar", UnknownType.getUnknownType(), "myVar", false) func1 = NodeBuilder.newFunctionDeclaration("func1", "private int func1() { return 1; }") func2 = NodeBuilder.newFunctionDeclaration("func2", "private int func2() { return 1; }") func3 = NodeBuilder.newFunctionDeclaration("func3", "private int func2() { return 1; }") val paramA = NodeBuilder.newMethodParameterIn("paramA", UnknownType.getUnknownType(), false, "paramA"); val paramB = NodeBuilder.newMethodParameterIn("paramB", UnknownType.getUnknownType(), false, "paramB"); func1.addParameter(paramA) func2.addParameter(paramB) // create some dummy nodes to make queries a little bit slower for (i in 0..10000) { db += NodeBuilder.newVariableDeclaration("var${i}", UnknownType.getUnknownType(), "var${i}", true) } db += func1 db += func2 db += func3 db += paramA db += paramB } } }
0
null
0
0
23671c71c37d0024281bef05a8e5e2e15b1c8c51
5,192
cpg
Apache License 2.0
inference/inference-core/src/jvmMain/kotlin/io/kinference.core/operators/seq/SequenceInsert.kt
JetBrains-Research
244,400,016
false
null
package io.kinference.core.operators.seq import io.kinference.attribute.Attribute import io.kinference.core.KIONNXData import io.kinference.core.data.seq.KIONNXSequence import io.kinference.core.data.tensor.* import io.kinference.data.* import io.kinference.graph.Contexts import io.kinference.ndarray.arrays.NumberNDArrayCore import io.kinference.operator.* import io.kinference.protobuf.message.TensorProto import io.kinference.types.TensorShape import io.kinference.types.ValueTypeInfo sealed class SequenceInsert( name: String, info: OperatorInfo, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String> ) : Operator<KIONNXData<*>, KIONNXSequence>(name, info, attributes, inputs, outputs) { companion object { private val DEFAULT_VERSION = VersionInfo(sinceVersion = 11) operator fun invoke(name: String, version: Int?, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>): SequenceInsert { return when (version ?: DEFAULT_VERSION.sinceVersion) { in SequenceInsertVer11.VERSION.asRange() -> SequenceInsertVer11(name, attributes, inputs, outputs) else -> error("Unsupported version of SequenceInsert operator: $version") } } } } class SequenceInsertVer11 internal constructor( name: String, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String> ) : SequenceInsert(name, INFO, attributes, inputs, outputs) { companion object { private val TYPE_CONSTRAINTS = ALL_DATA_TYPES private val INPUTS_INFO = listOf( IOInfo(0, TYPE_CONSTRAINTS, "input_sequence", optional = false, onnxDataType = ONNXDataType.ONNX_SEQUENCE), IOInfo(1, TYPE_CONSTRAINTS, "tensor", optional = false), IOInfo(2, setOf(TensorProto.DataType.INT64, TensorProto.DataType.INT32), "position", optional = true) ) private val OUTPUTS_INFO = listOf( IOInfo(0, TYPE_CONSTRAINTS, "output_sequence", optional = false, onnxDataType = ONNXDataType.ONNX_SEQUENCE) ) internal val VERSION = VersionInfo(sinceVersion = 11) private val INFO = OperatorInfo("SequenceInsert", emptyMap(), INPUTS_INFO, OUTPUTS_INFO, VERSION, OperatorInfo.DEFAULT_DOMAIN) } override suspend fun <D : ONNXData<*, *>> apply(contexts: Contexts<D>, inputs: List<KIONNXData<*>?>): List<KIONNXSequence?> { val seq = ArrayList(inputs[0]!!.data as List<KITensor>) val tensor = inputs[1]!! as KITensor val positionTensor = inputs.getOrNull(2)?.data as? NumberNDArrayCore val position = (positionTensor?.singleValue() as? Number)?.toInt() ?: seq.size val actualPosition = if (position >= 0) position else seq.size + position require(actualPosition >= 0 && actualPosition <= seq.size) { "Index $position is out of range [-${seq.size}, ${seq.size}]" } seq.add(actualPosition, tensor) val outputSeq = KIONNXSequence( name = "output_sequence", data = seq, info = ValueTypeInfo.SequenceTypeInfo( elementType = ValueTypeInfo.TensorTypeInfo( shape = TensorShape.unknown(), type = tensor.info.type ) ) ) return listOf(outputSeq) } }
7
null
7
154
d98a9c110118c861a608552f4d18b6256897ccad
3,396
kinference
Apache License 2.0
app/src/main/java/org/xiaoxingqi/gmdoc/MainActivity.kt
dflamingoY
64,825,990
false
{"Java": 661607, "Kotlin": 410150, "JavaScript": 8604, "HTML": 2675, "CSS": 1000}
package org.xiaoxingqi.gmdoc import android.Manifest import android.annotation.SuppressLint import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.os.Build import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import androidx.drawerlayout.widget.DrawerLayout import android.text.TextUtils import android.util.Log import android.view.Gravity import android.view.KeyEvent import android.view.View import android.view.WindowManager import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import kotlinx.android.synthetic.main.activity_main.* import okhttp3.WebSocket import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.xiaoxingqi.gmdoc.core.App import org.xiaoxingqi.gmdoc.core.BaseActivity import org.xiaoxingqi.gmdoc.entity.BaseRespData import org.xiaoxingqi.gmdoc.entity.TokenData import org.xiaoxingqi.gmdoc.entity.user.UserInfoData import org.xiaoxingqi.gmdoc.eventbus.SocketEvent import org.xiaoxingqi.gmdoc.eventbus.SocketOffline import org.xiaoxingqi.gmdoc.impl.IConstant import org.xiaoxingqi.gmdoc.impl.MainCallBack import org.xiaoxingqi.gmdoc.modul.game.GameFragment import org.xiaoxingqi.gmdoc.modul.global.WriteDynamicActivity import org.xiaoxingqi.gmdoc.modul.home.* import org.xiaoxingqi.gmdoc.modul.lifeCircle.LifCircleFragment import org.xiaoxingqi.gmdoc.modul.login.LoginActivity import org.xiaoxingqi.gmdoc.modul.message.MsgFragment import org.xiaoxingqi.gmdoc.onEvent.LoginEvent import org.xiaoxingqi.gmdoc.presenter.MainPresenter import org.xiaoxingqi.gmdoc.tools.AppTools import org.xiaoxingqi.gmdoc.tools.PreferenceTools import org.xiaoxingqi.gmdoc.tools.SPUtils import org.xiaoxingqi.gmdoc.tools.SocketUtils class MainActivity : BaseActivity<MainPresenter>() { private var socket: WebSocket? = null companion object { private const val REQUEST_PERMISSION = 0x01 } private val map by lazy { HashMap<String, String>() } override fun createPresent(): MainPresenter { return MainPresenter(this, object : MainCallBack { override fun token(data: TokenData?) { App.s_Token = data?._token transLayout.showContent() } override fun loginOut(data: BaseRespData?) { /** * 退出登录 检测是否退出成功 */ drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) PreferenceTools.clear(this@MainActivity, IConstant.USERINFO) persent?.postToken() } @SuppressLint("SetTextI18n") override fun userInfo(data: UserInfoData?) { /** * 信息查询成功 表示用户已经登录 */ data?.let { if (it.data.jutou == 0) {//剧透打开 toggle_Button.isChecked = true SPUtils.setBoolean(this@MainActivity, IConstant.IS_SPOLIER, true) } else {//关闭 SPUtils.setBoolean(this@MainActivity, IConstant.IS_SPOLIER, false) toggle_Button.isChecked = false } PreferenceTools.saveObj(this@MainActivity, IConstant.USERINFO, it) drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) Glide.with(this@MainActivity) .applyDefaultRequestOptions(RequestOptions().error(R.mipmap.img_avatar_default) .centerCrop()) .asBitmap() .load(it.data.avatar) .into(iv_UserLogo) Glide.with(this@MainActivity) .applyDefaultRequestOptions(RequestOptions().centerCrop()) .load(it.data.top_image) .into(user_Home_Bg) tv_UserName.text = it.data.username if (TextUtils.isEmpty(it.data.like_num)) { tv_UserLike.text = "0 关注 · " } else { tv_UserLike.text = "${it.data.follow_num} 关注 · " } if (it.data.fans_switch == 0) {//切换是否隐藏读者数 if (TextUtils.isEmpty(it.data.fans_num)) { tv_UserFans.text = "0 读者" } else { tv_UserFans.text = "${it.data.fans_num} 读者" } } else { tv_UserFans.text = "未知 读者" } socket = SocketUtils.initSocket() // updateFrag() if (TextUtils.isEmpty(it.data.like_game) || TextUtils.isEmpty(it.data.username)) { // startActivity(Intent(this@MainActivity, PerfectInfoActivity::class.java)) } else { if (!TextUtils.isEmpty(it.data.like_game)) { val split = it.data.like_game.split(",") if (split.isEmpty()) { // startActivity(Intent(this@MainActivity, PerfectInfoActivity::class.java)) } } } } } override fun onError(obj: Any?) { /** * 错误的时候 未登录 */ drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) transLayout.showContent() } }) } private val homeFrag = HomeFragment() private val gameFrag = GameFragment() private val lifeCircle = LifCircleFragment() private val msgFrag = MsgFragment() private var currentFrag: Fragment? = null override fun setContent() { setContent(R.layout.activity_main) } override fun initView() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = window window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = Color.TRANSPARENT } drawerlayout.closeDrawers() val params = left_drawer.layoutParams as DrawerLayout.LayoutParams params.gravity = Gravity.START left_drawer.layoutParams = params // drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) } override fun initData() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_PERMISSION) } } switchFragment(TypeFragment.Home) persent?.postToken() persent?.queryInfo() } override fun initEvent() { actionbarView.setOnTabClickListener { when (it.id) { R.id.tab_01 -> { switchFragment(TypeFragment.Home) true } R.id.tab_02 -> { switchFragment(TypeFragment.Echoe) true } R.id.Iv_HomeButton -> { if (AppTools.isLogin(this)) { startActivity(Intent(this, WriteDynamicActivity::class.java)) } else { startActivity(Intent(this, LoginActivity::class.java)) overridePendingTransition(R.anim.act_enter_trans, 0) } true } R.id.tab_03 -> { if (!AppTools.isLogin(this)) { startActivity(Intent(this, LoginActivity::class.java)) overridePendingTransition(R.anim.act_enter_trans, 0) false } else { switchFragment(TypeFragment.Listen) true } } R.id.tab_04 -> { switchFragment(TypeFragment.Me) true } else -> { false } } } iv_login_out.setOnClickListener { map["_token"] = App.s_Token!! persent?.loginOut(map) } relative_User_Home.setOnClickListener { val infoData = PreferenceTools.getObj(this, IConstant.USERINFO, UserInfoData::class.java) startActivity(Intent(this, UserHomeActivity::class.java).putExtra("userId", infoData.data.uid)) } relative_love_game.setOnClickListener { val infoData = PreferenceTools.getObj(this, IConstant.USERINFO, UserInfoData::class.java) startActivity(Intent(this, UserGameListActivity::class.java) .putExtra("userId", infoData.data.uid)) } relative_text.setOnClickListener { val infoData = PreferenceTools.getObj(this, IConstant.USERINFO, UserInfoData::class.java) startActivity(Intent(this, UserEditTextActivity::class.java) .putExtra("userId", infoData.data.uid)) } relative_album.setOnClickListener { val infoData = PreferenceTools.getObj(this, IConstant.USERINFO, UserInfoData::class.java) startActivity(Intent(this, UserAlbumActivity::class.java) .putExtra("userId", infoData.data.uid) ) } relative_User_Wallet.setOnClickListener { startActivity(Intent(this, UserWalletActivity::class.java)) } relative_User_Enjoy.setOnClickListener { startActivity(Intent(this, UserEnjoyActivity::class.java)) } relative_Setting.setOnClickListener { startActivity(Intent(this, UserSetActivity::class.java)) } iv_Help.setOnClickListener { startActivity(Intent(this, InviteCodeActivity::class.java)) } tv_UserLike.setOnClickListener { val infoData = PreferenceTools.getObj(this, IConstant.USERINFO, UserInfoData::class.java) startActivity(Intent(this, LoveListActivity::class.java).putExtra("userId", infoData.data.uid)) } } override fun request() { } private fun switchFragment(type: TypeFragment) { val transTemp = supportFragmentManager.beginTransaction() currentFrag?.let { transTemp.hide(currentFrag!!) } when (type) { TypeFragment.Home -> currentFrag = homeFrag TypeFragment.Echoe -> currentFrag = gameFrag TypeFragment.Listen -> currentFrag = lifeCircle TypeFragment.Me -> currentFrag = msgFrag } currentFrag?.let { if (!currentFrag!!.isAdded) { transTemp.add(R.id.frame_Fragment, currentFrag!!) } } transTemp.show(currentFrag!!) transTemp.commit() } enum class TypeFragment(type: Int) { Home(0), Echoe(1), Listen(2), Me(3); var value = type } override fun onDestroy() { super.onDestroy() socket?.let { it.close(1000, "") socket = null } } @Subscribe(threadMode = ThreadMode.MAIN) fun loginEvent(event: LoginEvent) { persent?.queryInfo() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_PERMISSION) { } } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { val intent = Intent(Intent.ACTION_MAIN) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK// 注意 intent.addCategory(Intent.CATEGORY_HOME) this.startActivity(intent) return true } return super.onKeyDown(keyCode, event) } @Subscribe(threadMode = ThreadMode.MAIN) fun socketEvent(event: SocketEvent) { Log.d("Mozator", event.msg) } @Subscribe(threadMode = ThreadMode.MAIN) fun offline(event: SocketOffline) { /** * 断线重连 */ socket?.let { socket = null } } }
1
Java
1
3
9c135be1c110057c732e7b8e1d22cd7384305864
12,917
gmBeta
MIT License
app/src/main/java/com/lukieoo/rickandmorty/util/ProgressStatus.kt
Lukieoo
323,849,579
false
null
package com.lukieoo.rickandmorty.util interface ProgressStatus { fun hideProgress() fun showProgress() }
0
Kotlin
0
0
eba16653ae59dea2977e58b509055739e37ec991
113
RickAndMorty
MIT License
Task2/src/main/kotlin/ru/spbau/mit/testing/pages/BasePage.kt
e5l
91,070,528
false
null
package ru.spbau.mit.testing.pages import org.openqa.selenium.WebDriver import ru.spbau.mit.testing.Locators open class BasePage(val driver: WebDriver) { val name get() = driver.findElement(Locators.name) val image get() = driver.findElement(Locators.image) val price get() = driver.findElement(Locators.price) /* tabs */ val descriptionTab get() = driver.findElement(Locators.descriptionTab) val specsTab get() = driver.findElement(Locators.specificationTab) val offersTab get() = driver.findElement(Locators.offersTab) val mapTab get() = driver.findElement(Locators.mapTab) val reviewsTab get() = driver.findElement(Locators.reviewsTab) val articlesTab get() = driver.findElement(Locators.articlesTab) val forumsTab get() = driver.findElement(Locators.forumsTab) val toCartButton get() = driver.findElement(Locators.toCartButton) val toWishlistButton get() = driver.findElement(Locators.wishlistButton) val toCompareButton get() = driver.findElement(Locators.toCompareButton) fun descriptionClick(): DescriptionPage { descriptionTab.click() return DescriptionPage(driver) } fun specificationsClick(): SpecsPage { specsTab.click() return SpecsPage(driver) } fun offersClick(): OffersPage { offersTab.click() return OffersPage(driver) } fun mapClick(): MapPage { mapTab.click() return MapPage(driver) } fun reviewsClick(): ReviewsPage { reviewsTab.click() return ReviewsPage(driver) } fun articlesClick(): ArticlesPage { articlesTab.click() return ArticlesPage(driver) } fun forumsClick(): ForumsPage { forumsTab.click() return ForumsPage(driver) } fun addToCart() { toCartButton.click() } fun addToWishList() { toWishlistButton.click() } fun addToCompare() { toCompareButton.click() } }
0
Kotlin
0
0
691d54f7c15d9f952a7c065cf6e1392bbb4249f5
1,976
Testing
The Unlicense
app/src/main/java/com/example/newair/fragments/settings/RemoveLocationDialog.kt
vladislav-iliev
606,184,408
false
null
package com.example.newair.fragments.settings import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.fragment.app.activityViewModels import com.example.newair.R import com.example.newair.data.SensorViewModel import com.google.android.material.dialog.MaterialAlertDialogBuilder internal class RemoveLocationDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog { val builder = MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.delete_user_location_dialog_title) addListeners(builder, setUpDeletionList()) return builder.create() } private fun setUpDeletionList(): Array<String> { val viewModel: SensorViewModel by activityViewModels() return viewModel.uiState.value!!.userLocations.map { it.name }.toTypedArray() } private fun addListeners(builder: AlertDialog.Builder, items: Array<String>) { val viewModel: SensorViewModel by activityViewModels() builder.setItems(items) { d, pos -> viewModel.removeUserLocation(items[pos]) d.dismiss() } builder.setNegativeButton(android.R.string.cancel) { d, _ -> d.cancel() } } }
0
Kotlin
0
0
fb8e049ada351e8be5abf2b1de3cdb7154927ff7
1,283
NewAir
MIT License
src/commonTest/kotlin/org/angproj/aux/pkg/prime/ShortTypeTest.kt
angelos-project
677,039,667
false
{"Kotlin": 1030080, "Python": 196308}
package org.angproj.aux.pkg.prime import org.angproj.aux.buf.BinaryBuffer import org.angproj.aux.io.binOf import org.angproj.aux.pkg.FoldFormat import org.angproj.aux.pkg.type.BlockType import kotlin.test.Test import kotlin.test.assertEquals class ShortTypeTest { val first: Short = 25249 @Test fun enfoldToBlock() { val type = ShortType(first) val block = BlockType(binOf(type.foldSize(FoldFormat.BLOCK).toInt())) assertEquals(block.foldSize(FoldFormat.BLOCK), type.foldSize(FoldFormat.BLOCK)) type.enfoldToBlock(block, 0) val retrieved = ShortType.unfoldFromBlock(block, 0) assertEquals(type.value, retrieved.value) } @Test fun enfoldToStream() { val type = ShortType(first) val stream = BinaryBuffer() type.enfoldToStream(stream) stream.flip() assertEquals(stream.limit, type.foldSize(FoldFormat.STREAM).toInt()) val retrieved = ShortType.unfoldFromStream(stream) assertEquals(type.value, retrieved.value) } }
0
Kotlin
0
0
227b53e6242da4655fb3988cb8174a1b721f4729
1,051
angelos-project-aux
MIT License
v2-model-enumeration/src/commonMain/kotlin/com/bselzer/gw2/v2/model/enumeration/UpgradeAction.kt
Woody230
388,820,096
false
{"Kotlin": 750899}
package com.bselzer.gw2.v2.model.enumeration import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class UpgradeAction { @SerialName("queued") QUEUED, @SerialName("cancelled") CANCELLED, @SerialName("completed") COMPLETED, @SerialName("sped_up") SPED_UP }
2
Kotlin
0
2
32f1fd4fc4252dbe886b6fc0f4310cf34ac2ef27
339
GW2Wrapper
Apache License 2.0
appcues/src/test/java/com/appcues/action/appcues/LinkActionTest.kt
appcues
413,524,565
false
{"Kotlin": 1237822, "Shell": 17991, "Ruby": 1503}
package com.appcues.action.appcues import android.content.ActivityNotFoundException import android.net.Uri import com.appcues.Appcues import com.appcues.AppcuesScopeTest import com.appcues.NavigationHandler import com.appcues.di.component.get import com.appcues.logging.Logcues import com.appcues.rules.TestScopeRule import com.appcues.util.LinkOpener import com.google.common.truth.Truth.assertThat import io.mockk.Called import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.verify import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test internal class LinkActionTest : AppcuesScopeTest { @get:Rule override val scopeRule = TestScopeRule() @Before fun setUp() { // mocking of android.net.Uri is required https://stackoverflow.com/a/63890812 val mockWebUri = mockk<Uri>(relaxed = true) { every { [email protected]() } returns "https://test/path" every { [email protected] } returns "https" } val mockAppSchemeUri = mockk<Uri>(relaxed = true) { every { [email protected]() } returns "myapp://test/path" every { [email protected] } returns "myapp" } val invalidUri = mockk<Uri>(relaxed = true) { every { [email protected]() } returns "invalid:url" every { [email protected] } returns null } mockkStatic(Uri::class) every { Uri.parse("https://test/path") } returns mockWebUri every { Uri.parse("myapp://test/path") } returns mockAppSchemeUri every { Uri.parse("invalid:url") } returns invalidUri } @Test fun `link SHOULD have expected type name`() { assertThat(LinkAction.TYPE).isEqualTo("@appcues/link") } @Test fun `custom constructor SHOULD include url to configMap`() = runTest { // GIVEN val linkOpener: LinkOpener = get() val appcues = mockk<Appcues>(relaxed = true) val action = LinkAction(redirectUrl = "custom-url", linkOpener, appcues, mockk(relaxed = true)) // THEN assertThat(action.config).containsEntry("url", "custom-url") } @Test fun `category SHOULD be link`() { // GIVEN val linkOpener: LinkOpener = get() val appcues = mockk<Appcues>(relaxed = true) val action = LinkAction(mapOf(), linkOpener, appcues, mockk(relaxed = true)) // THEN assertThat(action.category).isEqualTo("link") } @Test fun `destination SHOULD match url`() { // GIVEN val linkOpener: LinkOpener = get() val appcues = mockk<Appcues>(relaxed = true) val action = LinkAction(mapOf("url" to "test-url.com"), linkOpener, appcues, mockk(relaxed = true)) // THEN assertThat(action.destination).isEqualTo("test-url.com") } @Test fun `destination SHOULD be empty if no url is present`() { // GIVEN val linkOpener: LinkOpener = get() val appcues = mockk<Appcues>(relaxed = true) val action = LinkAction(mapOf(), linkOpener, appcues, mockk(relaxed = true)) // THEN assertThat(action.destination).isEmpty() } @Test fun `link SHOULD call LinkOpener startNewIntent for external web link WHEN no navigationHandler is set`() = runTest { // GIVEN val uri: Uri = Uri.parse("https://test/path") val linkOpener: LinkOpener = get() val appcues = mockk<Appcues>(relaxed = true) { every { [email protected] } returns null } val action = LinkAction(mapOf("url" to uri.toString(), "openExternally" to true), linkOpener, appcues, mockk(relaxed = true)) // WHEN action.execute() // THEN verify { linkOpener.startNewIntent(uri) } } @Test fun `link SHOULD call navigationHandler navigate for external web link WHEN navigationHandler is set`() = runTest { // GIVEN val uri: Uri = Uri.parse("https://test/path") val linkOpener: LinkOpener = get() val mockkNavigationHandler = mockk<NavigationHandler>(relaxed = true) val appcues = mockk<Appcues>(relaxed = true) { every { [email protected] } returns mockkNavigationHandler } val action = LinkAction(mapOf("url" to uri.toString(), "openExternally" to true), linkOpener, appcues, mockk(relaxed = true)) // WHEN action.execute() // THEN coVerify { mockkNavigationHandler.navigateTo(uri) } verify { linkOpener wasNot Called } } @Test fun `link SHOULD call LinkOpener openCustomTabs by default for web link`() = runTest { // GIVEN val uri: Uri = Uri.parse("https://test/path") val linkOpener: LinkOpener = get() val action = LinkAction(mapOf("url" to uri.toString()), linkOpener, get(), mockk(relaxed = true)) // WHEN action.execute() // THEN verify { linkOpener.openCustomTabs(uri) } } @Test fun `link SHOULD call LinkOpener startNewIntent for app scheme link WHEN no navigationHandler is set`() = runTest { // GIVEN val uri: Uri = Uri.parse("myapp://test/path") val linkOpener: LinkOpener = get() val appcues = mockk<Appcues>(relaxed = true) { every { [email protected] } returns null } val action = LinkAction(mapOf("url" to uri.toString()), linkOpener, appcues, mockk(relaxed = true)) // WHEN action.execute() // THEN verify { linkOpener.startNewIntent(uri) } } @Test fun `link SHOULD call navigationHandler navigate for app scheme link WHEN navigationHandler is set`() = runTest { // GIVEN val uri: Uri = Uri.parse("myapp://test/path") val linkOpener: LinkOpener = get() val mockkNavigationHandler = mockk<NavigationHandler>(relaxed = true) val appcues = mockk<Appcues>(relaxed = true) { every { [email protected] } returns mockkNavigationHandler } val action = LinkAction(mapOf("url" to uri.toString()), linkOpener, appcues, mockk(relaxed = true)) // WHEN action.execute() // THEN coVerify { mockkNavigationHandler.navigateTo(uri) } verify { linkOpener wasNot Called } } @Test fun `execute SHOULD not call anything when url is null`() = runTest { // GIVEN val linkOpener: LinkOpener = get() val mockkNavigationHandler = mockk<NavigationHandler>(relaxed = true) val appcues = mockk<Appcues>(relaxed = true) { every { [email protected] } returns mockkNavigationHandler } val action = LinkAction(mapOf(), linkOpener, appcues, mockk(relaxed = true)) // WHEN action.execute() // THEN coVerify { mockkNavigationHandler wasNot Called } verify { linkOpener wasNot Called } } @Test fun `execute SHOULD not call anything when url scheme is null`() = runTest { // GIVEN val uri: Uri = Uri.parse("invalid:url") val linkOpener: LinkOpener = get() val mockkNavigationHandler = mockk<NavigationHandler>(relaxed = true) val appcues = mockk<Appcues>(relaxed = true) { every { [email protected] } returns mockkNavigationHandler } val action = LinkAction(mapOf("url" to uri.toString()), linkOpener, appcues, mockk(relaxed = true)) // WHEN action.execute() // THEN coVerify { mockkNavigationHandler wasNot Called } verify { linkOpener wasNot Called } } @Test fun `execute SHOULD call logcues error when ActivityNotFoundException is thrown by linkOpener`() = runTest { // GIVEN val uri: Uri = Uri.parse("myapp://test/path") val exception = ActivityNotFoundException("Invalid Activity") val linkOpener: LinkOpener = mockk(relaxed = true) { every { startNewIntent(any()) } throws exception } val appcues = mockk<Appcues>(relaxed = true) { every { [email protected] } returns null } val logcues = mockk<Logcues>(relaxed = true) val action = LinkAction(mapOf("url" to uri.toString()), linkOpener, appcues, logcues) // WHEN action.execute() // THEN verify { logcues.error(message = "Unable to process deep link myapp://test/path\n\n Reason: ${exception.message}") } } @Test fun `execute SHOULD call logcues error when ActivityNotFoundException is thrown by navigationHandler`() = runTest { // GIVEN val uri: Uri = Uri.parse("myapp://test/path") val linkOpener: LinkOpener = get() val exception = ActivityNotFoundException("Invalid Activity") val appcues = mockk<Appcues>(relaxed = true) { every { [email protected] } returns mockk(relaxed = true) { coEvery { navigateTo(any()) } throws exception } } val logcues = mockk<Logcues>(relaxed = true) val action = LinkAction(mapOf("url" to uri.toString()), linkOpener, appcues, logcues) // WHEN action.execute() // THEN verify { logcues.error(message = "Unable to process deep link myapp://test/path\n\n Reason: ${exception.message}") } } }
3
Kotlin
1
9
2773df84e5da2a16188c1226f261bdef82f53c8a
9,513
appcues-android-sdk
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/HalfSpace.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: HalfSpace * * Full name: System`HalfSpace * * HalfSpace[n, p] represents the half-space of points x such that n . (x - p) ≤ 0. * Usage: HalfSpace[n, c] represents the half-space of points x such that n . x ≤ c. * * Options: None * * Attributes: Protected * * local: paclet:ref/HalfSpace * Documentation: web: http://reference.wolfram.com/language/ref/HalfSpace.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun halfSpace(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("HalfSpace", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,053
mathemagika
Apache License 2.0
visitor/src/main/kotlin/io/kommons/designpatterns/visitor/Commander.kt
debop
235,066,649
false
null
package io.kommons.designpatterns.visitor /** * Commander * * @author debop * @since 29/09/2019 */ class Commander(override val children: MutableList<Node> = mutableListOf()): Node { override fun accept(visitor: NodeVisitor) { visitor.visit(this) super.accept(visitor) } override fun toString(): String = "commander" }
0
Kotlin
11
53
c00bcc0542985bbcfc4652d0045f31e5c1304a70
354
kotlin-design-patterns
Apache License 2.0
parsing_json_demo/android/app/src/main/kotlin/com/example/parsing_json_demo/MainActivity.kt
honkerSK
162,970,921
false
{"Dart": 160968, "Swift": 11648, "Kotlin": 8284, "Objective-C": 6761, "Java": 4472, "Ruby": 4405}
package com.example.parsing_json_demo import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
1
1
13d786c5688c2f8bd6b77c057c8828f25fcb7e5e
134
SKFlutterDemo
MIT License
knotion-core/src/main/kotlin/io/github/rgbrizzlehizzle/knotion/models/page/property/UrlPageProperty.kt
rgbrizzlehizzle
367,649,156
false
null
package io.github.rgbrizzlehizzle.knotion.models.page.property import kotlinx.serialization.Serializable @Serializable data class UrlPageProperty( override val id: String? = null, val url: String? ) : PageProperty
3
Kotlin
0
1
0ea51bc9b1ffb4c590d3724e969b345de3b4d176
220
knotion
MIT License
src/main/kotlin/com/tul/carshop/configurations/Swagger.kt
ManuGarcia1989
352,328,507
false
null
package com.tul.carshop.configurations import com.tul.carshop.CarshopApplication import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import springfox.documentation.builders.PathSelectors import springfox.documentation.builders.RequestHandlerSelectors import springfox.documentation.spi.DocumentationType import springfox.documentation.spring.web.plugins.Docket import springfox.documentation.swagger2.annotations.EnableSwagger2 @Configuration @EnableSwagger2 class Swagger { @Bean fun api():Docket = Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage(CarshopApplication:: class.java.`package`.name)) .paths(PathSelectors.any()) .build() }
0
Kotlin
0
0
6334b44dd954519ee84685f88dd4491deb305b1e
776
shoppingcar
Info-ZIP License
idea/src/org/jetbrains/kotlin/idea/quickfix/migration/RemoveAnnotationFix.kt
culvert
42,346,712
false
{"Markdown": 34, "XML": 694, "Ant Build System": 44, "Git Attributes": 1, "Ignore List": 7, "Maven POM": 51, "Kotlin": 19994, "Groovy": 23, "Java": 4435, "Shell": 11, "Batchfile": 10, "Java Properties": 11, "Gradle": 74, "HTML": 144, "INI": 7, "CSS": 2, "JavaScript": 63, "Text": 4403, "ANTLR": 1, "Protocol Buffer": 7, "JAR Manifest": 3, "Roff": 39, "Roff Manpage": 10, "Proguard": 1, "JFlex": 2}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.quickfix.migration import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.quickfix.JetIntentionAction import org.jetbrains.kotlin.idea.quickfix.JetSingleIntentionActionFactory import org.jetbrains.kotlin.idea.quickfix.quickfixUtil.createIntentionForFirstParentOfType import org.jetbrains.kotlin.psi.JetAnnotationEntry import org.jetbrains.kotlin.psi.JetFile public class RemoveAnnotationFix(element: JetAnnotationEntry) : JetIntentionAction<JetAnnotationEntry>(element) { override fun getFamilyName(): String = getText() override fun getText(): String = "Remove annotation" override fun invoke(project: Project, editor: Editor?, file: JetFile) { element.delete() } object Factory : JetSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = diagnostic.createIntentionForFirstParentOfType(::RemoveAnnotationFix) } }
1
null
1
1
69038ba6c09a4427ace5158fd434e27f1672d3f0
1,639
kotlin
Apache License 2.0
mvp/src/main/java/com/gilgoldzweig/mvp/mvp/BaseContract.kt
gilgoldzweig
167,931,739
false
null
package com.gilgoldzweig.mvp.mvp import android.arch.lifecycle.Lifecycle import android.support.annotation.UiThread /** * A contract between a view(ie: Activity, Fragment) and a presenter handling the logic of the view */ interface BaseContract { /** * The view's part of the contract * all functions that the presenter can call and return values will be here * * It's the presenter's job to make sure that all calls to the view we be on the UI thread * * example: * * interface ViewImpl : BaseContract.View { * * fun onNetworkRequestCompletedSuccessfully(data: Data) * * fun onNetworkRequestFailed(reason: ExceptionReason) * } */ @UiThread interface View /** * The presenter's part of the contract * all functions that the view can call to perform actions * * The presenter needs to return the actions on the UI thread * * example: * * interface PresenterImpl : BaseContract.Presenter<ViewImpl> { * * fun performNetworkRequest() * * } */ interface Presenter<V : View> { /** * The View's way to be attached to the presenter * @param lifecycle if a lifecycle is provided the presenter will be bound to it, and be able to detach automatically */ fun attach(view: V, lifecycle: Lifecycle? = null) /** * Detach's the view from the presenter and verify that all processes running are killed, * remove all references of the view */ fun detach() } }
2
Kotlin
0
3
82c26faa2ec1ca760f09e40267a67d9da58bfac8
1,449
MVP-Project-starter
Apache License 2.0
src/support/integration/src/main/kotlin/kiit/integration/apis/CacheApi.kt
slatekit
55,942,000
false
{"Text": 42, "Ignore List": 42, "YAML": 3, "Markdown": 22, "Gradle": 79, "Shell": 46, "Batchfile": 40, "Java Properties": 25, "Kotlin": 884, "JSON": 12, "INI": 9, "EditorConfig": 26, "Java": 13, "SQL": 1, "XML": 4, "Swift": 3}
/** * <kiit_header> * url: www.kiit.dev * git: www.github.com/slatekit/kiit * org: www.codehelix.co * author: <NAME> * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * * * </kiit_header> */ package kiit.integration.apis import kiit.apis.Api import kiit.apis.Action import kiit.apis.AuthModes import kiit.apis.Verbs import kiit.apis.support.FileSupport import kiit.cache.* import kiit.common.crypto.Encryptor import kiit.common.log.Logger import kiit.common.Sources import kiit.context.Context import kiit.results.Outcome import kiit.results.builders.Outcomes @Api(area = "infra", name = "cache", desc = "api info about the application and host", auth = AuthModes.KEYED, roles = ["admin"], verb = Verbs.AUTO, sources = [Sources.ALL]) class CacheApi(override val context: Context, val caches: List<AsyncCache>) : FileSupport { private val lookup = caches.map { it.id.name to it }.toMap() override val encryptor: Encryptor? = context.enc override val logger: Logger? = context.logs.getLogger() @Action(desc = "gets the names of keys in the cache") suspend fun keys(name:String): List<String>? { return lookup[name]?.keys() } @Action(desc = "gets the size of the cache") suspend fun size(name:String): Int? { return lookup[name]?.size() } @Action(desc = "gets the details of a single cache item") suspend fun get(name:String, key: String): Any? { return lookup[name]?.getAsync<Any>(key) } @Action(desc = "gets the details of a single cache item") suspend fun stats(name:String): List<CacheStats>? { return lookup[name]?.stats() } @Action(desc = "invalidates a single cache item") suspend fun delete(name:String, key: String):Outcome<Boolean> { return operate(name) { it.delete(key) } } @Action(desc = "invalidates the entire cache") suspend fun deleteAll(name:String):Outcome<Boolean> { return operate(name) { it.deleteAll() } } @Action(desc = "invalidates a single cache item") suspend fun expire(name:String, key: String):Outcome<Boolean> { return operate(name) { it.expire(key) } } @Action(desc = "invalidates the entire cache") suspend fun expireAll(name:String):Outcome<Boolean> { return operate(name) { it.expireAll() } } private suspend fun <T> operate(key:String, op:suspend (AsyncCache) -> Outcome<T>): Outcome<T> { return when(val cache = lookup[key]) { null -> Outcomes.invalid("Cache with name $key not found") else -> op(cache) } } }
3
Kotlin
13
112
d17b592aeb28c5eb837d894e98492c69c4697862
2,634
slatekit
Apache License 2.0
reactive-assembler-kotlin-extension/src/test/kotlin/io/github/pellse/reactive/assembler/test/FluxAssemblerKotlinTest.kt
MrLoyal
641,446,443
false
{"Gradle": 11, "Shell": 1, "Markdown": 9, "Batchfile": 1, "Text": 1, "Ignore List": 10, "Java": 95, "Kotlin": 3, "INI": 1}
/* * Copyright 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 io.github.pellse.reactive.assembler.test import io.github.pellse.reactive.assembler.Rule.rule import io.github.pellse.reactive.assembler.RuleMapper.oneToMany import io.github.pellse.reactive.assembler.RuleMapper.oneToOne import io.github.pellse.reactive.assembler.cache.caffeine.CaffeineCacheFactory.caffeineCache import io.github.pellse.reactive.assembler.caching.AutoCacheFactory.autoCache import io.github.pellse.reactive.assembler.caching.AutoCacheFactoryBuilder.autoCacheBuilder import io.github.pellse.reactive.assembler.caching.AutoCacheFactoryBuilder.autoCacheEvents import io.github.pellse.reactive.assembler.caching.CacheEvent.* import io.github.pellse.reactive.assembler.caching.CacheFactory.cache import io.github.pellse.reactive.assembler.kotlin.* import io.github.pellse.reactive.assembler.test.ReactiveAssemblerTestUtils.* import io.github.pellse.reactive.assembler.util.* import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.reactivestreams.Publisher import reactor.core.publisher.Flux import reactor.core.scheduler.Schedulers.parallel import reactor.test.StepVerifier import java.time.Duration.ofMillis import java.util.concurrent.atomic.AtomicInteger class FluxAssemblerKotlinTest { private val billingInvocationCount = AtomicInteger() private val ordersInvocationCount = AtomicInteger() private fun getBillingInfo(customerIds: List<Long>): Publisher<BillingInfo> { return Flux.just(billingInfo1, billingInfo3) .filter { customerIds.contains(it.customerId) } .doOnComplete(billingInvocationCount::incrementAndGet) } private fun getAllOrders(customerIds: List<Long>): Publisher<OrderItem> { return Flux.just(orderItem11, orderItem12, orderItem13, orderItem21, orderItem22) .filter { customerIds.contains(it.customerId) } .doOnComplete(ordersInvocationCount::incrementAndGet) } private fun getBillingInfoWithIdSet(customerIds: Set<Long>): Publisher<BillingInfo> { return Flux.just(billingInfo1, billingInfo3) .filter { customerIds.contains(it.customerId()) } .doOnComplete { billingInvocationCount.incrementAndGet() } } private fun getAllOrdersWithIdSet(customerIds: Set<Long>): Publisher<OrderItem> { return Flux.just(orderItem11, orderItem12, orderItem13, orderItem21, orderItem22) .filter { customerIds.contains(it.customerId()) } .doOnComplete { ordersInvocationCount.incrementAndGet() } } private fun getCustomers(): Flux<Customer> { return Flux.just( customer1, customer2, customer3, customer1, customer2, customer3, customer1, customer2, customer3 ) } private fun getBillingInfoNonReactive(customerIds: List<Long>): List<BillingInfo> { val list = listOf(billingInfo1, billingInfo3) .filter { billingInfo: BillingInfo -> customerIds.contains(billingInfo.customerId()) } billingInvocationCount.incrementAndGet() return list } private fun getAllOrdersNonReactive(customerIds: List<Long>): List<OrderItem> { val list = listOf(orderItem11, orderItem12, orderItem13, orderItem21, orderItem22) .filter { orderItem: OrderItem -> customerIds.contains(orderItem.customerId()) } ordersInvocationCount.incrementAndGet() return list } @BeforeEach fun setup() { billingInvocationCount.set(0) ordersInvocationCount.set(0) } @Test fun testReusableAssemblerBuilderWithFluxWithBuffering() { val assembler = assembler<Transaction>() .withCorrelationIdExtractor(Customer::customerId) .withAssemblerRules( rule(BillingInfo::customerId, ::getBillingInfo.oneToOne(::BillingInfo)), rule(OrderItem::customerId, ::getAllOrders.oneToMany(OrderItem::id)), ::Transaction ).build() StepVerifier.create( getCustomers() .window(3) .flatMapSequential(assembler::assemble) ) .expectSubscription() .expectNext( transaction1, transaction2, transaction3, transaction1, transaction2, transaction3, transaction1, transaction2, transaction3 ) .expectComplete() .verify() assertEquals(3, billingInvocationCount.get()) assertEquals(3, ordersInvocationCount.get()) } @Test fun testReusableAssemblerBuilderTransactionSet() { val assembler = assembler<TransactionSet>() .withCorrelationIdExtractor(Customer::customerId) .withAssemblerRules( rule(BillingInfo::customerId, ::hashSetOf, ::getBillingInfoWithIdSet.oneToOne(::BillingInfo)), rule(OrderItem::customerId, ::hashSetOf, ::getAllOrdersWithIdSet.oneToMany(OrderItem::id, ::hashSetOf)), ::TransactionSet ).build() StepVerifier.create( getCustomers() .window(3) .flatMapSequential(assembler::assemble) ) .expectSubscription() .expectNext( transactionSet1, transactionSet2, transactionSet3, transactionSet1, transactionSet2, transactionSet3, transactionSet1, transactionSet2, transactionSet3 ) .expectComplete() .verify() assertEquals(3, billingInvocationCount.get()) assertEquals(3, ordersInvocationCount.get()) } @Test fun testReusableAssemblerBuilderWithNonReactiveDatasources() { val assembler = assembler<Transaction>() .withCorrelationIdExtractor(Customer::customerId) .withAssemblerRules( rule(BillingInfo::customerId, oneToOne(::getBillingInfoNonReactive.toPublisher(), ::BillingInfo)), rule(OrderItem::customerId, oneToMany(OrderItem::id, ::getAllOrdersNonReactive.toPublisher())), ::Transaction ).build() StepVerifier.create( getCustomers() .window(3) .flatMapSequential(assembler::assemble) ) .expectSubscription() .expectNext( transaction1, transaction2, transaction3, transaction1, transaction2, transaction3, transaction1, transaction2, transaction3 ) .expectComplete() .verify() assertEquals(3, billingInvocationCount.get()) assertEquals(3, ordersInvocationCount.get()) } @Test fun testReusableAssemblerBuilderWithNonReactiveCachedDatasources() { val assembler = assembler<Transaction>() .withCorrelationIdExtractor(Customer::customerId) .withAssemblerRules( rule( BillingInfo::customerId, oneToOne(::getBillingInfoNonReactive.toPublisher().cached(), ::BillingInfo) ), rule(OrderItem::customerId, oneToMany(OrderItem::id, ::getAllOrdersNonReactive.toPublisher().cached())), ::Transaction ).build() StepVerifier.create( getCustomers() .window(3) .flatMapSequential(assembler::assemble) ) .expectSubscription() .expectNext( transaction1, transaction2, transaction3, transaction1, transaction2, transaction3, transaction1, transaction2, transaction3 ) .expectComplete() .verify() assertEquals(3, billingInvocationCount.get()) assertEquals(3, ordersInvocationCount.get()) } @Test fun testReusableAssemblerBuilderWithCacheWindow3() { val assembler = assembler<Transaction>() .withCorrelationIdExtractor(Customer::customerId) .withAssemblerRules( rule(BillingInfo::customerId, oneToOne(::getBillingInfo.cached(::sortedMapOf), ::BillingInfo)), rule(OrderItem::customerId, oneToMany(OrderItem::id, ::getAllOrders.cached())), ::Transaction ).build() StepVerifier.create( getCustomers() .window(3) .delayElements(ofMillis(100)) .flatMapSequential(assembler::assemble) ) .expectSubscription() .expectNext( transaction1, transaction2, transaction3, transaction1, transaction2, transaction3, transaction1, transaction2, transaction3 ) .expectComplete() .verify() assertEquals(1, billingInvocationCount.get()) assertEquals(1, ordersInvocationCount.get()) } @Test fun testReusableAssemblerBuilderWithCacheWindow2() { val assembler = assembler<Transaction>() .withCorrelationIdExtractor(Customer::customerId) .withAssemblerRules( rule(BillingInfo::customerId, oneToOne(::getBillingInfo.cached(cache(::sortedMapOf)), ::BillingInfo)), rule(OrderItem::customerId, oneToMany(OrderItem::id, ::getAllOrders.cached(caffeineCache()))), ::Transaction ).build() StepVerifier.create( getCustomers() .window(2) .delayElements(ofMillis(100)) .flatMapSequential(assembler::assemble) ) .expectSubscription() .expectNext( transaction1, transaction2, transaction3, transaction1, transaction2, transaction3, transaction1, transaction2, transaction3 ) .expectComplete() .verify() assertEquals(2, billingInvocationCount.get()) assertEquals(2, ordersInvocationCount.get()) } sealed interface CDC<T> { val item: T } data class CDCAdd<T>(override val item: T) : CDC<T> data class CDCDelete<T>(override val item: T) : CDC<T> @Test fun testReusableAssemblerBuilderWithAutoCachingEvents2() { val getAllOrders = { customerIds: List<Long> -> assertEquals(listOf(3L), customerIds) Flux.just(orderItem11, orderItem12, orderItem13, orderItem21, orderItem22) .filter { orderItem: OrderItem -> customerIds.contains(orderItem.customerId()) } .doOnComplete { ordersInvocationCount.incrementAndGet() } } val updatedBillingInfo2 = BillingInfo(2L, 2L, "4540111111111111") val billingInfoFlux = Flux.just(updated(billingInfo1), updated(billingInfo2), updated(updatedBillingInfo2), updated(billingInfo3)) .subscribeOn(parallel()) val orderItemFlux = Flux.just( CDCAdd(orderItem11), CDCAdd(orderItem12), CDCAdd(orderItem13), CDCAdd(orderItem21), CDCAdd(orderItem22), CDCAdd(orderItem31), CDCAdd(orderItem32), CDCAdd(orderItem33), CDCDelete(orderItem31), CDCDelete(orderItem32), CDCDelete(orderItem33) ) .map { when (it) { is CDCAdd -> Updated(it.item) is CDCDelete -> Removed(it.item) } } .subscribeOn(parallel()) val transaction2 = Transaction(customer2, updatedBillingInfo2, listOf(orderItem21, orderItem22)) val assembler = assembler<Transaction>() .withCorrelationIdExtractor(Customer::customerId) .withAssemblerRules( rule( BillingInfo::customerId, oneToOne(::getBillingInfo.cached(autoCacheEvents(billingInfoFlux).maxWindowSize(3).build())) ), rule( OrderItem::customerId, oneToMany( OrderItem::id, getAllOrders.cached(cache(), autoCacheEvents(orderItemFlux).maxWindowSize(3).build()) ) ), ::Transaction ) .build() StepVerifier.create( getCustomers() .window(3) .delayElements(ofMillis(100)) .flatMapSequential(assembler::assemble) ) .expectSubscription() .expectNext( transaction1, transaction2, transaction3, transaction1, transaction2, transaction3, transaction1, transaction2, transaction3 ) .expectComplete() .verify() assertEquals(0, billingInvocationCount.get()) assertEquals(1, ordersInvocationCount.get()) } @Test fun testReusableAssemblerBuilderWithAutoCachingEvents3() { val billingInfoFlux: Flux<CDC<BillingInfo>> = Flux.just(CDCAdd(billingInfo1), CDCAdd(billingInfo2), CDCAdd(billingInfo3), CDCDelete(billingInfo3)) val orderItemFlux: Flux<CDC<OrderItem>> = Flux.just( CDCAdd(orderItem31), CDCAdd(orderItem32), CDCAdd(orderItem33), CDCDelete(orderItem31), CDCDelete(orderItem32), CDCDelete(orderItem33) ) val assembler = assembler<Transaction>() .withCorrelationIdExtractor(Customer::customerId) .withAssemblerRules( rule(BillingInfo::customerId, oneToOne( ::getBillingInfo.cached(autoCache(billingInfoFlux, CDCAdd::class::isInstance) { it.item }))), rule(OrderItem::customerId, oneToMany(OrderItem::id, ::getAllOrders.cached( autoCacheBuilder(orderItemFlux, CDCAdd::class::isInstance, CDC<OrderItem>::item) .maxWindowSize(3) .build()))), ::Transaction) .build() } }
1
null
1
1
82e00748f142d2ed8c7fc296d025ef3653ba4ee1
15,473
Assembler
Apache License 2.0
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/AndroidParcelizeProject/app/src/main/java/com/example/parcelize/MyActivity.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.parcelize import android.os.Bundle import android.os.Parcelable import android.app.Activity import kotlinx.parcelize.* class HomeActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val user = User("John", 18) outState.putParcelable("foo", user) } } @Parcelize class User(val name: String, val age: Int): Parcelable
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,187
kotlin
Apache License 2.0
src/main/kotlin/me/steven/indrev/recipes/machines/CompressorRecipe.kt
Elleery
287,177,196
true
{"Kotlin": 363553, "JavaScript": 28235, "Java": 18399}
package me.steven.indrev.recipes.machines import com.google.gson.JsonObject import me.steven.indrev.IndustrialRevolution import me.steven.indrev.utils.getFirstMatch import me.steven.indrev.utils.identifier import net.minecraft.inventory.Inventory import net.minecraft.item.ItemStack import net.minecraft.network.PacketByteBuf import net.minecraft.recipe.Ingredient import net.minecraft.recipe.Recipe import net.minecraft.recipe.RecipeSerializer import net.minecraft.recipe.RecipeType import net.minecraft.util.Identifier import net.minecraft.util.JsonHelper import net.minecraft.util.collection.DefaultedList import net.minecraft.util.registry.Registry import net.minecraft.world.World class CompressorRecipe(private val id: Identifier, val processTime: Int, private val output: ItemStack, val input: Ingredient) : Recipe<Inventory> { override fun craft(inv: Inventory?): ItemStack = output.copy() override fun getId(): Identifier = id override fun getType(): RecipeType<*> = TYPE override fun fits(width: Int, height: Int): Boolean = true override fun getSerializer(): RecipeSerializer<*> = SERIALIZER override fun getOutput(): ItemStack = output override fun getPreviewInputs(): DefaultedList<Ingredient> = DefaultedList.of<Ingredient>().also { it.add(input) } override fun matches(inv: Inventory?, world: World?): Boolean = input.test(inv?.getStack(0)) companion object { val TYPE = object : RecipeType<CompressorRecipe> {} val SERIALIZER = Serializer() val IDENTIFIER = identifier("compress") class Serializer : RecipeSerializer<CompressorRecipe> { override fun write(buf: PacketByteBuf, recipe: CompressorRecipe) { recipe.input.write(buf) buf.writeInt(recipe.processTime) buf.writeItemStack(recipe.output) } override fun read(id: Identifier, json: JsonObject): CompressorRecipe { val input = Ingredient.fromJson(json.getAsJsonObject("ingredient")) val result = json.get("output").asJsonObject val itemPath = result.get("item").asString val item = if (itemPath.contains(":")) Registry.ITEM.get(Identifier(itemPath)) else getFirstMatch( arrayOf( Identifier(IndustrialRevolution.CONFIG.compatibility.targetModId, itemPath), identifier(itemPath) ), Registry.ITEM ) val output = ItemStack { item } output.count = JsonHelper.getInt(result, "count", 1) val ticks = json.get("processTime").asInt return CompressorRecipe(id, ticks, output, input) } override fun read(id: Identifier, buf: PacketByteBuf): CompressorRecipe { val input = Ingredient.fromPacket(buf) val processTime = buf.readInt() val output = buf.readItemStack() return CompressorRecipe( id, processTime, output, input ) } } } }
0
Kotlin
0
0
d3eebf7f3608bb10796ae06708c7fdedf21d335b
3,314
Industrial-Revolution
Apache License 2.0
libraries/tools/kotlin-tooling-core/src/test/kotlin/org/jetbrains/kotlin/tooling/core/ExtrasSerializableTest.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.tooling.core import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotSame import kotlin.test.assertSame class ExtrasSerializableTest { @Test fun `test - serialize deserialize - MutableExtras`() { val extras = mutableExtrasOf(extrasKeyOf<String>() withValue "hello") val deserializedExtras = extras.serialize().deserialize<Extras>() assertNotSame(extras, deserializedExtras) assertEquals(extras, deserializedExtras) } @Test fun `test - serialize deserialize - EmptyExtras`() { assertSame(emptyExtras(), emptyExtras()) assertSame(emptyExtras(), emptyExtras().serialize().deserialize()) } @Test fun `test - serialize deserialize - ImmutableExtras`() { val extras = extrasOf(extrasKeyOf<String>() withValue "hello") val deserializedExtras = extras.serialize().deserialize<Extras>() assertNotSame(extras, deserializedExtras) assertEquals(extras, deserializedExtras) assertSame(extras.javaClass, deserializedExtras.javaClass) } private fun Any.serialize(): ByteArray { return ByteArrayOutputStream().use { byteArrayOutputStream -> ObjectOutputStream(byteArrayOutputStream).use { objectOutputStream -> objectOutputStream.writeObject(this) } byteArrayOutputStream.toByteArray() } } private inline fun <reified T : Any> ByteArray.deserialize(): T { return ObjectInputStream(ByteArrayInputStream(this)).use { stream -> stream.readObject() as T } } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,963
kotlin
Apache License 2.0
core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/methodSignatureBuilding.kt
cypressious
52,316,479
true
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.load.kotlin import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.name.ClassId import java.util.* inline fun <T> signatures(block: SignatureBuildingComponents.() -> T) = with(SignatureBuildingComponents, block) object SignatureBuildingComponents { fun javaLang(name: String) = "java/lang/$name" fun javaUtil(name: String) = "java/util/$name" fun constructors(vararg signatures: String) = signatures.map { "<init>($it)V" }.toTypedArray() fun inJavaLang(name: String, vararg signatures: String) = inClass(javaLang(name), *signatures) fun inJavaUtil(name: String, vararg signatures: String) = inClass(javaUtil(name), *signatures) fun inClass(internalName: String, vararg signatures: String) = signatures.mapTo(LinkedHashSet()) { internalName + "." + it } fun signature(classDescriptor: ClassDescriptor, jvmDescriptor: String) = signature(classDescriptor.internalName, jvmDescriptor) fun signature(classId: ClassId, jvmDescriptor: String) = signature(classId.internalName, jvmDescriptor) fun signature(internalName: String, jvmDescriptor: String) = internalName + "." + jvmDescriptor }
0
Java
0
1
0e0cbfd89bee55f51c09f77f84759ed2269a0778
1,786
kotlin
Apache License 2.0
core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/methodSignatureBuilding.kt
cypressious
52,316,479
true
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.load.kotlin import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.name.ClassId import java.util.* inline fun <T> signatures(block: SignatureBuildingComponents.() -> T) = with(SignatureBuildingComponents, block) object SignatureBuildingComponents { fun javaLang(name: String) = "java/lang/$name" fun javaUtil(name: String) = "java/util/$name" fun constructors(vararg signatures: String) = signatures.map { "<init>($it)V" }.toTypedArray() fun inJavaLang(name: String, vararg signatures: String) = inClass(javaLang(name), *signatures) fun inJavaUtil(name: String, vararg signatures: String) = inClass(javaUtil(name), *signatures) fun inClass(internalName: String, vararg signatures: String) = signatures.mapTo(LinkedHashSet()) { internalName + "." + it } fun signature(classDescriptor: ClassDescriptor, jvmDescriptor: String) = signature(classDescriptor.internalName, jvmDescriptor) fun signature(classId: ClassId, jvmDescriptor: String) = signature(classId.internalName, jvmDescriptor) fun signature(internalName: String, jvmDescriptor: String) = internalName + "." + jvmDescriptor }
0
Java
0
1
0e0cbfd89bee55f51c09f77f84759ed2269a0778
1,786
kotlin
Apache License 2.0
app/src/main/java/jp/mihailskuzmins/sugoinihongoapp/features/base/list/ListViewModelBase.kt
MihailsKuzmins
240,947,625
false
null
package jp.mihailskuzmins.sugoinihongoapp.features.base.list import android.app.Application import io.reactivex.Observable import io.reactivex.rxkotlin.addTo import io.reactivex.subjects.ReplaySubject import io.reactivex.subjects.Subject import jp.mihailskuzmins.sugoinihongoapp.extensions.whenActivated import jp.mihailskuzmins.sugoinihongoapp.features.base.ViewModelBase import jp.mihailskuzmins.sugoinihongoapp.features.base.interfaces.FilterableListViewModel import jp.mihailskuzmins.sugoinihongoapp.features.base.interfaces.HasItemsViewModel import jp.mihailskuzmins.sugoinihongoapp.helpers.delegatedprops.ReactiveProp typealias ItemsAction<T> = (items: List<T>) -> Unit abstract class ListViewModelBase<TModel>(app: Application): ViewModelBase(app), HasItemsViewModel { private val mItemsSubject: Subject<List<TModel>> = ReplaySubject.createWithSize(1) private val mHasItemsSubject: Subject<Boolean> = ReplaySubject.createWithSize(1) var hasItems by ReactiveProp(false, mHasItemsSubject::onNext) private set init { mItemsSubject .map { it.isNotEmpty() } .distinctUntilChanged() .subscribe { hasItems = it } .addTo(cleanUp) whenActivated { initItems { x -> mItemsSubject.onNext(x) isInitialisedSubject.onNext(true) } } } val itemsObservable: Observable<List<TModel>> get() = mItemsSubject final override val hasItemsObservable: Observable<Boolean> get() = mHasItemsSubject.startWith(hasItems).distinctUntilChanged() protected abstract fun initItems(itemsAction: ItemsAction<TModel>) @Suppress("unused") // Needed in order to prevent other viewModels from using this method protected fun FilterableListViewModel.publishItems(items: List<TModel>) = mItemsSubject.onNext(items) }
1
null
1
1
57e19b90b4291dc887a92f6d57f9be349373a444
1,743
sugoi-nihongo-android
Apache License 2.0
plugins/kotlin/code-insight/inspections-shared/tests/testData/inspectionsLocal/redundantSuspend/localVariable.kt
JetBrains
2,489,216
false
{"Text": 9788, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 633, "Markdown": 750, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7904, "SVG": 4537, "Kotlin": 60205, "Java": 84268, "HTML": 3803, "Java Properties": 217, "Gradle": 462, "Maven POM": 95, "JavaScript": 232, "CSS": 79, "JSON": 1436, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 735, "Groovy": 3102, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 73, "GraphQL": 127, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17095, "C": 110, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 85, "E-mail": 18, "Roff": 289, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// PROBLEM: none suspend<caret> fun test(action: suspend () -> String) { val local = action() }
1
null
1
1
0d546ea6a419c7cb168bc3633937a826d4a91b7c
101
intellij-community
Apache License 2.0
app/src/main/java/com/soyoungboy/kotlinapp/bean/GankNewsList.kt
soyoungboy
119,641,146
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Batchfile": 2, "Text": 1, "Ignore List": 3, "Markdown": 1, "Proguard": 2, "Kotlin": 23, "XML": 24, "Java": 8, "PureBasic": 1}
package com.soyoungboy.kotlinapp.bean import java.util.* /** * Created by soyoungboy on 2018/1/29. */ class GankNewsList(val error: Boolean, val results: ArrayList<GankNews>)
0
Kotlin
0
1
4246fd29e5ad9cfb906f0ba9cc6e48764a53c048
178
KotlinApp
MIT License
src/main/kotlin/de/qualersoft/robotframework/gradleplugin/configurations/TidyRobotConfiguration.kt
qualersoft
367,071,447
false
null
package de.qualersoft.robotframework.gradleplugin.configurations import de.qualersoft.robotframework.gradleplugin.utils.Arguments import de.qualersoft.robotframework.gradleplugin.utils.GradleProperty import org.gradle.api.Project import javax.inject.Inject class TidyRobotConfiguration @Inject constructor(project: Project) { private val objects = project.objects /** * Tidy given file(s) so that original file(s) are overwritten. * When this option is used, it is possible to give multiple * input files. * * *Default-Value:* `false` */ var inplace by GradleProperty(objects, Boolean::class, false) /** * Process given directory recursively. Files in the directory * are processed in-place similarly as when [inplace] option * is used. Does not process referenced resource files. * * *Default-Value:* `false` */ var recursive by GradleProperty(objects, Boolean::class, false) /** * Use pipe ('|') as a column separator in the plain text format. * * *Default-Value:* `false` */ var usepipes by GradleProperty(objects, Boolean::class, false) /** * Line separator to use in outputs. * * **`native`**: use operating system's native line separators * * **`windows`**: use Windows line separators (CRLF) * * **`unix`**: use Unix line separators (LF) * * *Default-Value:* `native` */ var lineseparator by GradleProperty(objects, String::class, "native") /** * The number of spaces between cells in the plain text format. * * *Default-Value:* `4` */ var spacecount by GradleProperty(objects, Int::class, DEFAULT_SPACES) fun generateArguments() = Arguments().apply { addFlagToArguments(inplace.orNull, "--inplace") addFlagToArguments(recursive.orNull, "--recursive") addFlagToArguments(usepipes.orNull, "--usepipes") addStringToArguments(lineseparator.get(), "--lineseparator") addStringToArguments(spacecount.get().toString(), "--spacecount") }.toArray() private companion object { const val DEFAULT_SPACES = 4 } }
2
Kotlin
3
1
c5161bb8197ab087c31c64d47706244e7a78d78a
2,056
robotframework-gradle-plugin
Apache License 2.0