Datasets:
path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/kotlin/io/trewartha/positional/ui/ViewModelEvent.kt | mtrewartha | 62,930,438 | false | null | package io.trewartha.positional.ui
abstract class ViewModelEvent {
var handled = false
} | 1 | Kotlin | 2 | 18 | 63f1e5813ae5351459c970f46c1c8dd77f66a8b5 | 94 | positional | MIT License |
demo-app/src/main/java/com/zero/xera/parcelable/demo/LargeData.kt | 0xera | 746,013,123 | false | {"Kotlin": 30604, "Java": 19845} | package com.zero.xera.parcelable.demo
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import java.io.Serializable
import java.util.UUID
internal interface LargeData {
val list: List<String>
}
private val genData = MutableList(50_000) {
UUID.randomUUID().toString()
}
data class SerializableLargeData(override val list: List<String>) : LargeData, Serializable {
companion object {
// 1950,84 kb
val instance = SerializableLargeData(genData)
}
}
@Parcelize
data class ParcelableLargeData(override val list: List<String>) : LargeData, Parcelable {
companion object {
// 4000,676 kb
val instance = ParcelableLargeData(genData)
}
} | 0 | Kotlin | 0 | 8 | f1be77798e430e91c07b21e181c71c6b6c544216 | 704 | parcelable | MIT License |
app/src/main/kotlin/org/mifos/mobile/cn/ui/adapter/DebtIncomeReportAdapter.kt | openMF | 133,982,000 | false | null | package org.mifos.mobile.cn.ui.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_debt_income_report.view.*
import org.mifos.mobile.cn.R
import org.mifos.mobile.cn.data.models.accounts.loan.CreditWorthinessFactor
import java.util.ArrayList
import javax.inject.Inject
class DebtIncomeReportAdapter @Inject constructor() : RecyclerView.Adapter<DebtIncomeReportAdapter.ViewHolder>() {
private var creditWorthinessFactors: List<CreditWorthinessFactor> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DebtIncomeReportAdapter.ViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_debt_income_report,parent,false)
return ViewHolder(view);
}
override fun getItemCount(): Int {
return creditWorthinessFactors.size
}
fun setCreditWorthinessFactors(creditWorthinessFactors: List<CreditWorthinessFactor>) {
this.creditWorthinessFactors = creditWorthinessFactors
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val creditWorthinessFactor = creditWorthinessFactors[position]
holder.tvAmount.text =creditWorthinessFactor.amount.toString()
holder.tvDescription.text = creditWorthinessFactor.description
}
class ViewHolder constructor(v:View): RecyclerView.ViewHolder(v){
var tvAmount = v.tv_amount
var tvDescription = v.tv_description
}
} | 66 | Kotlin | 65 | 37 | 2dd8750cb34e62e9458469da09c3fb55a258b067 | 1,574 | mifos-mobile-cn | Apache License 2.0 |
attribouter/src/main/java/me/jfenn/attribouter/wedges/PlayStoreLinkWedge.kt | fennifith | 124,246,346 | false | null | package me.jfenn.attribouter.wedges
import android.content.Context
import android.view.View
import me.jfenn.attribouter.utils.UrlClickListener
class PlayStoreLinkWedge @JvmOverloads constructor(url: String? = null, priority: Int = 0) : LinkWedge(
id = "playStore",
name = "@string/attribouter_title_play_store",
url = url,
icon = "@drawable/attribouter_ic_play_store",
priority = priority
) {
override fun getListener(context: Context): View.OnClickListener? {
return UrlClickListener(url ?: run {
"https://play.google.com/store/apps/details?id=${context.applicationInfo.packageName}"
})
}
}
| 5 | Kotlin | 13 | 118 | bfa65610b55a1b88673a321dd3bdd9ac409cf6a0 | 671 | Attribouter | Apache License 2.0 |
app/src/main/java/com/razi/booking/BookingHistoryActivity.kt | alokrathava | 352,985,296 | false | {"Java": 67727, "Kotlin": 34757} | package com.razi.booking
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.adapters.OrderAdapter
import com.data.Order
import com.network.ApiService
import com.network.RetroClass
import com.razi.furnitar.databinding.ActivityBookingHistoryBinding
import com.utils.Config
import com.utils.toast
import kotlinx.coroutines.launch
class BookingHistoryActivity : AppCompatActivity(), OrderAdapter.OrderInterface {
companion object {
private const val TAG = "BookingActivity"
}
private lateinit var binding: ActivityBookingHistoryBinding
private val context = this
private val bookingHistoryAdapter = OrderAdapter(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBookingHistoryBinding.inflate(layoutInflater)
setContentView(binding.root)
handleToolbar()
init()
getOrders()
}
/*--------------------------------- Handle Toolbar --------------------------------*/
private fun handleToolbar() {
binding.includedToolbar.title.text = "Order History"
binding.includedToolbar.backBtn.setOnClickListener { finish() }
}
private fun init() {
binding.recyclerView.adapter = bookingHistoryAdapter
}
private fun getOrders() {
lifecycleScope.launch {
try {
val apiInterface: ApiService = RetroClass.createService(ApiService::class.java)
val response = apiInterface.getOrderHistory(Config.user_id)
Log.d(TAG, "getRestaurantDetails: $response")
bookingHistoryAdapter.submitList(response.orders)
} catch (exception: Exception) {
toast(exception.message.toString())
}
}
}
override fun onClick(order: Order) {
}
} | 1 | Java | 0 | 0 | bc3377154c39207afa1a0d39ac7dcf8c7c9b6cfa | 1,949 | ARCLONE | MIT License |
src/main/kotlin/net/sportsday/routes/v1/UsersRouter.kt | Sports-day | 589,245,462 | false | {"Kotlin": 220880, "Dockerfile": 330} | package net.sportsday.routes.v1
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.plugins.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import net.sportsday.models.LogEvents
import net.sportsday.models.OmittedUser
import net.sportsday.plugins.Role
import net.sportsday.plugins.UserPrincipal
import net.sportsday.plugins.withRole
import net.sportsday.services.UsersService
import net.sportsday.utils.DataMessageResponse
import net.sportsday.utils.DataResponse
import net.sportsday.utils.MessageResponse
import net.sportsday.utils.logger.Logger
import net.sportsday.utils.respondOrInternalError
/**
* Created by testusuke on 2023/03/10
* @author testusuke
*/
fun Route.usersRouter() {
route("/users") {
/**
* Get all users
*/
get {
val users = UsersService.getAll()
call.respond(HttpStatusCode.OK, DataResponse(users.getOrDefault(listOf())))
}
withRole(Role.ADMIN) {
/**
* create user
*/
post {
val omittedUser = call.receive<OmittedUser>()
UsersService
.create(omittedUser)
.respondOrInternalError {
call.respond(
DataMessageResponse(
"created user",
it,
),
)
// Logger
Logger.commit(
"[UsersRouter] created user: ${it.name}",
LogEvents.CREATE,
call.authentication.principal<UserPrincipal>()?.microsoftAccount,
)
}
}
}
route("/{id?}") {
/**
* Get user
*/
get {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
UsersService
.getById(id)
.respondOrInternalError {
call.respond(HttpStatusCode.OK, DataResponse(it))
}
}
withRole(Role.ADMIN) {
/**
* update user
*/
put {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
val omittedUser = call.receive<OmittedUser>()
UsersService
.update(id, omittedUser)
.respondOrInternalError {
call.respond(
HttpStatusCode.OK,
DataMessageResponse(
"updated user",
it,
),
)
// Logger
Logger.commit(
"[UsersRouter] updated user: ${it.name}",
LogEvents.UPDATE,
call.authentication.principal<UserPrincipal>()?.microsoftAccount,
)
}
}
/**
* delete user
*/
delete {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
UsersService
.deleteById(id)
.respondOrInternalError {
call.respond(HttpStatusCode.OK, MessageResponse("deleted user"))
// Logger
Logger.commit(
"[UsersRouter] deleted user: $id",
LogEvents.DELETE,
call.authentication.principal<UserPrincipal>()?.microsoftAccount,
)
}
}
route("/microsoft-accounts") {
/**
* Get user what linked by microsoft account
*/
get {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
UsersService
.getLinkedMicrosoftAccount(id)
.respondOrInternalError {
call.respond(HttpStatusCode.OK, DataResponse(it))
}
}
}
}
route("/teams") {
/**
* Get all teams what user belong
*/
get {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
UsersService
.getTeams(id)
.respondOrInternalError {
call.respond(HttpStatusCode.OK, DataResponse(it))
}
}
}
}
}
}
| 9 | Kotlin | 0 | 0 | 368f79670b349e93c5ff03c81d8e38433672e6b7 | 5,436 | SportsDayAPI | Apache License 2.0 |
compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/secondaryConstructor.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // MEMBER_CLASS_FILTER: org.jetbrains.kotlin.fir.symbols.impl.FirConstructorSymbol
// BODY_RESOLVE
package util
@Target(AnnotationTarget.TYPE)
annotation class Anno(val position: String)
const val prop = "str"
abstract class AbstractClass<T>
class <caret>MyClass() : @Anno("super type call $prop") AbstractClass<@Anno("nested super type ref $prop") List<@Anno("nested nested super type ref $prop") Int>>() | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 409 | kotlin | Apache License 2.0 |
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/test/java/com/android/build/gradle/internal/services/AsyncResourceProcessorTest.kt | jomof | 374,736,765 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 2020 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.build.gradle.internal.services
import com.android.build.gradle.internal.fixtures.FakeNoOpAnalyticsService
import com.android.build.gradle.options.SyncOptions
import com.android.builder.tasks.BooleanLatch
import com.android.testutils.concurrency.OnDemandExecutorService
import com.google.common.io.Closer
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.After
import org.junit.Test
import java.io.Closeable
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.atomic.AtomicInteger
class AsyncResourceProcessorTest {
private val closer = Closer.create()
private val executor = OnDemandExecutorService()
val forkJoinPool: ForkJoinPool by lazy {
ForkJoinPool(2).also { closer.register(Closeable { it.shutdown() }) }
}
@After
fun close() {
closer.close()
}
@Test
fun smokeTest() {
val counter = AtomicInteger()
createAsyncResourceProcessor(counter).use { processor ->
processor.submit(FakeNoOpAnalyticsService()) {
it.incrementAndGet()
}
assertThat(counter.get()).isEqualTo(0)
executor.run(1)
assertThat(counter.get()).isEqualTo(1)
}
}
/** This test simulates what the verify library resources task does */
@Test
fun testCloseAwaitsExecutionCompletion() {
val counter = AtomicInteger()
// Steps for the processor to go through.
val compileSubmitted = BooleanLatch()
val awaitComplete = BooleanLatch()
val linkSubmitted = BooleanLatch()
val processorClosed = BooleanLatch()
forkJoinPool.submit {
createAsyncResourceProcessor(counter).use { processor ->
processor.submit(FakeNoOpAnalyticsService()) {
it.incrementAndGet()
}
compileSubmitted.signal()
Thread.yield()
processor.await()
awaitComplete.signal()
Thread.yield()
processor.submit(FakeNoOpAnalyticsService()) {
it.incrementAndGet()
}
linkSubmitted.signal()
Thread.yield()
}
processorClosed.signal()
Thread.yield()
}
compileSubmitted.await()
assertWithMessage("processor await should be blocked on executor running").that(
awaitComplete.isSignalled
).isFalse()
assertThat(counter.get()).isEqualTo(0)
executor.runAll()
assertThat(counter.get()).isEqualTo(1)
awaitComplete.await()
assertThat(counter.get()).isEqualTo(1)
linkSubmitted.await()
assertThat(counter.get()).isEqualTo(1)
executor.runAll()
assertThat(counter.get()).isEqualTo(2)
processorClosed.await()
assertThat(counter.get()).isEqualTo(2)
}
private fun createAsyncResourceProcessor(counter: AtomicInteger): AsyncResourceProcessor<AtomicInteger> {
return AsyncResourceProcessor(
projectName = "testProject",
owner = "testTask",
executor = executor,
service = counter,
errorFormatMode = SyncOptions.ErrorFormatMode.HUMAN_READABLE
)
}
} | 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 3,990 | CppBuildCacheWorkInProgress | Apache License 2.0 |
paper/src/main/kotlin/net/prosavage/factionsx/manager/ConfigFileManager.kt | ryderbelserion | 669,875,997 | false | null | package net.prosavage.factionsx.manager
import net.prosavage.factionsx.FactionsX
import net.prosavage.factionsx.persist.IConfigFile
import net.prosavage.factionsx.persist.Message
import net.prosavage.factionsx.persist.config.*
import net.prosavage.factionsx.persist.config.gui.AccessGUIConfig
import net.prosavage.factionsx.persist.config.gui.PermsGUIConfig
import net.prosavage.factionsx.persist.config.gui.UpgradesGUIConfig
import org.bukkit.plugin.java.JavaPlugin
object ConfigFileManager {
private val plugin = JavaPlugin.getPlugin(FactionsX::class.java)
fun setup() {
register(Config)
register(EconConfig)
register(RoleConfig)
register(PermsGUIConfig)
register(AccessGUIConfig)
register(ProtectionConfig)
register(UpgradesConfig)
register(UpgradesGUIConfig)
register(MapConfig)
register(FlyConfig)
register(ScoreboardConfig)
register(Message)
}
val files = hashSetOf<IConfigFile>()
fun register(configurableFile: IConfigFile) {
files.add(configurableFile)
}
fun load() {
files.forEach { it.load(this.plugin) }
}
fun save() {
files.forEach {
// Load changes first, then save.
it.load(this.plugin)
it.save(this.plugin)
}
}
} | 0 | Kotlin | 0 | 0 | 2d3ed828660aa9b9f35ca55edbda519a11ed7756 | 1,339 | Factions | MIT License |
lib/src/test/java/com/sha/bulletin/toast/StandardToastTest.kt | ShabanKamell | 228,855,441 | false | null | package com.sha.bulletin.toast
import com.sha.bulletin.DefaultDuplicateStrategy
import org.junit.Before
import org.junit.Test
class StandardToastTest {
lateinit var options: StandardToast.Options.Builder
@Before
fun setup() {
options = StandardToast.Options.Builder()
}
@Test
fun content() {
options.content("content")
assert(options.build().content == "content")
}
@Test
fun duplicateStrategy() {
val strategy = DefaultDuplicateStrategy()
options.duplicateStrategy(strategy)
assert(options.build().duplicateStrategy == strategy)
}
} | 0 | Kotlin | 0 | 5 | 16dcc2b867ae362830b9249e84bb911af7e8a82d | 626 | Bulletin | Apache License 2.0 |
kt/godot-library/src/main/kotlin/godot/gen/godot/OpenXRInterface.kt | utopia-rise | 289,462,532 | false | {"Kotlin": 1464908, "GDScript": 492843, "C++": 484675, "C#": 10278, "C": 8523, "Shell": 8429, "Java": 2136, "CMake": 939, "Python": 75} | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.Quaternion
import godot.core.TypeManager
import godot.core.VariantArray
import godot.core.VariantType.ARRAY
import godot.core.VariantType.BOOL
import godot.core.VariantType.DOUBLE
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.QUATERNION
import godot.core.VariantType.STRING
import godot.core.VariantType.VECTOR3
import godot.core.Vector3
import godot.core.memory.TransferContext
import godot.signals.Signal0
import godot.signals.signal
import godot.util.VoidPtr
import kotlin.Any
import kotlin.Boolean
import kotlin.Double
import kotlin.Float
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.jvm.JvmInline
@GodotBaseType
public open class OpenXRInterface : XRInterface() {
public val sessionBegun: Signal0 by signal()
public val sessionStopping: Signal0 by signal()
public val sessionFocussed: Signal0 by signal()
public val sessionVisible: Signal0 by signal()
public val poseRecentered: Signal0 by signal()
public var displayRefreshRate: Float
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getDisplayRefreshRatePtr, DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat()
}
set(`value`) {
TransferContext.writeArguments(DOUBLE to value.toDouble())
TransferContext.callMethod(rawPtr, MethodBindings.setDisplayRefreshRatePtr, NIL)
}
public var renderTargetSizeMultiplier: Double
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getRenderTargetSizeMultiplierPtr, DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double)
}
set(`value`) {
TransferContext.writeArguments(DOUBLE to value)
TransferContext.callMethod(rawPtr, MethodBindings.setRenderTargetSizeMultiplierPtr, NIL)
}
public var foveationLevel: Int
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getFoveationLevelPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
set(`value`) {
TransferContext.writeArguments(LONG to value.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.setFoveationLevelPtr, NIL)
}
public var foveationDynamic: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getFoveationDynamicPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setFoveationDynamicPtr, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_OPENXRINTERFACE, scriptIndex)
return true
}
public fun isFoveationSupported(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isFoveationSupportedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public fun isActionSetActive(name: String): Boolean {
TransferContext.writeArguments(STRING to name)
TransferContext.callMethod(rawPtr, MethodBindings.isActionSetActivePtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public fun setActionSetActive(name: String, active: Boolean): Unit {
TransferContext.writeArguments(STRING to name, BOOL to active)
TransferContext.callMethod(rawPtr, MethodBindings.setActionSetActivePtr, NIL)
}
public fun getActionSets(): VariantArray<Any?> {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getActionSetsPtr, ARRAY)
return (TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>)
}
public fun getAvailableDisplayRefreshRates(): VariantArray<Any?> {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getAvailableDisplayRefreshRatesPtr, ARRAY)
return (TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>)
}
public fun setMotionRange(hand: Hand, motionRange: HandMotionRange): Unit {
TransferContext.writeArguments(LONG to hand.id, LONG to motionRange.id)
TransferContext.callMethod(rawPtr, MethodBindings.setMotionRangePtr, NIL)
}
public fun getMotionRange(hand: Hand): HandMotionRange {
TransferContext.writeArguments(LONG to hand.id)
TransferContext.callMethod(rawPtr, MethodBindings.getMotionRangePtr, LONG)
return OpenXRInterface.HandMotionRange.from(TransferContext.readReturnValue(LONG) as Long)
}
public fun getHandJointFlags(hand: Hand, joint: HandJoints): HandJointFlags {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointFlagsPtr, LONG)
return HandJointFlagsValue(TransferContext.readReturnValue(LONG) as Long)
}
public fun getHandJointRotation(hand: Hand, joint: HandJoints): Quaternion {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointRotationPtr, QUATERNION)
return (TransferContext.readReturnValue(QUATERNION, false) as Quaternion)
}
public fun getHandJointPosition(hand: Hand, joint: HandJoints): Vector3 {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointPositionPtr, VECTOR3)
return (TransferContext.readReturnValue(VECTOR3, false) as Vector3)
}
public fun getHandJointRadius(hand: Hand, joint: HandJoints): Float {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointRadiusPtr, DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat()
}
public fun getHandJointLinearVelocity(hand: Hand, joint: HandJoints): Vector3 {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointLinearVelocityPtr, VECTOR3)
return (TransferContext.readReturnValue(VECTOR3, false) as Vector3)
}
public fun getHandJointAngularVelocity(hand: Hand, joint: HandJoints): Vector3 {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointAngularVelocityPtr, VECTOR3)
return (TransferContext.readReturnValue(VECTOR3, false) as Vector3)
}
public fun isHandTrackingSupported(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isHandTrackingSupportedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public fun isEyeGazeInteractionSupported(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isEyeGazeInteractionSupportedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public enum class Hand(
id: Long,
) {
HAND_LEFT(0),
HAND_RIGHT(1),
HAND_MAX(2),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class HandMotionRange(
id: Long,
) {
HAND_MOTION_RANGE_UNOBSTRUCTED(0),
HAND_MOTION_RANGE_CONFORM_TO_CONTROLLER(1),
HAND_MOTION_RANGE_MAX(2),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class HandJoints(
id: Long,
) {
HAND_JOINT_PALM(0),
HAND_JOINT_WRIST(1),
HAND_JOINT_THUMB_METACARPAL(2),
HAND_JOINT_THUMB_PROXIMAL(3),
HAND_JOINT_THUMB_DISTAL(4),
HAND_JOINT_THUMB_TIP(5),
HAND_JOINT_INDEX_METACARPAL(6),
HAND_JOINT_INDEX_PROXIMAL(7),
HAND_JOINT_INDEX_INTERMEDIATE(8),
HAND_JOINT_INDEX_DISTAL(9),
HAND_JOINT_INDEX_TIP(10),
HAND_JOINT_MIDDLE_METACARPAL(11),
HAND_JOINT_MIDDLE_PROXIMAL(12),
HAND_JOINT_MIDDLE_INTERMEDIATE(13),
HAND_JOINT_MIDDLE_DISTAL(14),
HAND_JOINT_MIDDLE_TIP(15),
HAND_JOINT_RING_METACARPAL(16),
HAND_JOINT_RING_PROXIMAL(17),
HAND_JOINT_RING_INTERMEDIATE(18),
HAND_JOINT_RING_DISTAL(19),
HAND_JOINT_RING_TIP(20),
HAND_JOINT_LITTLE_METACARPAL(21),
HAND_JOINT_LITTLE_PROXIMAL(22),
HAND_JOINT_LITTLE_INTERMEDIATE(23),
HAND_JOINT_LITTLE_DISTAL(24),
HAND_JOINT_LITTLE_TIP(25),
HAND_JOINT_MAX(26),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public sealed interface HandJointFlags {
public val flag: Long
public infix fun or(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.or(other.flag))
public infix fun or(other: Long): HandJointFlags = HandJointFlagsValue(flag.or(other))
public infix fun xor(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.xor(other.flag))
public infix fun xor(other: Long): HandJointFlags = HandJointFlagsValue(flag.xor(other))
public infix fun and(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.and(other.flag))
public infix fun and(other: Long): HandJointFlags = HandJointFlagsValue(flag.and(other))
public operator fun plus(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.plus(other.flag))
public operator fun plus(other: Long): HandJointFlags = HandJointFlagsValue(flag.plus(other))
public operator fun minus(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.minus(other.flag))
public operator fun minus(other: Long): HandJointFlags = HandJointFlagsValue(flag.minus(other))
public operator fun times(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.times(other.flag))
public operator fun times(other: Long): HandJointFlags = HandJointFlagsValue(flag.times(other))
public operator fun div(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.div(other.flag))
public operator fun div(other: Long): HandJointFlags = HandJointFlagsValue(flag.div(other))
public operator fun rem(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.rem(other.flag))
public operator fun rem(other: Long): HandJointFlags = HandJointFlagsValue(flag.rem(other))
public fun unaryPlus(): HandJointFlags = HandJointFlagsValue(flag.unaryPlus())
public fun unaryMinus(): HandJointFlags = HandJointFlagsValue(flag.unaryMinus())
public fun inv(): HandJointFlags = HandJointFlagsValue(flag.inv())
public infix fun shl(bits: Int): HandJointFlags = HandJointFlagsValue(flag shl bits)
public infix fun shr(bits: Int): HandJointFlags = HandJointFlagsValue(flag shr bits)
public infix fun ushr(bits: Int): HandJointFlags = HandJointFlagsValue(flag ushr bits)
public companion object {
public val HAND_JOINT_NONE: HandJointFlags = HandJointFlagsValue(0)
public val HAND_JOINT_ORIENTATION_VALID: HandJointFlags = HandJointFlagsValue(1)
public val HAND_JOINT_ORIENTATION_TRACKED: HandJointFlags = HandJointFlagsValue(2)
public val HAND_JOINT_POSITION_VALID: HandJointFlags = HandJointFlagsValue(4)
public val HAND_JOINT_POSITION_TRACKED: HandJointFlags = HandJointFlagsValue(8)
public val HAND_JOINT_LINEAR_VELOCITY_VALID: HandJointFlags = HandJointFlagsValue(16)
public val HAND_JOINT_ANGULAR_VELOCITY_VALID: HandJointFlags = HandJointFlagsValue(32)
}
}
@JvmInline
internal value class HandJointFlagsValue internal constructor(
public override val flag: Long,
) : HandJointFlags
public companion object
internal object MethodBindings {
public val getDisplayRefreshRatePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_display_refresh_rate")
public val setDisplayRefreshRatePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_display_refresh_rate")
public val getRenderTargetSizeMultiplierPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_render_target_size_multiplier")
public val setRenderTargetSizeMultiplierPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_render_target_size_multiplier")
public val isFoveationSupportedPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "is_foveation_supported")
public val getFoveationLevelPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_foveation_level")
public val setFoveationLevelPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_foveation_level")
public val getFoveationDynamicPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_foveation_dynamic")
public val setFoveationDynamicPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_foveation_dynamic")
public val isActionSetActivePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "is_action_set_active")
public val setActionSetActivePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_action_set_active")
public val getActionSetsPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_action_sets")
public val getAvailableDisplayRefreshRatesPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_available_display_refresh_rates")
public val setMotionRangePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_motion_range")
public val getMotionRangePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_motion_range")
public val getHandJointFlagsPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_flags")
public val getHandJointRotationPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_rotation")
public val getHandJointPositionPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_position")
public val getHandJointRadiusPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_radius")
public val getHandJointLinearVelocityPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_linear_velocity")
public val getHandJointAngularVelocityPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_angular_velocity")
public val isHandTrackingSupportedPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "is_hand_tracking_supported")
public val isEyeGazeInteractionSupportedPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "is_eye_gaze_interaction_supported")
}
}
public infix fun Long.or(other: godot.OpenXRInterface.HandJointFlags): Long = this.or(other.flag)
public infix fun Long.xor(other: godot.OpenXRInterface.HandJointFlags): Long = this.xor(other.flag)
public infix fun Long.and(other: godot.OpenXRInterface.HandJointFlags): Long = this.and(other.flag)
public operator fun Long.plus(other: godot.OpenXRInterface.HandJointFlags): Long =
this.plus(other.flag)
public operator fun Long.minus(other: godot.OpenXRInterface.HandJointFlags): Long =
this.minus(other.flag)
public operator fun Long.times(other: godot.OpenXRInterface.HandJointFlags): Long =
this.times(other.flag)
public operator fun Long.div(other: godot.OpenXRInterface.HandJointFlags): Long =
this.div(other.flag)
public operator fun Long.rem(other: godot.OpenXRInterface.HandJointFlags): Long =
this.rem(other.flag)
| 61 | Kotlin | 33 | 445 | 1dfa11d5c43fc9f85de2260b8e88f4911afddcb9 | 16,527 | godot-kotlin-jvm | MIT License |
app/src/main/java/ru/dronelektron/investmentcalculator/di/module/PresentationModule.kt | dronelektron | 294,493,925 | false | null | package ru.dronelektron.investmentcalculator.di.module
import androidx.lifecycle.ViewModelProvider
import dagger.Module
import dagger.Provides
import ru.dronelektron.investmentcalculator.di.annotation.InvestForm
import ru.dronelektron.investmentcalculator.domain.usecase.CalculateProfitUseCase
import ru.dronelektron.investmentcalculator.presentation.investform.InvestFormViewModelFactory
@Module
class PresentationModule {
@Provides
@InvestForm
fun provideInvestFormViewModelFactory(
calculateProfitUseCase: CalculateProfitUseCase
): ViewModelProvider.Factory = InvestFormViewModelFactory(calculateProfitUseCase)
}
| 0 | Kotlin | 0 | 0 | 5108e1a2e11f9dade739a277610ff3be9d7f85af | 642 | investment-calculator | MIT License |
app/src/main/java/com/example/inventory/ui/item/ItemEditViewModel.kt | sagargupta35 | 722,047,338 | false | {"Kotlin": 67521} | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.inventory.ui.item
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.inventory.data.ItemsRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/**
* ViewModel to retrieve and update an item from the [ItemsRepository]'s data source.
*/
class ItemEditViewModel(
savedStateHandle: SavedStateHandle,
private val itemsRepository: ItemsRepository
) : ViewModel() {
/**
* Holds current item ui state
*/
var itemUiState by mutableStateOf(ItemUiState())
private set
init {
// viewModelScope.launch{
// Log.d("TAG", itemId.toString())
// itemsRepository.getItemStream(itemId)
// .collect{
// itemUiState = it?.toItemUiState(true) ?: ItemUiState(
// itemDetails = ItemDetails(name = "Test", price = "23", quantity = "69")
// )
// }
// }
updateUiState()
}
private val itemId: Int = checkNotNull(savedStateHandle[ItemEditDestination.itemIdArg])
private fun updateUiState(){
viewModelScope.launch {
itemUiState = itemsRepository.getItemStream(ItemDetailsDestination.itemId)
.filterNotNull()
.first()
.toItemUiState(true)
}
}
fun updateUiState(itemDetails: ItemDetails) {
itemUiState =
ItemUiState(itemDetails = itemDetails, isEntryValid = validateInput(itemDetails))
}
private fun validateInput(uiState: ItemDetails = itemUiState.itemDetails): Boolean {
return with(uiState) {
name.isNotBlank() && price.isNotBlank() && quantity.isNotBlank()
}
}
suspend fun updateItem(){
if(validateInput(itemUiState.itemDetails)){
itemsRepository.updateItem(itemUiState.itemDetails.toItem())
}
}
}
| 0 | Kotlin | 0 | 0 | 0422029f18ecf3d41592280596bbb88bae09d634 | 3,003 | Inventory | Apache License 2.0 |
common/src/main/kotlin/io/liquidsoftware/common/logging/Logging.kt | edreyer | 445,325,795 | false | {"Kotlin": 197484, "Procfile": 119} | package io.liquidsoftware.common.logging
import org.slf4j.Logger
import org.slf4j.LoggerFactory.getLogger
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import kotlin.reflect.full.companionObject
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
override fun getValue(thisRef: R, property: KProperty<*>): Logger =
getLogger(getClassForLogging(thisRef.javaClass))
}
fun <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
return javaClass.enclosingClass?.takeIf {
it.kotlin.companionObject?.java == javaClass
} ?: javaClass
}
| 13 | Kotlin | 9 | 28 | 1cb7199d8aee3d534f9b3369555eb399a613eb64 | 594 | modulith | MIT License |
app/src/main/java/com/blockeq/stellarwallet/models/SelectionModel.kt | Block-Equity | 128,590,362 | false | null | package com.blockeq.stellarwallet.models
import org.stellar.sdk.Asset
open class SelectionModel(var label: String, var value: Int, var holdings: Double, var asset : Asset?) {
override fun toString(): String {
return label
}
} | 14 | Kotlin | 24 | 32 | 7996e9c75f4af6dc49241e918494155d0b82493e | 243 | stellar-android-wallet | MIT License |
app/src/main/java/org/simple/clinic/contactpatient/ContactPatientUi.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.contactpatient
import org.simple.clinic.overdue.TimeToAppointment
import java.time.LocalDate
interface ContactPatientUi {
fun showProgress()
fun hideProgress()
/**
* Call patient view
*/
fun switchToCallPatientView()
fun switchToSetAppointmentReminderView()
fun renderPatientDetails(patientDetails: PatientDetails)
fun showSecureCallUi()
fun hideSecureCallUi()
fun showNormalCallButtonText()
fun showCallButtonText()
fun showPatientWithNoPhoneNumberUi()
fun hidePatientWithNoPhoneNumberUi()
fun showPatientWithPhoneNumberUi()
fun hidePatientWithPhoneNumberUi()
fun setResultOfCallLabelText()
fun setResultLabelText()
fun setRegisterAtLabelText()
fun setTransferredFromLabelText()
fun showPatientWithPhoneNumberCallResults()
fun hidePatientWithPhoneNumberCallResults()
fun showPatientWithNoPhoneNumberResults()
fun showDeadPatientStatus()
fun hideDeadPatientStatus()
/**
* Select reminder view
*/
fun renderSelectedAppointmentDate(
selectedAppointmentReminderPeriod: TimeToAppointment,
selectedDate: LocalDate
)
fun disablePreviousReminderDateStepper()
fun enablePreviousReminderDateStepper()
fun disableNextReminderDateStepper()
fun enableNextReminderDateStepper()
fun showCallResult()
fun hideCallResult()
fun setupAgreedToVisitCallResultOutcome()
fun setupRemindToCallLaterCallResultOutcome(appointmentReminderDate: LocalDate)
fun setupRemovedFromListCallResultOutcome(removeReasonStringRes: Int)
fun setCallResultUpdatedAtDate(callResultUpdatedAt: LocalDate)
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 1,603 | simple-android | MIT License |
app/src/main/java/com/example/quotidian/repo/data/Quotes.kt | lssarao | 579,010,205 | false | {"Kotlin": 19016} | package com.example.quotidian.repo.data
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.Serializable
@Serializable
@Parcelize
@Entity(tableName = "Daily_Quotes")
data class Quotes(
@SerializedName("q") val quote: String?,
@SerializedName("a") val author: String,
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "ID") val id: Int = 0,
) : Parcelable | 0 | Kotlin | 0 | 1 | aff9d2bebb0eaa763f6a92c2aa36ae48d238c577 | 554 | jetpack-compose-quotidian | MIT License |
libraries/report/src/commonMain/kotlin/com/zegreatrob/testmints/report/MintReporterConfig.kt | robertfmurdock | 172,112,213 | false | {"Kotlin": 170915, "JavaScript": 796, "Batchfile": 697, "Dockerfile": 282} | package com.zegreatrob.testmints.report
import kotlin.native.concurrent.ThreadLocal
@ThreadLocal
object MintReporterConfig : ReporterProvider {
override var reporter: MintReporter = PlaceholderMintReporter
}
| 0 | Kotlin | 2 | 6 | 9044806e7f09bb6365b1854a69a8cf67f2404587 | 214 | testmints | MIT License |
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/simple/RemoveDuplicates.kt | scientificCommunity | 352,868,267 | false | {"Java": 154453, "Kotlin": 69817} | package org.baichuan.sample.algorithms.leetcode.simple
/**
* https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
* 26. 删除有序数组中的重复项
*/
class RemoveDuplicates {
fun removeDuplicates(nums: IntArray): Int {
var pre: Int? = null
var end = 0
var i = 0
while (true) {
if (i > nums.size - 1 - end) {
break
}
if (nums[i] == pre) {
reRange(i, nums, end)
end++
i--
} else {
pre = nums[i]
}
i++
}
return nums.size - end
}
private fun reRange(start: Int, nums: IntArray, end: Int) {
for (i in start until nums.size - end - 1) {
nums[i] = nums[i + 1]
}
}
}
fun main() {
RemoveDuplicates().removeDuplicates(arrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4).toIntArray())
} | 1 | Java | 0 | 8 | 36e291c0135a06f3064e6ac0e573691ac70714b6 | 935 | blog-sample | Apache License 2.0 |
Chapter07/Journaler API/api/src/main/kotlin/com/journaler/api/reactor/NotesCountNotificationServiceImpl.kt | PacktPublishing | 102,436,360 | false | null | package com.journaler.api.reactor
import com.journaler.api.mail.MailMessage
import com.journaler.api.mail.MailService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class NotesCountNotificationServiceImpl : NotesCountNotificationService {
@Autowired
private lateinit var mailService: MailService
override fun notify(notification: NotesCountNotification) {
val to = "<EMAIL>"
val subject = "Notes count notification"
val text = "Notes reached ${notification.notesCount} count."
val message = MailMessage(to, subject, text)
mailService.sendMessage(message)
}
} | 0 | Kotlin | 12 | 22 | 914a9d5d336e3563c3a12b6ad7b8e3321f3ec46d | 720 | Building-Applications-with-Spring-5-and-Kotlin | MIT License |
src/main/kotlin/com/notify/scheduler/ScheduledTasks.kt | u-verma | 288,201,627 | false | null | package com.notify.scheduler
import com.notify.api.user.repository.UserProfileRepository
import com.notify.client.email.service.EmailService
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.text.SimpleDateFormat
@Component
class ScheduledTasks(val emailService: EmailService,
val userProfileRepository: UserProfileRepository) {
private val logger = LoggerFactory.getLogger(ScheduledTasks::class.java)
private val dateFormat = SimpleDateFormat("HH:mm:ss")
@Scheduled(cron = "0 * * ? * *")
fun reportCurrentTime() {
val userList = userProfileRepository.getUsersForSchedulingEmail()
logger.info("The User List for scheduling email: ${userList.isEmpty()}")
if (userList.isNotEmpty()) {
emailService.execute(userList)
run { userProfileRepository.updateLastEmailSentTs(userList) }
}
}
} | 0 | Kotlin | 0 | 0 | c739d5712d03349722c417eefbae348a256a6b4a | 983 | notification | Apache License 2.0 |
archimedes-data-jdbc/src/main/kotlin/io/archimedesfw/data/EntityVersionedString.kt | archimedes-projects | 362,401,748 | false | null | package io.archimedesfw.data
interface EntityVersionedString : EntityVersioned<String>, EntityString
| 0 | Kotlin | 4 | 25 | 000669e868c4d2a1ee84f9007ca9d291b64521b2 | 102 | archimedes-jvm | Apache License 2.0 |
compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/fixStack/BasicTypeInterpreter.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2021 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.codegen.optimization.fixStack
import org.jetbrains.kotlin.codegen.inline.insnOpcodeText
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Opcodes.*
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException
import org.jetbrains.org.objectweb.asm.tree.analysis.Interpreter
import org.jetbrains.org.objectweb.asm.tree.analysis.Value
abstract class BasicTypeInterpreter<V : Value> : Interpreter<V>(API_VERSION) {
protected abstract fun uninitializedValue(): V
protected abstract fun booleanValue(): V
protected abstract fun charValue(): V
protected abstract fun byteValue(): V
protected abstract fun shortValue(): V
protected abstract fun intValue(): V
protected abstract fun longValue(): V
protected abstract fun floatValue(): V
protected abstract fun doubleValue(): V
protected abstract fun nullValue(): V
protected abstract fun objectValue(type: Type): V
protected abstract fun arrayValue(type: Type): V
protected abstract fun methodValue(type: Type): V
protected abstract fun handleValue(handle: Handle): V
protected abstract fun typeConstValue(typeConst: Type): V
protected abstract fun aaLoadValue(arrayValue: V): V
override fun newValue(type: Type?): V? =
if (type == null)
uninitializedValue()
else when (type.sort) {
Type.VOID -> null
Type.BOOLEAN -> booleanValue()
Type.CHAR -> charValue()
Type.BYTE -> byteValue()
Type.SHORT -> shortValue()
Type.INT -> intValue()
Type.FLOAT -> floatValue()
Type.LONG -> longValue()
Type.DOUBLE -> doubleValue()
Type.ARRAY -> arrayValue(type)
Type.OBJECT -> objectValue(type)
Type.METHOD -> methodValue(type)
else -> throw AssertionError("Unexpected type: $type")
}
override fun newEmptyValue(local: Int): V {
return uninitializedValue()
}
override fun newOperation(insn: AbstractInsnNode): V? =
when (insn.opcode) {
ACONST_NULL ->
nullValue()
ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5 ->
intValue()
LCONST_0, LCONST_1 ->
longValue()
FCONST_0, FCONST_1, FCONST_2 ->
floatValue()
DCONST_0, DCONST_1 ->
doubleValue()
BIPUSH, SIPUSH ->
intValue()
LDC -> {
when (val cst = (insn as LdcInsnNode).cst) {
is Int -> intValue()
is Float -> floatValue()
is Long -> longValue()
is Double -> doubleValue()
is String -> objectValue(AsmTypes.JAVA_STRING_TYPE)
is Handle -> handleValue(cst)
is Type -> typeConstValue(cst)
else -> throw IllegalArgumentException("Illegal LDC constant $cst")
}
}
GETSTATIC ->
newValue(Type.getType((insn as FieldInsnNode).desc))
NEW ->
newValue(Type.getObjectType((insn as TypeInsnNode).desc))
else ->
throw IllegalArgumentException("Unexpected instruction: " + insn.insnOpcodeText)
}
override fun binaryOperation(insn: AbstractInsnNode, value1: V, value2: V): V? =
when (insn.opcode) {
IALOAD, BALOAD, CALOAD, SALOAD, IADD, ISUB, IMUL, IDIV, IREM, ISHL, ISHR, IUSHR, IAND, IOR, IXOR ->
intValue()
FALOAD, FADD, FSUB, FMUL, FDIV, FREM ->
floatValue()
LALOAD, LADD, LSUB, LMUL, LDIV, LREM, LSHL, LSHR, LUSHR, LAND, LOR, LXOR ->
longValue()
DALOAD, DADD, DSUB, DMUL, DDIV, DREM ->
doubleValue()
AALOAD ->
aaLoadValue(value1)
LCMP, FCMPL, FCMPG, DCMPL, DCMPG ->
intValue()
IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE, PUTFIELD ->
null
else ->
throw IllegalArgumentException("Unexpected instruction: " + insn.insnOpcodeText)
}
override fun ternaryOperation(insn: AbstractInsnNode, value1: V, value2: V, value3: V): V? =
null
override fun naryOperation(insn: AbstractInsnNode, values: List<V>): V? =
when (insn.opcode) {
MULTIANEWARRAY ->
newValue(Type.getType((insn as MultiANewArrayInsnNode).desc))
INVOKEDYNAMIC ->
newValue(Type.getReturnType((insn as InvokeDynamicInsnNode).desc))
else ->
newValue(Type.getReturnType((insn as MethodInsnNode).desc))
}
override fun returnOperation(insn: AbstractInsnNode, value: V?, expected: V?) {
}
override fun unaryOperation(insn: AbstractInsnNode, value: V): V? =
when (insn.opcode) {
INEG, IINC, L2I, F2I, D2I, I2B, I2C, I2S ->
intValue()
FNEG, I2F, L2F, D2F ->
floatValue()
LNEG, I2L, F2L, D2L ->
longValue()
DNEG, I2D, L2D, F2D ->
doubleValue()
IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, TABLESWITCH, LOOKUPSWITCH, IRETURN, LRETURN, FRETURN, DRETURN, ARETURN, PUTSTATIC ->
null
GETFIELD ->
newValue(Type.getType((insn as FieldInsnNode).desc))
NEWARRAY ->
when ((insn as IntInsnNode).operand) {
T_BOOLEAN -> newValue(Type.getType("[Z"))
T_CHAR -> newValue(Type.getType("[C"))
T_BYTE -> newValue(Type.getType("[B"))
T_SHORT -> newValue(Type.getType("[S"))
T_INT -> newValue(Type.getType("[I"))
T_FLOAT -> newValue(Type.getType("[F"))
T_DOUBLE -> newValue(Type.getType("[D"))
T_LONG -> newValue(Type.getType("[J"))
else -> throw AnalyzerException(insn, "Invalid array type")
}
ANEWARRAY ->
newValue(Type.getType("[" + Type.getObjectType((insn as TypeInsnNode).desc)))
ARRAYLENGTH ->
intValue()
ATHROW ->
null
CHECKCAST ->
newValue(Type.getObjectType((insn as TypeInsnNode).desc))
INSTANCEOF ->
intValue()
MONITORENTER, MONITOREXIT, IFNULL, IFNONNULL ->
null
else ->
throw IllegalArgumentException("Unexpected instruction: " + insn.insnOpcodeText)
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 7,187 | kotlin | Apache License 2.0 |
compiler/tests-spec/testData/diagnostics/linked/expressions/constant-literals/the-types-for-integer-literals/p-1/neg/2.3.fir.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // SKIP_TXT
/*
* KOTLIN DIAGNOSTICS SPEC TEST (NEGATIVE)
*
* SPEC VERSION: 0.1-100
* MAIN LINK: expressions, constant-literals, the-types-for-integer-literals -> paragraph 1 -> sentence 2
* NUMBER: 3
* DESCRIPTION: Type checking (comparison with invalid types) of various integer literals.
* HELPERS: checkType
*/
// TESTCASE NUMBER: 1
fun case_1() {
0 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
0 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
0 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
}
// TESTCASE NUMBER: 2
fun case_2() {
127 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
127 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
127 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>128<!>)
128 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
128 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
128 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
-128 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-128 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-128 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-129<!>)
-129 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-129 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-129 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
}
// TESTCASE NUMBER: 3
fun case_3() {
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>32767<!>)
32767 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
32767 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
32767 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>32768<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>32768<!>)
32768 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
32768 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
32768 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-32768<!>)
-32768 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-32768 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-32768 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-32769<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>-32769<!>)
-32769 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-32769 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-32769 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
}
// TESTCASE NUMBER: 4
fun case_4() {
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>2147483647<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>2147483647<!>)
2147483647 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
2147483647 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
2147483647 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>2147483648<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>2147483648<!>)
checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>2147483648<!>)
2147483648 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
2147483648 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
2147483648 checkType { <!NONE_APPLICABLE!>check<!><Int>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-2147483648<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>-2147483648<!>)
-2147483648 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-2147483648 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-2147483648 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-2147483649<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>-2147483649<!>)
checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>-2147483649<!>)
-2147483649 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-2147483649 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-2147483649 checkType { <!NONE_APPLICABLE!>check<!><Int>() }
}
// TESTCASE NUMBER: 5
fun case_5() {
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>9223372036854775807<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>9223372036854775807<!>)
checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>9223372036854775807<!>)
9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Int>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-9223372036854775807<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>-9223372036854775807<!>)
checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>-9223372036854775807<!>)
-9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Int>() }
}
// TESTCASE NUMBER: 6
fun case_6() {
checkSubtype<Byte>(<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!>)
checkSubtype<Short>(<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!>)
checkSubtype<Int>(<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!>)
checkSubtype<Long>(<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!>)
<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!> <!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>checkType<!> { <!INAPPLICABLE_CANDIDATE!>check<!><<!CANNOT_INFER_PARAMETER_TYPE!>Byte<!>>() }
<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!> <!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>checkType<!> { <!INAPPLICABLE_CANDIDATE!>check<!><<!CANNOT_INFER_PARAMETER_TYPE!>Short<!>>() }
<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!> <!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>checkType<!> { <!INAPPLICABLE_CANDIDATE!>check<!><<!CANNOT_INFER_PARAMETER_TYPE!>Int<!>>() }
<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!> <!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>checkType<!> { <!INAPPLICABLE_CANDIDATE!>check<!><<!CANNOT_INFER_PARAMETER_TYPE!>Long<!>>() }
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 6,435 | kotlin | Apache License 2.0 |
analysis/low-level-api-fir/testData/lazyResolveTypeAnnotations/destructuringDeclaration/scriptStatementLevelAsLastStatement.kts | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // RESOLVE_SCRIPT
// BODY_RESOLVE
package util
annotation class Anno(val str: String)
const val constant = "s"
data class Pair(val a: @Anno("a type $constant") List<@Anno("a nested type $constant") Collection<@Anno("a nested nested type $constant") String>>?, val b: @Anno("b type $constant") Array<@Anno("b nested type $constant") List<@Anno("b nested nested type $constant") Int>>?)
const val prop = "str"
if (true) {
@Anno("destr 1 $prop")
val (@Anno("a $prop") a, @Anno("b $prop") b) = Pair(null, null)
@Anno("destr 1 $prop")
val (@Anno("c $prop") c, @Anno("d $prop") d) = Pair(null, null)
}
fun foo() {} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 628 | kotlin | Apache License 2.0 |
app/src/main/java/com/vshyrochuk/topcharts/data/datasource/ChartsRemoteDataSource.kt | Mc231 | 524,970,692 | false | null | package com.vshyrochuk.topcharts.data.datasource
import com.vshyrochuk.topcharts.BuildConfig
import com.vshyrochuk.topcharts.data.network.ChartsApi
import com.vshyrochuk.topcharts.data.network.mapping.toDomain
import com.vshyrochuk.topcharts.domain.domain.ChartsDataSource
import com.vshyrochuk.topcharts.domain.model.ChartEntity
class ChartsRemoteDataSource(private val api: ChartsApi) : ChartsDataSource {
override suspend fun load(): List<ChartEntity> {
return api.getCharts(BuildConfig.COUNTRY, BuildConfig.LOAD_LIMIT).toDomain()
}
} | 0 | Kotlin | 0 | 0 | 8b9f6ae00d38e69b81cc466adb14bb7d2b48c20f | 556 | Top-Charts | MIT License |
nitrozen-android-lib/src/main/java/com/fynd/nitrozen/components/button/text/TextButton.kt | gofynd | 238,860,720 | false | null | package com.fynd.nitrozen.components.button.text
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import com.fynd.nitrozen.components.button.NitrozenButtonConfiguration
import com.fynd.nitrozen.components.button.NitrozenButtonConfiguration.Default
import com.fynd.nitrozen.components.button.NitrozenButtonStyle
import com.fynd.nitrozen.components.button.NitrozenButtonStyle.Default
import com.fynd.nitrozen.theme.NitrozenTheme
@Preview(showBackground = true)
@Composable
private fun NitrozenTextButton_Enabled() {
NitrozenTheme {
NitrozenTextButton(
text = "Text Button Enabled",
onClick = {},
enabled = true
)
}
}
@Preview(showBackground = true)
@Composable
private fun NitrozenTextButton_Disabled() {
NitrozenTheme {
NitrozenTextButton(
text = "Text Button Disabled",
onClick = {},
enabled = false
)
}
}
@Preview(showBackground = true)
@Composable
private fun NitrozenTextButton_Underlined() {
NitrozenTheme {
NitrozenTextButton(
text = "Text Button Underlined",
onClick = {},
enabled = true,
style = NitrozenButtonStyle.Text.Default.copy(
textDecoration = TextDecoration.Underline,
),
)
}
}
@Composable
fun NitrozenTextButton(
modifier: Modifier = Modifier,
text: String,
onClick: () -> Unit,
enabled: Boolean = true,
style: NitrozenButtonStyle.Text = NitrozenButtonStyle.Text.Default,
configuration: NitrozenButtonConfiguration.Text = NitrozenButtonConfiguration.Text.Default,
) {
val textColor =
if (enabled)
style.textColorEnabled
else
style.textColorDisabled
TextButton(
onClick = onClick,
colors = ButtonDefaults.textButtonColors(),
modifier = modifier
.heightIn(min = configuration.minHeight),
shape = configuration.shape,
enabled = enabled,
contentPadding = configuration.contentPadding,
) {
Text(
text = text,
style = style.textStyle,
color = textColor,
textDecoration = style.textDecoration,
)
}
} | 1 | Kotlin | 4 | 5 | 2e0506c5ddd9bd0ebd45814ca1c8fef232db336f | 2,554 | nitrozen-android | MIT License |
common/src/commonMain/kotlin/drop/DropEvaluator.kt | alexsocha | 181,845,813 | false | {"Kotlin": 429248, "Dockerfile": 861, "JavaScript": 402, "Shell": 114} | package mod.lucky.common.drop
import mod.lucky.common.*
import mod.lucky.common.attribute.*
import mod.lucky.common.attribute.evalAttr
import kotlin.math.pow
const val DEBUG = false
private var debugDropFilters = listOf<String>()
private var debugDropIndexRange = 0..1000
private var debugDropIndex = debugDropIndexRange.first
class DropError(msg: String) : Exception("Error performing Lucky Block function: $msg")
data class DropContext(
val world: World,
val pos: Vec3d,
val player: PlayerEntity? = null,
val hitEntity: Entity? = null,
val bowPower: Double = 1.0,
val sourceId: String,
) { companion object }
fun createDropEvalContext(dropContext: DropContext, drop: SingleDrop? = null): EvalContext {
return EvalContext(LuckyRegistry.templateVarFns, DropTemplateContext(drop, dropContext, random=KotlinRandom()))
}
fun createVecSpec(baseName: String, partNames: Triple<String, String, String>, type: AttrType? = null): Array<Pair<String, AttrSpec>> {
return arrayOf(
partNames.first to ValueSpec(type),
partNames.second to ValueSpec(type),
partNames.third to ValueSpec(type),
baseName to ListSpec(listOf(ValueSpec(type), ValueSpec(type), ValueSpec(type)))
)
}
fun evalDrop(template: BaseDrop, context: EvalContext): List<SingleDrop> {
if (template is WeightedDrop) {
return evalDrop(template.drop, context)
}
if (template is GroupDrop) {
val shuffledDrops = if (template.shuffle) template.drops.shuffled() else template.drops
val groupAmount = (evalAttr(template.amount, context) as ValueAttr).value as Int
return (0 until groupAmount).map {
evalDrop(shuffledDrops[it], context)
}.flatten().toList()
}
if (template is SingleDrop) {
val contextWithDrop = if (context.templateContext is DropTemplateContext) {
context.copy(templateContext=context.templateContext.copy(drop=template))
} else context
val drop = template.eval(contextWithDrop)
val repeatAmount: Int = drop["amount"]
val evalOnRepeat: Boolean = drop["reinitialize"]
val evalAfterDelay: Boolean = drop["postDelayInit"]
if ("delay" in template) {
// Evaluation conditions for delayed drops:
// evalAfterDelay & evalOnRepeat: add N templates, evaluate each later
// evalAfterDelay & not evalOnRepeat: add one template, evaluate later
// not evalAfterDelay & evalOnRepeat: add N differently evaluated drops
// not evalAfterDelay & not evalOnRepeat: add one evaluated drop
if (evalOnRepeat) {
return (0 until repeatAmount).map {
if (evalAfterDelay) template.evalKeys(listOf("delay"), contextWithDrop)
else if (it == 0) drop else template.eval(contextWithDrop)
}.toList()
}
return listOf(if (evalAfterDelay) template.copy(props = template.props.with(mapOf("delay" to drop["delay"]))) else drop)
}
return (0 until repeatAmount).map {
if (it == 0) drop else if (evalOnRepeat) template.eval(contextWithDrop) else drop
}.toList()
}
return emptyList()
}
fun evalDropAfterDelay(dropOrTemplate: SingleDrop, context: EvalContext): List<SingleDrop> {
val evalAfterDelay: Boolean = dropOrTemplate["postDelayInit"]
val drop = if (evalAfterDelay) dropOrTemplate.eval(context) else dropOrTemplate
// if buildOnRepeat is true, this must be one of N delayed drops, each with amount=1
val evalOnRepeat: Boolean = drop["reinitialize"]
if (evalOnRepeat) return listOf(drop)
return (0 until drop["amount"]).map { drop }.toList()
}
private fun getDropIndexByWeight(weightPoints: ArrayList<Double>, randomIndex: Double): Int {
for (i in weightPoints.indices) {
if (randomIndex >= weightPoints[i] && randomIndex < weightPoints[i + 1]) return i
}
return 0
}
private fun chooseRandomDrop(drops: List<WeightedDrop>, luck: Int): WeightedDrop {
if (drops.isEmpty()) throw DropError("No drops found")
var lowestLuck = 0
var heighestLuck = 0
for (i in drops.indices) {
if (drops[i].luck < lowestLuck) lowestLuck = drops[i].luck
if (drops[i].luck > heighestLuck) heighestLuck = drops[i].luck
}
heighestLuck += lowestLuck * -1 + 1
val levelIncrease = 1.0 / (1.0 - (if (luck < 0) luck * -1 else luck) * 0.77 / 100.0)
var weightTotal = 0.0
val weightPoints = ArrayList<Double>()
weightPoints.add(0.0)
for (drop in drops) {
val dropLuck = drop.luck + lowestLuck * -1 + 1
val newLuck =
if (luck >= 0) levelIncrease.pow(dropLuck.toDouble()).toFloat() else levelIncrease
.pow(heighestLuck + 1 - dropLuck.toDouble()).toFloat()
val newChance = (drop.chance ?: 1.0) * newLuck * 100
weightTotal += newChance
weightPoints.add(weightTotal)
}
val randomIndex = DEFAULT_RANDOM.randDouble(0.0, 1.0) * weightTotal
return drops[getDropIndexByWeight(weightPoints, randomIndex)]
}
fun runEvaluatedDrop(drop: SingleDrop, context: DropContext) {
if ("delay" in drop && drop.get<Double>("delay") > 0.0) {
GAME_API.scheduleDrop(drop, context, drop["delay"])
} else {
val fn = LuckyRegistry.dropActions[drop.type]!!
fn(drop, context)
}
}
fun runDrop(drop: WeightedDrop, context: DropContext, showOutput: Boolean) {
if (showOutput) GAME_API.logInfo("Chosen Lucky Drop: ${drop.dropString}")
val singleDrops = evalDrop(drop, createDropEvalContext(context))
singleDrops.forEach { runEvaluatedDrop(it, context) }
}
fun runDropAfterDelay(delayedDrop: SingleDrop, context: DropContext) {
val evalContext = createDropEvalContext(context)
val singleDrops = evalDropAfterDelay(delayedDrop, evalContext)
for (drop in singleDrops) {
val fn = LuckyRegistry.dropActions[drop.type]!!
fn(drop, context)
}
}
fun nextDebugDrop(drops: List<WeightedDrop>): WeightedDrop {
// during hot reloading, edit the values here
val newFilters: List<String> = debugDropFilters
val newIndexRange = debugDropIndexRange
if (newIndexRange != debugDropIndexRange || newFilters != debugDropFilters) {
debugDropIndexRange = newIndexRange
debugDropFilters = newFilters
debugDropIndex = debugDropIndexRange.first
}
val filteredDrops = if (debugDropFilters.isNotEmpty()) drops.filter { d -> debugDropFilters.any { it in d.dropString } } else drops
if (debugDropIndex > debugDropIndexRange.last || debugDropIndex >= filteredDrops.size) debugDropIndex = debugDropIndexRange.first
if (debugDropIndex >= filteredDrops.size) debugDropIndex = 0
val index = debugDropIndex
debugDropIndex += 1
return filteredDrops[index]
}
fun runRandomDrop(customDrops: List<WeightedDrop>? = null, luck: Int, context: DropContext, showOutput: Boolean) {
val drops = customDrops ?: LuckyRegistry.drops[context.sourceId] ?: emptyList()
val drop = if (DEBUG && customDrops == null) nextDebugDrop(drops) else chooseRandomDrop(drops, luck)
runDrop(drop, context, showOutput)
}
| 24 | Kotlin | 19 | 32 | ecccf2ae066b6c511bce35f16c0b1e06519c31c0 | 7,204 | luckyblock | FSF All Permissive License |
command/src/main/kotlin/com/amarcolini/joos/command/SequentialCommand.kt | 19279-M1C2 | 477,597,033 | true | {"Kotlin": 541606, "Java": 1396} | package com.amarcolini.joos.command
/**
* A command that runs commands in sequence.
*/
class SequentialCommand @JvmOverloads constructor(
override val isInterruptable: Boolean = true,
vararg val commands: Command
) : CommandGroup(false, *commands) {
private var index = -1
override fun init() {
index = 0
commands[index].init()
}
override fun execute() {
if (index < 0 || index >= commands.size) return
commands[index].execute()
if (commands[index].isFinished()) {
commands[index].end(false)
index++
if (index < commands.size) commands[index].init()
}
}
override fun isFinished() = index >= commands.size
override fun end(interrupted: Boolean) {
if (index < 0) return
if (interrupted) commands[index].end(interrupted)
super.end(interrupted)
}
} | 0 | Kotlin | 0 | 0 | 9e65a6ac51025627c837e697fe648ab4f95c5169 | 901 | joos | MIT License |
projects/execution/src/main/kotlin/silentorb/imp/execution/Types.kt | silentorb | 235,929,224 | false | {"Kotlin": 189044} | package silentorb.imp.execution
import silentorb.imp.core.*
data class CompleteFunction(
val path: PathKey,
val signature: CompleteSignature,
val implementation: FunctionImplementation
)
data class TypeAlias(
val path: TypeHash,
val alias: TypeHash? = null,
val numericConstraint: NumericTypeConstraint? = null
)
data class ExecutionStep(
val node: PathKey,
val execute: NodeImplementation
)
data class ExecutionUnit(
val steps: List<ExecutionStep>,
val values: OutputValues,
val output: PathKey
)
| 3 | Kotlin | 0 | 1 | ca465c2b0a9864ded53114120d8b98dad44551dd | 547 | imp-kotlin | MIT License |
src/main/kotlin/com/ort/howlingwolf/domain/service/ability/DivineDomainService.kt | h-orito | 176,481,255 | false | null | package com.ort.howlingwolf.domain.service.ability
import com.ort.dbflute.allcommon.CDef
import com.ort.howlingwolf.domain.model.ability.AbilityType
import com.ort.howlingwolf.domain.model.charachip.Chara
import com.ort.howlingwolf.domain.model.charachip.Charas
import com.ort.howlingwolf.domain.model.daychange.DayChange
import com.ort.howlingwolf.domain.model.message.Message
import com.ort.howlingwolf.domain.model.village.Village
import com.ort.howlingwolf.domain.model.village.ability.VillageAbilities
import com.ort.howlingwolf.domain.model.village.ability.VillageAbility
import com.ort.howlingwolf.domain.model.village.participant.VillageParticipant
import org.springframework.stereotype.Service
@Service
class DivineDomainService : IAbilityDomainService {
override fun getAbilityType(): AbilityType = AbilityType(CDef.AbilityType.占い)
override fun getSelectableTargetList(
village: Village,
participant: VillageParticipant?
): List<VillageParticipant> {
participant ?: return listOf()
// 自分以外の生存者全員
return village.participant.memberList.filter {
it.id != participant.id && it.isAlive()
}
}
override fun getSelectingTarget(
village: Village,
participant: VillageParticipant?,
villageAbilities: VillageAbilities
): VillageParticipant? {
participant ?: return null
val targetVillageParticipantId = villageAbilities
.filterLatestday(village)
.filterByType(getAbilityType()).list
.find { it.myselfId == participant.id }
?.targetId
targetVillageParticipantId ?: return null
return village.participant.member(targetVillageParticipantId)
}
override fun createSetMessage(myChara: Chara, targetChara: Chara?): String {
return "${myChara.charaName.fullName()}が占い対象を${targetChara?.charaName?.fullName() ?: "なし"}に設定しました。"
}
override fun getDefaultAbilityList(
village: Village,
villageAbilities: VillageAbilities
): List<VillageAbility> {
// 進行中のみ
if (!village.status.isProgress()) return listOf()
// 生存している占い能力持ちごとに
return village.participant.filterAlive().memberList.filter {
it.skill!!.toCdef().isHasDivineAbility
}.mapNotNull { seer ->
// 対象は自分以外の生存者からランダム
village.participant
.filterAlive()
.findRandom { it.id != seer.id }
?.let {
VillageAbility(
villageDayId = village.day.latestDay().id,
myselfId = seer.id,
targetId = it.id,
abilityType = getAbilityType()
)
}
}
}
override fun processDayChangeAction(dayChange: DayChange, charas: Charas): DayChange {
val latestDay = dayChange.village.day.latestDay()
var messages = dayChange.messages.copy()
var village = dayChange.village.copy()
dayChange.village.participant.memberList.filter {
it.isAlive() && it.skill!!.toCdef().isHasDivineAbility
}.forEach { seer ->
dayChange.abilities.filterYesterday(village).list.find {
it.myselfId == seer.id
}?.let { ability ->
messages = messages.add(createDivineMessage(dayChange.village, charas, ability, seer))
// 呪殺対象なら死亡
if (isDivineKill(dayChange, ability.targetId!!)) village = village.divineKillParticipant(ability.targetId, latestDay)
}
}
return dayChange.copy(
messages = messages,
village = village
).setIsChange(dayChange)
}
override fun isAvailableNoTarget(village: Village): Boolean = false
override fun isUsable(village: Village, participant: VillageParticipant): Boolean {
// 生存していたら行使できる
return participant.isAlive()
}
// ===================================================================================
// Assist Logic
// ============
private fun createDivineMessage(
village: Village,
charas: Charas,
ability: VillageAbility,
seer: VillageParticipant
): Message {
val myself = village.participant.member(ability.myselfId)
val myChara = charas.chara(myself.charaId)
val targetChara = charas.chara(village.participant, ability.targetId!!)
val isWolf = village.participant.member(ability.targetId).skill!!.toCdef().isDivineResultWolf
val text = createDivineMessageString(myChara, targetChara, isWolf)
return Message.createSeerPrivateMessage(text, village.day.latestDay().id, seer)
}
private fun createDivineMessageString(chara: Chara, targetChara: Chara, isWolf: Boolean): String =
"${chara.charaName.fullName()}は、${targetChara.charaName.fullName()}を占った。\n${targetChara.charaName.fullName()}は人狼${if (isWolf) "の" else "ではない"}ようだ。"
private fun isDivineKill(dayChange: DayChange, targetId: Int): Boolean {
// 対象が既に死亡していたら呪殺ではない
if (!dayChange.village.participant.member(targetId).isAlive()) return false
// 対象が呪殺対象でなければ呪殺ではない
return dayChange.village.participant.member(targetId).skill!!.toCdef().isDeadByDivine
}
} | 0 | Kotlin | 1 | 3 | 7ef6d01ade6cfeb96935d6430a1a404bd67ae54e | 5,763 | howling-wolf-api | MIT License |
compiler/testData/diagnostics/nativeTests/specialBackendChecks/objCInterop/t33.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// WITH_PLATFORM_LIBS
import kotlinx.cinterop.*
import platform.darwin.*
import platform.Foundation.*
class Zzz : NSString {
<!CONSTRUCTOR_OVERRIDES_ALREADY_OVERRIDDEN_OBJC_INITIALIZER!>@OptIn(kotlinx.cinterop.BetaInteropApi::class)
@OverrideInit
constructor(coder: NSCoder) { }<!>
@Suppress("OVERRIDE_DEPRECATION")
override fun initWithCoder(coder: NSCoder): String? = "zzz"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 417 | kotlin | Apache License 2.0 |
idea/testData/findUsages/kotlin/findClassUsages/kotlinNestedClassAllUsages.1.kt | android | 263,405,600 | true | null | package b
import a.Outer
public class X(bar: String? = Outer.A.bar): Outer.A() {
var next: Outer.A? = Outer.A()
val myBar: String? = Outer.A.bar
init {
Outer.A.bar = ""
Outer.A.foo()
}
fun foo(a: Outer.A) {
val aa: Outer.A = a
aa.bar = ""
}
fun getNext(): Outer.A? {
return next
}
public override fun foo() {
super<Outer.A>.foo()
}
companion object: Outer.A() {
}
}
object O: Outer.A() {
}
fun X.bar(a: Outer.A = Outer.A()) {
}
fun Any.toA(): Outer.A? {
return if (this is Outer.A) this as Outer.A else null
} | 17 | Kotlin | 65 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 622 | kotlin | Apache License 2.0 |
intellij.tools.ide.starter/src/com/intellij/ide/starter/golang.kt | JetBrains | 499,194,001 | false | {"Kotlin": 426021, "C++": 3610, "Makefile": 713} | package com.intellij.ide.starter
import com.intellij.ide.starter.path.GlobalPaths
import com.intellij.openapi.util.SystemInfo
import com.intellij.ide.starter.utils.FileSystem
import com.intellij.ide.starter.utils.HttpClient
import java.nio.file.Path
fun downloadGoSdk(version: String): Path {
val os = when {
SystemInfo.isWindows -> "windows"
SystemInfo.isLinux -> "linux"
SystemInfo.isMac -> "darwin"
else -> error("Unknown OS")
}
val arch = if (SystemInfo.isAarch64) "arm64" else "amd64"
val extension = if (SystemInfo.isWindows) ".zip" else ".tar.gz"
val sdkFileName = "go$version.$os-$arch$extension"
val url = "https://cache-redirector.jetbrains.com/dl.google.com/go/$sdkFileName"
val dirToDownload = GlobalPaths.instance.getCacheDirectoryFor("go-sdk/$version")
val downloadedFile = dirToDownload.resolve(sdkFileName)
val goRoot = dirToDownload.resolve("go-roots")
if (goRoot.toFile().exists()) {
return goRoot.resolve("go")
}
HttpClient.download(url, downloadedFile)
FileSystem.unpack(downloadedFile, goRoot)
return goRoot.resolve("go")
} | 0 | Kotlin | 2 | 8 | 79dad83d28351750817d8e0c49ec516941b7c248 | 1,095 | intellij-ide-starter | Apache License 2.0 |
analysis/analysis-api-standalone/tests/org/jetbrains/kotlin/analysis/api/standalone/fir/test/configurators/AnalysisApiFirStandaloneModeTestConfiguratorFactory.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 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.analysis.api.standalone.fir.test.configurators
import org.jetbrains.kotlin.analysis.test.framework.test.configurators.*
object AnalysisApiFirStandaloneModeTestConfiguratorFactory : AnalysisApiTestConfiguratorFactory() {
override fun createConfigurator(data: AnalysisApiTestConfiguratorFactoryData): AnalysisApiTestConfigurator {
requireSupported(data)
return when (data.moduleKind) {
TestModuleKind.Source -> when (data.analysisSessionMode) {
AnalysisSessionMode.Normal -> StandaloneModeConfigurator
AnalysisSessionMode.Dependent -> unsupportedModeError(data)
}
TestModuleKind.LibraryBinary -> when (data.analysisSessionMode) {
AnalysisSessionMode.Normal -> StandaloneModeLibraryBinaryTestConfigurator
AnalysisSessionMode.Dependent -> unsupportedModeError(data)
}
else -> {
unsupportedModeError(data)
}
}
}
override fun supportMode(data: AnalysisApiTestConfiguratorFactoryData): Boolean {
return when {
data.frontend != FrontendKind.Fir -> false
data.analysisSessionMode != AnalysisSessionMode.Normal -> false
data.analysisApiMode != AnalysisApiMode.Standalone -> false
else -> when (data.moduleKind) {
TestModuleKind.Source,
TestModuleKind.LibraryBinary,
-> true
TestModuleKind.ScriptSource,
TestModuleKind.LibrarySource
-> false
}
}
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,847 | kotlin | Apache License 2.0 |
idea/testData/intentions/addForLoopIndices/explicitParamType.kt | android | 263,405,600 | true | null | // WITH_RUNTIME
fun a() {
val b = listOf(1,2,3,4,5)
for (<caret>c : Int in b) {
}
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 96 | kotlin | Apache License 2.0 |
src/test/kotlin/com/dprint/services/editorservice/process/EditorProcessTest.kt | dprint | 419,904,216 | false | {"Kotlin": 130008} | package com.dprint.services.editorservice.process
import com.dprint.config.UserConfiguration
import com.dprint.utils.getValidConfigPath
import com.dprint.utils.getValidExecutablePath
import com.dprint.utils.infoLogWithConsole
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.openapi.project.Project
import io.kotest.core.spec.style.FunSpec
import io.mockk.EqMatcher
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.mockkStatic
import io.mockk.verify
import java.io.File
import java.util.concurrent.CompletableFuture
class EditorProcessTest : FunSpec({
mockkStatic(ProcessHandle::current)
mockkStatic(::infoLogWithConsole)
mockkStatic("com.dprint.utils.FileUtilsKt")
val project = mockk<Project>()
val processHandle = mockk<ProcessHandle>()
val process = mockk<Process>()
val userConfig = mockk<UserConfiguration>()
val editorProcess = EditorProcess(project, userConfig)
beforeEach {
every { infoLogWithConsole(any(), project, any()) } returns Unit
}
afterEach {
clearAllMocks()
}
test("it creates a process with the correct args") {
val execPath = "/bin/dprint"
val configPath = "./dprint.json"
val workingDir = "/working/dir"
val parentProcessId = 1L
mockkConstructor(GeneralCommandLine::class)
mockkConstructor(File::class)
mockkConstructor(StdErrListener::class)
every { getValidExecutablePath(project) } returns execPath
every { getValidConfigPath(project) } returns configPath
every { ProcessHandle.current() } returns processHandle
every { processHandle.pid() } returns parentProcessId
every { userConfig.state } returns UserConfiguration.State()
every { constructedWith<File>(EqMatcher(configPath)).parent } returns workingDir
every { process.pid() } returns 2L
every { process.onExit() } returns CompletableFuture.completedFuture(process)
every { anyConstructed<StdErrListener>().listen() } returns Unit
val expectedArgs =
listOf(
execPath,
"editor-service",
"--config",
configPath,
"--parent-pid",
parentProcessId.toString(),
"--verbose",
)
// This essentially tests the correct args are passed in.
every { constructedWith<GeneralCommandLine>(EqMatcher(expectedArgs)).createProcess() } returns process
editorProcess.initialize()
verify(
exactly = 1,
) { constructedWith<GeneralCommandLine>(EqMatcher(expectedArgs)).withWorkDirectory(workingDir) }
verify(exactly = 1) { constructedWith<GeneralCommandLine>(EqMatcher(expectedArgs)).createProcess() }
}
})
| 4 | Kotlin | 2 | 7 | 191ab01e4eb5b0fa941c6f807ccf40915d007257 | 2,889 | dprint-intellij | MIT License |
src/main/kotlin/app/quiz/images/ImageRepository.kt | waterlink | 150,397,627 | false | null | package app.quiz.images
interface ImageRepository {
fun upload(image: ByteArray): String
}
| 13 | Kotlin | 3 | 10 | e4968ba369ce40258e9d3c069d918430fef015c0 | 96 | kotlin-spring-boot-mvc-starter | MIT License |
app/src/main/java/com/davismiyashiro/expenses/model/localrepo/TabDbSchema.kt | DavisJP | 109,140,022 | false | null | /*
* MIT License
*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.davismiyashiro.expenses.model.localrepo
/**
* Class that defines the tables attributes
*/
class TabDbSchema {
object TabTable {
const val TABLE_NAME = "tabs"
const val UUID = "uuid"
const val GROUPNAME = "groupName"
}
object ParticipantTable {
const val TABLE_NAME = "participants"
const val UUID = "uuid"
const val NAME = "name"
const val EMAIL = "email"
const val NUMBER = "number"
const val TAB_ID = "tab_id"
}
object ExpenseTable {
const val TABLE_NAME = "expenses"
const val UUID = "uuid"
const val DESCRIPTION = "description"
const val VALUE = "value"
const val TAB_ID = "tab_id"
}
object SplitTable {
const val TABLE_NAME = "splits"
const val UUID = "uuid"
const val PARTICIPANT_ID = "participantId"
const val EXPENSE_ID = "expenseId"
const val SPLIT_VAL = "valueByParticipant"
const val TAB_ID = "tabId"
}
}
| 0 | Kotlin | 0 | 0 | e88daf146151fa7ff3d2d4cc0a378af480dc48aa | 2,164 | Expenses | MIT License |
imagepicker/src/main/java/com/shz/imagepicker/imagepicker/model/PickedResult.kt | ShiftHackZ | 418,227,897 | false | {"Kotlin": 61367} | package com.shz.imagepicker.imagepicker.model
import java.io.Serializable
import com.shz.imagepicker.imagepicker.ImagePickerCallback
/**
* Describes all available business logic pick-operation result.
*
* Implements [Serializable].
*
* @see ImagePickerCallback
*/
sealed class PickedResult : Serializable {
/**
* Member of [PickedResult].
* Determines that nothing was selected during pick-operation.
*/
object Empty : PickedResult()
/**
* Member of [PickedResult].
* Determines that only one image was selected during pick-operation.
*
* @param image instance of selected [PickedImage].
*
* @see PickedImage
*/
data class Single(val image: PickedImage) : PickedResult()
/**
* Member of [PickedResult].
* Determines that only multiple images were selected during pick-operation.
*
* @param images collection of selected [PickedImage].
*
* @see PickedImage
*/
data class Multiple(val images: List<PickedImage>) : PickedResult()
/**
* Member of [PickedResult].
* Determines that some error occurred during pick-operation.
*
* @param throwable issue that happened with operation.
*
* @see Throwable
*/
data class Error(val throwable: Throwable) : PickedResult()
}
| 0 | Kotlin | 4 | 8 | 5fff8486c1dc3c4a6ad4a60bdb9505593f9f980c | 1,324 | ImagePicker | Apache License 2.0 |
ktor-client/ktor-client-java/build.gradle.kts | ddadon10 | 378,281,313 | true | {"Kotlin": 5244117, "Python": 948, "JavaScript": 775, "HTML": 88, "Mustache": 77} | val coroutines_version: String by project.extra
kotlin.sourceSets {
val jvmMain by getting {
dependencies {
api(project(":ktor-client:ktor-client-core"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutines_version")
}
}
val jvmTest by getting {
dependencies {
api(project(":ktor-client:ktor-client-tests"))
}
}
}
| 6 | null | 1 | 1 | 425fc32d020317f6b6b8aa30f2182904270919ec | 420 | ktor | Apache License 2.0 |
app/src/main/kotlin/com/rayfantasy/icode/model/ICodeTheme.kt | RayFantasyStudio | 50,503,759 | false | null | /*
* Copyright 2016 <NAME> aka. ztc1997
*
* 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.rayfantasy.icode.model
import android.content.Context
import android.databinding.ObservableInt
import com.rayfantasy.icode.R
import com.rayfantasy.icode.extension.colorAnim
import org.jetbrains.anko.defaultSharedPreferences
object ICodeTheme {
const val PREF_ICODE_THEME = "pref_icode_theme"
const val THEME_BLUE = 0
const val THEME_RED = 1
const val THEME_PURPLE = 2
const val THEME_GRAY = 3
const val THEME_YELLOW = 4
const val THEME_DEEPBLUE = 5
const val THEME_DEFAULT = THEME_RED
internal val colorPrimaryRes = intArrayOf(R.color.colorPrimary_blue, R.color.colorPrimary_red,
R.color.colorPrimary_purple, R.color.colorPrimary_gray, R.color.colorPrimary_yellow, R.color.colorPrimary_deepblue)
internal val colorPrimaryDarkRes = intArrayOf(R.color.colorPrimaryDark_blue, R.color.colorPrimaryDark_red,
R.color.colorPrimaryDark_purple, R.color.colorPrimaryDark_gray, R.color.colorPrimaryDark_yellow, R.color.colorPrimaryDark_deepblue)
internal val colorAccentRes = intArrayOf(R.color.colorAccent_blue, R.color.colorAccent_red,
R.color.colorAccent_purple, R.color.colorAccent_gray, R.color.colorAccent_yellow, R.color.colorAccent_deepblue)
internal val colorHighLightRes = intArrayOf(R.color.high_light_blue, R.color.high_light_red,
R.color.high_light_purple, R.color.high_light_gray, R.color.high_light_yellow, R.color.high_light_deepblue)
fun init(ctx: Context) {
val theme = ctx.defaultSharedPreferences.getInt(PREF_ICODE_THEME, THEME_DEFAULT)
ctx.changeTheme(theme)
}
val colorPrimary = ObservableInt()
val colorPrimaryDark = ObservableInt()
val colorAccent = ObservableInt()
val colorHighLight = ObservableInt()
val icon = ObservableInt()
}
fun Context.changeTheme(theme: Int) = with(ICodeTheme) {
changeColor(colorPrimary, resources.getColor(colorPrimaryRes[theme]))
changeColor(colorPrimaryDark, resources.getColor(colorPrimaryDarkRes[theme]))
changeColor(colorAccent, resources.getColor(colorAccentRes[theme]))
changeColor(colorHighLight, resources.getColor(colorHighLightRes[theme]))
defaultSharedPreferences.edit().putInt(PREF_ICODE_THEME, theme).apply()
}
private fun changeColor(observableInt: ObservableInt, color: Int) {
val i = observableInt.get()
if (i == color) return
if (i != 0) {
colorAnim(i, color, 300, { observableInt.set(it) })
} else
observableInt.set(color)
}
| 6 | Kotlin | 7 | 12 | 9751ec05a22f333e66cb0dccb013108127320f58 | 3,116 | iCode-Android | Apache License 2.0 |
src/test/java/tech/sirwellington/cs/MainTest.kt | SirWellington | 172,366,874 | false | {"Java": 9509, "Kotlin": 2162} | package tech.sirwellington.cs
import org.junit.runner.RunWith
import tech.sirwellington.alchemy.test.junit.runners.*
@RunWith(AlchemyTestRunner::class)
class MainTest
{
@org.junit.Before
fun setup()
{
}
} | 0 | Java | 0 | 0 | fc8e2c3850eaaf6d5db042471f6588f281bf5ff3 | 224 | CS-Fundamentals | MIT License |
app/src/main/java/com/dkmkknub/villtech/component/PostingField.kt | fahmigutawan | 510,392,118 | false | {"Kotlin": 197257} | package com.dkmkknub.villtech.component
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
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.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.ub.villtech.R
import com.dkmkknub.villtech.rootViewModel
import com.dkmkknub.villtech.ui.theme.Dark
import com.dkmkknub.villtech.ui.theme.GreenMint
import com.dkmkknub.villtech.ui.theme.Light
import com.dkmkknub.villtech.ui.theme.Typography
import com.dkmkknub.villtech.utils.LoginChecker
import com.dkmkknub.villtech.viewmodel.AdminHomeViewModel
import org.koin.androidx.compose.get
import org.koin.androidx.compose.getViewModel
@Composable
fun PostingTextField(
modifier: Modifier = Modifier,
titleValueState: MutableState<String>,
descriptionValueState: MutableState<String>
) {
val viewModel = getViewModel<AdminHomeViewModel>()
val context = LocalContext.current
val loginChecker = get<LoginChecker>()
val vidPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent(),
onResult = {
if (it != null) {
if (viewModel.isVideoIsFit(context, it)) {
viewModel.videoUri = it
if (viewModel.videoUri != null) {
viewModel.uploadVideoEnabled = false
viewModel.uploadPhotoEnabled = false
viewModel.uploadPhotoColor = Color.Gray
viewModel.uploadVideoColor = Color.Gray
} else {
viewModel.uploadVideoEnabled = true
viewModel.uploadPhotoEnabled = true
viewModel.uploadPhotoColor = Dark
viewModel.uploadVideoColor = Dark
}
} else {
rootViewModel.showSnackbar("Gagal. Pastikan Ukuran File Di bawah 250MB")
}
}
}
)
val imgPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetMultipleContents(),
onResult = {
it.forEach { uri ->
viewModel.photoUri.add(uri)
}
if (viewModel.photoUri.isNotEmpty()) {
viewModel.uploadVideoEnabled = false
viewModel.uploadVideoColor = Color.Gray
} else {
viewModel.uploadVideoEnabled = true
viewModel.uploadPhotoEnabled = true
viewModel.uploadPhotoColor = Dark
viewModel.uploadVideoColor = Dark
}
})
//Composable
val profilePictureWidth = LocalConfiguration.current.screenWidthDp / 7
val imageWithProfilePicture: @Composable () -> Unit = {
AsyncImage(
modifier = Modifier
.size(profilePictureWidth.dp)
.clip(CircleShape),
model = loginChecker.adminInfo.image_url,
contentDescription = "PROFILE PICTURE"
)
}
val imageWithNoPicture: @Composable () -> Unit = {
AsyncImage(
modifier = Modifier
.size(profilePictureWidth.dp)
.clip(CircleShape),
model = R.drawable.ic_no_picture,
contentDescription = "PROFILE PICTURE"
)
}
/**CONTENT*/
LazyColumn(modifier = Modifier, horizontalAlignment = Alignment.CenterHorizontally) {
/**PREVIEW*/
item {
//IF VIDEO
if (viewModel.videoUri != null)
AdminPostingMediaPreviewVideo(
uri = viewModel.videoUri!!,
modifier = Modifier.padding(start = 16.dp, end = 16.dp)
)
else if (viewModel.photoUri.isNotEmpty()) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp),
contentAlignment = Alignment.BottomCenter
) {
LazyRow(horizontalArrangement = Arrangement.Center) {
items(viewModel.photoUri) { uri ->
AdminPostingMediaPreviewImage(
modifier = Modifier.padding(end = 8.dp),
uri = uri
)
}
}
}
} else {
/**DO SOMETHING WHEN NO MEDIA PICKED*/
/**DO SOMETHING WHEN NO MEDIA PICKED*/
}
}
/**TITLE*/
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
//Profile picture
if (loginChecker.adminInfo.image_url != "null") imageWithProfilePicture()
else imageWithNoPicture()
//Space 16dp
Spacer(modifier = Modifier.width(16.dp))
//Title field
OutlinedTextField(
value = titleValueState.value,
onValueChange = { titleValueState.value = it },
shape = RoundedCornerShape(CornerSize(14.dp)),
colors = TextFieldDefaults
.outlinedTextFieldColors(
textColor = Dark,
backgroundColor = Light,
focusedBorderColor = Dark,
unfocusedBorderColor = Dark
),
placeholder = { Text(text = "Tulis judul di sini...", color = Color.Gray) }
)
}
}
/**DESCRIPTION*/
item {
Card(
modifier = modifier
.padding(start = 16.dp, end = 16.dp)
.fillMaxWidth(),
shape = RoundedCornerShape(CornerSize(14.dp)),
border = BorderStroke(width = 1.dp, color = Color.DarkGray)
) {
Column(
modifier = modifier
.padding(8.dp)
) {
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
Row(verticalAlignment = Alignment.CenterVertically) {
//Image
IconButton(
onClick = { imgPicker.launch("image/jpeg") },
enabled = viewModel.uploadPhotoEnabled
) {
Icon(
painter = painterResource(id = R.drawable.ic_add_image),
contentDescription = "Photo",
tint = viewModel.uploadPhotoColor
)
}
//Video
IconButton(
onClick = { vidPicker.launch("video/mp4") },
enabled = viewModel.uploadVideoEnabled
) {
Icon(
painter = painterResource(id = R.drawable.ic_add_video),
contentDescription = "Video",
tint = viewModel.uploadVideoColor
)
}
}
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
BasicTextField(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
value = descriptionValueState.value,
onValueChange = { descriptionValueState.value = it },
decorationBox = { innerTextField ->
if (descriptionValueState.value == "") {
Text(text = "Tulis deskripsi di sini...", color = Color.Gray)
}
innerTextField()
})
}
}
}
/**FILE CONSTRAINT*/
item {
Column(modifier = Modifier.padding(start = 16.dp, top = 8.dp)) {
Text(
modifier = Modifier.fillMaxWidth(),
text = "* Hanya gunakan file .JPEG atau .MP4",
color = Color.Black,
style = Typography.body2,
textAlign = TextAlign.Start
)
Text(
modifier = Modifier.fillMaxWidth(),
text = "* Untuk .MP4 maksimal sebesar 250 MB",
color = Color.Black,
style = Typography.body2,
textAlign = TextAlign.Start
)
}
}
/**CATEGORY*/
item {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp, start = 16.dp, end = 16.dp),
textAlign = TextAlign.Start,
text = "Pilih Kategori",
fontFamily = FontFamily(Font(R.font.poppins_semibold)),
color = Dark
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = viewModel.isCategoryInfografisSelected,
onClick = {
if (!viewModel.category.contains("infografis")) {
viewModel.category += "infografis,"
}
viewModel.isCategoryInfografisSelected =
!viewModel.isCategoryInfografisSelected
}
)
Text(text = "Infografis", style = Typography.body2)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = viewModel.isCategoryVideoSelected,
onClick = {
if (!viewModel.category.contains("video")) {
viewModel.category += "video,"
}
viewModel.isCategoryVideoSelected =
!viewModel.isCategoryVideoSelected
}
)
Text(text = "Video", style = Typography.body2)
}
}
/**UPLOAD PROGRESS*/
item {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.height(5.dp),
progress = viewModel.uploadProgress.toFloat(),
color = GreenMint
)
}
/**BUTTON*/
item {
val loginChecker = get<LoginChecker>()
Spacer(modifier = Modifier.height(8.dp))
GreenButton(
onClick = { uploadContent(viewModel, loginChecker) },
text = "Upload",
enabled = viewModel.isUploadButtonEnabled
)
}
}
}
private fun uploadContent(viewModel: AdminHomeViewModel, loginChecker: LoginChecker) {
val isVideoUriNotNull = viewModel.videoUri != null
val isPhotoUriNotEmpty = viewModel.photoUri.isNotEmpty()
val onFailed: () -> Unit = { rootViewModel.showSnackbar("Terjadi kesalahan coba lagi nanti") }
val onMediaJpegUploaded: (Int) -> Unit = { contentId ->
viewModel.uploadPostWithImage(
contentId = contentId,
loginChecker = loginChecker,
onSuccess = {
rootViewModel.showSnackbar("Postingan berhasil diupload")
viewModel.resetPostData()
viewModel.updateCount(contentId)
},
onFailed = onFailed
)
}
val onMediaVideoUploaded: (Int) -> Unit = { contentId ->
viewModel.uploadPostWithVideo(
contentId = contentId,
loginChecker = loginChecker,
onSuccess = {
rootViewModel.showSnackbar("Postingan berhasil diupload")
viewModel.resetPostData()
viewModel.updateCount(contentId)
},
onFailed = onFailed
)
}
val onCountRetrieved: (Int) -> Unit = { contentId ->
if(viewModel.isDataNotFulfilled()) {
rootViewModel.showSnackbar("Harap isi semua data!")
}else{
if (isVideoUriNotNull) {
viewModel.uploadMp4(
contentId = contentId,
onSuccess = { onMediaVideoUploaded(contentId) },
onFailed = onFailed
)
}
else if (isPhotoUriNotEmpty) {
viewModel.uploadJpeg(
contentId = contentId,
onSuccess = { onMediaJpegUploaded(contentId) },
onFailed = onFailed
)
}
else {
rootViewModel.showSnackbar("Harap pilih Gambar atau Video terlebih dahulu")
}
}
}
/**UPLOAD LOGIC START HERE*/
viewModel
.getContentCount()
.addOnSuccessListener {
val count = if(it.value.toString()=="null") 0 else Integer.parseInt(it.value.toString())
onCountRetrieved(count + 1)
}.addOnFailureListener {
onFailed()
}
} | 0 | Kotlin | 0 | 0 | 899205eef1d12aa40a04a0603d4b4af0540e2673 | 15,439 | Jetpack-VillTech | MIT License |
core/descriptors/src/org/jetbrains/kotlin/resolve/sam/SamConstructorDescriptor.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 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.resolve.sam
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.synthetic.FunctionInterfaceConstructorDescriptor
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude
interface SamConstructorDescriptor : SimpleFunctionDescriptor, FunctionInterfaceConstructorDescriptor {
fun getSingleAbstractMethod(): CallableMemberDescriptor
}
class SamConstructorDescriptorImpl(
containingDeclaration: DeclarationDescriptor,
private val samInterface: ClassDescriptor
) : SimpleFunctionDescriptorImpl(
containingDeclaration,
null,
samInterface.annotations,
samInterface.name,
CallableMemberDescriptor.Kind.SYNTHESIZED,
samInterface.source
), SamConstructorDescriptor {
override val baseDescriptorForSynthetic: ClassDescriptor
get() = samInterface
override fun getSingleAbstractMethod(): CallableMemberDescriptor =
getAbstractMembers(samInterface).single()
}
object SamConstructorDescriptorKindExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) = descriptor is SamConstructorDescriptor
override val fullyExcludedDescriptorKinds: Int get() = 0
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,705 | kotlin | Apache License 2.0 |
app/src/main/java/com/agenda/up/listeners/telamain/VerificarCurrentUser.kt | Araujo-Alisson | 596,383,449 | false | null | package com.agenda.up.listeners.telamain
interface VerificarCurrentUser {
fun onSucesso()
fun onFailure()
}
| 1 | Kotlin | 0 | 0 | 1a74801e3a82982d024fb85defa664396ade2eb9 | 125 | Up | Apache License 2.0 |
src/main/kotlin/com/kotlinHSE/sergey/tinkoff_api/schemas/Candles.kt | SergeyHSE7 | 333,788,653 | false | null | package com.kotlinHSE.sergey.tinkoff_api.schemas
import kotlinx.serialization.Serializable
@Serializable
data class Candles(
val figi: String,
val interval: String,
val candles: Array<Candle>
)
| 0 | Kotlin | 0 | 0 | 97c3e66ed96e70f54c7cdaadf60ae810e840b191 | 220 | kotlin_fin-assistant | Apache License 2.0 |
src/test/java/com/kimen/Tester.kt | Kimentanm | 331,475,192 | false | {"Vue": 23918, "JavaScript": 16804, "Kotlin": 15560, "HTML": 804, "Dockerfile": 677, "Java": 592, "Shell": 180} | package com.kimen
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
@Rollback
abstract class Tester {
} | 0 | Vue | 2 | 2 | 75e4015c5b2d03fba83415250ff0cb7ee418f5f6 | 305 | whale-photos | MIT License |
compiler/fir/analysis-tests/testData/resolveWithStdlib/functionAndFunctionN.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | fun takeAnyFun(function: Function<*>) {}
fun test(block: () -> Unit) {
takeAnyFun(block)
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 96 | kotlin | Apache License 2.0 |
app/src/main/java/com/newsapp/models/news/Article.kt | Anasmirza20 | 428,017,744 | false | {"Kotlin": 26961} | package com.newsapp.models.news
data class Article(
val author: String,
val content: String?,
val description: String?,
val publishedAt: String,
val source: Source,
val title: String,
val url: String?,
val urlToImage: String?,
var isAlreadyLike: Boolean = false,
var isAlreadyDislike: Boolean = false,
) | 0 | Kotlin | 0 | 0 | c6314f04244aa638321b836d8208c2731a612c1d | 344 | News-App | Apache License 2.0 |
compiler/testData/diagnostics/tests/modifiers/annotations.fir.kt | android | 263,405,600 | true | null | annotation class My(
public val x: Int,
protected val y: Int,
internal val z: Int,
private val w: Int
)
open class Your {
open val x: Int = 0
}
annotation class His(override val x: Int): Your() | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 215 | kotlin | Apache License 2.0 |
RateBottomSheet/app/src/main/java/com/timac/ratebottomsheet/MainActivity.kt | HenryMacharia254 | 327,206,499 | false | {"Kotlin": 23971} | package com.timac.ratebottomsheet
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.mikhaellopez.ratebottomsheet.AskRateBottomSheet
import com.mikhaellopez.ratebottomsheet.RateBottomSheet
import com.mikhaellopez.ratebottomsheet.RateBottomSheetManager
import com.timac.ratebottomsheet.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnRateMe.setOnClickListener {
showRateBottomSheet()
}
}
private fun showRateBottomSheet() {
RateBottomSheetManager(this)
.setInstallDays(1) // 3 by default
.setLaunchTimes(2) // 5 by default
.setRemindInterval(1) // 2 by default
.setShowAskBottomSheet(true) // True by default
.setShowLaterButton(true) // True by default
.setShowCloseButtonIcon(true) // True by default
.setDebugForceOpenEnable(true) // to show bottom sheet without conditions check. False by Default
.monitor()
// Show bottom sheet if meets conditions
// With AppCompatActivity or Fragment
RateBottomSheet.showRateBottomSheetIfMeetsConditions(this, // Optional Listeners after context
listener = object : AskRateBottomSheet.ActionListener {
override fun onDislikeClickListener() {
Toast.makeText(this@MainActivity, "OnDislike", Toast.LENGTH_SHORT).show()
}
override fun onRateClickListener() {
Toast.makeText(this@MainActivity, "onRate", Toast.LENGTH_SHORT).show()
}
override fun onNoClickListener() {
Toast.makeText(this@MainActivity, "onNoClick", Toast.LENGTH_SHORT).show()
}
})
}
} | 0 | Kotlin | 0 | 0 | e69d7b4f9bbf62fb9b7d84ef5e084544e7448c28 | 2,201 | Android-UI--Implementations | MIT License |
sphinx/screens-detail/contact/edit-contact/src/main/java/chat/sphinx/edit_contact/ui/EditContactFragment.kt | stakwork | 340,103,148 | false | {"Kotlin": 4002503, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453} | package chat.sphinx.edit_contact.ui
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import by.kirich1409.viewbindingdelegate.viewBinding
import chat.sphinx.concept_user_colors_helper.UserColorsHelper
import chat.sphinx.contact.databinding.LayoutContactBinding
import chat.sphinx.contact.databinding.LayoutContactDetailScreenHeaderBinding
import chat.sphinx.contact.databinding.LayoutContactSaveBinding
import chat.sphinx.contact.ui.ContactFragment
import chat.sphinx.edit_contact.R
import chat.sphinx.edit_contact.databinding.FragmentEditContactBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
internal class EditContactFragment : ContactFragment<
FragmentEditContactBinding,
EditContactFragmentArgs,
EditContactViewModel
>(R.layout.fragment_edit_contact)
{
@Inject
lateinit var userColorsHelperInj: UserColorsHelper
override val userColorsHelper: UserColorsHelper
get() = userColorsHelperInj
override val viewModel: EditContactViewModel by viewModels()
override val binding: FragmentEditContactBinding by viewBinding(FragmentEditContactBinding::bind)
override val headerBinding: LayoutContactDetailScreenHeaderBinding by viewBinding(
LayoutContactDetailScreenHeaderBinding::bind, R.id.include_edit_contact_header
)
override val contactBinding: LayoutContactBinding by viewBinding(
LayoutContactBinding::bind, R.id.include_edit_contact_layout
)
override val contactSaveBinding: LayoutContactSaveBinding by viewBinding(
LayoutContactSaveBinding::bind, R.id.include_edit_contact_layout_save
)
override fun getHeaderText(): String = getString(R.string.edit_contact_header_name)
override fun getSaveButtonText(): String = getString(R.string.save_contact_button)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
headerBinding.apply {
textViewDetailScreenSubscribe.setOnClickListener {
lifecycleScope.launch(viewModel.mainImmediate) {
viewModel.toSubscriptionDetailScreen()
}
}
}
}
}
| 96 | Kotlin | 8 | 18 | 4fd9556a4a34f14126681535558fe1e39747b323 | 2,345 | sphinx-kotlin | MIT License |
src/test/kotlin/io/github/trustedshops_public/spring_boot_starter_keycloak_path_based_resolver/keycloak/NoPathMatcherExceptionTest.kt | trustedshops-public | 524,078,409 | false | {"Kotlin": 22803} | package io.github.trustedshops_public.spring_boot_starter_keycloak_path_based_resolver.keycloak
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class NoPathMatcherExceptionTest {
@Test
fun `Verify that error message can be built`() {
assertEquals(
NoPathMatcherException(DummyFacadeRequest("/test")).message,
"No path configured for request path '/test'"
)
}
}
| 2 | Kotlin | 0 | 0 | 451885d836f596ae1423b78d9a7a873552b42e18 | 443 | spring-boot-starter-keycloak-path-based-resolver | MIT License |
src/commonMain/kotlin/de/tfr/game/util/Timer.kt | TobseF | 172,265,691 | false | {"Kotlin": 34687, "Shell": 1210} | package de.tfr.game.util
class Timer(var actionTime: Double, private val timerAction: () -> Unit) : Time {
override var time = 0.0
private var pause = false
fun update(deltaTime: Double) {
time += deltaTime
if (!pause && time >= actionTime) {
time = 0.0
timerAction.invoke()
}
}
fun togglePause() {
pause = !pause
}
fun reset() {
time = 0.0
}
}
| 1 | Kotlin | 5 | 24 | a378d865d06ddd7455343ee899b0531565b2f768 | 448 | HitKlack | MIT License |
app/src/main/kotlin/io/orangebuffalo/simpleaccounting/domain/documents/storage/noop/NoopDocumentsStorage.kt | orange-buffalo | 154,902,725 | false | {"Kotlin": 915625, "TypeScript": 536700, "Vue": 256779, "SCSS": 30586, "JavaScript": 6806, "HTML": 633, "CSS": 10} | package io.orangebuffalo.simpleaccounting.domain.documents.storage.noop
import io.orangebuffalo.simpleaccounting.domain.documents.storage.DocumentsStorage
import io.orangebuffalo.simpleaccounting.domain.documents.storage.DocumentsStorageStatus
import io.orangebuffalo.simpleaccounting.domain.documents.storage.SaveDocumentRequest
import io.orangebuffalo.simpleaccounting.domain.documents.storage.SaveDocumentResponse
import io.orangebuffalo.simpleaccounting.services.persistence.entities.Workspace
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.reactive.asFlow
import org.springframework.core.io.buffer.DataBuffer
import org.springframework.core.io.buffer.DataBufferUtils
import org.springframework.core.io.buffer.DefaultDataBufferFactory
import org.springframework.security.util.InMemoryResource
import org.springframework.stereotype.Service
import java.util.concurrent.ThreadLocalRandom
import kotlin.math.max
@Service
class NoopDocumentsStorage : DocumentsStorage {
private val bufferFactory = DefaultDataBufferFactory()
override suspend fun saveDocument(request: SaveDocumentRequest): SaveDocumentResponse {
val filename = request.fileName
if (filename.contains("fail")) {
throw RuntimeException("Upload failed")
}
return SaveDocumentResponse(filename, getFakeContent(filename).contentLength())
}
private fun getFakeContent(filename:String) : InMemoryResource {
return InMemoryResource(
"START-// ${filename.repeat(
ThreadLocalRandom.current().nextInt(20_000, 30_000)
)} //-END"
)
}
override fun getId(): String = "noop"
override suspend fun getDocumentContent(workspace: Workspace, storageLocation: String): Flow<DataBuffer> {
val resource = getFakeContent(storageLocation)
val contentLength = resource.contentLength()
val bufferSize = max(1, contentLength / 30)
return DataBufferUtils
.read(
resource,
bufferFactory,
bufferSize.toInt()
)
.asFlow()
// simulate some storage delay
.map { dataBuffer ->
delay(100)
dataBuffer
}
}
override suspend fun getCurrentUserStorageStatus() = DocumentsStorageStatus(true)
}
| 67 | Kotlin | 0 | 1 | bec32d609ecb678203f5ab1afecb9b7e627858ef | 2,426 | simple-accounting | Creative Commons Attribution 3.0 Unported |
the.orm.itest/src/test/kotlin/io/the/orm/test/functional/ExamplesTest.kt | christophsturm | 260,202,802 | false | {"Kotlin": 221994} | package io.the.orm.test.functional
import failgood.Test
import io.the.orm.ConnectedRepo
import io.the.orm.test.DBS
import io.the.orm.test.describeOnAllDbs
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/** examples for standard use-cases. they run as part of the test suite to make sure they work. */
@Test
object ExamplesTest {
val context =
describeOnAllDbs("examples", DBS.databases, USERS_SCHEMA) { connectionProvider ->
test("throttled bulk inserts") {
val user = User(name = "a user", email = "with email")
val repo = ConnectedRepo.create<User>(connectionProvider)
val channel = Channel<Deferred<User>>(capacity = 40)
val entries = 1000
coroutineScope {
launch {
connectionProvider.transaction {
repeat(entries) {
channel.send(
async {
repo.create(
user.copy(
email = java.util.UUID.randomUUID().toString()
)
)
}
)
}
}
}
repeat(entries) { channel.receive().await() }
}
}
}
}
| 11 | Kotlin | 0 | 0 | 198962eaa510e50fb0790c147fb88440ed26f587 | 1,677 | the.orm | MIT License |
src/main/kotlin/no/nav/arbeidsgiver/min_side/services/ereg/EregService.kt | navikt | 170,528,339 | false | {"Kotlin": 271228, "Dockerfile": 85} | package no.nav.arbeidsgiver.min_side.services.ereg
import com.fasterxml.jackson.databind.JsonNode
import com.github.benmanes.caffeine.cache.Caffeine
import no.nav.arbeidsgiver.min_side.clients.retryInterceptor
import no.nav.arbeidsgiver.min_side.models.Organisasjon
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.cache.annotation.Cacheable
import org.springframework.cache.caffeine.CaffeineCache
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.client.RestClientResponseException
import java.util.*
@Component
class EregService(
@Value("\${ereg-services.baseUrl}") eregBaseUrl: String?,
restTemplateBuilder: RestTemplateBuilder
) {
private val restTemplate = restTemplateBuilder
.rootUri(eregBaseUrl)
.additionalInterceptors(
retryInterceptor(
3,
250L,
org.apache.http.NoHttpResponseException::class.java,
java.net.SocketException::class.java,
javax.net.ssl.SSLHandshakeException::class.java,
)
)
.build()
@Cacheable(EREG_CACHE_NAME)
fun hentUnderenhet(virksomhetsnummer: String): Organisasjon? {
return try {
val json = restTemplate.getForEntity(
"/v1/organisasjon/{virksomhetsnummer}?inkluderHierarki=true",
JsonNode::class.java,
mapOf("virksomhetsnummer" to virksomhetsnummer)
).body
underenhet(json)
} catch (e: RestClientResponseException) {
if (e.statusCode == HttpStatus.NOT_FOUND) {
return null
}
throw e
}
}
@Cacheable(EREG_CACHE_NAME)
fun hentOverenhet(orgnummer: String): Organisasjon? {
return try {
val json = restTemplate.getForEntity(
"/v1/organisasjon/{orgnummer}",
JsonNode::class.java,
mapOf("orgnummer" to orgnummer)
).body
overenhet(json)
} catch (e: RestClientResponseException) {
if (e.statusCode == HttpStatus.NOT_FOUND) {
return null
}
throw e
}
}
fun underenhet(json: JsonNode?): Organisasjon? {
if (json == null || json.isEmpty) {
return null
}
val juridiskOrgnummer = json.at("/inngaarIJuridiskEnheter/0/organisasjonsnummer").asText()
val orgleddOrgnummer = json.at("/bestaarAvOrganisasjonsledd/0/organisasjonsledd/organisasjonsnummer").asText()
val orgnummerTilOverenhet = orgleddOrgnummer.ifBlank { juridiskOrgnummer }
return Organisasjon(
samletNavn(json),
"Business",
orgnummerTilOverenhet,
json.at("/organisasjonsnummer").asText(),
json.at("/organisasjonDetaljer/enhetstyper/0/enhetstype").asText(),
"Active"
)
}
fun overenhet(json: JsonNode?): Organisasjon? {
return if (json == null) {
null
} else Organisasjon(
samletNavn(json),
"Enterprise",
null,
json.at("/organisasjonsnummer").asText(),
json.at("/organisasjonDetaljer/enhetstyper/0/enhetstype").asText(),
"Active"
)
}
companion object {
private fun samletNavn(json: JsonNode) = listOf(
json.at("/navn/navnelinje1").asText(null),
json.at("/navn/navnelinje2").asText(null),
json.at("/navn/navnelinje3").asText(null),
json.at("/navn/navnelinje4").asText(null),
json.at("/navn/navnelinje5").asText(null)
)
.filter(Objects::nonNull)
.joinToString(" ")
}
}
const val EREG_CACHE_NAME = "ereg_cache"
@Configuration
class EregCacheConfig {
@Bean
fun eregCache() = CaffeineCache(
EREG_CACHE_NAME,
Caffeine.newBuilder()
.maximumSize(600000)
.recordStats()
.build()
)
} | 0 | Kotlin | 0 | 0 | e625f3abc5d915bdbe5aa1861d25e29aabe2dc0e | 4,269 | min-side-arbeidsgiver-api | MIT License |
spigot-core/src/main/kotlin/ru/astrainteractive/astralibs/serialization/KyoriComponentSerializerType.kt | Astra-Interactive | 422,588,271 | false | {"Kotlin": 110093} | package ru.astrainteractive.astralibs.serialization
import kotlinx.serialization.Serializable
@Serializable
enum class KyoriComponentSerializerType {
Json, Gson, Plain, MiniMessage, Legacy
}
| 1 | Kotlin | 0 | 3 | 047f85e57d853166d1aec64ea52e0a956197e711 | 197 | AstraLibs | MIT License |
app/src/main/kotlin/useless/android/app/module/app/Colors.kt | kepocnhh | 543,966,743 | false | {"Kotlin": 34319} | package useless.android.app.module.app
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
@Immutable
internal class Colors private constructor(
val background: Color,
val foreground: Color,
) {
companion object {
val dark = Colors(
background = Color.Black,
foreground = Color.White,
)
val light = Colors(
background = Color.White,
foreground = Color.Black,
)
}
}
| 0 | Kotlin | 0 | 0 | 22c2325164b49a592e027991ed34700073f601fe | 495 | AndroidAppUseless | MIT License |
compiler/testData/diagnostics/tests/generics/wrongNumberOfTypeArgumentsDiagnostic.kt | android | 263,405,600 | true | null | // !WITH_NEW_INFERENCE
// !DIAGNOSTICS: -UNUSED_PARAMETER, -UNUSED_VARIABLE
fun myFun(i : String) {}
fun myFun(i : Int) {}
fun test1() {
<!NI;NONE_APPLICABLE!>myFun<!><!OI;WRONG_NUMBER_OF_TYPE_ARGUMENTS!><Int><!>(3)
<!NONE_APPLICABLE!>myFun<!><String>('a')
}
fun test2() {
val m0 = java.util.<!NI;NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER, OI;TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>HashMap<!>()
val m1 = java.util.HashMap<!WRONG_NUMBER_OF_TYPE_ARGUMENTS!><String, String, String><!>()
val m2 = java.util.HashMap<!WRONG_NUMBER_OF_TYPE_ARGUMENTS!><String><!>()
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 590 | kotlin | Apache License 2.0 |
compiler/testData/codegen/box/properties/backingField/independentBackingFieldType.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM_IR
// TARGET_BACKEND: JS_IR
// TARGET_BACKEND: JS_IR_ES6
// TARGET_BACKEND: WASM
// IGNORE_BACKEND_K1: JVM_IR, JS_IR, JS_IR_ES6, WASM
fun createString() = "AAA" + "BBB"
class A {
var it: Int
field = 3.14
get() = (field + 10).toInt()
set(value) {
field = (value - 10).toDouble()
if (field < -3 || -1 < field) {
throw Exception("fail: value = $value, field = $field")
}
}
var that: Int
field = createString() + "!"
get() = field.length
set(value) {
field = value.toString()
if (field != "17") {
throw Exception("fail: value = $value, field = $field")
}
}
}
fun box(): String {
try {
val a = A()
val it: Int = A().it and 10
a.it = it
val that: Int = a.that
a.that = that + 10
} catch (e: Exception) {
return e.message ?: "fail"
}
return "OK"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,012 | kotlin | Apache License 2.0 |
android/room/src/main/java/com/example/splitandpay/room/di/RoomModule.kt | timatifey | 718,057,019 | false | {"Kotlin": 116639, "TypeScript": 52420, "Swift": 26466, "CSS": 24361, "HTML": 9914, "JavaScript": 1425, "Dockerfile": 404} | package com.example.splitandpay.room.di
import com.example.splitandpay.room.RoomModelMapper
import com.example.splitandpay.room.RoomViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val roomModule = module {
single { RoomModelMapper() }
viewModel {
RoomViewModel(get(), get(), get())
}
} | 0 | Kotlin | 0 | 3 | 3e24e188d15308b67d1eae1169072c67fb11c403 | 345 | split-and-pay | MIT License |
js/js.translator/testData/box/coroutines/dynamicSuspendReturnWithArrayAccess.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // IGNORE_BACKEND: JS
// WITH_STDLIB
// EXPECTED_REACHABLE_NODES: 1292
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
suspend fun foo(): dynamic {
return js("[1, 2, 3]")
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(object : Continuation<Unit> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<Unit>) {}
})
}
fun box(): String {
var result: dynamic = 0
val count = 0;
builder {
result += foo()[count + 0] + foo()[count + 1] * foo()[count + 2]
}
return if (result == 7) "OK" else "fail: the wrong answer. Expect to have 7 but got $result"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 666 | kotlin | Apache License 2.0 |
mpdomain/src/main/java/com/jpp/mpdomain/usecase/GetCreditsUseCase.kt | perettijuan | 156,444,935 | false | null | package com.jpp.mpdomain.usecase
import com.jpp.mpdomain.CastCharacter
import com.jpp.mpdomain.Connectivity
import com.jpp.mpdomain.Credits
import com.jpp.mpdomain.ImagesConfiguration
import com.jpp.mpdomain.repository.ConfigurationRepository
import com.jpp.mpdomain.repository.ConnectivityRepository
import com.jpp.mpdomain.repository.CreditsRepository
/**
* Use case to retrieve the [Credits] of a particular movie.
*/
class GetCreditsUseCase(
private val creditsRepository: CreditsRepository,
private val configurationRepository: ConfigurationRepository,
private val connectivityRepository: ConnectivityRepository
) {
suspend fun execute(movieId: Double): Try<Credits> {
return when (connectivityRepository.getCurrentConnectivity()) {
is Connectivity.Disconnected -> Try.Failure(Try.FailureCause.NoConnectivity)
is Connectivity.Connected -> creditsRepository.getCreditsForMovie(movieId)
?.let { credits ->
Try.Success(credits.copy(cast = credits.cast.map { character ->
configureCharacterProfilePath(
character
)
}))
} ?: Try.Failure(Try.FailureCause.Unknown)
}
}
private suspend fun configureCharacterProfilePath(castCharacter: CastCharacter): CastCharacter {
return configurationRepository.getAppConfiguration()?.let { appConfiguration ->
castCharacter.configureProfilePath(appConfiguration.images)
} ?: castCharacter
}
private fun CastCharacter.configureProfilePath(imagesConfig: ImagesConfiguration): CastCharacter {
return copy(
profile_path = profile_path.createUrlForPath(
imagesConfig.base_url,
imagesConfig.profile_sizes.last()
)
)
}
}
| 9 | Kotlin | 7 | 46 | 7921806027d5a9b805782ed8c1cad447444f476b | 1,879 | moviespreview | Apache License 2.0 |
app/src/main/java/ru/mail/march/sample/PresenterImpl.kt | mailru | 263,284,417 | false | null | package ru.mail.march.sample
import ru.mail.march.interactor.InteractorObtainer
class PresenterImpl(view: Presenter.View, interactorObtainer: InteractorObtainer): Presenter {
private val interactor = interactorObtainer.obtain(SampleInteractor::class.java) {
SampleInteractor()
}
init {
interactor.errorChannel.observe { view.showError(it) }
interactor.wordChannel.observe { view.showText(it) }
interactor.timeChannel.observe { view.showTime(it) }
}
override fun onButtonClick() {
interactor.request()
}
} | 2 | Kotlin | 1 | 11 | 74522ab9e1cc2b07763a3ee240c727155d45f194 | 572 | March | MIT License |
feature-staking-api/src/main/java/jp/co/soramitsu/feature_staking_api/domain/model/StakingAccount.kt | izhestkov | 346,603,452 | true | {"Kotlin": 1066068} | package jp.co.soramitsu.feature_staking_api.domain.model
import jp.co.soramitsu.core.model.CryptoType
import jp.co.soramitsu.core.model.Network
data class StakingAccount(
val address: String,
val name: String?,
val cryptoType: CryptoType,
val network: Network
) | 0 | null | 0 | 0 | f63b80c711d17b9f07e8632260b69029dea6e517 | 279 | fearless-Android | Apache License 2.0 |
pubsub/src/main/kotlin/glitch/pubsub/events/json/moderation.kt | GlitchLib | 146,582,041 | false | {"Java": 236506, "Kotlin": 125095} | package glitch.pubsub.events.json
import com.google.gson.annotations.JsonAdapter
import com.google.gson.annotations.SerializedName
import glitch.api.objects.json.interfaces.IDObject
import glitch.pubsub.`object`.adapters.ModerationActionAdapter
import java.util.*
/**
*
* @author <NAME> [<EMAIL>]
* @version %I%, %G%
* @since 1.0
*/
data class Timeout(
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long,
val duration: Int,
val reason: String?
) : IModerator, ITarget {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById,
data.args[0],
data.targetId,
data.args[1].toInt(),
if (data.args.size > 2) data.args[2] else null
)
}
data class Ban(
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long,
val reason: String?
) : IModerator, ITarget {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById,
data.args[0],
data.targetId,
if (data.args.size > 1) data.args[1] else null
)
}
data class Host(
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long
) : IModerator, ITarget {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById,
data.args[0],
data.targetId
)
}
data class MessageDelete(
override val id: UUID,
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long,
val message: String
) : IDObject<UUID>, IModerator, ITarget {
constructor(data: ModerationData) : this(
UUID.fromString(data.args[2]),
data.createdBy,
data.createdById,
data.args[0],
data.targetId,
data.args[1]
)
}
data class ModerationData(
val type: String,
@JsonAdapter(ModerationActionAdapter::class)
val moderationAction: Action,
val args: List<String>,
val createdBy: String,
@SerializedName("created_by_user_id")
val createdById: Long,
@SerializedName("target_user_id")
val targetId: Long
) {
enum class Action {
TIMEOUT,
BAN,
UNBAN,
UNTIMEOUT,
HOST,
SUBSCRIBERS,
SUBSCRIBERSOFF,
CLEAR,
EMOTEONLY,
EMOTEONLYOFF,
R9KBETA,
R9KBETAOFF,
DELETE
}
}
data class Moderator(
override val moderatorName: String,
override val moderatorId: Long
) : IModerator {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById
)
}
data class ActivationByMod(
override val moderatorName: String,
override val moderatorId: Long,
@get:SerializedName("active")
val isActive: Boolean
) : IModerator {
constructor(data: ModerationData, isActive: Boolean) : this(
data.createdBy,
data.createdById,
isActive
)
}
data class Unban(
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long
) : IModerator, ITarget {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById,
data.args[0],
data.targetId
)
} | 15 | Java | 3 | 11 | 81283227ee6c3b63866fe1371959a72f8b0d2640 | 3,812 | glitch | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/MusicNote2.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11029508, "Java": 256912} |
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.MusicNote2: ImageVector
get() {
if (_musicNote2 != null) {
return _musicNote2!!
}
_musicNote2 = fluentIcon(name = "Regular.MusicNote2") {
fluentPath {
moveTo(19.7f, 2.15f)
curveToRelative(0.19f, 0.14f, 0.3f, 0.36f, 0.3f, 0.6f)
lineTo(20.0f, 16.5f)
arcToRelative(3.5f, 3.5f, 0.0f, true, true, -1.5f, -2.87f)
lineTo(18.5f, 7.76f)
lineTo(10.0f, 10.3f)
verticalLineToRelative(8.19f)
arcToRelative(3.5f, 3.5f, 0.0f, true, true, -1.5f, -2.87f)
lineTo(8.5f, 5.75f)
curveToRelative(0.0f, -0.33f, 0.22f, -0.62f, 0.53f, -0.72f)
lineToRelative(10.0f, -3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.67f, 0.12f)
close()
moveTo(10.0f, 8.75f)
lineToRelative(8.5f, -2.56f)
lineTo(18.5f, 3.76f)
lineTo(10.0f, 6.3f)
verticalLineToRelative(2.43f)
close()
moveTo(6.5f, 16.5f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, 0.0f, 4.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 0.0f, -4.0f)
close()
moveTo(14.5f, 16.5f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, 4.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, -4.0f, 0.0f)
close()
}
}
return _musicNote2!!
}
private var _musicNote2: ImageVector? = null
| 4 | Kotlin | 4 | 155 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 1,872 | compose-fluent-ui | Apache License 2.0 |
src/main/kotlin/fp/kotlin/example/chapter11/exercise/11_2_writeMonad_gcd.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter11.exercise
import fp.kotlin.example.chapter10.Maybe
import fp.kotlin.example.chapter10.Nothing
import fp.kotlin.example.chapter10.exercise.FunStream
import fp.kotlin.example.chapter10.exercise.funStreamOf
import fp.kotlin.example.chapter11.logging.WriterMonad
/**
*
* 연습문제 11-2
*
* 최대공약수를 구하는 유클리드 알고리즘(Euclidean algorithm)의 동작 로그를 살펴볼 수 있는 함수 ``gcd``를 WriterMonad를 사용해서 만들어보자.
*
* 힌트 : ``gcd(60, 48)``를 호출했을때 아래와 같이 출력되어야 한다.
* [60 mod 48 = 12, 48 mod 12 = 0, Finished with 12]
*
*/
fun main() {
require(gcd(60, 48) == funStreamOf("60 mod 48 = 12", "48 mod 12 = 0", "Finished with 12"))
require(gcd2(60, 48) == funStreamOf("60 mod 48 = 12", "48 mod 12 = 0", "Finished with 12"))
require(gcd(48, 60) == funStreamOf("48 mod 60 = 48", "60 mod 48 = 12", "48 mod 12 = 0", "Finished with 12"))
require(gcd2(48, 60) == funStreamOf("48 mod 60 = 48", "60 mod 48 = 12", "48 mod 12 = 0", "Finished with 12"))
require(gcd(60, 5) == funStreamOf("60 mod 5 = 0", "Finished with 5"))
require(gcd2(60, 5) == funStreamOf("60 mod 5 = 0", "Finished with 5"))
require(gcd(61, 3) == funStreamOf("61 mod 3 = 1", "3 mod 1 = 0", "Finished with 1"))
require(gcd2(61, 3) == funStreamOf("61 mod 3 = 1", "3 mod 1 = 0", "Finished with 1"))
require(gcd(63, 24) == funStreamOf("63 mod 24 = 15", "24 mod 15 = 9", "15 mod 9 = 6", "9 mod 6 = 3", "6 mod 3 = 0",
"Finished with 3"))
require(gcd2(63, 24) == funStreamOf("63 mod 24 = 15", "24 mod 15 = 9", "15 mod 9 = 6", "9 mod 6 = 3", "6 mod 3 = 0",
"Finished with 3"))
}
fun gcd(x: Int, y: Int,
maybeWriteMonad: Maybe<WriterMonad<Pair<Int, Int>>> = Nothing): FunStream<String> = TODO()
fun gcd2(x: Int, y: Int, writeMonad: WriterMonad<Pair<Int, Int>>? = null): FunStream<String> = TODO()
private infix fun <T> T.withLog(log: String): WriterMonad<T> = TODO() | 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 2,014 | fp-kotlin-example | MIT License |
Dataset Summary
KStack is the largest collection of permissively licensed Kotlin code.
Comparison with The Stack v2
In the table below one can find the comparsion between the Kotlin part of The Stack v2 and KStack:
Files | Repositories | Lines | Tokens | |
---|---|---|---|---|
Kotlin in The Stack v2 | 2M | 109,457 | 162M | 1.7B |
Kstack | 4M | 168,902 | 292M | 3.1B |
Dataset Creation
Collection procedure
We collected repositories from GitHub with the main language being Kotlin, as well as any repositories with Kotlin files that have received 10 or more stars (as of February 2024). Additionally, we gathered repositories with Kotlin files from The Stack v1.2. Kotlin files were identified using go-enry and include files with extensions such as .kt
, .kts
, and .gradle.kts
. It is estimated that we have collected 97% of available Kotlin repositories as of February 2024.
Initial filtering
We conducted full deduplication, using the hash of file content, as well as near deduplication using the same method as in The Stack v1.2. We aggregated the files from one near-deduplicated cluster into a file from the repository with the most stars.
Detecting permissive licenses
We filtered permissive repositories based on the licenses detected by GitHub, and using go-license-detector if GitHub did not have licensing information available. The list of permissive licenses used in dataset can be found here.
Personal and Sensitive Information
To filter out personal information, we applied the same model that was used for The Stack v2 — star-pii.
Column description
The dataset contains the following columns:
size
— size of the file in bytescontent
— text (content) of the file after removing personal identifiable informationrepo_id
— GitHub ID of the repositorypath
— path to a fileowner
— repo owner on GitHubname
— repo name on GitHubcommit_sha
— hash of the commit, from which the revision of the file is takenstars
— number of stars in the repo at the moment of collectionforks
— number of forks in the repo at the moment of collectionissues
— number of issues in the repo at the moment of collectionis_fork
—true
if the repo is a fork or not as defined by GitHubmain_language
— main language of the repo as defined by GitHublanguages_distribution
— JSON with the distribution of languages by size in bytes in the repolicense
— permissive license of the repository
Opt-out
If you want your data to be removed from dataset, or have any other questions, please reach out to Sergey Titov: [email protected]
- Downloads last month
- 451