path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
airbyte-cdk/java/airbyte-cdk/typing-deduping/src/main/kotlin/io/airbyte/integrations/base/destination/typing_deduping/V2TableMigrator.kt
tim-werner
511,419,970
false
{"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2}
/* * Copyright (c) 2023 Airbyte, Inc., all rights reserved. */ package io.airbyte.integrations.base.destination.typing_deduping /** * Prefer [io.airbyte.integrations.base.destination.typing_deduping.migrators.Migration] instead. */ interface V2TableMigrator { @Throws(Exception::class) fun migrateIfNecessary(streamConfig: StreamConfig?) }
1
null
1
1
b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff
349
airbyte
MIT License
src/main/kotlin/com/github/tyrrx/vb6language/psi/tree/definition/variable/VB6VariableListElement.kt
bluehands
511,430,044
false
{"Java": 1027191, "Kotlin": 319653, "ANTLR": 31013}
package com.github.tyrrx.vb6language.psi.tree.definition.variable import com.github.tyrrx.vb6language.psi.base.VB6SubscriptsOwner import com.github.tyrrx.vb6language.psi.declarations.VB6VariableDeclaration import com.github.tyrrx.vb6language.psi.inference.VB6TypeClauseOwner import com.github.tyrrx.vb6language.psi.mixins.VB6TypeHintOwnerMixin import com.github.tyrrx.vb6language.psi.scope.VB6VisibilityOwner import com.intellij.psi.PsiElement /** * This interface specifies a (static) variable declaration element * * Merged: * Dim-Statement: https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa243352(v=vs.60) * Static-Statement: https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa266296(v=vs.60) * */ interface VB6VariableListElement : VB6VariableDeclaration, VB6VisibilityOwner, VB6TypeClauseOwner, VB6SubscriptsOwner, VB6TypeHintOwnerMixin { val isModuleVariable: Boolean // reference to variableStmt or moduleVariableStmt val parentVariableStmt: PsiElement // not valid in module with events https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa243352(v=vs.60) val isArray: Boolean val withEvents: Boolean val isStatic: Boolean }
1
null
1
1
1a742a07d78681a5bd11787a38c72c68cddd7f77
1,304
IntelliJ-VB6-language-support
MIT License
app/src/main/java/com/pt/common/mutual/life/GlobalActivity.kt
OmAr-Kader
674,357,483
false
{"Kotlin": 2780433}
package com.pt.common.mutual.life import com.pt.common.global.* import com.pt.common.stable.alsoSus import com.pt.common.stable.applySus import com.pt.common.stable.launchImdMain abstract class GlobalActivity : GlobalBaseActivity() { internal var fasten: DSack<android.widget.FrameLayout, android.widget.FrameLayout, androidx.appcompat.widget.AppCompatImageView>? = null override fun onCreate(savedInstanceState: android.os.Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { launchImdMain { intiGlobalViews { initActivity(it) } } } else { recreateAct() } } override fun onAttachedToWindow() { window?.apply { myBaseActivity(theme.findAttr(android.R.attr.textColorPrimary) == fetchColor(com.pt.pro.R.color.bla)) } super.onAttachedToWindow() } private suspend fun intiGlobalViews(a: suspend (Int) -> Unit) { com.pt.common.stable.justCoroutine { inflate( resources.statusBarHeight, actionBarHeight ).alsoSus { @com.pt.common.global.ViewAnn fasten = it }.applySus { one.applySus(::setContentView) }.also { a.invoke(it.two.id) } } } private fun android.content.Context.inflate( stat: Int, act: Int, ): DSack<android.widget.FrameLayout, android.widget.FrameLayout, androidx.appcompat.widget.AppCompatImageView> { return android.widget.FrameLayout( this@inflate ).run root@{ android.view.WindowManager.LayoutParams( com.pt.common.stable.MATCH, com.pt.common.stable.MATCH ).also(this@root::setLayoutParams) setBackgroundColor(theme.findAttr(com.pt.pro.R.attr.rmoBackground)) val img = androidx.appcompat.widget.AppCompatImageView( context ).apply { framePara(com.pt.common.stable.MATCH, act + stat) {} svgReColor(theme.findAttr(android.R.attr.colorPrimary)) compactImage(com.pt.pro.R.drawable.card_back) { setImageDrawable(this@compactImage) } }.also(this@root::addView) val frame = android.widget.FrameLayout( context ).apply { id = com.pt.pro.R.id.globalFrame framePara(com.pt.common.stable.MATCH, com.pt.common.stable.MATCH) { topMargin = stat.topFrameMargin } }.also(this@root::addView) com.pt.common.global.DSack(this@root, frame, img) } } abstract val Int.topFrameMargin: Int abstract suspend fun initActivity(@androidx.annotation.IdRes i: Int) @com.pt.common.global.MainAnn abstract fun DSack<android.widget.FrameLayout, android.widget.FrameLayout, androidx.appcompat.widget.AppCompatImageView>.initViews( statusHeight: Int ) @com.pt.common.global.MainAnn override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { super.onConfigurationChanged(newConfig) fasten?.initViews(resources.statusBarHeight) } override fun onDestroy() { com.pt.common.mutual.pref.DbPrefInitializer.preference = null com.pt.common.stable.catchy(Unit) { fasten?.one?.removeAllViewsInLayout() } super.onDestroy() fasten = null } }
0
Kotlin
0
0
fe57fe5a4029119ac287ab8d3d4b5ccfc05af3a0
3,632
PT-All-Pro
Apache License 2.0
app/src/main/java/com/jutikorn/eddieplayer/song/structure/di/SongComponentImpl.kt
jutikorn
144,380,852
false
null
package com.jutikorn.eddieplayer.song.structure.di import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.ViewModelProviders import android.support.v4.app.Fragment import com.jutikorn.eddieplayer.song.SongContract import com.jutikorn.eddieplayer.song.structure.MusicPlayerImpl import com.jutikorn.eddieplayer.song.structure.SongUseCaseImpl import com.jutikorn.eddieplayer.song.structure.viewmodel.SongViewModel import com.jutikorn.eddieplayer.song.view.SongFragmentArgs class SongComponentImpl(fragment: Fragment) : SongComponent { override val lifecycleOwner: LifecycleOwner = fragment override val viewModel: SongContract.IViewModel = ViewModelProviders.of(fragment).get(SongViewModel::class.java).apply { this.songsLiveData.value = SongFragmentArgs.fromBundle(fragment.arguments).song } override val player: SongContract.MusicPlayer by lazy { MusicPlayerImpl(fragment).apply { viewModel.songsLiveData.value?.url?.let { setSource(it) } lifecycleOwner.lifecycle.addObserver(this) } } override val interactor: SongContract.UseCase by lazy { SongUseCaseImpl(player) } }
0
Kotlin
0
0
122082e17817795792cfda957e7ce090b1daf03b
1,195
eddieplayer
MIT License
solar/src/main/java/com/chiksmedina/solar/linear/messagesconversation/Pen.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.linear.messagesconversation import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.linear.MessagesConversationGroup val MessagesConversationGroup.Pen: ImageVector get() { if (_pen != null) { return _pen!! } _pen = Builder( name = "Pen", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(14.3601f, 4.0787f) lineTo(15.2869f, 3.1518f) curveTo(16.8226f, 1.6161f, 19.3125f, 1.6161f, 20.8482f, 3.1518f) curveTo(22.3839f, 4.6875f, 22.3839f, 7.1774f, 20.8482f, 8.7131f) lineTo(19.9213f, 9.6399f) moveTo(14.3601f, 4.0787f) curveTo(14.3601f, 4.0787f, 14.4759f, 6.0483f, 16.2138f, 7.7862f) curveTo(17.9517f, 9.5241f, 19.9213f, 9.6399f, 19.9213f, 9.6399f) moveTo(14.3601f, 4.0787f) lineTo(5.8388f, 12.5999f) curveTo(5.2617f, 13.1771f, 4.9731f, 13.4656f, 4.7249f, 13.7838f) curveTo(4.4321f, 14.1592f, 4.1811f, 14.5653f, 3.9763f, 14.995f) curveTo(3.8027f, 15.3593f, 3.6737f, 15.7465f, 3.4156f, 16.5208f) lineTo(2.3218f, 19.8021f) moveTo(19.9213f, 9.6399f) lineTo(11.4001f, 18.1612f) curveTo(10.8229f, 18.7383f, 10.5344f, 19.0269f, 10.2162f, 19.2751f) curveTo(9.8408f, 19.5679f, 9.4347f, 19.8189f, 9.005f, 20.0237f) curveTo(8.6407f, 20.1973f, 8.2535f, 20.3263f, 7.4792f, 20.5844f) lineTo(4.1979f, 21.6782f) moveTo(4.1979f, 21.6782f) lineTo(3.3958f, 21.9456f) curveTo(3.0148f, 22.0726f, 2.5947f, 21.9734f, 2.3106f, 21.6894f) curveTo(2.0266f, 21.4053f, 1.9274f, 20.9852f, 2.0545f, 20.6042f) lineTo(2.3218f, 19.8021f) moveTo(4.1979f, 21.6782f) lineTo(2.3218f, 19.8021f) } } .build() return _pen!! } private var _pen: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
2,894
SolarIconSetAndroid
MIT License
src/Day06.kt
olezhabobrov
572,687,414
false
{"Kotlin": 27363}
fun main() { fun part1(input: String, windowSize: Int = 4): Int { input.windowed(windowSize) { window -> val set = mutableSetOf<Char>() set.addAll(window.asSequence()) set.size }.forEachIndexed { index, value -> if (value == windowSize) return index + windowSize } return -1 } fun part2(input: String): Int = part1(input, 14) // test if implementation meets criteria from the description, like: check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06") println(part1(input[0])) println(part2(input[0])) }
0
Kotlin
0
0
31f2419230c42f72137c6cd2c9a627492313d8fb
1,107
AdventOfCode
Apache License 2.0
src/main/kotlin/algorithmic_toolbox/week2/FibonnaciWarmup.kt
eniltonangelim
369,331,780
false
null
package algorithmic_toolbox.week2 import java.util.* fun calcFib(n: Long): Long { return if (n <= 1) n else calcFib(n - 1) + calcFib(n - 2) } fun power(n: Long, x: Int = 2): Long { if (x == 0) return n return power(n * n, x - 1) } fun lastDigitOfNumber(n: Long): Long { var fibAList = LongArray((n+1).toInt()) fibAList[0] = 0 fibAList[1] = 1 if ( n < 2) return n for (i in 2..n) { fibAList[i.toInt()] = (fibAList[(i-1).toInt()] + fibAList[(i-2).toInt()]) % 10 } return fibAList[n.toInt()] } fun getPisanoPeriod(m: Long): Long { var period = 0L var previous = 0L var current = 1L for (i in 2 until m*m) { val tmpPrevious = previous previous = current current = (tmpPrevious+current) % m if (previous == 0L && current == 1L){ period = i - 1 break } } return period } fun calcFibMod(n: Long, m: Long): Long { if ( n <= 1) return n val pisanoPeriod = getPisanoPeriod(m) val remainder = n % pisanoPeriod var previous = 0L var current = 1L for (i in 0 until remainder-1) { val tmpPrevious = previous previous = current current = (tmpPrevious+current) % m } return current % m } fun calcLastDigitOfTheSumFibonacci(n: Long): Long { if (n <= 2) return n var fibAList = LongArray((n + 1).toInt()) fibAList[0] = 0L fibAList[1] = 1L for (i in 2..n) { fibAList[i.toInt()] = (fibAList[(i - 1).toInt()] + fibAList[(i - 2).toInt()]) % 10 } return fibAList.sum() % 10 } fun calcLastDigitOfTheSumFibonacci(m: Long, n: Long): Long { val pisanoPeriod = 60 // pisanoPeriod(10) = 60 var fibAList = LongArray(pisanoPeriod - 1) fibAList[0] = 0L fibAList[1] = 1L for (i in 2 until pisanoPeriod - 1) { fibAList[i] = (fibAList[i-1] + fibAList[i-2]) % 10 } var begin = m % pisanoPeriod var end = n % pisanoPeriod if (end < begin) end += pisanoPeriod var result = 0L for (i in begin..end) { result += fibAList[(i % pisanoPeriod).toInt()] } return result % 10 } fun calcLastDigitOfTheSumOfSquaresFibonacci(n: Long): Long { val pisanoPeriod = 60 val horizontal = lastDigitOfNumber((n +1) % pisanoPeriod) val vertical = lastDigitOfNumber( n % pisanoPeriod) return (horizontal * vertical) % 10 } fun main(args: Array<String>) { val scanner = Scanner(System.`in`) val n = scanner.nextLong() println(calcFib(n)) }
0
Kotlin
0
0
031bccb323339bec05e8973af7832edc99426bc1
2,549
AlgorithmicToolbox
MIT License
src/main/kotlin/SharedSecret.kt
sander
606,774,943
false
null
package nl.sanderdijkhuis.noise @JvmInline value class SharedSecret(val data: Data) { init { require(data.size == SIZE) } val inputKeyMaterial get() = InputKeyMaterial(data) companion object { val SIZE = Size(32) } }
1
Kotlin
0
0
5b961e181eb30ae5807f160ed04c629d0ebc5916
258
noise-kotlin
MIT License
TimeTracker/app/src/main/java/github/informramiz/timetracker/domain/user/model/CreateUserDomainModel.kt
informramiz
336,497,767
false
null
package github.informramiz.timetracker.domain.user.model import github.informramiz.timetracker.data.cloudfunctions.model.CreateUserApiModel import github.informramiz.timetracker.domain.authentication.model.UserRole import github.informramiz.timetracker.domain.authentication.model.toApiModel data class CreateUserDomainModel( val name: String, val email: String, val password: String, val role: UserRole ) fun CreateUserDomainModel.toApiModel() = CreateUserApiModel( name = name, email = email, password = password, role = role.toApiModel() )
0
Kotlin
0
0
4a3ff709f0ce1e8526422cd0183cc263b2ee9139
578
WorkLogTracker
MIT License
android/app/src/main/kotlin/com/topappfield/torcher/MainActivity.kt
topappfield
412,857,096
false
{"Dart": 14300, "HTML": 3926, "Ruby": 1354, "Swift": 404, "Shell": 144, "Kotlin": 128, "Objective-C": 38}
package com.topappfield.torcher import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
10aed8eaf88aefb9c52d4b534a18a0ba6ddcc6f3
128
torcher
MIT License
src/main/kotlin/de/dqmme/andimaru/dataclass/TeleportNPCData.kt
DQMME
434,850,146
false
{"Kotlin": 250697}
package de.dqmme.andimaru.dataclass import org.bukkit.Location data class TeleportNPCData( var displayName: String?, var location: Location?, var imitatePlayer: Boolean = true, var lookAtPlayer: Boolean = true, var teleportLocation: Location?, var title: String?, var skin: Skin )
0
Kotlin
0
0
3d20097a52cf01c1fa115e369b520a577f634be9
311
andimarucommunityserver
MIT License
Chapter15/Activity15.01/app/src/main/java/com/example/tvguide/model/TVShow.kt
PacktPublishing
575,781,987
false
null
package com.example.tvguide.model import androidx.room.Entity import com.squareup.moshi.Json @Entity(tableName = "tvshows", primaryKeys = [("id")]) data class TVShow( @field:Json(name = "backdrop_path") val backdropPath: String? = "", @field:Json(name = "first_air_date") val firstAirDate: String = "", val id: Int = 0, val name: String = "", @field:Json(name = "original_language") val originalLanguage: String = "", @field:Json(name = "original_name") val originalName: String = "", val overview: String = "", val popularity: Float = 0f, @field:Json(name = "poster_path") val posterPath: String? = "", @field:Json(name = "vote_average") val voteAverage: Float = 0f, @field:Json(name = "vote_count") val voteCount: Int = 0 )
1
Kotlin
1
8
69028f4bc9fee3812072504bb1b9ec07c722db35
801
How-to-Build-Android-Apps-with-Kotlin-Second-Edition
MIT License
src/main/java/com/cumulocity/client/api/ChildOperationsApi.kt
SoftwareAG
525,378,320
false
null
// Copyright (c) 2014-2022 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors. // Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your License Agreement with Software AG. package com.cumulocity.client.api import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.converter.gson.ExtendedGsonConverterFactory import retrofit2.Retrofit import retrofit2.Call import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.DELETE import retrofit2.http.Path import retrofit2.http.Query import retrofit2.http.Body import retrofit2.http.Header import retrofit2.http.Headers import okhttp3.OkHttpClient import retrofit2.converter.gson.ReadOnlyProperties import okhttp3.ResponseBody import com.cumulocity.client.model.ChildOperationsAddOne import com.cumulocity.client.model.ChildOperationsAddMultiple import com.cumulocity.client.model.ManagedObject import com.cumulocity.client.model.ManagedObjectReferenceCollection import com.cumulocity.client.model.ManagedObjectReference /** * Managed objects can contain collections of references to child devices, additions and assets. * * > **&#9432; Info:** The Accept header should be provided in all POST requests, otherwise an empty response body will be returned. * </br> * */ interface ChildOperationsApi { companion object Factory { fun create(baseUrl: String): ChildOperationsApi { return create(baseUrl, null) } fun create(baseUrl: String, clientBuilder: OkHttpClient.Builder?): ChildOperationsApi { val retrofitBuilder = Retrofit.Builder().baseUrl(baseUrl) .addConverterFactory(ExtendedGsonConverterFactory()) .addConverterFactory(ScalarsConverterFactory.create()) if (clientBuilder != null) { retrofitBuilder.client(clientBuilder.build()) } return retrofitBuilder.build().create(ChildOperationsApi::class.java) } } /** * Retrieve all child additions of a specific managed object </br> * Retrieve all child additions of a specific managed object by a given ID, or a subset based on queries. <section><h5>Required roles</h5> ROLE_INVENTORY_READ <b>OR</b> owner of the source <b>OR</b> MANAGE_OBJECT_READ permission on the source </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 The request has succeeded and all child additions are sent in the response.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param currentPage The current page of the paginated results. * @param pageSize Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. * @param query Use query language to perform operations and/or filter the results. Details about the properties and supported operations can be found in [Query language](#tag/Query-language). * @param withChildren Determines if children with ID and name should be returned when fetching the managed object. Set it to `false` to improve query performance. * @param withChildrenCount When set to `true`, the returned result will contain the total number of children in the respective objects (`childAdditions`, `childAssets` and `childDevices`). * @param withTotalElements When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). * @param withTotalPages When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). */ @Headers("Accept:application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json") @GET("/inventory/managedObjects/{id}/childAdditions") fun getChildAdditions( @Path("id") id: String, @Query("currentPage") currentPage: Int? = null, @Query("pageSize") pageSize: Int? = null, @Query("query") query: String? = null, @Query("withChildren") withChildren: Boolean? = null, @Query("withChildrenCount") withChildrenCount: Boolean? = null, @Query("withTotalElements") withTotalElements: Boolean? = null, @Query("withTotalPages") withTotalPages: Boolean? = null ): Call<ManagedObjectReferenceCollection> /** * Assign a managed object as child addition </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child addition of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child additions of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child addition to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child addition.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreference+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childAdditions") fun assignAsChildAddition( @Body body: ChildOperationsAddOne, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Assign a managed object as child addition </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child addition of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child additions of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child addition to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child addition.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childAdditions") fun assignAsChildAddition( @Body body: ChildOperationsAddMultiple, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Assign a managed object as child addition </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child addition of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child additions of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child addition to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child addition.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobject+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childAdditions") @ReadOnlyProperties("owner", "additionParents", "lastUpdated", "childDevices", "childAssets", "creationTime", "childAdditions", "self", "assetParents", "deviceParents", "id") fun assignAsChildAddition( @Body body: ManagedObject, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Remove specific child additions from its parent </br> * Remove specific child additions (by given child IDs) from its parent (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> owner of the source (parent) <b>OR</b> owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>204 Child additions were removed.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Unprocessable Entity – invalid payload.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json", "Accept:application/json"]) @DELETE("/inventory/managedObjects/{id}/childAdditions") fun unassignChildAdditions( @Body body: ChildOperationsAddMultiple, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Retrieve a specific child addition of a specific managed object </br> * Retrieve a specific child addition (by a given child ID) of a specific managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_READ <b>OR</b> MANAGE_OBJECT_READ permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 The request has succeeded and the child addition is sent in the response.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param childId Unique identifier of the child object. */ @Headers("Accept:application/vnd.com.nsn.cumulocity.managedobjectreference+json, application/vnd.com.nsn.cumulocity.error+json") @GET("/inventory/managedObjects/{id}/childAdditions/{childId}") fun getChildAddition( @Path("id") id: String, @Path("childId") childId: String ): Call<ManagedObjectReference> /** * Remove a specific child addition from its parent </br> * Remove a specific child addition (by a given child ID) from its parent (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> owner of the source (parent) <b>OR</b> owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>204 A child addition was removed.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param childId Unique identifier of the child object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers("Accept:application/json") @DELETE("/inventory/managedObjects/{id}/childAdditions/{childId}") fun unassignChildAddition( @Path("id") id: String, @Path("childId") childId: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Retrieve all child assets of a specific managed object </br> * Retrieve all child assets of a specific managed object by a given ID, or a subset based on queries. <section><h5>Required roles</h5> ROLE_INVENTORY_READ <b>OR</b> owner of the source <b>OR</b> MANAGE_OBJECT_READ permission on the source </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 The request has succeeded and all child assets are sent in the response.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param currentPage The current page of the paginated results. * @param pageSize Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. * @param query Use query language to perform operations and/or filter the results. Details about the properties and supported operations can be found in [Query language](#tag/Query-language). * @param withChildren Determines if children with ID and name should be returned when fetching the managed object. Set it to `false` to improve query performance. * @param withChildrenCount When set to `true`, the returned result will contain the total number of children in the respective objects (`childAdditions`, `childAssets` and `childDevices`). * @param withTotalElements When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). * @param withTotalPages When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). */ @Headers("Accept:application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json") @GET("/inventory/managedObjects/{id}/childAssets") fun getChildAssets( @Path("id") id: String, @Query("currentPage") currentPage: Int? = null, @Query("pageSize") pageSize: Int? = null, @Query("query") query: String? = null, @Query("withChildren") withChildren: Boolean? = null, @Query("withChildrenCount") withChildrenCount: Boolean? = null, @Query("withTotalElements") withTotalElements: Boolean? = null, @Query("withTotalPages") withTotalPages: Boolean? = null ): Call<ManagedObjectReferenceCollection> /** * Assign a managed object as child asset </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child asset of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child assets of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child asset to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child asset.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreference+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childAssets") fun assignAsChildAsset( @Body body: ChildOperationsAddOne, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Assign a managed object as child asset </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child asset of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child assets of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child asset to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child asset.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childAssets") fun assignAsChildAsset( @Body body: ChildOperationsAddMultiple, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Assign a managed object as child asset </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child asset of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child assets of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child asset to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child asset.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobject+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childAssets") @ReadOnlyProperties("owner", "additionParents", "lastUpdated", "childDevices", "childAssets", "creationTime", "childAdditions", "self", "assetParents", "deviceParents", "id") fun assignAsChildAsset( @Body body: ManagedObject, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Remove specific child assets from its parent </br> * Remove specific child assets (by given child IDs) from its parent (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> owner of the source (parent) <b>OR</b> owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>204 Child assets were removed.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Unprocessable Entity – invalid payload.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json", "Accept:application/json"]) @DELETE("/inventory/managedObjects/{id}/childAssets") fun unassignChildAssets( @Body body: ChildOperationsAddMultiple, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Retrieve a specific child asset of a specific managed object </br> * Retrieve a specific child asset (by a given child ID) of a specific managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_READ <b>OR</b> MANAGE_OBJECT_READ permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 The request has succeeded and the child asset is sent in the response.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param childId Unique identifier of the child object. */ @Headers("Accept:application/vnd.com.nsn.cumulocity.managedobjectreference+json, application/vnd.com.nsn.cumulocity.error+json") @GET("/inventory/managedObjects/{id}/childAssets/{childId}") fun getChildAsset( @Path("id") id: String, @Path("childId") childId: String ): Call<ManagedObjectReference> /** * Remove a specific child asset from its parent </br> * Remove a specific child asset (by a given child ID) from its parent (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> owner of the source (parent) <b>OR</b> owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>204 A child asset was removed.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param childId Unique identifier of the child object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers("Accept:application/json") @DELETE("/inventory/managedObjects/{id}/childAssets/{childId}") fun unassignChildAsset( @Path("id") id: String, @Path("childId") childId: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Retrieve all child devices of a specific managed object </br> * Retrieve all child devices of a specific managed object by a given ID, or a subset based on queries. <section><h5>Required roles</h5> ROLE_INVENTORY_READ <b>OR</b> owner of the source <b>OR</b> MANAGE_OBJECT_READ permission on the source </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 The request has succeeded and all child devices are sent in the response.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param currentPage The current page of the paginated results. * @param pageSize Indicates how many entries of the collection shall be returned. The upper limit for one page is 2,000 objects. * @param query Use query language to perform operations and/or filter the results. Details about the properties and supported operations can be found in [Query language](#tag/Query-language). * @param withChildren Determines if children with ID and name should be returned when fetching the managed object. Set it to `false` to improve query performance. * @param withChildrenCount When set to `true`, the returned result will contain the total number of children in the respective objects (`childAdditions`, `childAssets` and `childDevices`). * @param withTotalElements When set to `true`, the returned result will contain in the statistics object the total number of elements. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). * @param withTotalPages When set to `true`, the returned result will contain in the statistics object the total number of pages. Only applicable on [range queries](https://en.wikipedia.org/wiki/Range_query_(database)). */ @Headers("Accept:application/vnd.com.nsn.cumulocity.error+json, application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json") @GET("/inventory/managedObjects/{id}/childDevices") fun getChildDevices( @Path("id") id: String, @Query("currentPage") currentPage: Int? = null, @Query("pageSize") pageSize: Int? = null, @Query("query") query: String? = null, @Query("withChildren") withChildren: Boolean? = null, @Query("withChildrenCount") withChildrenCount: Boolean? = null, @Query("withTotalElements") withTotalElements: Boolean? = null, @Query("withTotalPages") withTotalPages: Boolean? = null ): Call<ManagedObjectReferenceCollection> /** * Assign a managed object as child device </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child device of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child devices of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child device to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child device.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreference+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childDevices") fun assignAsChildDevice( @Body body: ChildOperationsAddOne, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Assign a managed object as child device </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child device of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child devices of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child device to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child device.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childDevices") fun assignAsChildDevice( @Body body: ChildOperationsAddMultiple, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Assign a managed object as child device </br> * The possible ways to assign child objects are: * Assign an existing managed object (by a given child ID) as child device of another managed object (by a given ID). * Assign multiple existing managed objects (by given child IDs) as child devices of another managed object (by a given ID). * Create a managed object in the inventory and assign it as a child device to another managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> ((owner of the source <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source) <b>AND</b> (owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the child)) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>201 A managed object was assigned as child device.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobject+json", "Accept:application/json"]) @POST("/inventory/managedObjects/{id}/childDevices") @ReadOnlyProperties("owner", "additionParents", "lastUpdated", "childDevices", "childAssets", "creationTime", "childAdditions", "self", "assetParents", "deviceParents", "id") fun assignAsChildDevice( @Body body: ManagedObject, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Remove specific child devices from its parent </br> * Remove specific child devices (by given child IDs) from its parent (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> owner of the source (parent) <b>OR</b> owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>204 Child devices were removed.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Unprocessable Entity – invalid payload.</li> * </ul> * * @param body * @param id Unique identifier of the managed object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers(*["Content-Type:application/vnd.com.nsn.cumulocity.managedobjectreferencecollection+json", "Accept:application/json"]) @DELETE("/inventory/managedObjects/{id}/childDevices") fun unassignChildDevices( @Body body: ChildOperationsAddMultiple, @Path("id") id: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> /** * Retrieve a specific child device of a specific managed object </br> * Retrieve a specific child device (by a given child ID) of a specific managed object (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_READ <b>OR</b> MANAGE_OBJECT_READ permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>200 The request has succeeded and the child device is sent in the response.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param childId Unique identifier of the child object. */ @Headers("Accept:application/vnd.com.nsn.cumulocity.managedobjectreference+json, application/vnd.com.nsn.cumulocity.error+json") @GET("/inventory/managedObjects/{id}/childDevices/{childId}") fun getChildDevice( @Path("id") id: String, @Path("childId") childId: String ): Call<ManagedObjectReference> /** * Remove a specific child device from its parent </br> * Remove a specific child device (by a given child ID) from its parent (by a given ID). <section><h5>Required roles</h5> ROLE_INVENTORY_ADMIN <b>OR</b> owner of the source (parent) <b>OR</b> owner of the child <b>OR</b> MANAGE_OBJECT_ADMIN permission on the source (parent) </section> * * <br>The following table gives an overview of the possible response codes and their meanings:</br> * <ul> * <li>204 A child device was removed.</li> * <li>401 Authentication information is missing or invalid.</li> * <li>404 Managed object not found.</li> * <li>422 Invalid data was sent.</li> * </ul> * * @param id Unique identifier of the managed object. * @param childId Unique identifier of the child object. * @param xCumulocityProcessingMode Used to explicitly control the processing mode of the request. See [Processing mode](#processing-mode) for more details. */ @Headers("Accept:application/json") @DELETE("/inventory/managedObjects/{id}/childDevices/{childId}") fun unassignChildDevice( @Path("id") id: String, @Path("childId") childId: String, @Header("X-Cumulocity-Processing-Mode") xCumulocityProcessingMode: String? = null ): Call<ResponseBody> }
0
Kotlin
0
2
ca48e21dc65698a38aedf39ea728f7d7d0372f14
36,076
cumulocity-clients-kotlin
Apache License 2.0
src/main/kotlin/com/gnaderi/islandhopping/common/TileType.kt
gnaderi
246,167,516
false
null
package com.gnaderi.islandhopping.common enum class TileType ( val id: Int, val type: String) { LAND(1, "LAND"), WATER(2, "WATER"); }
0
Kotlin
0
0
cb37a92e099ee648479f9896076f9f5a8d385b1e
140
IslandHopping
Apache License 2.0
app/src/main/java/com/example/hospitalfinder/activity/MainActivity.kt
aalshawa97
274,258,169
false
null
package com.example.hospitalfinder.activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.hospitalfinder.R import com.google.android.gms.auth.api.Auth import com.google.android.gms.common.api.GoogleApiClient import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.contacts_list_item.* class MainActivity : AppCompatActivity() { private var firebaseAuth: FirebaseAuth? = null private var authStateListener: FirebaseAuth.AuthStateListener? = null private var googleApiClient: GoogleApiClient? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_maps) Toast.makeText(this, "Could you please click a button in the right top corner to begin?", Toast.LENGTH_LONG).show() firebaseAuth = FirebaseAuth.getInstance() authStateListener = FirebaseAuth.AuthStateListener { firebaseAuth -> val firebaseUser = firebaseAuth.currentUser if (firebaseUser == null) { val intent = Intent(this, LoginActivity::class.java) startActivity(intent) } } googleApiClient = GoogleApiClient.Builder(this).addApi(Auth.GOOGLE_SIGN_IN_API).build() } private fun signOut() { if (firebaseAuth != null) { firebaseAuth!!.signOut() } if (googleApiClient!!.isConnected) { Auth.GoogleSignInApi.signOut(googleApiClient) } } private fun encrypt() { Toast.makeText(this, "Encrypting", Toast.LENGTH_LONG).show() } override fun onStart() { super.onStart() googleApiClient!!.connect() firebaseAuth!!.addAuthStateListener(this.authStateListener!!) val firebaseUser = FirebaseAuth.getInstance().currentUser if (firebaseUser != null) { val fromUid = firebaseUser.uid val rootRef = FirebaseFirestore.getInstance() val uidRef = rootRef.collection("users").document(fromUid) uidRef.get().addOnCompleteListener { task -> if (task.isSuccessful) { val document = task.result if (document.exists()) { val fromUser = document.toObject(User::class.java) val userRoomsRef = rootRef.collection("rooms").document(fromUid).collection("userRooms") userRoomsRef.get().addOnCompleteListener{ t -> if (t.isSuccessful) { val listOfToUserNames = ArrayList<String>() val listOfToUsers = ArrayList<User>() val listOfRooms = ArrayList<String>() for (d in t.result) { val toUser = d.toObject(User::class.java) listOfToUserNames.add(toUser.userName) listOfToUsers.add(toUser) listOfRooms.add(d.id) } val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, listOfToUserNames) list_viw.adapter = arrayAdapter list_viw.onItemClickListener = AdapterView.OnItemClickListener{ _, _, position, _ -> val intent = Intent(this, ChatActivity::class.java) intent.putExtra("fromUser", fromUser) intent.putExtra("toUser", listOfToUsers[position]) intent.putExtra("roomId", listOfRooms[position]) startActivity(intent) } } } } } } } } override fun onStop() { super.onStop() if (googleApiClient!!.isConnected) { googleApiClient!!.disconnect() } firebaseAuth!!.removeAuthStateListener(this.authStateListener!!) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return true } override fun onOptionsItemSelected(menuItem: MenuItem): Boolean { return when (menuItem.itemId) { R.id.add_friend -> { val intent = Intent(this, ContactsActivity::class.java) startActivity(intent) true } R.id.sign_out_button -> { signOut() true } R.id.encrypt_button -> { encrypt() val intent = Intent(this, MainActivityJ::class.java) startActivity(intent) true } else -> super.onOptionsItemSelected(menuItem) } } companion object { //private const val TAG = "MainActivityTag" } }
0
Kotlin
0
0
8c2967cd9ccf9bb08a8553dbdcecb6eaf543b91f
5,438
HosiptalLocator
MIT License
src/main/kotlin/net/radstevee/istats/ui/PlayerStatisticScreen.kt
iStats-mc
838,904,398
false
{"Kotlin": 19565, "Java": 4226}
package net.radstevee.istats.ui import net.minecraft.client.MinecraftClient import net.minecraft.client.gui.DrawContext import net.minecraft.client.gui.screen.Screen import net.minecraft.text.Text import net.minecraft.util.Colors import net.minecraft.util.Identifier import net.radstevee.istats.Game import net.radstevee.istats.IslandPlayer import net.radstevee.istats.ServerCategory import net.radstevee.istats.util.drawTextRelative import net.radstevee.istats.util.getPosition import net.radstevee.istats.util.relative class PlayerStatisticScreen( val input: String, val islandPlayer: IslandPlayer, ) : Screen(Text.literal("Statistics for ${islandPlayer.username ?: input}")) { val username = islandPlayer.username ?: input override fun close() { MinecraftClient.getInstance().setScreen(IStatsScreen) } override fun init() { /* val skin = MinecraftClient .getInstance() .skinProvider .getSkinTexturesSupplier(GameProfile(islandPlayer.uuid, islandPlayer.username)) println( "Game profile: ${ GameProfile( islandPlayer.uuid, islandPlayer.username, ) }, UUID: ${islandPlayer.uuid}, actual username: ${islandPlayer.username}, skin: $skin", ) val skinWidget = PlayerSkinWidget( 20, 60, client!!.entityModelLoader, skin, ) addDrawableChild(skinWidget) */ } override fun render( context: DrawContext, mouseX: Int, mouseY: Int, delta: Float, ) { super.render(context, mouseX, mouseY, delta) val textPosition = context.getPosition(textRenderer, Text.literal(username), 50, 5) context.drawText( textRenderer, Text.literal(username), textPosition.first, textPosition.second, Colors.WHITE, true, ) val rankX = textPosition.first - (textPosition.first / 10) val rankY = textPosition.second - (textPosition.second / 3) context.drawTexture( islandPlayer.primaryRank.texture, rankX, rankY, 0f, 0f, 16, 16, 16, 16, ) if (islandPlayer.status?.online == true) { if (islandPlayer.status.server?.category == ServerCategory.LOBBY) { val (texture, text) = when (islandPlayer.status.server.associatedGame) { Game.BATTLE_BOX -> Game.BATTLE_BOX.texture to Text.literal("In the Battle Box lobby") Game.TGTTOS -> Game.TGTTOS.texture to Text.literal("In the TGTTOS lobby") Game.DYNABALL -> Game.DYNABALL.texture to Text.literal("In the Dynaball Lobby") Game.SKY_BATTLE -> Game.SKY_BATTLE.texture to Text.literal("In the Sky Battle Lobby") Game.ROCKET_SPLEEF -> Game.ROCKET_SPLEEF.texture to Text.literal("In the RSR Lobby") Game.HOLE_IN_THE_WALL -> Game.HOLE_IN_THE_WALL.texture to Text.literal("In the HITW lobby") Game.PARKOUR_WARRIOR -> Game.PARKOUR_WARRIOR.texture to Text.literal("In the Parkour Warrior lobby") Game.LOBBY -> error("How the fuck did that happen?? Associated server game from a game server is lobby. ???") null -> Identifier.of("istats", "textures/misc/main_island.png") to Text.literal("On the Main Island") } val textPosition = context.getPosition(textRenderer, text, 50, 13) context.drawText( textRenderer, text, textPosition.first, textPosition.second, Colors.WHITE, true, ) val textureX = textPosition.first - (textPosition.first / 10) val textureY = textPosition.second - (textPosition.second / 7) context.drawTexture( texture, textureX, textureY, 0f, 0f, 16, 16, 16, 16, ) } else if (islandPlayer.status.server?.category == ServerCategory.GAME && islandPlayer.status.server.associatedGame != null) { val texture = islandPlayer.status.server.associatedGame.texture val text = Text.literal("Playing ${islandPlayer.status.server.associatedGame.displayName}") val textPosition = context.getPosition(textRenderer, text, 50, 13) context.drawText( textRenderer, text, textPosition.first, textPosition.second, Colors.WHITE, true, ) val textureX = textPosition.first - (textPosition.first / 10) val textureY = textPosition.second - (textPosition.second / 7) context.drawTexture( texture, textureX, textureY, 0f, 0f, 16, 16, 16, 16, ) } else { context.drawTextRelative( textRenderer, Text.literal("Online"), 50, 13, Colors.WHITE, true, ) } } else { islandPlayer.status?.lastJoin?.let { lastJoin -> context.drawTextRelative( textRenderer, Text.literal("Last logged on ${lastJoin.relative()}"), 50, 13, Colors.WHITE, true, ) } } } }
0
Kotlin
0
0
42780dcdbfe2576cd809f07e74210b138779a38d
6,274
iStats
Creative Commons Zero v1.0 Universal
database/src/main/java/com/kafka/data/db/KafkaDatabase.kt
vipulyaara
170,554,386
false
null
package com.kafka.data.db import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.kafka.data.dao.FileDao import com.kafka.data.dao.FollowedItemDao import com.kafka.data.dao.ItemDao import com.kafka.data.dao.ItemDetailDao import com.kafka.data.dao.LanguageDao import com.kafka.data.dao.RecentItemDao import com.kafka.data.dao.RecentSearchDao import com.kafka.data.dao.SearchDao import com.kafka.data.entities.File import com.kafka.data.entities.FollowedItem import com.kafka.data.entities.Item import com.kafka.data.entities.ItemDetail import com.kafka.data.entities.Language import com.kafka.data.entities.QueueEntity import com.kafka.data.entities.RecentItem import com.kafka.data.entities.RecentSearch interface KafkaDatabase { fun itemDetailDao(): ItemDetailDao fun fileDao(): FileDao fun recentItemDao(): RecentItemDao fun followedItemDao(): FollowedItemDao fun searchDao(): SearchDao fun itemDao(): ItemDao fun languageDao(): LanguageDao fun searchConfigurationDao(): RecentSearchDao } @Database( entities = [ ItemDetail::class, File::class, Item::class, Language::class, RecentItem::class, FollowedItem::class, QueueEntity::class, RecentSearch::class ], version = 2, exportSchema = false ) @TypeConverters(AppTypeConverters::class) abstract class KafkaRoomDatabase : RoomDatabase(), KafkaDatabase
0
Kotlin
4
26
41e41fae10351ff316fedd2bcde2e10152cc9a65
1,473
Kafka
Apache License 2.0
app/src/main/java/app/android/issue5101/Util.kt
dconeybe
809,895,500
false
{"Kotlin": 12098, "TypeScript": 8095, "JavaScript": 888}
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 app.android.issue5101 import java.io.ByteArrayOutputStream import java.io.InputStream import kotlin.random.Random /** * Generates and returns a string containing random alphanumeric characters. * * The characters returned are taken from the set of characters comprising of the 10 numeric digits * and the 26 lowercase English characters. * * @param length the number of random characters to generate and include in the returned string; * must be greater than or equal to zero. * @return a string containing the given number of random alphanumeric characters. * @hide */ fun Random.nextAlphanumericString(length: Int): String { require(length >= 0) { "invalid length: $length" } return (0 until length).map { ALPHANUMERIC_ALPHABET.random(this) }.joinToString(separator = "") } // The set of characters comprising of the 10 numeric digits and the 26 lowercase letters of the // English alphabet with some characters removed that can look similar in different fonts, like // '1', 'l', and 'i'. @Suppress("SpellCheckingInspection") private const val ALPHANUMERIC_ALPHABET = "23456789abcdefghjkmnpqrstvwxyz" fun readAllBytes(inputStream: InputStream): ByteArray { val buffer = ByteArray(8192) // 8 KB buffer for efficient reading val outputStream = ByteArrayOutputStream() var bytesRead: Int while (inputStream.read(buffer).also { bytesRead = it } > 0) { outputStream.write(buffer, 0, bytesRead) } return outputStream.toByteArray() } fun String.ellipsized(maxLength: Int): String { require(maxLength >= 5) { "invalid maxLength: $maxLength (must be at least 5)" } if (length <= maxLength) { return this } val chunkSize = (maxLength - 3) / 2 return take(chunkSize) + "..." + takeLast(chunkSize) }
0
Kotlin
0
0
1b4f71fa90516251d47dd4ffc90b94429ee686a4
2,346
android-issue-5101
Apache License 2.0
spesialist-selve/src/main/kotlin/no/nav/helse/mediator/Utils.kt
navikt
244,907,980
false
{"Kotlin": 2893512, "PLpgSQL": 29687, "HTML": 1741, "Dockerfile": 265}
package no.nav.helse.mediator import com.fasterxml.jackson.databind.JsonNode import java.util.UUID internal fun JsonNode.asUUID() = UUID.fromString(asText())
0
Kotlin
4
0
10a6f89a36a591c084ca41edad9e8fb1ed4324f7
160
helse-spesialist
MIT License
app/src/main/java/com/jakeparker/coccocdemo/MainViewModelFactory.kt
LongJakeparker
326,251,343
false
null
package com.jakeparker.coccocdemo import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.jakeparker.coccocdemo.repository.NewsRepository import javax.inject.Inject /** * @author <NAME> * @since 02/01/2021 */ class MainViewModelFactory @Inject constructor( private val newsRepository: NewsRepository ) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { return MainViewModel(newsRepository) as T } }
0
Kotlin
0
0
87c71e02c38b62ac0c19411eb639e3e1357acf7c
547
CocCocDemo
MIT License
eva-examples/src/main/kotlin/com/razz/eva/examples/wallet/WalletPaging.kt
razz-team
477,827,497
false
{"Kotlin": 607724, "PLpgSQL": 6537, "Dockerfile": 178}
package com.razz.eva.examples.wallet import com.razz.eva.examples.schema.db.Tables.WALLET import com.razz.eva.examples.schema.db.tables.records.WalletRecord import com.razz.eva.paging.Offset import com.razz.eva.repository.ModelPagingStrategy import java.time.Instant import java.util.* object WalletPaging : ModelPagingStrategy<UUID, Wallet.Id, Wallet, Wallet, Instant, WalletRecord>(Wallet::class) { override fun tableOrdering() = WALLET.EXPIRE_AT override fun tableId() = WALLET.ID override fun tableOffset(offset: Offset) = UUID.fromString(offset) override fun ordering(data: Wallet) = data.expireAt override fun offset(data: Wallet) = data.id().stringValue() }
6
Kotlin
0
49
38bb888f963894a6ce636bc98c6ea92182e53775
692
eva
Apache License 2.0
src/main/java/com/beautifulapp/basis_adk/helper/database/DataBase.kt
James97231
307,127,165
false
null
package com.beautifulapp.basis_adk.helper.database import com.beautifulapp.basis_adk.helper.pattern.CustomDataClass import java.io.File import java.io.InputStream /** * Interface minimaliste pour decrivant les methodes d'une base de données */ interface DataBase { fun getItem(className: String, objectId: String, listener: ((Boolean, MutableMap<String, Any?>?) -> Unit)? = null) fun <T : CustomDataClass> getItem(clazz: Class<T>, objectId: String, listener: ((Boolean, T?) -> Unit)? = null) fun <T : CustomDataClass> remove(clazz: Class<T>, objectId: String, listener: ((Boolean) -> Unit)? = null) fun getList( className: String, where: Collection<Triple<String, Where, Any>>? = null, listener: ((Boolean, MutableList<MutableMap<String, Any>?>?) -> Unit)? = null ) fun <T : CustomDataClass> getList( clazz: Class<T>, where: Collection<Triple<String, Where, Any>>? = null, listener: ((Boolean, MutableList<T>?) -> Unit)? = null ) fun post(data: CustomDataClass, listener: ((Boolean, MutableMap<String, Any?>?) -> Unit)? = null) fun upload(to: String, rawData: ByteArray? = null, inputStream: InputStream? = null, file: File? = null, listener: ((Boolean, String) -> Unit)? = null) fun postWithUpload( data: CustomDataClass, uploadAction: ((String, (CustomDataClass?) -> Unit) -> Unit)? = null, listener: ((Boolean, MutableMap<String, Any?>?) -> Unit)? = null ) fun <T : CustomDataClass> removeIncludeMedias(clazz: Class<T>, objectId: String, mediaPath: Collection<String>? = null, listener: ((Boolean) -> Unit)?) enum class Where(key: String) { Equal("="), Sup(">"), SupEqual(">="), Inf("<"), InfEqual("<="), ArrayContain("C"), sortedBy("**"), } }
0
Kotlin
0
0
257bab28867a33585440e77812ff741819547904
1,835
basic-adk
Apache License 2.0
src/main/kotlin/moe/sdl/tracks/util/Log.kt
Colerar
454,784,355
false
null
package moe.sdl.tracks.util import org.fusesource.jansi.Ansi import org.fusesource.jansi.Ansi.ansi object Log { fun debug(throwable: Throwable? = null, lazyMessage: () -> String) { if (moe.sdl.tracks.config.debug) { println("[DEBUG]" + lazyMessage()) throwable?.let { println(it) } } } } @Suppress("NOTHING_TO_INLINE") inline val String.color: Ansi get() = ansi().render(this)
1
Kotlin
0
12
5e3cea5d0ded8911dde91676c0f56f6dc9306db0
432
Tracks
MIT License
functions/types/infix.kt
ViniciusMaiaM
567,769,368
false
{"Kotlin": 29518}
// Função que podem ser convertida através de funções membros ou extensões com um único parâmetro fun main(){ infix fun Int.times(str: String) = str.repeat(this) //Pega a string de parametro e repete o número de vezes println(2 times "Bye ") val pair = "Ferrari" to "Katrina" //Dessa maneira cria um par de strings println(pair) infix fun String.onto(other:String) = Pair(this,other) //Simula oq está acima val mypair = "Mclaren" onto "Lucas" //To e onto funciona para a criação de par println(mypair) val sophia = Person("Sophia") val claudia = Person("Claudia") sophia likes claudia //Assim fica mais idiomatico de ler } class Person(val name: String){ val liked_people = mutableListOf<Person>() //Lista mutavel de pessoas gostadas infix fun likes(other: Person) { liked_people.add(other)} //Função que adiona pessoas na lista }
0
Kotlin
0
0
8b531dbcb5099350e1137707c32124fbcb33b37a
889
Kotlin-experience
MIT License
Android/app/src/main/java/dark/andapp/dfinnb/presentaion/adapters/NamedAdapter.kt
ShadowOfFallenLord
622,295,925
false
null
package dark.andapp.dfinnb.presentaion.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import dark.andapp.dfinnb.databinding.RecyclerViewNamedListItemBinding import dark.andapp.dfinnb.domain.entity.NamedEntity class NamedAdapter( private val entities: List<NamedEntity> ) : RecyclerView.Adapter<NamedAdapter.ViewHolder>() { class ViewHolder(val binding: RecyclerViewNamedListItemBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = RecyclerViewNamedListItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder.binding) { val entity = entities[position] tvId.text = entity.id.toString() tvName.text = entity.name } } override fun getItemCount(): Int { return entities.count() } }
0
Kotlin
0
0
a40bb92612b99f5c27f4eeae6e579bd15767ecff
1,135
DFinancialNotebook
MIT License
app/src/main/java/com/example/borutoapp/ui/theme/Dimens.kt
gemaxd
464,274,084
false
{"Kotlin": 104271}
package com.example.borutoapp.ui.theme import androidx.compose.ui.unit.dp val EXTRA_LARGE_PADDING = 40.dp val LARGE_PADDING = 20.dp val MEDIUM_PADDING = 16.dp val SMALL_PADDING = 10.dp val EXTRA_SMALL_PADDING = 6.dp val TOP_APP_ABR_HEIGHT = 56.dp val PAGING_INDICATOR_WIDTH = 12.dp val PAGING_INDICATOR_SPACING = 8.dp val HERO_ITEM_HEIGHT = 400.dp val NAME_PLACEHOLDER_HEIGHT = 30.dp val ABOUT_PLACEHOLDER_HEIGHT = 15.dp val RATING_PLACEHOLDER_HEIGHT = 20.dp val NETWORK_ERROR_ICON_HEIGHT = 120.dp val INFO_ICON_SIZE = 32.dp val MIN_SHEET_HEIGHT = 140.dp val EXPANDED_RADIUS_LEVEL = 0.dp
0
Kotlin
0
1
d7daa4e41d583cdc1b075ee80511f320f05c4998
595
borutoApp
MIT License
src/main/kotlin/icu/windea/pls/core/listeners/ParadoxUpdateLibraryOnProjectOpenedListener.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.core.listeners import com.intellij.openapi.project.* import com.intellij.openapi.startup.* import icu.windea.pls.* /** * 项目启动时刷新库信息。 */ class ParadoxUpdateLibraryOnProjectOpenedListener: StartupActivity { override fun runActivity(project: Project) { val paradoxLibrary = project.paradoxLibrary paradoxLibrary.refreshRoots() } }
2
Kotlin
2
14
a3816071d500f8cf993240885895966be67ef5c8
379
Paradox-Language-Support
MIT License
order/src/main/kotlin/cz/zubal/spring/multimodule/order/RepositoryOrderService.kt
mzubal
123,785,587
false
null
package cz.zubal.spring.multimodule.order import cz.zubal.spring.multimodule.customer.api.CustomerService import cz.zubal.spring.multimodule.item.api.ItemService import cz.zubal.spring.multimodule.order.api.Order import cz.zubal.spring.multimodule.order.api.OrderService import org.modelmapper.ModelMapper import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component @Component internal class RepositoryOrderService : OrderService { @Autowired lateinit var customerService: CustomerService @Autowired lateinit var itemService: ItemService @Autowired lateinit var orderRepo: OrderRepo @Autowired lateinit var modelMapper: ModelMapper override fun list(): List<Order> { return orderRepo.findAll().map { it -> mapToApiOrder(it) } } override fun findByUuid(uuid: String): Order { return mapToApiOrder(orderRepo.findByUuid(uuid)) } override fun create(order: Order): Order { val orderEntity = modelMapper.map(order, OrderEntity::class.java) orderEntity.username = order.customer?.username orderEntity.items = order.items.map{it -> it.uuid}.requireNoNulls() return mapToApiOrder(orderRepo.save(orderEntity)) } private fun mapToApiOrder(dbOrder: OrderEntity): Order { val order = modelMapper.map(dbOrder, Order::class.java) order.customer = customerService.findByUsername(dbOrder.username) order.items = itemService.findByUuids(dbOrder.items) return order } }
0
Kotlin
3
26
083e6953c7baf5d82c75e3dc2ec555cbf984efcc
1,557
spring-gradle-kotlin-multimodule
MIT License
app/src/main/java/com/breezefsmp12/features/reimbursement/model/ReimbursementConfigFetchResponseModel.kt
DebashisINT
652,463,111
false
{"Kotlin": 14144630, "Java": 1003051}
package com.breezefsmp12.features.reimbursement.model import com.breezefsmp12.base.BaseResponse /** * Created by Saikat on 24-01-2019. */ class ReimbursementConfigFetchResponseModel : BaseResponse() { var maximum_allowance: String? = null var distance: String? = null var rate: String? = null }
0
Kotlin
0
0
4670dd69aff7fea867f314682a5f6b5786f9aeee
310
StepUpP12
Apache License 2.0
src/main/kotlin/collections/list.kt
prasad-psp
586,469,600
false
null
package collections fun main() { val monthList = listOf("Jan","Feb","March") val anyTypeList = listOf(1,2,3,true,"Raj") // println(anyTypeList.size) // Get size of list // println(monthList[2]) // Get particular element // for(month in monthList) { // println(month) // } /** * Mutable list */ val additionMonths = monthList.toMutableList() val newMonths = arrayOf("Apr","May") additionMonths.addAll(newMonths) additionMonths.add("June") println(additionMonths) /** * Mutable list */ val mutableList = mutableListOf("Mon","Tue") mutableList.add("Wed") mutableList.removeAt(1) // Remove Tue indexing is start from 0 println(mutableList) val removeList = mutableListOf("Mon","Tue") mutableList.removeAll(removeList) // mutableList.clear() // Remove all items in the list println(mutableList) }
0
Kotlin
0
0
9658a221cf4a49629dca6ca18896597f789f1cec
911
Kotlin-Tutorials
MIT License
app/src/main/java/com/f1reking/gank/module/main/girl/GirlFragment.kt
DB-BOY
135,396,402
true
{"Kotlin": 136506, "Java": 19953}
/* * Copyright (c) 2018 F1ReKing * * 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.f1reking.gank.module.main.girl import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.androidkun.xtablayout.XTabLayout import com.f1reking.gank.R import com.f1reking.gank.base.BaseFragment import com.f1reking.gank.inflate import com.f1reking.gank.module.main.gank.TabPagerAdapter import com.f1reking.gank.module.main.girl.gank.GankGirlFragment import com.f1reking.gank.module.main.girl.jd.JDGirlFragment import kotlinx.android.synthetic.main.fragment_girl.tab_girl import kotlinx.android.synthetic.main.fragment_girl.vp_girl /** * @author: F1ReKing * @date: 2018/6/4 * @desc: */ class GirlFragment :BaseFragment(){ private var layout: View? = null private var fragmentList = ArrayList<Fragment>() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { layout = container!!.inflate(R.layout.fragment_girl) return layout } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val mGankGirlFragment = GankGirlFragment() val mJDGrilFragment = JDGirlFragment() fragmentList.add(mGankGirlFragment) fragmentList.add(mJDGrilFragment) val pagerAdapter = TabPagerAdapter(childFragmentManager, fragmentList, resources.getStringArray(R.array.tab_girl)) vp_girl.apply { adapter = pagerAdapter offscreenPageLimit = fragmentList.size } tab_girl.apply { setupWithViewPager(vp_girl) setOnTabSelectedListener(object : XTabLayout.OnTabSelectedListener { override fun onTabReselected(tab: XTabLayout.Tab?) { } override fun onTabUnselected(tab: XTabLayout.Tab?) { } override fun onTabSelected(tab: XTabLayout.Tab?) { vp_girl.currentItem = tab!!.position } }) } } }
0
Kotlin
0
0
7d3ef9ebec052e135052b2102b51a3cbb2fe26cc
2,766
Mr.Gank
Apache License 2.0
app/src/main/java/com/example/kotlinpaging3/di/NetworkSetup.kt
Ak5hay01
596,383,138
false
null
package com.example.kotlinpaging3.di import com.example.kotlinpaging3.retrofit.QuoteAPI import com.example.kotlinpaging3.utils.Constants.BASE_URL import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class NetworkSetup { @Singleton @Provides fun getRetrofit():Retrofit{ return Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } @Singleton @Provides fun getQuotes(retrofit: Retrofit):QuoteAPI{ return retrofit.create(QuoteAPI::class.java) } }
0
Kotlin
0
0
b02a7d8c7b909f68a0234791951dc7120db54500
788
Kotlin-Paging3-with-Remote-Mediator
MIT License
drm-backend/src/main/kotlin/controller/ChainController.kt
Smileslime47
738,883,139
false
{"Kotlin": 59316, "Vue": 26085, "Java": 16984, "TypeScript": 10268, "Solidity": 2406, "CSS": 1156, "Shell": 649, "HTML": 390}
package moe._47saikyo.controller import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import moe._47saikyo.configuration.security.authenticateAfterLogin import moe._47saikyo.constant.Constant import moe._47saikyo.constant.HttpStatus import moe._47saikyo.models.HttpResponse import moe._47saikyo.service.AccountService import moe._47saikyo.service.UserService import org.koin.java.KoinJavaComponent /** * BlockChain HTTP Controller * * @author 刘一邦 */ fun Application.chainController() { val userService: UserService by KoinJavaComponent.inject(UserService::class.java) val accountService: AccountService by KoinJavaComponent.inject(AccountService::class.java) routing { route("/chain") { authenticate(Constant.Authentication.NEED_LOGIN){ get("/balance") { val addr = call.request.queryParameters["addr"] if (addr == null || !addr.matches(Regex("0x[0-9A-Fa-f]{40}"))) { call.respond(HttpResponse(HttpStatus.BAD_REQUEST)) return@get } val balance = accountService.getBalance(addr) call.respond(HttpResponse(data = balance)) } post("/charge") { val value = call.receive<String>() val loginId = call.principal<JWTPrincipal>()?.payload?.getClaim(Constant.Authentication.USER_ID_CLAIM) ?.asLong() val loginUser = loginId?.let { id -> userService.getUser(id) } when { //检查登陆用户合法性 (loginUser == null) -> { call.respond(HttpResponse(HttpStatus.UNAUTHORIZED)) return@post } (loginUser.chainAddress == null || loginUser.chainAddress!!.isEmpty()) -> { call.respond(HttpResponse(HttpStatus(HttpStatus.Code.FORBIDDEN, "当前账号未开通链上账户"))) return@post } } when (accountService.chargeFromBank(loginUser!!.chainAddress!!, value)) { true -> call.respond( HttpResponse( data = mapOf(Constant.RespondField.SUCCESS to true) ) ) false -> call.respond( HttpResponse( data = mapOf(Constant.RespondField.SUCCESS to false) ) ) } } } authenticateAfterLogin(Constant.Authentication.PERMISSION_CREATE_CHAIN_ACCOUNT) { post("/new-account") { data class PasswordForm( val password: String, val confirmPassword: String ) val form = call.receive<PasswordForm>() val password = form.password val confirmPassword = form.confirmPassword val loginId = call.principal<JWTPrincipal>()?.payload?.getClaim(Constant.Authentication.USER_ID_CLAIM) ?.asLong() val loginUser = loginId?.let { id -> userService.getUser(id) } when { //两次密码相同 (password != confirmPassword) -> { call.respond(HttpResponse(HttpStatus(HttpStatus.Code.BAD_REQUEST, "两次密码不匹配"))) return@post } //检查登陆用户合法性 (loginUser == null) -> { call.respond(HttpResponse(HttpStatus.UNAUTHORIZED)) return@post } //单一用户仅能绑定一个链上账号 (loginUser.chainAddress != null && loginUser.chainAddress!!.isNotEmpty()) -> { call.respond(HttpResponse(HttpStatus(HttpStatus.Code.FORBIDDEN, "该用户已绑定链上账户"))) return@post } } try { //创建新的链上账户 val addr = accountService.newAccountByPersonal(password!!) if (addr.isEmpty()) { HttpResponse( data = mapOf(Constant.RespondField.SUCCESS to false) ) } //将链上账户地址绑定至用户信息并更新 loginUser!!.chainAddress = addr when (userService.updateUser(loginUser)) { true -> call.respond( HttpResponse( data = mapOf( Constant.RespondField.ADDRESS to addr, Constant.RespondField.SUCCESS to true ) ) ) false -> call.respond( HttpResponse( data = mapOf(Constant.RespondField.SUCCESS to false) ) ) } } catch (e: Exception) { call.respond( HttpResponse( HttpStatus( HttpStatus.Code.SERVER_ERROR, e.message ?: "Unknown Error" ) ) ) return@post } } } } } }
0
Kotlin
0
1
e8a55a8c70317c1a03641fb9d0f984d67944ca9c
6,238
Digital-Rights-Management
MIT License
technocracy.optics/src/main/kotlin/net/cydhra/technocracy/optics/api/tileentities/components/LaserEmitterTileEntityComponent.kt
tth05
198,904,996
true
{"Kotlin": 1367573, "GLSL": 13066}
package net.cydhra.technocracy.optics.api.tileentities.components import net.cydhra.technocracy.foundation.api.ecs.ComponentType import net.cydhra.technocracy.foundation.content.tileentities.components.AbstractTileEntityCapabilityComponent import net.cydhra.technocracy.foundation.util.compound import net.cydhra.technocracy.optics.api.capabilities.laser.ILaserAbsorber import net.cydhra.technocracy.optics.api.capabilities.laser.ILaserEmitter import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.EnumFacing import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.capabilities.CapabilityInject class LaserEmitterTileEntityComponent( var canEmitAt: Set<EnumFacing>, var limit: Int) : AbstractTileEntityCapabilityComponent(), ILaserEmitter { // this is not serialized, because reestablishing laser link is a lot easier and less error-prone, while not // really disturbing connectivity by more than a few ticks. val connectedTo = mutableMapOf<EnumFacing, ILaserAbsorber>() companion object { @JvmStatic @CapabilityInject(ILaserEmitter::class) lateinit var CAPABILITY_LASER_EMITTER: Capability<ILaserEmitter> private const val NBT_KEY_EMITTER_CAP = "emitter" private const val NBT_KEY_LIMIT = "limit" } override val type: ComponentType = ComponentType.OTHER override fun <T : Any?> getCapability(capability: Capability<T>, facing: EnumFacing?): T? { return if (this.hasCapability(capability, facing)) { CAPABILITY_LASER_EMITTER.cast<T>(this) } else { null } } override fun hasCapability(capability: Capability<*>, facing: EnumFacing?): Boolean { return capability == CAPABILITY_LASER_EMITTER && (facing == null || this.canEmitLaser(facing)) } override fun serializeNBT(): NBTTagCompound { return compound { NBT_KEY_EMITTER_CAP to CAPABILITY_LASER_EMITTER.storage.writeNBT(CAPABILITY_LASER_EMITTER, this@LaserEmitterTileEntityComponent, null) NBT_KEY_LIMIT to [email protected] } } override fun deserializeNBT(nbt: NBTTagCompound) { CAPABILITY_LASER_EMITTER.storage.readNBT(CAPABILITY_LASER_EMITTER, this, null, nbt.getCompoundTag(NBT_KEY_EMITTER_CAP)) this.limit = nbt.getInteger(NBT_KEY_LIMIT) } override fun stopTransmission(facing: EnumFacing) { // TODO } override fun canEmitLaser(facing: EnumFacing): Boolean { return this.canEmitAt.contains(facing) } }
0
Kotlin
0
1
057d12813fbcb73a11b202caae0631020b2fa303
2,600
Technocracy
MIT License
src/main/kotlin/com/elements/jvmbykotlin/classfile/entity/attribute/RuntimeVisibleAnnotationsAttribute.kt
QinGeneral
461,483,156
false
null
package com.elements.jvmbykotlin.classfile.entity.attribute import com.elements.jvmbykotlin.classfile.ClassReader import com.elements.jvmbykotlin.classfile.entity.AttributeInfo class RuntimeVisibleAnnotationsAttribute( override val nameIndex: UShort, override val length: UInt, classReader: ClassReader, ) : AttributeInfo(nameIndex, length) { val numOfAnnotations: UShort val annotations: ArrayList<AnnotationItem> = ArrayList() init { numOfAnnotations = classReader.readU2() for (i in 0 until numOfAnnotations.toInt()) { annotations.add(AnnotationItem(classReader)) } } class AnnotationItem(classReader: ClassReader) { val typeIndex: UShort val numOfElementValuePairs: UShort init { typeIndex = classReader.readU2() numOfElementValuePairs = classReader.readU2() } override fun toString(): String { return "AnnotationItem(typeIndex=$typeIndex, numOfElementValuePairs=$numOfElementValuePairs)" } // todo // val elementValuePairs: ArrayList<> // class Element { // val elementNameIndex: UShort; // // } } override fun toString(): String { return "RuntimeVisibleAnnotationsAttribute(nameIndex=$nameIndex, length=$length, numOfAnnotations=$numOfAnnotations, annotations=$annotations)" } }
0
Kotlin
0
14
856324357c16dee08b1f495d28fcf748bf70f2fe
1,409
jvm.kotlin
MIT License
src/main/kotlin/com/elements/jvmbykotlin/classfile/entity/attribute/RuntimeVisibleAnnotationsAttribute.kt
QinGeneral
461,483,156
false
null
package com.elements.jvmbykotlin.classfile.entity.attribute import com.elements.jvmbykotlin.classfile.ClassReader import com.elements.jvmbykotlin.classfile.entity.AttributeInfo class RuntimeVisibleAnnotationsAttribute( override val nameIndex: UShort, override val length: UInt, classReader: ClassReader, ) : AttributeInfo(nameIndex, length) { val numOfAnnotations: UShort val annotations: ArrayList<AnnotationItem> = ArrayList() init { numOfAnnotations = classReader.readU2() for (i in 0 until numOfAnnotations.toInt()) { annotations.add(AnnotationItem(classReader)) } } class AnnotationItem(classReader: ClassReader) { val typeIndex: UShort val numOfElementValuePairs: UShort init { typeIndex = classReader.readU2() numOfElementValuePairs = classReader.readU2() } override fun toString(): String { return "AnnotationItem(typeIndex=$typeIndex, numOfElementValuePairs=$numOfElementValuePairs)" } // todo // val elementValuePairs: ArrayList<> // class Element { // val elementNameIndex: UShort; // // } } override fun toString(): String { return "RuntimeVisibleAnnotationsAttribute(nameIndex=$nameIndex, length=$length, numOfAnnotations=$numOfAnnotations, annotations=$annotations)" } }
0
Kotlin
0
14
856324357c16dee08b1f495d28fcf748bf70f2fe
1,409
jvm.kotlin
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/modules/swap/liquidity/list/LiquidityListViewModel.kt
SAFE-anwang
438,491,711
true
{"Java": 40900402, "C++": 39908445, "C": 28652842, "Kotlin": 6021221, "Assembly": 2284555, "Perl": 2029915, "Go": 1684952, "CMake": 209997, "NASL": 144869, "Objective-C++": 137819, "Python": 83928, "Objective-C": 60293, "Shell": 19944, "Raku": 9275, "AIDL": 8443, "Roff": 2711, "MATLAB": 2068, "Starlark": 1886, "Dockerfile": 1759, "Ruby": 1350, "CSS": 885, "Makefile": 79}
package io.horizontalsystems.bankwallet.modules.swap.liquidity.list import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.gson.Gson import io.horizontalsystems.bankwallet.core.App import io.horizontalsystems.bankwallet.core.AppLogger import io.horizontalsystems.bankwallet.core.HSCaution import io.horizontalsystems.bankwallet.core.IAccountManager import io.horizontalsystems.bankwallet.core.IAdapterManager import io.horizontalsystems.bankwallet.core.IWalletStorage import io.horizontalsystems.bankwallet.core.managers.MarketKitWrapper import io.horizontalsystems.bankwallet.entities.ViewState import io.horizontalsystems.bankwallet.entities.Wallet import io.horizontalsystems.bankwallet.modules.amount.AmountValidator import io.horizontalsystems.bankwallet.modules.swap.SwapMainModule import io.horizontalsystems.bankwallet.modules.swap.liquidity.LiquidityPair import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.BalanceOf import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.Connect import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.Constants import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.MethodID import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.Name import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.PairAddressNonce import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.PermitData import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.Token import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.TokenAmount import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.TotalSupply import io.horizontalsystems.bankwallet.modules.swap.liquidity.util.TransactionContractSend import io.horizontalsystems.core.SingleLiveEvent import io.horizontalsystems.marketkit.models.BlockchainType import io.horizontalsystems.marketkit.models.TokenEntity import io.reactivex.disposables.CompositeDisposable import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.web3j.abi.FunctionEncoder import org.web3j.abi.datatypes.Address import org.web3j.abi.datatypes.Bool import org.web3j.abi.datatypes.Type import org.web3j.abi.datatypes.generated.Bytes32 import org.web3j.abi.datatypes.generated.Uint256 import org.web3j.abi.datatypes.generated.Uint8 import org.web3j.crypto.Credentials import org.web3j.crypto.ECKeyPair import org.web3j.crypto.Sign import org.web3j.crypto.StructuredDataEncoder import org.web3j.protocol.core.DefaultBlockParameterName import org.web3j.utils.Convert import org.web3j.utils.Numeric import java.math.BigDecimal import java.math.BigInteger import java.math.RoundingMode class LiquidityListViewModel( private val accountManager: IAccountManager, private val storage: IWalletStorage, private val adapterManager: IAdapterManager, private val marketKit: MarketKitWrapper, private val liquidityViewItemFactory: LiquidityViewItemFactory ) : ViewModel() { val logger = AppLogger("LiquidityListViewModel") private val web3j = Connect.connect() private val disposable = CompositeDisposable() private var liquidityItems = mutableListOf<LiquidityListModule.LiquidityItem>() private var liquidityViewItems = listOf<LiquidityViewItem>() private var viewState: ViewState = ViewState.Loading private var isRefreshing = false private val amountValidator = AmountValidator() var amountCaution: HSCaution? = null private var inputRemoveAmount: BigDecimal? = null var tempItem: LiquidityViewItem? = null var tempIndex: Int? = null private var removePercent = 25 private var requestCount = 1 private val Max_Request_Count = 5 var uiState by mutableStateOf( LiquidityUiState( liquidityViewItems = liquidityViewItems, viewState = viewState, true, removePercent ) ) private set val removeErrorMessage = SingleLiveEvent<String?>() val removeSuccessMessage = SingleLiveEvent<String>() private var amount = "" private var secondaryInfo: String = "" private var isEstimated = false private var isLoading = false private var amountEnabled = true private var validDecimals: Int = 0 val state: SwapMainModule.SwapAmountInputState get() = SwapMainModule.SwapAmountInputState( amount = amount, secondaryInfo = secondaryInfo, primaryPrefix = null, validDecimals = validDecimals, amountEnabled = amountEnabled, dimAmount = isLoading && isEstimated, ) private fun getWethAddress(chain: BlockchainType): String { val wethAddressHex = when (chain) { BlockchainType.Ethereum -> "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" BlockchainType.Optimism -> "0x4200000000000000000000000000000000000006" BlockchainType.BinanceSmartChain -> "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c" BlockchainType.Polygon -> "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270" BlockchainType.Avalanche -> "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7" BlockchainType.ArbitrumOne -> "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1" else -> "" } return wethAddressHex } init { getAllLiquidity() } fun onEnterAmount(amount: BigDecimal?, availableBalance: BigDecimal) { amountCaution = amountValidator.validate( coinAmount = amount, coinCode = "", availableBalance = availableBalance ) inputRemoveAmount = amount emitState() } fun reset() { amountCaution = null inputRemoveAmount = null emitState() } fun setRemovePercent(percent: Int) { removePercent = percent emitState() } fun refresh() { getAllLiquidity() } private fun getTokenEntity(uids: List<String>, type: String):List<TokenEntity> { return marketKit.getTokenEntity(uids, type) } private fun getAllLiquidity() { viewState = ViewState.Loading val activeWallets = accountManager.activeAccount?.let { storage.wallets(it).filter { it.token.blockchainType is BlockchainType.BinanceSmartChain && it.token.coin.code != "Cake-LP" } } ?: listOf() if (activeWallets.isEmpty()) return val uids = activeWallets.map { it.coin.uid } val tokenEntityList = getTokenEntity(uids, "binance-smart-chain") liquidityItems.clear() viewModelScope.launch(Dispatchers.IO) { isRefreshing = true emitState() var requestError = false val list = mutableListOf<LiquidityViewItem>() getAllPair(activeWallets).forEach { pair -> requestCount = 1 requestError = false val tokenEntityA = tokenEntityList.find { it.coinUid == pair.first.coin.uid }?.reference ?: getWethAddress(pair.first.token.blockchain.type) val tokenEntityB = tokenEntityList.find { it.coinUid == pair.second.coin.uid }?.reference ?: getWethAddress(pair.second.token.blockchain.type) if (tokenEntityA != null && tokenEntityB != null) { try { getLiquidity(pair.first, tokenEntityA, pair.second, tokenEntityB)?.let { liquidityItems.add(it) list.add(liquidityViewItemFactory.viewItem(it)) } } catch (e: Exception) { if (requestCount == Max_Request_Count) { viewState = ViewState.Error(e) } else { requestCount ++ } requestError = true } } } if (requestError && requestCount == Max_Request_Count) { refresh() } viewState = ViewState.Success liquidityViewItems = list.map { it } isRefreshing = false emitState() } } private fun getAllPair(activeWallets: List<Wallet>): List<Pair<Wallet, Wallet>> { val pairs = mutableListOf<Pair<Wallet, Wallet>>() for (i in activeWallets.indices) { for (j in i + 1 until activeWallets.size) { pairs.add(Pair(activeWallets[i], activeWallets[j])) } } return pairs } private fun getLiquidity(walletA: Wallet, tokenAAddress: String, walletB: Wallet, tokenBAddress: String): LiquidityListModule.LiquidityItem? { val adapterA = adapterManager.getReceiveAdapterForWallet(walletA) ?: return null val tokenA = Token( tokenAAddress, walletA.coin.name, walletA.coin.code, walletA.decimal ) val tokenB = Token( tokenBAddress, walletB.coin.name, walletB.coin.code, walletB.decimal ) val pair = LiquidityPair.getPairReservesForPancakeSwap(web3j, tokenA, tokenB) ?: return null val pairAddress = pair.get(0) as String val token0 = pair.get(1) as Token val token1 = pair.get(2) as Token val isChange = token0.address != tokenAAddress val r0: BigInteger = pair[3] as BigInteger val r1: BigInteger = pair[4] as BigInteger // 查询 流动性代币的数量 val poolTokenTotalSupply = TotalSupply.getTotalSupply(web3j, pairAddress) // 查询 当前用户拥有的流动性代币数量 val balanceOfAccount = BalanceOf.balanceOf(web3j, pairAddress, adapterA.receiveAddress) Log.d("Pool Token TotalSupply = {}", "$poolTokenTotalSupply") Log.d("BalanceOf {} = {}", "${adapterA.receiveAddress}, ${balanceOfAccount}") // 计算用户在池子中的流动性占比 var shareRate = BigDecimal(balanceOfAccount).divide( BigDecimal(poolTokenTotalSupply), 18, RoundingMode.DOWN ) Log.d( "用户流动性占比:{}", shareRate.toString() + "%" ) val pooledR0Amount = TokenAmount.toBigDecimal( token0, r0, token0.decimals ).multiply(shareRate) val pooledR1Amount = TokenAmount.toBigDecimal( token1, r1, token1.decimals ).multiply(shareRate) // 没有添加流动性 if (balanceOfAccount.equals(BigInteger.ZERO)) return null return LiquidityListModule.LiquidityItem( if (isChange) walletB else walletA, if (isChange) walletA else walletB, tokenAAddress, tokenBAddress, pooledR0Amount, pooledR1Amount, balanceOfAccount, shareRate.multiply(BigDecimal("100")), poolTokenTotalSupply ) } private fun emitState() { val newUiState = LiquidityUiState( liquidityViewItems = liquidityViewItems, viewState = viewState, isRefreshing = isRefreshing, removePercent, amountCaution = amountCaution ) viewModelScope.launch { uiState = newUiState } } private fun removeItem(removeIndex: Int) { val list = mutableListOf<LiquidityViewItem>() liquidityViewItems.forEachIndexed{ index, liquidityViewItem -> if (removeIndex != index) { list.add(liquidityViewItem) } } liquidityViewItems = list emitState() } fun removeLiquidity(index: Int, walletA: Wallet, tokenAAddress: String, walletB: Wallet, tokenBAddress: String) { if (amountCaution != null) return viewModelScope.launch(Dispatchers.IO) { try { val evmKitWrapper = App.evmBlockchainManager.getEvmKitManager(walletA.token.blockchainType).evmKitWrapper ?: return@launch val tokenA = Token( tokenAAddress, walletA.coin.name, walletA.coin.code, walletA.decimal ) val tokenB = Token( tokenBAddress, walletB.coin.name, walletB.coin.code, walletB.decimal ) val pair = LiquidityPair.getPairReservesForPancakeSwap(web3j, tokenA, tokenB) ?: return@launch val pairAddress = pair.get(0) as String val token00 = pair.get(1) as Token val token11 = pair.get(2) as Token //val isChange = token00.address != tokenAAddress val isChange = false val token0 = if (isChange) token11 else token00 val token1 = if (isChange) token00 else token11 val r0: BigInteger = pair[3] as BigInteger val r1: BigInteger = pair[4] as BigInteger // 查询 流动性代币的数量 val poolTokenTotalSupply = TotalSupply.getTotalSupply(web3j, pairAddress) // 查询 当前用户拥有的流动性代币数量 val balanceOfAccount = BalanceOf.balanceOf( web3j, pairAddress, evmKitWrapper!!.evmKit.receiveAddress.hex ) Log.d("Pool Token TotalSupply = {}", "$poolTokenTotalSupply") Log.d( "BalanceOf {} = {}", "${evmKitWrapper!!.evmKit.receiveAddress.hex}, ${balanceOfAccount}" ) // 计算用户在池子中的流动性占比 val shareRate = BigDecimal(balanceOfAccount).divide( BigDecimal(poolTokenTotalSupply), 18, RoundingMode.DOWN ) Log.i( "用户流动性占比:{}", shareRate.multiply(BigDecimal("100")).toString() + "%" ) val pooledR0Amount = TokenAmount.toBigDecimal(token0, r0, token0.decimals).multiply(shareRate) val pooledR1Amount = TokenAmount.toBigDecimal(token1, r1, token1.decimals).multiply(shareRate) Log.i("用户在池子中抵押:{} ({})", "$pooledR0Amount, ${token0.symbol}") Log.i("用户在池子中抵押:{} ({})", "$pooledR1Amount, ${token1.symbol}") // 用户期望移除抵押 的代币 的百分比; val removePercent = (removePercent / 100f).toString() val removeLiquidityAmount = BigDecimal(balanceOfAccount).multiply(BigDecimal(removePercent)).toBigInteger() // 将会得到的 token0 和 token1 的数量 val removeToken0Amount = pooledR0Amount.multiply(BigDecimal(removePercent)) val removeToken1Amount = pooledR1Amount.multiply(BigDecimal(removePercent)) Log.i( "Receive {} Amount : {}", "${token0.symbol}, $removeToken0Amount" ) Log.i( "Receive {} Amount : {}", "${token1.symbol}, $removeToken1Amount" ) // 通过用户设置的滑点,计算最低移除数量. val removeMinToken0Amount = removeToken0Amount.multiply(BigDecimal.ONE.subtract(BigDecimal(Constants.slippage))) val removeMinToken1Amount = removeToken1Amount.multiply( BigDecimal.ONE.subtract( BigDecimal( Constants.slippage ) ) ) // 通过合约获取流动性代币的名称 , PancakeSwap 的流动性代币名称都是 "Pancake LPs" val name = Name.name(web3j, pairAddress) val nonces = PairAddressNonce.nonce( web3j, pairAddress, evmKitWrapper!!.evmKit.receiveAddress.hex ) val deadline = Constants.getDeadLine() val json = buildSignJson( name, 56, pairAddress, evmKitWrapper!!.evmKit.receiveAddress.hex, Constants.DEX.PANCAKE_V2_ROUTER_ADDRESS, removeLiquidityAmount, nonces, deadline ) val ecKeyPair = ECKeyPair.create(evmKitWrapper!!.signer!!.privateKey) val structuredDataEncoder = StructuredDataEncoder(json) val signatureData = Sign.signMessage(structuredDataEncoder.hashStructuredData(), ecKeyPair, false) val inputParameters: MutableList<Type<*>> = mutableListOf() /* function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); */ inputParameters.add(Address(token0.address)) inputParameters.add(Address(token1.address)) inputParameters.add(Uint256(removeLiquidityAmount)) inputParameters.add( Uint256( TokenAmount.toRawBigInteger( token0, removeMinToken0Amount ) ) ) inputParameters.add( Uint256( TokenAmount.toRawBigInteger( token1, removeMinToken1Amount ) ) ) inputParameters.add(Address(evmKitWrapper.evmKit.receiveAddress.hex)) inputParameters.add(Uint256(deadline)) inputParameters.add(Bool(false)) inputParameters.add(Uint8(Numeric.toBigInt(signatureData.v))) inputParameters.add(Bytes32(signatureData.r)) inputParameters.add(Bytes32(signatureData.s)) val encode = FunctionEncoder.encode( MethodID.generate("removeLiquidityWithPermit(address,address,uint256,uint256,uint256,address,uint256,bool,uint8,bytes32,bytes32)"), inputParameters ) Log.d("removeLiquidityWithPermit encode result:{}", encode) // 获取 nonce val nonce = web3j.ethGetTransactionCount( evmKitWrapper.evmKit.receiveAddress.hex, DefaultBlockParameterName.LATEST ) .send().transactionCount val hash = TransactionContractSend.send( web3j, Credentials.create(evmKitWrapper.signer!!.privateKey.toString(16)), Constants.DEX.PANCAKE_V2_ROUTER_ADDRESS, encode, BigInteger.ZERO, nonce, Convert.toWei("10", Convert.Unit.GWEI).toBigInteger(), // GAS PRICE : 5GWei BigInteger("500000") // GAS LIMIT ) // 0xab43576d55e54c3c51ecff56b030cd83945ec7ee0892539953a8ee467570a73d // 0xab43576d55e54c3c51ecff56b030cd83945ec7ee0892539953a8ee467570a73d Log.i("Execute Router.removeLiquidityWithPermit Hash = {}", hash) withContext(Dispatchers.Main) { removeItem(index) removeSuccessMessage.value = if (App.languageManager.currentLanguage == "zh") { "移除成功" } else { "Remove Success" } } // refresh() } catch (e: Throwable) { Log.e("removeLiquidity", "error=$e") withContext(Dispatchers.Main) { removeErrorMessage.value = e.message } } } } private fun buildSignJson( name: String, chainId: Int, pairAddress: String, owner: String, spender: String, value: BigInteger, nonce: BigInteger, deadline: BigInteger ): String? { val data = PermitData() data.domain.name = name data.domain.version = "1" data.domain.chainId = chainId data.domain.verifyingContract = pairAddress data.message.owner = owner data.message.spender = spender data.message.value = value data.message.nonce = Numeric.toHexStringWithPrefix(nonce) data.message.deadline = deadline.toLong() return Gson().toJson(data) } override fun onCleared() { disposable.dispose() } } data class LiquidityUiState( val liquidityViewItems: List<LiquidityViewItem>, val viewState: ViewState, val isRefreshing: Boolean, val selectPercent: Int, val amountCaution: HSCaution? = null ) /*private class PermitData { var types = Types() var primaryType = "Permit" var domain = Domain() var message = Message() class Domain { var name: String? = null var version: String? = null var chainId: Int? = null var verifyingContract: String? = null } class Message { var owner: String? = null var spender: String? = null var value: BigInteger? = null var nonce: String? = null var deadline: Long = 0 } class Types { var eIP712Domain = arrayOf( TypeDefine("name", "string"), TypeDefine("version", "string"), TypeDefine("chainId", "uint256"), TypeDefine("verifyingContract", "address") ) var permit = arrayOf( TypeDefine("owner", "address"), TypeDefine("spender", "address"), TypeDefine("value", "uint256"), TypeDefine("nonce", "uint256"), TypeDefine("deadline", "uint256") ) } class TypeDefine(var name: String, var type: String) }*/
0
Java
3
3
a6fb06ea11a0cb366dcf093dcbeb053e628877a9
22,748
SafeWallet-android
MIT License
appointment/src/main/kotlin/com/itavgur/omul/appointment/exception/DatabaseConstraintException.kt
itAvgur
211,451,348
false
{"Kotlin": 297016, "Smarty": 4598, "Dockerfile": 1120}
package com.itavgur.omul.appointment.exception import org.springframework.http.HttpStatus class DatabaseConstraintException(override val message: String?, val httpCode: HttpStatus? = null) : RuntimeException(message)
0
Kotlin
1
0
ecdad770074ca157d8041a4d97399aeea7604d2b
222
omul
The Unlicense
cloud/src/main/kotlin/xyz/luccboy/noobcloud/console/commands/HelpCommand.kt
NoobCloudSystems
518,232,292
false
{"Kotlin": 155606, "Shell": 69, "Batchfile": 45}
package xyz.luccboy.noobcloud.console.commands import org.jline.builtins.Completers.TreeCompleter.Node import org.jline.builtins.Completers.TreeCompleter.node import xyz.luccboy.noobcloud.NoobCloud import xyz.luccboy.noobcloud.console.Command class HelpCommand : Command { override val name: String = "help" override val description: String = "Lists all commands" override val aliases: Array<String> = arrayOf("help") override val completer: Node = node(name, *aliases) override fun execute(args: Array<String>) { NoobCloud.instance.logger.info("Here is a list of all commands:") NoobCloud.instance.commandHandler.commandList.forEach { command -> NoobCloud.instance.logger.info(command.name + " - " + command.description) } } }
1
Kotlin
2
3
0ecea76f391fa60bec8d7e924af45922543093c3
789
NoobCloud
Apache License 2.0
stickHeader/src/main/java/com/fxf/stickheader/ExtendKt.kt
fxfSean
299,338,702
false
null
package com.fxf.stickheader import android.content.res.Resources import android.util.TypedValue val Int.dp: Int get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),Resources.getSystem().displayMetrics).toInt() val Float.dp: Float get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),Resources.getSystem().displayMetrics).toFloat()
0
Kotlin
0
0
59738fba09d60cf54b6dd6b9a5b9053db3b29f7f
392
StickHeaderView
Apache License 2.0
app/src/main/java/com/example/foodapplication/utils/Extensions.kt
rezakardan
719,028,366
false
{"Kotlin": 60562}
package com.example.foodapplication.utils import android.content.Context import android.net.ConnectivityManager import android.view.View import com.google.android.material.snackbar.Snackbar import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Scheduler import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers //RxJava fun <T : Any> Single<T>.applyScheduler(scheduler: Scheduler): Single<T> = subscribeOn(scheduler).observeOn(AndroidSchedulers.mainThread()) fun <T : Any> Single<T>.applyIoScheduler() = applyScheduler(Schedulers.io()) //Check network fun Context.isNetworkAvailable(): Boolean { val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val info = cm.activeNetworkInfo return info != null && info.isConnected } //SnackBar fun View.showSnackBar(message: String) { Snackbar.make(this, message, Snackbar.LENGTH_SHORT).show() }
0
Kotlin
0
0
21934aeb61cc85b5e3bfe3a30e26d74023ac649d
968
foodApp_Git
MIT License
app/src/main/java/com/udacity/asteroidradar/data/api/AsteroidApiService.kt
ihermandev
434,214,366
false
{"Kotlin": 30954}
package com.udacity.asteroidradar.data.api import com.udacity.asteroidradar.Constants.FEED_URL import com.udacity.asteroidradar.Constants.IMAGE_OF_DAY_URL import com.udacity.asteroidradar.Constants.nasaApiKey import retrofit2.http.GET import retrofit2.http.Query interface AsteroidApiService { @GET(FEED_URL) suspend fun getAsteroids( @Query("start_date") startData: String, @Query("end_date") endDate: String, @Query("api_key") apiKey: String = nasaApiKey ): String @GET(IMAGE_OF_DAY_URL) suspend fun getImgOfDayData( @Query("api_key") apiKey: String = nasaApiKey ): NetworkPictureOfDay }
0
Kotlin
0
0
a0f2f152bbe8c565b4259847847f33ae8f81a878
651
AsteroidRadarUdemy
NASA Open Source Agreement 1.3
providers/aws/src/main/kotlin/cloudspec/aws/ec2/EC2NetworkAclLoader.kt
efoncubierta
259,448,965
false
null
/*- * #%L * CloudSpec AWS Provider * %% * Copyright (C) 2020 <NAME> * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package cloudspec.aws.ec2 import arrow.fx.IO import cloudspec.aws.IAWSClientsProvider import kotlin.streams.toList class EC2NetworkAclLoader(clientsProvider: IAWSClientsProvider) : EC2ResourceLoader<EC2NetworkAcl>(clientsProvider) { override fun resourcesInRegion(region: String, ids: List<String>): IO<List<EC2NetworkAcl>> = requestInRegion(region) { client -> val filters = buildFilters( mapOf( FILTER_NETWORK_ACL_ID to ids ) ) client // https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeNetworkAcls.html .describeNetworkAcls { builder -> if (filters.isNotEmpty()) { builder.filters(filters) } } .networkAcls() .stream() .map { it.toEC2NetworkAcl(region) } .toList() } companion object { private const val FILTER_NETWORK_ACL_ID = "network-acl-id" } }
3
Kotlin
2
26
edabff96392cdb1f0d55b3a9c57ae5c433c7be69
1,853
cloudspec
Apache License 2.0
aaper/src/test/java/com/likethesalad/android/aaper/defaults/launchers/FragmentRequestLauncherTest.kt
LikeTheSalad
289,293,129
false
null
package com.likethesalad.android.aaper.defaults.launchers import androidx.fragment.app.Fragment import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.anyArray import com.nhaarman.mockitokotlin2.doNothing import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner /** * Created by <NAME> on 13/08/20. */ @RunWith(PowerMockRunner::class) @PrepareForTest(Fragment::class) class FragmentRequestLauncherTest { private val requestCode = 12345 private lateinit var host: Fragment private lateinit var fragmentRequestLauncher: FragmentRequestLauncher @Before fun setUp() { host = PowerMockito.mock(Fragment::class.java) fragmentRequestLauncher = FragmentRequestLauncher() } @Test fun `Delegate request to ActivityCompat`() { val permissions = listOf("one", "two") doNothing().whenever(host).requestPermissions(anyArray(), any()) fragmentRequestLauncher.launchPermissionsRequest(host, permissions, requestCode) verify(host).requestPermissions(permissions.toTypedArray(), requestCode) } }
0
Kotlin
7
143
a206b9355b68080af99e16cbe939e4558d763b37
1,360
aaper
MIT License
cryptocurrencychallenge/src/main/java/com/yoti/android/cryptocurrencychallenge/presentation/common/Texts.kt
davidleiti
501,532,688
false
null
package com.yoti.android.cryptocurrencychallenge.presentation.common import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun Header5(modifier: Modifier = Modifier, text: String) { Text(modifier = modifier, text = text, style = MaterialTheme.typography.h5) } @Composable fun Subtitle1(modifier: Modifier = Modifier, text: String) { Text(modifier = modifier, text = text, style = MaterialTheme.typography.subtitle1) } @Composable fun Caption(modifier: Modifier = Modifier, text: String) { Text(modifier = modifier, text = text, style = MaterialTheme.typography.caption) }
0
Kotlin
0
0
ef65d9983e53ba1f34fbb9448a8c996739debb9f
710
CryptoCurrencyApp
MIT License
src/main/kotlin/troy/commands/funstuff/Burn.kt
daksh7011
440,123,158
false
{"Kotlin": 99491, "Groovy": 26750, "Dockerfile": 251}
package troy.commands.funstuff import dev.kord.core.Kord import dev.kordex.core.commands.Arguments import dev.kordex.core.commands.converters.impl.user import dev.kordex.core.extensions.Extension import dev.kordex.core.extensions.publicSlashCommand import org.koin.core.component.inject import troy.utils.DataProvider import troy.utils.isGirlfriend import troy.utils.isOwner class Burn : Extension() { private val kordClient: Kord by inject() override val name: String get() = "burn" class BurnArguments : Arguments() { val user by user { name = "user" description = "Which user do you want to light on fire?" } } override suspend fun setup() { publicSlashCommand(Burn::BurnArguments) { name = "burn" description = "Lights fire to mentioned user." action { val burnList = DataProvider.getBurnData() val randomBurn = burnList[kotlin.math.floor(Math.random() * burnList.size).toInt()] with(arguments) { when { user.id.isOwner() -> { respond { content = "You can't hurt the god, But here's one for you.\n${member?.mention}, $randomBurn" } return@action } user.id.isGirlfriend() -> { respond { content = "You can't hurt her. But here is one for you. Asshole.\n${member?.mention}, $randomBurn" } return@action } user.id == kordClient.selfId -> respond { content = "Huh, Burn me? But, $randomBurn" } else -> respond { content = "${user.mention}, $randomBurn" } } } } } } }
2
Kotlin
1
0
b5d22473b98d866dba39a4c03988cd91d69d1192
2,129
troy
MIT License
src/main/kotlin/Deck.kt
ArmandAgopian
92,569,260
false
{"Kotlin": 560}
/** * Created by Armand on 5/28/17. */ class Deck { val cards: Array<Card> = Array(52, fun (i: Int): Card { return Card(i % 13, getSuit(i)) } ) private fun getSuit(i: Int): String = when(i / 13){ 0 -> "Clubs" 1 -> "Diamonds" 2 -> "Hearts" else -> "Spades" } }
0
Kotlin
0
0
1deeb6a1b174772044514225ace76977d2f6565d
369
Solitaire
MIT License
src/test/kotlin/org/liquibase/kotlin/CustomRefactoringTests.kt
redundent
100,302,975
true
{"Kotlin": 286601, "Groovy": 878}
/* * Copyright 2011-2017 Tim Berglund and Steven C. Saliman * Kotlin conversion done by Jason Blackwell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.liquibase.kotlin import liquibase.change.core.ExecuteShellCommandChange import liquibase.change.core.RawSQLChange import liquibase.change.core.SQLFileChange import liquibase.change.custom.CustomChangeWrapper import liquibase.sql.visitor.PrependSqlVisitor import org.junit.Test import org.liquibase.kotlin.helper.assertType import kotlin.test.* /** * This is one of several classes that test the creation of refactoring changes * for ChangeSets. This particular class tests custom changes such as * {@code sql} and {@code executeCommand} * <p> * Since the Kotlin DSL parser is meant to act as a pass-through for Liquibase * itself, it doesn't do much in the way of error checking. For example, we * aren't concerned with whether or not required attributes are present - we * leave that to Liquibase itself. In general, each change will have 3 kinds * of tests:<br> * <ol> * <li>A test with an empty parameter map, and if supported, an empty closure. * This kind of test will make sure that the Kotlin parser doesn't introduce * any unintended attribute defaults for a change.</li> * <li>A test that sets all the attributes known to be supported by Liquibase * at this time. This makes sure that the Kotlin parser will send any given * kotlin attribute to the correct place in Liquibase. For changes that allow * a child closure, this test will include just enough in the closure to make * sure it gets processed, and that the right kind of closure is called.</li> * <li>Some tests take columns or a where clause in a child closure. The same * closure handles both, but should reject one or the other based on how the * closure gets called. These changes will have an additional test with an * invalid closure to make sure it sets up the closure properly</li> * </ol> * <p> * Some changes require a little more testing, such as the {@code sql} change * that can receive sql as a string, or as a closure, or the {@code delete} * change, which is valid both with and without a child closure. * <p> * We don't worry about testing combinations that don't make sense, such as * allowing a createIndex change a closure, but no attributes, since it doesn't * make sense to have this kind of change without both a table name and at * least one column. If a user tries it, they will get errors from Liquibase * itself. * * @author Steven C. Saliman * @author Jason Blackwell */ class CustomRefactoringTests : ChangeSetTests() { @Test fun customRefactoringWithClassAndNoParameters() { buildChangeSet { customChange(className = "org.liquibase.change.custom.MonkeyChange") } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<CustomChangeWrapper>(changes[0]) { assertEquals("org.liquibase.change.custom.MonkeyChange", it.className) assertNotNull(it.resourceAccessor) assertNotNull(it.customChange) } assertNoOutput() } @Test fun customRefactoringWithClassAndParameters() { buildChangeSet { customChange(className = "org.liquibase.change.custom.MonkeyChange") { param("emotion", "angry") param("rfid-tag", 28763) } } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<CustomChangeWrapper>(changes[0]) { assertEquals("org.liquibase.change.custom.MonkeyChange", it.className) assertNotNull(it.resourceAccessor) assertEquals(it.getParamValue("emotion"), "angry") assertEquals(it.getParamValue("rfid-tag"), "28763") } assertNoOutput() } /** * Test parsing an executeCommand with no args and an empty closure to make * sure the DSL doesn't introduce any unintended defaults. */ @Test fun executeCommandEmptyMapEmptyClosure() { buildChangeSet { executeCommand(executable = "") {} } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<ExecuteShellCommandChange>(changes[0]) { assertEquals("", it.executable) assertNull(it.os) val args = it.args assertNotNull(args) assertEquals(0, args.size) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing an executeCommand change when we have no attributes and there * is no closure. */ @Test fun executeCommandEmptyMapNoClosure() { buildChangeSet { executeCommand(executable = "") } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<ExecuteShellCommandChange>(changes[0]) { assertEquals("", it.executable) assertNull(it.os) val args = it.args assertNotNull(args) assertEquals(0, args.size) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing executeCommand when we have all supported attributes,but * no argument closure. */ @Test fun executeCommandWithNoArgs() { buildChangeSet { executeCommand(executable = "awk '/monkey/ { count++ } END { print count }'", os = "Mac OS X, Linux") } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<ExecuteShellCommandChange>(changes[0]) { assertEquals("awk '/monkey/ { count++ } END { print count }'", it.executable) assertNotNull(it.os) assertEquals(2, it.os.size) assertEquals("Mac OS X", it.os[0]) assertEquals("Linux", it.os[1]) val args = it.args assertNotNull(args) assertEquals(0, args.size) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing an executeCommand change where the arguments are just Strings. * This is not the way the XML does it, but it is the way the Kotlin DSL has * always done it, and it is nice shorthand. */ @Test fun executeCommandWithArgsInMap() { buildChangeSet { executeCommand(executable = "awk", os = "Mac OS X, Linux") { arg("/monkey/ { count++ } END { print count }") arg("-f database.log") } } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<ExecuteShellCommandChange>(changes[0]) { assertEquals("awk", it.executable) assertNotNull(it.os) assertEquals(2, it.os.size) assertEquals("Mac OS X", it.os[0]) assertEquals("Linux", it.os[1]) val args = it.args assertNotNull(args) assertEquals(2, args.size) assertEquals("/monkey/ { count++ } END { print count }", args[0]) assertEquals("-f database.log", args[1]) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Make sure modifySql works. Most of the tests for this are in * {@link ModifySqlDelegateTests}, this just needs to make sure that the * SqlVisitors that the delegate returns are added to the changeSet. This * one also tests that we can have a modifySql with no attributes of its own. */ @Test fun modifySqlValid() { buildChangeSet { modifySql { prepend(value = "engine INNODB") } } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(0, changes.size) assertEquals(1, changeSet.sqlVisitors.size) assertType<PrependSqlVisitor>(changeSet.sqlVisitors[0]) { assertEquals("engine INNODB", it.value) assertNull(it.applicableDbms) assertNull(it.contexts) assertFalse(it.isApplyToRollback) } assertNoOutput() } /** * Test parsing a sql change when we have an empty attribute map and an * empty closure to make sure we don't get any unintended defaults. Also test * our assumption that Liquibase will default splitStatements to true and * stripComments to false. */ @Test fun sqlWithoutAttributesOrClosure() { buildChangeSet { sql {} } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<RawSQLChange>(changes[0]) { assertNull(it.dbms) assertNull(it.endDelimiter) assertTrue(it.isSplitStatements) assertFalse(it.isStripComments) assertNull(it.sql) assertNull(it.comment) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing a sql change when we have no attributes or a closure, just * a string. */ @Test fun sqlIsString() { buildChangeSet { sql("UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)") } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<RawSQLChange>(changes[0]) { assertNull(it.dbms) assertNull(it.endDelimiter) assertTrue(it.isSplitStatements) assertFalse(it.isStripComments) assertEquals("UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)", it.sql) assertNull(it.comment) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * test parsing a sql change where we only have SQL in a closure. */ @Test fun sqlInClosure() { buildChangeSet { sql { -"UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)" } } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<RawSQLChange>(changes[0]) { assertNull(it.dbms) assertNull(it.endDelimiter) assertTrue(it.isSplitStatements) assertFalse(it.isStripComments) assertEquals("UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)", it.sql) assertNull(it.comment) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing a sql change when we have no attributes, but we do have a * comment in the closure. */ @Test fun sqlCommentInClosure() { buildChangeSet { sql { comment("No comment") -"UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)" } } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<RawSQLChange>(changes[0]) { assertNull(it.dbms) assertNull(it.endDelimiter) assertTrue(it.isSplitStatements) assertFalse(it.isStripComments) assertEquals("UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)", it.sql) assertEquals("No comment", it.comment) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing a sql chanve when we have all supported attributes present * and no comments in the closure. For this test set the two booleans to * the opposite of the Liquibase defaults. */ @Test fun sqlFullWithNoComments() { buildChangeSet { sql(dbms = "oracle", splitStatements = false, stripComments = true, endDelimiter = "!") { -"UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)" } } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<RawSQLChange>(changes[0]) { assertEquals("oracle", it.dbms) assertFalse(it.isSplitStatements) assertTrue(it.isStripComments) assertEquals("!", it.endDelimiter) assertEquals("UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)", it.sql) assertNull(it.comment) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing a sql change when we have all attributes and we have a comment * in the closure. For this test we only set splitStatements to true. */ @Test fun sqlFullWithComments() { buildChangeSet { sql(dbms = "oracle", splitStatements = false, stripComments = true, endDelimiter = "!") { comment("No comment") -"UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)" } } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<RawSQLChange>(changes[0]) { assertEquals("oracle", it.dbms) assertFalse(it.isSplitStatements) assertTrue(it.isStripComments) assertEquals("!", it.endDelimiter) assertEquals("UPDATE monkey SET emotion='ANGRY' WHERE id IN (1,2,3,4,5)", it.sql) assertEquals("No comment", it.comment) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing a sqlFile change with minimal attributes to confirm our * assumptions about Liquibase defaults, which we assume to be true for * splitStatements and false for stripComments. We can't test this one with * totally empty attributes because a sqlFile change will attempt to open the * file immediately to work around a Liquibase bug. This also means the file * in question must exist. */ @Test fun sqlFileEmpty() { buildChangeSet { sqlFile(path = "src/test/changelog/file.sql") } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<SQLFileChange>(changes[0]) { assertEquals("src/test/changelog/file.sql", it.path) assertNull(it.isRelativeToChangelogFile) assertNull(it.encoding) assertFalse(it.isStripComments) assertTrue(it.isSplitStatements) assertNull(it.endDelimiter) assertNull(it.dbms) assertNotNull(it.resourceAccessor) } assertNoOutput() } /** * Test parsing a sqlFile change when we have all supported options. For this * test, we set the two booleans to be the opposite of their default values. */ @Test fun sqlFileFull() { buildChangeSet { sqlFile(path = "src/test/changelog/file.sql", relativeToChangelogFile = false, stripComments = true, splitStatements = false, encoding = "UTF-8", endDelimiter = "@", dbms = "oracle") } assertEquals(0, changeSet.rollback.changes.size) val changes = changeSet.changes assertNotNull(changes) assertEquals(1, changes.size) assertType<SQLFileChange>(changes[0]) { assertEquals("src/test/changelog/file.sql", it.path) assertFalse(it.isRelativeToChangelogFile) assertEquals("UTF-8", it.encoding) assertTrue(it.isStripComments) assertFalse(it.isSplitStatements) assertEquals("@", it.endDelimiter) assertEquals("oracle", it.dbms) assertNotNull(it.resourceAccessor) } assertNoOutput() } }
0
Kotlin
2
9
eea7769d146a6c886e54bacd510b1d2664ccddd3
15,120
liquibase-kotlin-dsl
Apache License 2.0
src/main/kotlin/no/nav/pale/client/PdfClient.kt
purebase
153,675,583
false
null
package no.nav.pale.client import net.logstash.logback.argument.StructuredArguments import no.nav.pale.objectMapper import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import java.io.IOException class PdfClient(private val baseUrl: String) { private val client: OkHttpClient = OkHttpClient() fun generatePDF(pdfType: PdfType, domainObject: Any): ByteArray { val request = Request.Builder() .post(RequestBody.create(MediaType.parse("application/json"), objectMapper.writeValueAsBytes(domainObject))) .url("$baseUrl/v1/genpdf/pale/${pdfType.pdfGenName()}") .build() val response = client.newCall(request).execute() if (response.isSuccessful) { val bytes = response.body()?.bytes() if (bytes != null) { return bytes } throw IOException("Received no body from the PDF generator") } else { log.error("Received an error while contacting the PDF generator {}", StructuredArguments.keyValue("errorBody", response.body()?.string())) throw IOException("Unable to contact the PDF generator, got status code ${response.code()}") } } } enum class PdfType { FAGMELDING, BEHANDLINGSVEDLEGG } fun PdfType.pdfGenName(): String = name.toLowerCase()
0
Kotlin
0
0
8168e978017701b6016ee7d985036c6b94325d35
1,392
pale
MIT License
protocol-client-nft-order/src/main/kotlin/com/rarible/protocol/nftorder/api/client/SwarmNftOrderApiServiceUriProvider.kt
rarible
426,537,098
false
null
package com.rarible.protocol.nftorder.api.client import java.net.URI class SwarmNftOrderApiServiceUriProvider( private val environment: String ) : NftOrderApiServiceUriProvider { override fun getUri(blockchain: String): URI { return URI.create(String.format("http://%s-%s-nft-order-api:8080", environment, blockchain)) } }
1
Kotlin
1
7
6911989d1b62431f2eec0a7a37210ec5f69f4902
345
ethereum-openapi
MIT License
app/src/main/java/com/example/dispositivos_moviles_proyecto_gc_es1/logic/entities/marvel/Stories.kt
GeoWillC
643,371,344
false
null
package com.example.dispositivos_moviles_proyecto_gc_es1.logic.entities.marvel data class Stories( val available: Int, val collectionURI: String, val items: List<ItemXXX>, val returned: Int )
0
Kotlin
0
0
4ae1861c997559b35105e00ecd14ac81eaa00dfa
208
Dispositivos_moviles_proyecto_gc_es
MIT License
src/main/kotlin/io/layercraft/packetlib/packets/v1_19_2/play/clientbound/CollectPacket.kt
Layercraft
531,857,310
false
null
package io.layercraft.packetlib.packets.v1_19_2.play.clientbound import io.layercraft.packetlib.packets.* import io.layercraft.packetlib.serialization.MinecraftProtocolDeserializeInterface import io.layercraft.packetlib.serialization.MinecraftProtocolSerializeInterface /** * Pickup Item | 0x65 | play | clientbound * * @param collectedEntityId collectedEntityId * @param collectorEntityId collectorEntityId * @param pickupItemCount pickupItemCount * @see <a href="https://wiki.vg/index.php?title=Protocol&oldid=17873#Pickup_Item">https://wiki.vg/Protocol#Pickup_Item</a> */ @MinecraftPacket(id = 0x65, state = PacketState.PLAY, direction = PacketDirection.CLIENTBOUND) data class CollectPacket( val collectedEntityId: Int, // varint val collectorEntityId: Int, // varint val pickupItemCount: Int, // varint ) : ClientBoundPacket { companion object : PacketSerializer<CollectPacket> { override fun deserialize(input: MinecraftProtocolDeserializeInterface<*>): CollectPacket { val collectedEntityId = input.readVarInt() val collectorEntityId = input.readVarInt() val pickupItemCount = input.readVarInt() return CollectPacket(collectedEntityId, collectorEntityId, pickupItemCount) } override fun serialize(output: MinecraftProtocolSerializeInterface<*>, value: CollectPacket) { output.writeVarInt(value.collectedEntityId) output.writeVarInt(value.collectorEntityId) output.writeVarInt(value.pickupItemCount) } } }
0
Kotlin
1
4
3491d690689369264101853861e1d5a572cde24f
1,559
PacketLib
MIT License
app/src/main/java/com/fanstaticapps/randomticker/extensions/ActivityExtensions.kt
carvaq
300,246,718
false
null
package com.fanstaticapps.randomticker.extensions import android.app.Activity import android.app.KeyguardManager import android.view.LayoutInflater import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.viewbinding.ViewBinding inline fun <T : ViewBinding> AppCompatActivity.viewBinding( crossinline bindingInflater: (LayoutInflater) -> T ) = lazy(LazyThreadSafetyMode.NONE) { bindingInflater.invoke(layoutInflater) } fun Activity.turnScreenOnAndKeyguardOff() { if (isAtLeastO_MR1()) { setShowWhenLocked(true) setTurnScreenOn(true) } else { window.addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON ) } ContextCompat.getSystemService(this, KeyguardManager::class.java) ?.requestDismissKeyguard(this@turnScreenOnAndKeyguardOff, null) } fun Activity.turnScreenOffAndKeyguardOn() { if (isAtLeastO_MR1()) { setShowWhenLocked(false) setTurnScreenOn(false) } else { window.clearFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON ) } }
0
Kotlin
0
1
7882c81a7e5663e0ab63f968d0db0ccc616b62ba
1,334
random-ticker
Apache License 2.0
android/NewsAN/app/src/main/java/com/djupbyte/newsan/pdf/sharePdf.kt
iampranabray
678,745,966
false
{"Kotlin": 75257, "Swift": 73995, "HTML": 3414, "Ruby": 371}
package com.djupbyte.newsan.pdf import android.content.Context import android.content.Intent import android.net.Uri fun sharePdf(context: Context, uri: Uri) { val shareIntent = Intent().apply { action = Intent.ACTION_SEND type = "application/pdf" putExtra(Intent.EXTRA_STREAM, uri) } context.startActivity(Intent.createChooser(shareIntent, "Share PDF")) }
0
Kotlin
0
4
7ade1a6a379d25cafec06f4f9ad29ea0fe29eb71
394
NewsAN
MIT License
src/ClasesObjetos/Song.kt
DavidMerchan93
877,439,790
false
{"Kotlin": 8685}
package ClasesObjetos class Song( private val title: String, private val artist: String ) { private val artistUpper = artist.uppercase() private var duration: Int = 0 constructor( title: String, artist: String, duration: Int ) : this(title, artist) { this.duration = duration } init { println("Song $title created") } fun play() { println("Playing $title - $artistUpper, duration: $duration") } fun stop() { println("Stopped $title") } }
0
Kotlin
0
0
b1be223fb92f2ed9ad486ac915b98a645d16b75e
552
SolidPOO
MIT License
app/src/test/java/com/example/chessgame/CanKnightMoveUnitTest.kt
Souviksamanta34
583,057,229
false
{"Kotlin": 39466, "Java": 35438}
package com.example.chessgame import org.junit.Test import org.junit.Assert.* class CanKnightMoveUnitTest { @Test fun canKnightMove_singlePiece(){ ChessGame2.ChessGame.clear() ChessGame2.ChessGame.addPiece(ChessPiece(3,3, ChessPlayer.WHITE, Chessman.KNIGHT, -1)) println(ChessGame2.ChessGame) assertTrue(ChessGame2.ChessGame.canKnightMove(Square(3,3), Square(5,4))) assertTrue(ChessGame2.ChessGame.canKnightMove(Square(3,3),Square(4,5))) } }
0
Kotlin
0
1
1bfb89dafe7d907b9086e2dfd3dfb0bb5fdf930d
497
Chess
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/core/factories/AdapterFactory.kt
zhengweisk
198,141,030
true
{"Kotlin": 857264, "Ruby": 4839}
package io.horizontalsystems.bankwallet.core.factories import android.content.Context import io.horizontalsystems.bankwallet.core.* import io.horizontalsystems.bankwallet.core.utils.AddressParser import io.horizontalsystems.bankwallet.entities.CoinType class AdapterFactory( private val context: Context, private val appConfigProvider: IAppConfigProvider, private val ethereumKitManager: IEthereumKitManager, private val feeRateProvider: IFeeRateProvider) { fun adapterForCoin(wallet: Wallet): IAdapter? = when (wallet.coin.type) { is CoinType.Bitcoin -> BitcoinAdapter(wallet, appConfigProvider.testMode, feeRateProvider) is CoinType.BitcoinCash -> BitcoinCashAdapter(wallet, appConfigProvider.testMode, feeRateProvider) is CoinType.Dash -> DashAdapter(wallet, appConfigProvider.testMode, feeRateProvider) is CoinType.Ethereum -> { val addressParser = AddressParser("ethereum", true) EthereumAdapter(wallet, ethereumKitManager.ethereumKit(wallet), addressParser, feeRateProvider) } is CoinType.Erc20 -> { val addressParser = AddressParser("ethereum", true) Erc20Adapter(context, wallet, ethereumKitManager.ethereumKit(wallet), wallet.coin.type.decimal, wallet.coin.type.fee, wallet.coin.type.address, addressParser, feeRateProvider) } is CoinType.Eos -> null } fun unlinkAdapter(adapter: IAdapter) { when (adapter) { is EthereumBaseAdapter -> { ethereumKitManager.unlink() } } } }
0
Kotlin
0
0
64dc8d4e9a00c0fecf8dd612f56480f85e236077
1,602
unstoppable-wallet-android
MIT License
app/src/main/java/com/pt/pro/gallery/fasten/PictureBrowserFasten.kt
OmAr-Kader
674,357,483
false
{"Kotlin": 2780433}
package com.pt.pro.gallery.fasten data class PictureBrowserFasten( val root_: com.sothree.slidinguppanel.SlidingUpPanelLayout, val emptyFrame: android.widget.FrameLayout, val imagePager: androidx.viewpager2.widget.ViewPager2, val head: android.widget.FrameLayout, val headInner: androidx.constraintlayout.widget.ConstraintLayout, val pagerMenu: com.pt.common.moderator.over.ResizeImageView, val picName: androidx.appcompat.widget.AppCompatTextView, val unLockImage: com.pt.common.moderator.touch.TouchImageView, val rotationBarCard: androidx.cardview.widget.CardView, val rotationBarProgressBar: androidx.core.widget.ContentLoadingProgressBar, val headDown: android.widget.FrameLayout, val headOptions: androidx.constraintlayout.widget.ConstraintLayout, val videoDuration: androidx.appcompat.widget.AppCompatTextView, val currentDuration: android.widget.Chronometer, val floatingVideo: com.pt.common.moderator.over.ResizeImageView, val isFavorite: com.pt.common.moderator.over.ResizeImageView, val editActivity: com.pt.common.moderator.over.ResizeImageView, val rotateScreen: com.pt.common.moderator.over.ResizeImageView, val lockBrowser: com.pt.common.moderator.over.ResizeImageView, val lowerVideoOptions: android.widget.FrameLayout, val seekBar: androidx.appcompat.widget.AppCompatSeekBar, ) : androidx.viewbinding.ViewBinding { override fun getRoot(): com.sothree.slidinguppanel.SlidingUpPanelLayout = root_ }
0
Kotlin
0
0
fe57fe5a4029119ac287ab8d3d4b5ccfc05af3a0
1,503
PT-All-Pro
Apache License 2.0
fluentui_notification/src/main/java/com/microsoft/fluentui/tokenized/notification/Banner.kt
microsoft
257,221,908
false
{"Kotlin": 3021107, "Shell": 8996}
package com.microsoft.fluentui.tokenized.notification import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.text.ClickableText import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextStyle import com.microsoft.fluentui.theme.FluentTheme import com.microsoft.fluentui.theme.token.ControlTokens import com.microsoft.fluentui.theme.token.FluentIcon import com.microsoft.fluentui.theme.token.Icon import com.microsoft.fluentui.theme.token.controlTokens.BannerInfo import com.microsoft.fluentui.theme.token.controlTokens.BannerTokens /** * A Banner displays a prominent message and related actions for users to address it. Banners are dismissed by the user. * Banners are used to inform users about important changes or persistent conditions. They are non-modal, meaning users can either interact or ignore them, and continue with their task. * * @param text The text to be displayed in the banner. * @param modifier The modifier to be applied to the component. * @param isTextCentered Whether the text should be centered or not. Text is centered when there is no leading icon, action button, or accessory buttons. * @param leadingIcon The icon to be displayed before the text. * @param actionButtonOnClick The callback to be invoked when the action button is clicked. * @param actionButtonText The text to be displayed on the action button. ActionButtonIcon will be replaced when this is set. * @param actionButtonIcon The icon to be displayed on the action button. ActionButtonText should not be set to display the icon. * @param accessoryTextButton1 The text to be displayed on the first accessory button. * @param accessoryTextButton2 The text to be displayed on the second accessory button. * @param accessoryTextButton1OnClick The callback to be invoked when the first accessory button is clicked. * @param accessoryTextButton2OnClick The callback to be invoked when the second accessory button is clicked. * @param bannerTokens The tokens to be used to customize the component. */ @Composable fun Banner( text: String, modifier: Modifier = Modifier, isTextCentered: Boolean = false, leadingIcon: FluentIcon? = null, actionButtonOnClick: (() -> Unit)? = null, actionButtonText: String? = null, actionButtonIcon: FluentIcon? = null, accessoryTextButton1: String? = null, accessoryTextButton2: String? = null, accessoryTextButton1OnClick: (() -> Unit)? = null, accessoryTextButton2OnClick: (() -> Unit)? = null, bannerTokens: BannerTokens? = null, ) { val tokens = bannerTokens ?: FluentTheme.controlTokens.tokens[ControlTokens.ControlType.BannerControlType] as BannerTokens val actionButton1Enabled = accessoryTextButton1 != null && accessoryTextButton1OnClick != null val actionButton2Enabled = accessoryTextButton2 != null && accessoryTextButton2OnClick != null val bannerInfo = BannerInfo(actionButton1Enabled || actionButton2Enabled) var centerText = false if (isTextCentered && leadingIcon == null && actionButtonIcon == null && actionButtonText == null && !actionButton1Enabled && !actionButton2Enabled) { centerText = true } Box( modifier = modifier .background(tokens.backgroundColor(bannerInfo = bannerInfo)) .fillMaxWidth() ) { Column( modifier = Modifier.padding(tokens.padding(bannerInfo = bannerInfo)), horizontalAlignment = Alignment.CenterHorizontally ) { Row(verticalAlignment = Alignment.CenterVertically) { if (leadingIcon != null) { Icon( icon = leadingIcon, tint = tokens.leadingIconColor(bannerInfo = bannerInfo), modifier = Modifier.size( tokens.leadingIconSize( bannerInfo = bannerInfo ) ) ) } Spacer(modifier = Modifier.width(tokens.leadingIconAndTextSpacing(bannerInfo = bannerInfo))) BasicText( modifier = Modifier.weight(1f, !centerText), text = text, style = TextStyle(color = tokens.textColor(bannerInfo = bannerInfo)).merge( tokens.textTypography( bannerInfo = bannerInfo ) ) ) Spacer(modifier = Modifier.width(tokens.textAndActionButtonSpacing(bannerInfo = bannerInfo))) if (actionButtonOnClick != null) { if (actionButtonText != null) { ClickableText( text = AnnotatedString(actionButtonText), onClick = { actionButtonOnClick() }, style = TextStyle(color = tokens.actionButtonColor(bannerInfo = bannerInfo)).merge( tokens.actionButtonTextTypography( bannerInfo = bannerInfo ) ) ) } else if (actionButtonIcon != null) { Icon( icon = actionButtonIcon, modifier = Modifier .clickable(onClick = { actionButtonOnClick() }) .size(tokens.actionIconSize(bannerInfo = bannerInfo)), tint = tokens.actionIconColor( bannerInfo = bannerInfo ) ) } } } if (actionButton1Enabled || actionButton2Enabled) { Spacer(modifier = Modifier.height(tokens.textAndAccessoryButtonSpacing(bannerInfo = bannerInfo))) } Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { if (actionButton1Enabled) { ClickableText( text = AnnotatedString(accessoryTextButton1!!), style = TextStyle(color = tokens.actionButtonColor(bannerInfo = bannerInfo)).merge( tokens.actionButtonTextTypography( bannerInfo = bannerInfo ) ), onClick = { if (accessoryTextButton1OnClick != null) { accessoryTextButton1OnClick() } }) Spacer(modifier = Modifier.width(tokens.accessoryActionButtonsSpacing(bannerInfo = bannerInfo))) } if (actionButton2Enabled) { ClickableText( text = AnnotatedString(accessoryTextButton2!!), style = TextStyle(color = tokens.actionButtonColor(bannerInfo = bannerInfo)).merge( tokens.actionButtonTextTypography( bannerInfo = bannerInfo ) ), onClick = { if (accessoryTextButton2OnClick != null) { accessoryTextButton2OnClick() } }) } } } } }
25
Kotlin
103
574
851a4989a4fce5db50a1818aa4121538c1fb4ad9
8,322
fluentui-android
MIT License
app/src/main/java/com/alienspace/moviedb/movielist/domain/repo/MovieListRepo.kt
santhosh-anbazhagan
818,302,254
false
{"Kotlin": 50205}
package com.alienspace.moviedb.movielist.domain.repo import com.alienspace.moviedb.movielist.domain.model.Movie import com.alienspace.moviedb.movielist.utils.Resource import kotlinx.coroutines.flow.Flow interface MovieListRepo { suspend fun getMovieList( page:Int, category:String, forceFetchFomRemote:Boolean ):Flow<Resource<List<Movie>>> suspend fun getMovie(id:Int):Flow<Resource<Movie>> }
0
Kotlin
0
0
370e3703ccc720339a8d01acb5f8edb13ba6c6bc
432
MovieDB
MIT License
presentation/src/commonMain/kotlin/ireader/presentation/ui/core/theme/AppColors.kt
kazemcodes
540,829,865
true
{"Kotlin": 2179459}
package ireader.presentation.ui.core.theme import androidx.compose.material3.ColorScheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Shapes import androidx.compose.material3.Typography import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.Stable import androidx.compose.runtime.remember import androidx.compose.runtime.staticCompositionLocalOf import ireader.domain.models.theme.ExtraColors /** * All the application colors from both [MaterialTheme.colorScheme] and [ExtraColors] which can be * accessed through this class. */ @Stable @Suppress("unused") class AppColors( private val materialColors: ColorScheme, private val extraColors: ExtraColors, ) { val primary get() = materialColors.primary val primaryContainer get() = materialColors.primaryContainer val secondary get() = materialColors.secondary val secondaryContainer get() = materialColors.secondaryContainer val background get() = materialColors.background val surface get() = materialColors.surface val error get() = materialColors.error val onPrimary get() = materialColors.onPrimary val onSecondary get() = materialColors.onSecondary val onBackground get() = materialColors.onBackground val onSurface get() = materialColors.onSurface val onError get() = materialColors.onError val bars get() = extraColors.bars val onBars get() = extraColors.onBars val isBarLight get() = extraColors.isBarLight companion object { val current: AppColors @Composable @ReadOnlyComposable get() = LocalAppColors.current } } /** * Composable that provides the [LocalAppColors] composition to children composables with the * [materialColors] and [extraColors] provided. */ @Composable fun AppColors( materialColors: ColorScheme, extraColors: ExtraColors, typography: Typography, shape: Shapes, content: @Composable () -> Unit, ) { val rememberedCustomColors = remember { extraColors }.apply { updateFrom(extraColors) } val rememberedAppColors = remember { AppColors(materialColors, rememberedCustomColors) } MaterialTheme( colorScheme = materialColors, typography = typography, shapes = shape, ) { CompositionLocalProvider( LocalAppColors provides rememberedAppColors, content = content ) } } private val LocalAppColors = staticCompositionLocalOf<AppColors> { error("The AppColors composable must be called before usage") }
0
Kotlin
0
6
b6b2414fa002cec2aa0d199871fcfb4c2e190a8f
2,677
IReader
Apache License 2.0
app/src/main/java/com/lolo/io/onelist/widget/SimpleListWidget.kt
newhinton
234,555,103
true
{"Kotlin": 89806}
package com.lolo.io.onelist.widget import android.app.Activity import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.util.Log import android.widget.RemoteViews import com.lolo.io.onelist.PersistenceHelper import com.lolo.io.onelist.R /** * Implementation of App Widget functionality. * App Widget Configuration implemented in [SimpleListWidgetConfigureActivity] */ class SimpleListWidget : AppWidgetProvider() { companion object{ private val APPWIDGET_EXTRA = "appwidgetid" private val TAG: String = "SimpleListWidget" val NEXT = "next_action" val PREV = "previous_action" val UPDATE_ACTION = "update_action" val CONSUME_UNUSED = "CONSUME_UNUSED" val PREFERENCE = "appWidgetId_preference" } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } override fun onDeleted(context: Context, appWidgetIds: IntArray) { // When the user deletes the widget, delete the preference associated with it. for (appWidgetId in appWidgetIds) { //deleteTitlePref(context, appWidgetId) } } override fun onEnabled(context: Context) { // Enter relevant functionality for when the first widget is created } override fun onDisabled(context: Context) { // Enter relevant functionality for when the last widget is disabled } override fun onReceive(context: Context?, intent: Intent) { super.onReceive(context, intent) //add this line val p = PersistenceHelper(Activity()) context?.let { p.setC(it) } val maxlist = p.getAllLists().size-1 val appWidgetId = intent.getIntExtra(APPWIDGET_EXTRA,0) val appWidgetManager = AppWidgetManager.getInstance(context) var int = getListID(context!!, appWidgetId) if (intent.action == NEXT) { int++ if(int>maxlist){ int=0 } } else if (intent.action == PREV) { int-- if(int<0){ int=maxlist } } else if (intent.action == UPDATE_ACTION) { val id = intent.getLongExtra(WidgetListViewService.INTENT_STABLE_ID, 0) if(id > 0L){ var l = p.getAllLists()[int] for (i in l.items){ if(i.stableId==id){ i.done = !i.done Log.e(TAG, "Save: ${i.title} ${i.done}") } } p.saveList(l) } } else { Log.e(TAG, "unknown action: ${intent.action}") } if(intent.action == NEXT || intent.action == PREV){ Log.e(TAG, "action: ${intent.action}") } val sp = context?.getSharedPreferences(PREFERENCE,Context.MODE_PRIVATE) if (sp != null) { sp.edit().putInt(appWidgetId.toString(),int).apply() Log.e(TAG, "save listid($appWidgetId): $int") } Log.e(TAG, "got listid: ${getListID(context!!, appWidgetId)}") Log.e(TAG, "got listid: ${appWidgetManager.getAppWidgetIds(ComponentName(context, SimpleListWidget::class.java)).size}") val remoteViews = RemoteViews(context!!.packageName, R.layout.simple_list_widget) remoteViews.setTextViewText(R.id.appwidget_text, getTitle(context, appWidgetId)) val thisWidget = ComponentName(context, SimpleListWidget::class.java) val appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget) Log.e(TAG, "notify $appWidgetId") appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_view) Log.e(TAG, "update1") appWidgetManager.updateAppWidget(appWidgetId, remoteViews) Log.e(TAG, "update2") appWidgetManager.updateAppWidget(thisWidget, remoteViews) } fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) { val views = RemoteViews(context.packageName, R.layout.simple_list_widget) views.setOnClickPendingIntent(R.id.previousListButton, getPendingSelfIntent(context, PREV, appWidgetId)) views.setOnClickPendingIntent(R.id.nextListButton, getPendingSelfIntent(context, NEXT, appWidgetId)) views.setOnClickPendingIntent(R.id.main_layout, getPendingSelfIntent(context, CONSUME_UNUSED, appWidgetId)) views.setTextViewText(R.id.appwidget_text, getTitle(context, appWidgetId)) val intent = Intent(context, WidgetListViewService::class.java) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) views.setRemoteAdapter(R.id.list_view, intent) appWidgetManager.updateAppWidget(appWidgetId, views) val clickPendingIntentTemplate = getPendingSelfIntent(context, UPDATE_ACTION, appWidgetId) views.setPendingIntentTemplate(R.id.list_view, clickPendingIntentTemplate) appWidgetManager.updateAppWidget(appWidgetId, views) } fun getListID(context: Context, appWidgetId: Int): Int{ val sp = context.getSharedPreferences(PREFERENCE,Context.MODE_PRIVATE) return sp?.getInt(appWidgetId.toString(),0) ?: 0 } fun getTitle(context: Context, appWidgetId: Int): String{ return getTitleID(context, getListID(context, appWidgetId)) } fun getTitleID(context: Context, id: Int): String{ val p = PersistenceHelper(Activity()) p.setC(context) return p.getAllLists()[id].title } fun getPendingSelfIntent(context: Context, action: String, id: Int): PendingIntent? { val intent = Intent(context, SimpleListWidget::class.java) intent.action = action intent.putExtra(APPWIDGET_EXTRA, id) return PendingIntent.getBroadcast(context, 0, intent, 0) } }
0
Kotlin
0
1
401384430b0b64537347f7704d8f24aeacf8b795
6,204
OneList
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/ToolsKitchen.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.ToolsKitchen: ImageVector get() { if (_toolsKitchen != null) { return _toolsKitchen!! } _toolsKitchen = Builder(name = "ToolsKitchen", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 3.0f) horizontalLineToRelative(8.0f) lineToRelative(-1.0f, 9.0f) horizontalLineToRelative(-6.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.0f, 18.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(-2.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0f, 3.0f) verticalLineToRelative(12.0f) horizontalLineToRelative(-5.0f) curveToRelative(-0.023f, -3.681f, 0.184f, -7.406f, 5.0f, -12.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0f, 15.0f) verticalLineToRelative(6.0f) horizontalLineToRelative(-1.0f) verticalLineToRelative(-3.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(8.0f, 12.0f) lineToRelative(0.0f, 6.0f) } } .build() return _toolsKitchen!! } private var _toolsKitchen: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
3,421
compose-icon-collections
MIT License
src/view/dialogs/BluetoothConnectionModal.kt
Penguin-Dream-Team
312,890,456
false
{"Kotlin": 84543}
package view.dialogs import controllers.Store import javafx.geometry.Pos import javafx.scene.image.Image import javafx.scene.paint.Color import javafx.scene.text.FontWeight import tornadofx.* import utils.generateQrCode class BluetoothConnectionModal() : View("PenguBank | Connect to this Bluetooth Server") { private val store: Store by inject() override val root = borderpane { prefWidth = 580.0 top = vbox(5) { paddingVertical = 20.0 paddingHorizontal = 40.0 style { backgroundColor += Color.WHITE borderColor += box(Color.TRANSPARENT, Color.TRANSPARENT, c("#00000033"), Color.TRANSPARENT) } label("Connect to this Bluetooth Device") { style { fontSize = 18.px fontWeight = FontWeight.BOLD } } label { isWrapText = true style { fontSize = 14.px } text += "Scan this QRCode to start a Bluetooth connection and confirm your pending transactions on your smartphone application." } } center = vbox { paddingTop = 20.0 paddingHorizontal = 40.0 alignment = Pos.CENTER form { fieldset { imageview(Image(generateQrCode(store.user.email.valueSafe), 320.0, 320.0, true, true)) } } } bottom = buttonbar { paddingHorizontal = 40.0 paddingVertical = 25.0 style { backgroundColor += Color.WHITE borderColor += box(c("#00000033"), Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT) } } } }
0
Kotlin
0
0
79d85a99ca99529116e8ca5e7f20571b8b6b3f43
1,842
PenguBank-Desktop
MIT License
grundlagen-tag-19-packages-und-library-functions-just1984/Aufgabe4/src/4_SeitenlaengeEinesQuadrats.kt
just1984
639,436,580
false
null
import kotlin.math.sqrt fun main() { seitenLaenge() } fun seitenLaenge() { println("Bitte gebe die Fläche eines Quadrats ein (Double).") val flaeche = readln().toDouble() val seitenlaenge = sqrt(flaeche) println("Die Seitenlaenge ist: $seitenlaenge") }
0
Kotlin
0
0
3b6a84bb526f2c2151fe761526bdb1253f343df1
271
school_progress_kotlin
MIT License
feature/currency-picker/src/main/kotlin/com/kevlina/budgetplus/feature/currency/picker/CurrencyUiState.kt
kevinguitar
517,537,183
false
{"Kotlin": 686482}
package com.kevlina.budgetplus.feature.currency.picker import androidx.compose.runtime.Immutable @Immutable data class CurrencyUiState( val name: String, val currencyCode: String, val symbol: String, val isSelected: Boolean, )
2
Kotlin
0
9
9c964e063efdf797f84f58fcc3e8b17da75f8309
244
budgetplus-android
MIT License
app/src/main/java/com/ricardaparicio/cryptodemo/features/common/domain/model/FiatCurrency.kt
RicardAparicio
455,742,209
false
{"Kotlin": 137761}
/* * Copyright 2022 Ricard Aparicio * 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.ricardaparicio.cryptodemo.features.common.domain.model enum class FiatCurrency { Eur, Usd }
1
Kotlin
1
2
d1613dd61f299221f71f0607e65fdb54ff89b6bc
706
CryptoDemo
Apache License 2.0
app/src/main/java/com/alyndroid/decadeofmovies/domain/usecase/GetMovieImagesUseCaseImpl.kt
Alinasser96
348,125,632
false
null
package com.alyndroid.decadeofmovies.domain.usecase import com.alyndroid.decadeofmovies.domain.model.ImageWrapperResponse import com.alyndroid.decadeofmovies.domain.repositories.DetailsRepository import javax.inject.Inject class GetMovieImagesUseCaseImpl @Inject constructor(private val detailsRepository: DetailsRepository) : GetMovieImagesUseCase { override suspend fun invoke(query: String): ImageWrapperResponse = detailsRepository.getMovieImage(query) }
0
Kotlin
1
1
8d2a7477f199840e8d880c1d682ae1d0d3bba585
472
DecadeOfMovies
The Unlicense
app/src/main/java/com/xin/lovewallpaper/presenter/MainPresenter.kt
coolxinxin
277,076,332
false
null
/* * Copyright 2020 Leo * 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.xin.lovewallpaper.presenter import com.xin.lovewallpaper.base.BasePresenter import com.xin.lovewallpaper.contract.MainContract import com.xin.lovewallpaper.http.OnHttpListener import com.xin.lovewallpaper.http.getContentData import com.xin.lovewallpaper.http.parseContentData import org.jsoup.nodes.Document /** * * █████▒█ ██ ▄████▄ ██ ▄█▀ ██████╗ ██╗ ██╗ ██████╗ * ▓██ ▒ ██ ▓██▒▒██▀ ▀█ ██▄█▒ ██╔══██╗██║ ██║██╔════╝ * ▒████ ░▓██ ▒██░▒▓█ ▄ ▓███▄░ ██████╔╝██║ ██║██║ ███╗ * ░▓█▒ ░▓▓█ ░██░▒▓▓▄ ▄██▒▓██ █▄ ██╔══██╗██║ ██║██║ ██║ * ░▒█░ ▒▒█████▓ ▒ ▓███▀ ░▒██▒ █▄ ██████╔╝╚██████╔╝╚██████╔╝ * ▒ ░ ░▒▓▒ ▒ ▒ ░ ░▒ ▒ ░▒ ▒▒ ▓▒ ╚═════╝ ╚═════╝ ╚═════╝ * ░ ░░▒░ ░ ░ ░ ▒ ░ ░▒ ▒░ * ░ ░ ░░░ ░ ░ ░ ░ ░░ ░ * ░ ░ ░ ░ ░ *@author : Leo *@date : 2020/7/4 10:26 *@since : <EMAIL> *@desc : */ class MainPresenter : BasePresenter<MainContract.View>(), MainContract.Presenter { override fun getContent(page: Int) { getContentData(page, object : OnHttpListener { override fun onSuccess(document: Document) { parseContentData(document) } override fun onError(errorMsg: String) { getView()?.showShortToast(errorMsg) } }) } }
0
Kotlin
0
0
37baeb64c49bf2d9a5f7e0ab0103a505cb843def
1,937
LoveWallpaper
Apache License 2.0
src/main/kotlin/io/ipfs/kotlin/http4k/Http4kClientCommands.kt
GustaveNimant
240,869,379
false
null
package io.ipfs.kotlin.http4k import kotlin.system.exitProcess import io.ipfs.kotlin.defaults.* import io.ipfs.kotlin.url.* import io.ipfs.kotlin.* import java.io.File import java.util.Stack import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import org.http4k.client.ApacheClient import org.http4k.client.JavaHttpClient import org.http4k.client.OkHttp import org.http4k.core.Body import org.http4k.core.ContentType import org.http4k.core.Filter import org.http4k.core.HttpHandler import org.http4k.core.Method import org.http4k.core.Method.DELETE import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.MultipartFormBody import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.Status.Companion.OK import org.http4k.core.body.form import org.http4k.core.getFirst import org.http4k.core.then import org.http4k.core.toParametersMap import org.http4k.core.with import org.http4k.filter.CachingFilters import org.http4k.filter.DebuggingFilters.PrintRequestAndResponse import org.http4k.filter.ServerFilters import org.http4k.hamkrest.hasStatus import org.http4k.lens.FormField import org.http4k.lens.Header import org.http4k.lens.LensFailure import org.http4k.lens.MultipartForm import org.http4k.lens.MultipartFormField import org.http4k.lens.MultipartFormFile import org.http4k.lens.Validator import org.http4k.lens.WebForm import org.http4k.lens.int import org.http4k.lens.multipartForm import org.http4k.lens.webForm import org.http4k.routing.ResourceLoader.Companion.Classpath import org.http4k.routing.bind import org.http4k.routing.path import org.http4k.routing.routes import org.http4k.routing.singlePageApp import org.http4k.routing.static import org.http4k.server.Http4kServer import org.http4k.server.Jetty import org.http4k.server.SunHttp import org.http4k.server.asServer fun http4kClientAsAFunction () { val (here, caller) = moduleHereAndCaller() entering(here, caller) // --args="-http4k client func" val request = Request(Method.GET, "https://xkcd.com/info.0.json") val client: HttpHandler = JavaHttpClient() println("$here: response ------>") val response = client(request) println(response) println("$here: <------ end of response") exiting(here) } fun http4kClientGetOfUri (uri: String) { val (here, caller) = moduleHereAndCaller() entering(here, caller) // Ex.: -http4k client get http://82.67.137.54/js/json/files/test.json" if(isTrace(here)) println ("$here: input uri '$uri'") val request = Request(Method.GET, uri) val client: HttpHandler = JavaHttpClient() println("$here: response ------>") val response = client(request) println(response) println("$here: <------ end of response") exiting(here) } fun http4kClientResponse () { val (here, caller) = moduleHereAndCaller() entering(here, caller) // Ex.: -http4k client response // HTTP clients are also HttpHandlers! val client: HttpHandler = OkHttp() val request = Request(GET, "http://localhost:9000/greet/Bob") if(isVerbose(here)){ println("$here: request starts here") println(request) println("$here: request ends here") } val response: Response = client(request) if(isVerbose(here)){ println("$here: response starts here") println(response) println("$here: response ends here") } val status = response.status if(isVerbose(here))println("$here: response status $status") if (! status.successful) { val description = status.description val code = status.code when(code) { 503 -> fatalErrorPrint("server were started ",description," run for example : -http4k server jetty start", here) else -> fatalErrorPrint("Response were successful ",description,"Check", here) } } // Produces: // Request to /api/greet/Bob took 1ms // HTTP/1.1 200 // cache-control: private, must-revalidate // content-length: 9 // date: Thu, 08 Jun 2017 13:01:13 GMT // expires: 0 // server: Jetty(9.3.16.v20170120) // // hello Bob exiting(here) } fun menuHttp4kClientOfWordStack(wor_s: Stack<String>) { val (here, caller) = moduleHereAndCaller() entering(here, caller) if(isTrace(here)) println ("$here: input wor_s '$wor_s'") // Ex.: -http4k client function // Ex.: -http4k client get http://82.67.137.54/js/json/files/test.json try { val wor = wor_s.pop() val wor_3 = threeFirstCharactersOfStringOfCaller(wor, here) if(isLoop(here)) println("$here: while wor '$wor'") when (wor_3) { "fun" -> {http4kClientAsAFunction()} "get" -> { val uri = wor_s.pop() http4kClientGetOfUri(uri) } "res" -> {http4kClientResponse()} else -> { fatalErrorPrint ("command were 'fun'ction or 'get' or'res'ponse","'$wor'", "Check input", here) } // else } // when (wor_3) } // try catch (e: java.util.EmptyStackException) { fatalErrorPrint ("command were -http4k client 'fun'ction or 'get' or 'res'ponse","no arguments", "Complete input", here) } exiting(here) } fun menuHttp4kClientUrlGetOfWordStack(wor_s: Stack<String>) { val (here, caller) = moduleHereAndCaller() entering(here, caller) // Same as http4kClientResponse // Needs to launch server first (with -http4k server jetty full) // Ex.: -http4k get port 9000 host localhost route /greet/Jules if(isTrace(here)) println ("$here: input wor_s '$wor_s'") if (wor_s.isEmpty()){ fatalErrorPrint ("command were -http4k get 'hos't or 'por't or 'rou'te ","no get arguments", "Check input", here) } /* Local variables */ var hosStr ="" var porStr ="" var rouStr ="" var done = false while (!done) { try { val wor = wor_s.pop() val wor_3 = threeFirstCharactersOfStringOfCaller(wor, here) if(isLoop(here)) println("$here: while wor '$wor'") when (wor_3) { "hel" -> { printHelpOfString("get ") } "hos" -> { hosStr = wor_s.pop() } "por" -> { porStr = wor_s.pop() } "rou" -> { rouStr = wor_s.pop() println("$here: when porStr '$porStr'") println("$here: when hosStr '$hosStr'") println("$here: when rouStr '$rouStr'") } else -> { fatalErrorPrint ("command were 'hos't or 'por't or 'rou'te ","'$wor'", "Check input", here) } // else } // when (wor_3) } // try catch (e: java.util.EmptyStackException) {done = true} // catch } // while // HTTP clients are also HttpHandlers! val client: HttpHandler = OkHttp() println("$here: client OkHttp started") println("client") val uri = "http://" + hosStr + ":" + porStr + rouStr if(isDebug(here)) println ("$here: uri '$uri'") val request = Request(GET, uri) val response: Response = client(request) println("$here: response") println(response) val pattern = Regex("Client Error: Connection Refused") if(pattern.containsMatchIn(response.toString())){ fatalErrorPrint("server were started","it is not","run for example : -http4k server jetty start", here) } exiting(here) }
0
Kotlin
0
0
beb37a6dd94e342d589047b89144467ff1e59a62
7,205
irp-kotlin-minichain
MIT License
ethereumkit/src/main/java/org/p2p/ethereumkit/internal/spv/net/handlers/BlockHeadersTaskHandler.kt
p2p-org
306,035,988
false
null
package org.p2p.ethereumkit.internal.spv.net.handlers import org.p2p.ethereumkit.internal.spv.core.* import org.p2p.core.wrapper.eth.helpers.RandomHelper import org.p2p.ethereumkit.internal.spv.models.BlockHeader import org.p2p.ethereumkit.internal.spv.net.IInMessage import org.p2p.ethereumkit.internal.spv.net.les.messages.BlockHeadersMessage import org.p2p.ethereumkit.internal.spv.net.les.messages.GetBlockHeadersMessage import org.p2p.ethereumkit.internal.spv.net.tasks.BlockHeadersTask class BlockHeadersTaskHandler(private val listener: Listener? = null) : ITaskHandler, IMessageHandler { interface Listener { fun didReceive(peer: IPeer, blockHeaders: List<BlockHeader>, blockHeader: BlockHeader, reverse: Boolean) } private val tasks: MutableMap<Long, BlockHeadersTask> = HashMap() override fun perform(task: ITask, requester: ITaskHandlerRequester): Boolean { if (task !is BlockHeadersTask) { return false } val requestId = RandomHelper.randomLong() tasks[requestId] = task val message = GetBlockHeadersMessage(requestID = requestId, blockHeight = task.blockHeader.height, maxHeaders = task.limit, reverse = if (task.reverse) 1 else 0) requester.send(message) return true } override fun handle(peer: IPeer, message: IInMessage): Boolean { if (message !is BlockHeadersMessage) { return false } val task = tasks[message.requestID] ?: return false listener?.didReceive(peer, message.headers, task.blockHeader, task.reverse) return true } }
8
Kotlin
16
28
71b282491cdafd26be1ffc412a971daaa9c06c61
1,649
key-app-android
MIT License
src/commonTest/kotlin/dev/evo/kafka/connect/restclient/ClientTests.kt
anti-social
166,968,756
false
null
package dev.evo.kafka.connect.restclient import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond import io.ktor.client.engine.mock.respondError import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.http.Url import io.ktor.http.headersOf import kotlin.test.Test import kotlin.test.assertEquals import kotlinx.coroutines.CoroutineScope expect fun runTest(block: suspend CoroutineScope.() -> Unit) class ClientTests { companion object { fun getClientWithResponse( expectedMethod: HttpMethod, expectPath: String, content: String, shouldCheckContentType: Boolean = false ): KafkaConnectClient { return KafkaConnectClient(Url("http://localhost:8083"), MockEngine { request -> assertEquals(expectedMethod, request.method) assertEquals(expectPath, request.url.encodedPath) assertEquals("application/json", request.headers["Accept"]) if (shouldCheckContentType) { assertEquals("application/json", request.headers["Content-type"]) } respond( content, headers = headersOf( HttpHeaders.ContentType, ContentType.Application.Json.toString() ) ) }) } } @Test fun testInfo() = runTest { val client = getClientWithResponse( HttpMethod.Get, "/", """{"version":"1.1","commit":"deadbeaf"}""" ) val info = client.info() assertEquals(info.version, "1.1") assertEquals(info.commit, "deadbeaf") } @Test fun testConnectors() = runTest { val client = getClientWithResponse( HttpMethod.Get, "/connectors", """["connector-1", "connector-2"]""" ) assertEquals( listOf("connector-1", "connector-2"), client.connectors() ) } @Test fun testConnectorStatus() = runTest { val client = getClientWithResponse( HttpMethod.Get, "/connectors/hdfs-sink-connector/status", """ { "name": "hdfs-sink-connector", "connector": { "state": "RUNNING", "worker_id": "fakehost:8083" }, "tasks": [ { "id": 0, "state": "RUNNING", "worker_id": "fakehost:8083" }, { "id": 1, "state": "FAILED", "worker_id": "fakehost:8083", "trace": "org.apache.kafka.common.errors.RecordTooLargeException" } ] } """.trimIndent() ) assertEquals( ConnectorStatus( name = "hdfs-sink-connector", connector = ConnectorStatus.Connector( workerId = "fakehost:8083", state = ConnectorStatus.State.RUNNING ), tasks = listOf( ConnectorStatus.Task( id = 0, workerId = "fakehost:8083", state = ConnectorStatus.State.RUNNING ), ConnectorStatus.Task( id = 1, workerId = "fakehost:8083", state = ConnectorStatus.State.FAILED, trace = "org.apache.kafka.common.errors.RecordTooLargeException" ) ) ), client.status("hdfs-sink-connector") ) } @Test fun testPause() = runTest { val client = getClientWithResponse( HttpMethod.Put, "/connectors/hdfs-sink-connector/pause", "" ) assertEquals( client.pause("hdfs-sink-connector"), Unit ) } @Test fun testPauseWhenRebalance() = runTest { val client = KafkaConnectClient(Url("http://localhost:8083"), MockEngine { respondError( HttpStatusCode.Conflict, headers = headersOf( HttpHeaders.ContentType, ContentType.Application.Json.toString() ) ) }) val isExceptionRaised = try { client.pause("test-connector") false } catch (ex: KafkaConnectRebalanceException) { true } if (!isExceptionRaised) { throw AssertionError( "${KafkaConnectRebalanceException::class} exception was not raised" ) } } @Test fun testResume() = runTest { val client = getClientWithResponse( HttpMethod.Put, "/connectors/hdfs-sink-connector/resume", "" ) assertEquals( client.resume("hdfs-sink-connector"), Unit ) } }
0
Kotlin
0
0
1e4378cc76491d5a82a70222a2464c38955c2410
5,314
kafka-connect-rest-client
Apache License 2.0
src/main/kotlin/com/petukhovsky/snake/util/Direction.kt
arthur-snake
114,157,008
false
null
package com.petukhovsky.snake.util enum class Direction(val num: Int, val x: Int, val y: Int) { LEFT(0, 0, -1), UP(1, -1, 0), RIGHT(2, 0, 1), DOWN(3, 1, 0); fun opposite() = Direction.values()[num xor 2] } fun getDirectionFromInt(i: Int) = when (i) { in 0..3 -> Direction.values()[i] else -> throw IllegalArgumentException("bad direction"); }
4
Kotlin
0
3
e24da15441f6b6c673d1f1128ced494f4ed3d313
405
server
MIT License
app/src/main/java/cn/wearbbs/note/ui/activity/compose/MenuIconButton.kt
JackuXL
524,618,208
false
null
package cn.wearbbs.note.ui.activity.compose import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.runtime.Composable 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.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun MenuIconButton(text: String, icon: ImageVector, onClick: () -> Unit, background: Color) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Icon( imageVector = icon, contentDescription = text, modifier = Modifier .size(50.dp) .clip(CircleShape) .background(background) .clickable { onClick() } .padding(10.dp) ) Spacer(modifier = Modifier.height(3.dp)) Text( text = text, fontSize = 10.sp ) } }
0
Kotlin
0
7
29fdf57d7cc57a08cdbb5fc4293aa339f9807912
1,275
WearNote
Apache License 2.0
sqlite-open-helper/src/jvmMain/kotlin/exception/AndroidSqliteExceptions.jvm.kt
illarionov
769,429,996
false
null
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.exception public actual open class AndroidSqlException : RuntimeException { public actual constructor() : super() public actual constructor(message: String?) : super(message) public actual constructor(message: String?, cause: Throwable?) : super(message, cause) } public actual open class AndroidSqliteException : AndroidSqlException { public actual constructor() : super() public actual constructor(message: String?) : super(message) public actual constructor(message: String?, cause: Throwable?) : super(message, cause) } public actual open class AndroidSqliteDiskIoException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteDatabaseCorruptException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteConstraintException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteAbortException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteDoneException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteFullException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteMisuseException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteAccessPermException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteDatabaseLockedException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteTableLockedException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteReadOnlyDatabaseException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteCantOpenDatabaseException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteBlobTooBigException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteBindOrColumnIndexOutOfRangeException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteOutOfMemoryException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidSqliteDatatypeMismatchException : AndroidSqliteException { public actual constructor() : super() public actual constructor(message: String?) : super(message) } public actual open class AndroidOperationCanceledException : RuntimeException { public actual constructor() : super() public actual constructor(message: String?) : super(message) }
0
null
1
3
71b2bbf55fecf3a70ce130d8b902d8fa86ea61ab
4,197
wasm-sqlite-open-helper
Apache License 2.0
ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/utils/BluePrintEnhancerUtils.kt
YMalakov
171,684,193
true
{"Kotlin": 907808, "Java": 693579, "Shell": 39021, "Python": 18489, "Dockerfile": 2736, "Groovy": 2304, "PLSQL": 2262}
/* * Copyright © 2017-2018 AT&T Intellectual Property. * Modifications Copyright © 2019 Bell Canada. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onap.ccsdk.apps.controllerblueprints.service.utils import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException import org.onap.ccsdk.apps.controllerblueprints.core.data.ArtifactType import org.onap.ccsdk.apps.controllerblueprints.core.data.DataType import org.onap.ccsdk.apps.controllerblueprints.core.data.ErrorCode import org.onap.ccsdk.apps.controllerblueprints.core.data.NodeType import org.onap.ccsdk.apps.controllerblueprints.core.data.RelationshipType import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintRepoService import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintContext import org.springframework.http.codec.multipart.FilePart import org.springframework.util.StringUtils import reactor.core.publisher.Mono import java.io.File import java.io.IOException import java.nio.file.Path import java.util.* class BluePrintEnhancerUtils { companion object { fun populateDataTypes(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService, dataTypeName: String): DataType { val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) ?: bluePrintRepoService.getDataType(dataTypeName) ?: throw BluePrintException("couldn't get DataType($dataTypeName) from repo.") bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dataType) return dataType } fun populateRelationshipType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService, relationshipName: String): RelationshipType { val relationshipType = bluePrintContext.serviceTemplate.relationshipTypes?.get(relationshipName) ?: bluePrintRepoService.getRelationshipType(relationshipName) ?: throw BluePrintException("couldn't get RelationshipType($relationshipName) from repo.") bluePrintContext.serviceTemplate.relationshipTypes?.put(relationshipName, relationshipType) return relationshipType } fun populateNodeType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService, nodeTypeName: String): NodeType { val nodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(nodeTypeName) ?: bluePrintRepoService.getNodeType(nodeTypeName) ?: throw BluePrintException("couldn't get NodeType($nodeTypeName) from repo.") bluePrintContext.serviceTemplate.nodeTypes?.put(nodeTypeName, nodeType) return nodeType } fun populateArtifactType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService, artifactTypeName: String): ArtifactType { val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName) ?: bluePrintRepoService.getArtifactType(artifactTypeName) ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName) from repo.") bluePrintContext.serviceTemplate.artifactTypes?.put(artifactTypeName, artifactType) return artifactType } /** * This is a saveCBAFile method * take a [FilePart], transfer it to disk using a Flux of FilePart and return a [Mono] representing the CBA file name * * @param (filePart, targetDirectory) - the request part containing the file to be saved and the default directory where to save * @return a [Mono] String representing the result of the operation * @throws (BluePrintException, IOException) BluePrintException, IOException */ @Throws(BluePrintException::class, IOException::class) fun saveCBAFile(filePart: FilePart, targetDirectory: Path): Mono<String> { // Normalize file name val fileName = StringUtils.cleanPath(filePart.filename()) // Check if the file's extension is "CBA" if (StringUtils.getFilenameExtension(fileName) != "zip") { throw BluePrintException(ErrorCode.INVALID_FILE_EXTENSION.value, "Invalid file extension required ZIP") } // Change file name to match a pattern val changedFileName = UUID.randomUUID().toString() + ".zip" //String changedFileName = BluePrintFileUtils.Companion.getCBAGeneratedFileName(fileName, this.CBA_FILE_NAME_PATTERN); // Copy file to the target location (Replacing existing file with the same name) val targetLocation = targetDirectory.resolve(changedFileName) // if a file with the same name already exists in a repository, delete and recreate it val file = File(targetLocation.toString()) if (file.exists()) file.delete() file.createNewFile() return filePart.transferTo(file).thenReturn(changedFileName) } } }
0
Kotlin
0
0
01eff6bc81499a9e41395f6b384a5e893b366505
5,743
ccsdk-apps
Apache License 2.0
scratch/timing-issues-in-tests.kts
daveyarwood
15,570,045
false
{"HTML": 20861, "Ruby": 11908, "CSS": 10849, "Shell": 10243, "SCSS": 9223, "Kotlin": 1499}
import java.util.concurrent.LinkedBlockingQueue import kotlin.concurrent.thread typealias Test = () -> Boolean fun fail(msg : String) { println("FAIL: ${msg}") } fun retryUntilTrue(intervalMs : Long, timeoutMs : Long, test : Test) : Boolean { val deadline = System.currentTimeMillis() + timeoutMs while (System.currentTimeMillis() < deadline) { if (test()) { return true } Thread.sleep(intervalMs) } return false } fun assertEventuallyTrue( intervalMs : Long, timeoutMs : Long, failureMsg : String, test : Test ) { if (!retryUntilTrue(intervalMs, timeoutMs, test)) { fail(failureMsg); } } fun assertNeverTrue( intervalMs : Long, timeoutMs : Long, failureMsg : String, test : Test ) { if (retryUntilTrue(intervalMs, timeoutMs, test)) { fail(failureMsg); } } // assertEventuallyTrue(100, 1000, "nope", { false }) val iceCreamVotes = mutableMapOf<String, Int>() val queue = LinkedBlockingQueue<String>() // worker process thread { while (true) { val flavor = queue.take() val currentCount = iceCreamVotes.getOrElse(flavor) { 0 } iceCreamVotes[flavor] = currentCount + 1 } } queue.put("chocolate") // Thread.sleep(500) println(iceCreamVotes) fun voteCountedForRockyRoad() : Boolean { queue.put("rocky road") // Give the worker a little time to update the tally. Thread.sleep(5000) // Surely by now it's updated? val votesForRockyRoad = iceCreamVotes.getOrElse("rocky road") { 0 } return votesForRockyRoad > 0 }
0
HTML
1
6
a3f7e85a9535215a62b552858f40960d20a970ad
1,499
blog.djy.io
MIT License
app/src/main/java/com/lxy/kotlinwan/springTravel/risk/RiskCityAdapter.kt
luckylxyang
514,782,596
false
null
package com.lxy.kotlinwan.springTravel.risk import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import androidx.viewbinding.ViewBinding import com.lxy.kotlinwan.base.BaseAdapter import com.lxy.kotlinwan.databinding.ItemRiskCityBinding import com.lxy.kotlinwan.springTravel.risk.model.RiskArea import com.lxy.kotlinwan.springTravel.risk.model.RiskRegion class RiskCityAdapter() : BaseAdapter<RiskArea>() { override fun createViewBinding(inflater: LayoutInflater, parent: ViewGroup, viewType: Int): ViewBinding { Log.d("TAG", "createViewBinding: ") return ItemRiskCityBinding.inflate(inflater, parent, false) } override fun convert(viewHolder: ViewBindHolder, t: RiskArea, position: Int) { val holder = viewHolder.binding as ItemRiskCityBinding holder.itemTitle.text = t.area_name } }
0
Kotlin
0
0
476ad8d7ca52c66db2fdaafe743572d8a314dac6
871
kotlinWan
Apache License 2.0
app/src/main/java/co/tiagoaguiar/course/instagram/profile/util/ProfileAdapter.kt
BHM871
526,628,708
false
{"Kotlin": 163910}
package co.tiagoaguiar.course.instagram.profile.util import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import co.tiagoaguiar.course.instagram.R import co.tiagoaguiar.course.instagram.common.model.Post import com.bumptech.glide.Glide class ProfileAdapter( private val listener: (Post) -> Unit ) : RecyclerView.Adapter<ProfileAdapter.ProfileHolder>() { var list: List<Post> = mutableListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProfileHolder = ProfileHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_profile_grid, parent, false) ) override fun onBindViewHolder(holder: ProfileHolder, position: Int) { holder.bind(list[position]) } override fun getItemCount(): Int = list.size inner class ProfileHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(post: Post) = with(itemView) { val img = findViewById<ImageView>(R.id.item_profile_img_grid) Glide.with(context).load(post.photoUrl).into(img) img.setOnLongClickListener { listener.invoke(post) true } } } }
0
Kotlin
0
0
cba9539fa99b280f33f5bf8a9015decfecd70a4f
1,331
instagram
MIT License
definitions/src/test/kotlin/fledware/definitions/builtin/ObjectUpdaterLifecycleTest.kt
fledware
408,627,203
false
{"Kotlin": 545508}
package fledware.definitions.builtin import fledware.definitions.reader.gatherJar import fledware.definitions.tests.builder import fledware.definitions.tests.testJarPath import kotlin.test.Test import kotlin.test.assertContains class ObjectUpdaterLifecycleTest { @Test fun testBasicLoading() = builder(listOf(ObjectUpdaterLifecycle())) { builder -> builder.gatherJar("simpledefs".testJarPath.absolutePath) assertContains(builder.objectUpdater.selects.keys, "SomeNewSelectDirective") assertContains(builder.objectUpdater.operations.keys, "SomeNewOperationDirective") assertContains(builder.objectUpdater.predicates.keys, "SomeNewPredicateDirective") assertContains(builder.objectUpdater.predicates.keys, "SomeNewPredicateDirectiveCanNegate") } }
6
Kotlin
0
0
2422b5f3bce36d5e7ea5e0962e94f2f2bcd3997e
774
FledDefs
Apache License 2.0
domain/data/src/commonMain/kotlin/mehiz/abdallah/progres/data/daos/SubjectsDao.kt
abdallahmehiz
830,308,163
false
{"Kotlin": 449026, "Swift": 621}
package mehiz.abdallah.progres.data.daos import mehiz.abdallah.progres.data.db.ProgresDB import mehiz.abdallah.progres.data.db.SubjectTable class SubjectsDao( db: ProgresDB ) { private val queries = db.subjectTableQueries fun insert(subject: SubjectTable) { with(subject) { queries.insert( id = id, oofId = oofId, ofStringLatin = ofStringLatin, levelStringLatin = levelStringLatin, levelStringArabic = levelStringArabic, subjectId = subjectId, subjectStringLatin = subjectStringLatin, subjectStringArabic = subjectStringArabic, subjectCoefficient = subjectCoefficient, subjectCredit = subjectCredit, subjectCCCoefficient = subjectCCCoefficient, subjectCICoefficient = subjectCICoefficient, subjectExamCoefficient = subjectExamCoefficient, yearPeriodCode = yearPeriodCode ) } } fun getAllSubjects(): List<SubjectTable> { return queries.getAllSubjects().executeAsList() } fun deleteAllSubjects() { queries.deleteAllSubjects() } }
1
Kotlin
0
8
331d3c6c8caa126fdc7df033f2574cd3aa8f8e80
1,089
progres
MIT License
feature/settings/src/main/kotlin/com/najudoryeong/mineme/feature/story/navigation/SettingsNavigation.kt
NaJuDoRyeong
689,891,643
false
{"Kotlin": 313446}
package com.najudoryeong.mineme.feature.story.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavOptions import androidx.navigation.compose.composable import com.najudoryeong.mineme.feature.story.AccountScreen import com.najudoryeong.mineme.feature.story.SettingsRoute const val settingsNavigationRoute = "settings_route" fun NavController.navigateToSettings(navOptions: NavOptions? = null) { this.navigate(settingsNavigationRoute, navOptions) } fun NavGraphBuilder.settingsScreen() { composable( route = settingsNavigationRoute, ) { SettingsRoute() } }
2
Kotlin
0
0
7b1b46b14b8af6994cb86cb6ca844266a6429d68
666
mineme_AOS_new
Apache License 2.0
app/src/main/java/com/nvkhang96/fossilfileexplorer/feature_file_explorer/presentation/file_list/component/FileFolderItem.kt
nvkhang96
628,568,918
false
null
package com.nvkhang96.fossilfileexplorer.feature_file_explorer.presentation.file_list.component import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.InsertDriveFile import androidx.compose.material.icons.outlined.Folder import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import coil.compose.rememberAsyncImagePainter import com.nvkhang96.fossilfileexplorer.feature_file_explorer.domain.model.FileFolder import com.nvkhang96.fossilfileexplorer.core.util.DateUtils @Composable fun FileFolderItem( fileFolder: FileFolder, modifier: Modifier = Modifier, ) { Row( modifier = modifier .fillMaxWidth() .padding(8.dp), verticalAlignment = Alignment.CenterVertically ) { when { fileFolder.isDirectory -> { Icon( imageVector = Icons.Outlined.Folder, contentDescription = "Folder", modifier = Modifier.size(40.dp), tint = MaterialTheme.colors.primary, ) } fileFolder.isSupportedImage() -> { Image( painter = rememberAsyncImagePainter(model = fileFolder.path), contentDescription = null, modifier = Modifier.size(40.dp), contentScale = ContentScale.FillBounds ) } else -> { Icon( imageVector = Icons.Default.InsertDriveFile, contentDescription = "File", modifier = Modifier.size(40.dp), tint = MaterialTheme.colors.primary, ) } } Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier .fillMaxWidth() ) { Text( text = fileFolder.name, style = MaterialTheme.typography.body1.copy( fontWeight = FontWeight.Medium ), maxLines = 1, overflow = TextOverflow.Ellipsis ) Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = DateUtils.formatReadableDate(fileFolder.lastModified), style = MaterialTheme.typography.body2, color = Color.Gray, ) Text( text = if (fileFolder.isDirectory) fileFolder.readableChildrenCount else fileFolder.readableSize, style = MaterialTheme.typography.body2.copy( fontWeight = FontWeight.Medium ), color = Color.Gray, ) } Spacer(modifier = Modifier.height(8.dp)) Divider() } } }
0
Kotlin
0
0
f965c9b40c2b4bd76b3fede27ad0dd6a8aca4f8a
3,558
FossilFileExplorer
MIT License
kotlin/코틀린 완벽 가이드/080250/Chapter7/ForEachBlock.kt
devYSK
461,887,647
false
{"Java": 3507759, "JavaScript": 659549, "Kotlin": 563136, "HTML": 455168, "CSS": 446825, "Shell": 57444, "Groovy": 54414, "Batchfile": 47890, "Go": 26805, "Python": 9963, "Handlebars": 8554, "Makefile": 7837, "Vue": 5706, "TypeScript": 5172, "Dockerfile": 436, "Vim Snippet": 362, "Assembly": 278, "Procfile": 199}
import java.io.File fun main() { val file = File("data.bin") var sum = 0 file.forEachBlock { buffer, bytesRead -> (0 until bytesRead).forEach { sum += buffer[it] } } println(sum) }
1
null
1
1
7a7c6b1bab3dc2c84527f8c528b06b9408872635
199
study_repo
MIT License
app/src/main/java/com/perol/asdpl/pixivez/networks/RubySSLSocketFactory.kt
fangdawang
208,203,403
true
{"Batchfile": 1, "Shell": 1, "Markdown": 2, "Java Properties": 2, "Proguard": 1, "Kotlin": 129, "Java": 53}
/*MIT License Copyright (c) 2019 Perol_Notsfsssf 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.perol.asdpl.pixivez.networks import android.util.Log import java.net.InetAddress import java.net.Socket import javax.net.ssl.HttpsURLConnection import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory class RubySSLSocketFactory : SSLSocketFactory() { var hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier() private val conn: HttpsURLConnection? = null override fun getDefaultCipherSuites(): Array<String> { return arrayOf<String>() } override fun createSocket(plainSocket: Socket?, host: String?, port: Int, autoClose: Boolean): Socket { val address = plainSocket!!.inetAddress Log.d("address", address.hostAddress) if (autoClose) { plainSocket.close() } val sslSocketFactory = getDefault() val ssl = sslSocketFactory.createSocket(address, port) as SSLSocket ssl.enabledProtocols = ssl.supportedProtocols val session = ssl.session Log.i("!", "Protocol: " + session.protocol + " PeerHost: " + session.peerHost + " CipherSuite: " + session.cipherSuite); return ssl } override fun createSocket(p0: String?, p1: Int): Socket? { return null; } override fun createSocket(p0: String?, p1: Int, p2: InetAddress?, p3: Int): Socket? { return null; } override fun createSocket(p0: InetAddress?, p1: Int): Socket? { return null; } override fun createSocket(p0: InetAddress?, p1: Int, p2: InetAddress?, p3: Int): Socket? { return null; } override fun getSupportedCipherSuites(): Array<String> { return arrayOf<String>() }}
0
null
0
0
dc84b29b9b42ce4f78ef1c8354db4375c1028ae6
2,760
Pix-EzViewer
MIT License
app/src/main/code/entities/Recipes.kt
swetha3378
610,574,074
false
null
package com.example.cookingrecipes.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity(tableName = "Recipes") data class Recipes( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Int, @ColumnInfo(name = "recipeName") val recipeName: String, @ColumnInfo(name = "recipeImage") val recipeImage: String, @ColumnInfo(name = "isFavRecipe") val isFavRecipe: Boolean, @ColumnInfo(name = "rating") val rating: Float, @ColumnInfo(name = "shortDesc") val shortDesc: String, @ColumnInfo(name = "desc") val desc: String, @ColumnInfo(name = "ingredients") val ingredients: String, @ColumnInfo(name = "procedure") val procedure: String, @ColumnInfo(name = "cuisine") val cuisine: String, @ColumnInfo(name = "diet") val diet: String, ): Serializable
1
Kotlin
0
0
851492e5982d97ab04abbbf7eb80ce8df64e01a2
940
CookingRecipesApp-Kotlin-Room-MVVM-COI
MIT License
app/src/main/java/com/example/androiddevchallenge/ui/timer/TimerViewModel.kt
MarioNoll
344,232,315
false
null
/* * Copyright 2021 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.androiddevchallenge.ui.timer import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.androiddevchallenge.ui.timer.items.actions.TimerAction import com.example.androiddevchallenge.ui.timer.items.actions.TimerActionDisplayState import com.example.androiddevchallenge.ui.timer.items.countdown.CountdownInteractor import com.example.androiddevchallenge.ui.timer.items.countdown.CountdownState import com.example.androiddevchallenge.ui.timer.items.countdown.CountdownViewState import com.example.androiddevchallenge.ui.timer.items.countdown.formatCountdown import com.example.androiddevchallenge.ui.timer.items.time_picker.TimePickerInteractor import com.example.androiddevchallenge.ui.timer.items.time_picker.TimePickerListener import com.example.androiddevchallenge.ui.timer.items.time_picker.TimePickerState import com.example.androiddevchallenge.ui.timer.items.time_picker.picker.TimePickerViewState import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import kotlin.time.Duration internal class TimerViewModel( private val timePickerInteractor: TimePickerInteractor = TimePickerInteractor(), private val countdownInteractor: CountdownInteractor = CountdownInteractor() ) : ViewModel(), TimePickerListener by timePickerInteractor { private val timerActionState = MutableStateFlow<TimerAction?>(null) private val isCountdownVisibleState = MutableStateFlow(false) private var timerJob: Job? = null private val _state = MutableStateFlow(TimerState.DEFAULT) val state: StateFlow<TimerState> get() = _state init { viewModelScope.launch { combine( isCountdownVisibleState, timePickerInteractor.state, countdownInteractor.state, timerActionState ) { isCountdownVisible, timePickerState, countdownState, _ -> val timerActionDisplayState = if (timePickerState.input == Duration.ZERO) { TimerActionDisplayState.Hidden } else if (!isCountdownVisible) { TimerActionDisplayState.Idle } else if (countdownState.progress == 1F) { TimerActionDisplayState.Replay } else if (timerJob?.isActive == true) { TimerActionDisplayState.Active } else { TimerActionDisplayState.Paused } TimerState( timePickerViewState = timePickerState.toViewState(), countdownState = countdownState.toViewState(), isCountdownVisible = isCountdownVisible, timerActionDisplayState = timerActionDisplayState ) }.collect { _state.value = it } } } fun onTimerAction(type: TimerAction) { when (type) { TimerAction.Start -> start(initialize = _state.value.isTimePickerVisible) TimerAction.Pause -> pause() TimerAction.Stop -> stop() TimerAction.Replay -> start(initialize = true) } timerActionState.value = type } fun showTimerPicker() { timerJob?.cancel() isCountdownVisibleState.value = false } private fun start(initialize: Boolean) { if (initialize) { countdownInteractor.initialize(timePickerInteractor.state.value.input) } isCountdownVisibleState.value = true timerJob?.cancel() timerJob = viewModelScope.launch { countdownInteractor.start() } } private fun stop() { timerJob?.cancel() showTimerPicker() timePickerInteractor.reset() countdownInteractor.reset() } private fun pause() { timerJob?.cancel() } private fun CountdownState.toViewState() = CountdownViewState( progress = (elapsed / interval).toFloat(), countdown = (interval - elapsed).formatCountdown() ) private fun TimePickerState.toViewState() = TimePickerViewState( hours = input.inHours.format(), minutes = (input.inMinutes % 60).format(), seconds = (input.inSeconds % 60).format(), activeTimeUnit = activeTimeUnit ) private fun Double.format(): String = toInt() .let { if (it < 10) "0$it" else it.toString() } }
0
Kotlin
0
1
1fb62a66e42c4b0fdb8ed639badb79806bf0208d
5,219
android-dev-challenge-compose-week2
Apache License 2.0
src/main/kotlin/compiler/nodes/Node.kt
solkin
600,698,963
false
{"Kotlin": 86227}
package compiler.nodes import compiler.Context abstract class Node { open fun compile(ctx: Context): Type { throw NotImplementedError("Compile function for $this is not implemented") } }
0
Kotlin
0
3
33c72d7b7b24be9e48fd15ca281e016635cfed40
205
velo-lang
MIT License
infra/src/fanpoll/infra/database/jasync/JasyncConfig.kt
csieflyman
359,559,498
false
{"Kotlin": 785294, "JavaScript": 17435, "HTML": 6167, "PLpgSQL": 5563, "Dockerfile": 126}
/* * Copyright (c) 2024. fanpoll All rights reserved. */ package fanpoll.infra.database.jasync data class JasyncConfig( val jdbcUrl: String, val username: String, val password: String, val maxActiveConnections: Int, val maxIdleTime: Long, val connectionCreateTimeout: Long, val connectionTestTimeout: Long, val queryTimeout: Long? = null )
1
Kotlin
9
74
1a7d54115dbc42c6a02230f527d9ad56862b4a0b
375
multi-projects-architecture-with-Ktor
MIT License
infra/src/fanpoll/infra/database/jasync/JasyncConfig.kt
csieflyman
359,559,498
false
{"Kotlin": 785294, "JavaScript": 17435, "HTML": 6167, "PLpgSQL": 5563, "Dockerfile": 126}
/* * Copyright (c) 2024. fanpoll All rights reserved. */ package fanpoll.infra.database.jasync data class JasyncConfig( val jdbcUrl: String, val username: String, val password: String, val maxActiveConnections: Int, val maxIdleTime: Long, val connectionCreateTimeout: Long, val connectionTestTimeout: Long, val queryTimeout: Long? = null )
1
Kotlin
9
74
1a7d54115dbc42c6a02230f527d9ad56862b4a0b
375
multi-projects-architecture-with-Ktor
MIT License
post_api/android/app/src/main/kotlin/com/example/get_post_api/MainActivity.kt
CharmiGoswami
409,149,083
false
{"Rich Text Format": 14026518, "Dart": 526054, "HTML": 98365, "Swift": 25174, "Kotlin": 3473, "Ruby": 2684, "Objective-C": 1026}
package com.example.get_post_api import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Rich Text Format
2
0
8c50126943ebfe858cb321be727cbc46ea686f3d
129
Flutter
MIT License
mealkitary-domain/src/test/kotlin/com/mealkitary/reservation/domain/payment/service/CancelPaymentServiceTest.kt
le2sky
640,586,872
false
{"Kotlin": 290422}
package com.mealkitary.reservation.domain.payment.service import com.mealkitary.common.model.Money import com.mealkitary.reservation.domain.payment.Payment import com.mealkitary.reservation.domain.payment.PaymentGatewayService import com.mealkitary.reservation.domain.payment.PaymentStatus import com.mealkitary.reservation.domain.reservation.ReservationStatus import data.ReservationTestData import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.AnnotationSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.throwable.shouldHaveMessage import io.mockk.Called import io.mockk.every import io.mockk.mockk import io.mockk.verify class CancelPaymentServiceTest : AnnotationSpec() { private lateinit var paymentGatewayService: PaymentGatewayService @BeforeEach fun setUp() { paymentGatewayService = mockk<PaymentGatewayService>() } @Test fun `승인된 결제라면 결제를 취소할 수 있다`() { every { paymentGatewayService.cancel(any(), any()) } answers { } val cancelPaymentService = CancelPaymentService(paymentGatewayService) val payment = Payment.of( "abc", ReservationTestData.defaultReservation().withReservationStatus(ReservationStatus.NOTPAID).build(), Money.from(2000) ) payment.approve() cancelPaymentService.cancel(payment) payment.paymentStatus shouldBe PaymentStatus.CANCELED verify(exactly = 1) { paymentGatewayService.cancel(any(), "점주 측 예약 거부") } } @Test fun `이미 취소된 결제라면, 취소 요청을 시도하지 않는다`() { every { paymentGatewayService.cancel(any(), any()) } answers { } val cancelPaymentService = CancelPaymentService(paymentGatewayService) val payment = Payment.of( "abc", ReservationTestData.defaultReservation().withReservationStatus(ReservationStatus.NOTPAID).build(), Money.from(2000) ) payment.approve() payment.cancel() shouldThrow<IllegalStateException> { cancelPaymentService.cancel(payment) } shouldHaveMessage "이미 거절된 예약입니다." verify { paymentGatewayService wasNot Called } } }
3
Kotlin
0
2
fe3e6e2fb58f3516738ad140133c0704b790ed4c
2,189
mealkitary-server
Apache License 2.0
app/src/main/java/com/intact/moviesbox/ui/base/BaseActivity.kt
DevAnuragGarg
177,965,415
false
{"Kotlin": 195049}
package com.intact.moviesbox.ui.base import android.content.res.Configuration import android.widget.Toast import dagger.android.support.DaggerAppCompatActivity /** * Created by <NAME> on 19/03/19. * * Base activity that will be extended by all the activities * * DaggerAppCompatActivity: you don not need to use AndroidInjection.inject(this) in onCreate * Moreover you no need to extend the HasAndroidInjector, * @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> * override fun androidInjector(): AndroidInjector<Any> = androidInjector * This all is done in DaggerActivity * * Here we are checking what kind of night mode is enabled or disabled according to which we * are showing the toast to the user */ abstract class BaseActivity : DaggerAppCompatActivity() { // show dark theme enabled or not using toast fun showDarkThemeEnabled() { when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) { Configuration.UI_MODE_NIGHT_NO -> { Toast.makeText(this, "NIGHT MODE DISABLED", Toast.LENGTH_SHORT).show() } Configuration.UI_MODE_NIGHT_YES -> { Toast.makeText(this, "NIGHT MODE ENABLED", Toast.LENGTH_SHORT).show() } Configuration.UI_MODE_NIGHT_UNDEFINED -> { Toast.makeText(this, "NIGHT MODE DISABLED", Toast.LENGTH_SHORT).show() } } } }
0
Kotlin
5
14
6cfe0a54ff7936c1539b06130265cf270ad944cb
1,441
MovieBox
Apache License 2.0
persistence/src/main/java/br/com/movieapp/persistence/di/RoomModule.kt
gaxima
734,731,175
false
{"Kotlin": 198654, "Ruby": 46}
package br.com.movieapp.persistence.di import android.content.Context import androidx.room.Room import br.com.movieapp.persistence.MovieDataBase import br.com.movieapp.persistence.data.dao.MovieDao import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object RoomModule { @Provides @Singleton fun provideAppDataBase( @ApplicationContext context: Context ) = Room.databaseBuilder( context, MovieDataBase::class.java, "movie_database" ).build() @Provides @Singleton fun provideMovieDao(dataBase: MovieDataBase) : MovieDao { return dataBase.movieDao() } }
0
Kotlin
0
0
9f23970a46d07e36a47caf2aa0bad2f1ca1e9216
834
MovieApp
MIT License
androidApp/src/main/java/dev/johnoreilly/confetti/account/SignInView.kt
joreilly
436,024,503
false
null
package dev.johnoreilly.confetti.account import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInOptions import dev.johnoreilly.confetti.R import org.koin.compose.koinInject @Composable fun SignInRoute(onBackClick: () -> Unit) { Box( modifier = Modifier .fillMaxSize() ) { var error: String? by remember { mutableStateOf(null) } val launcher = rememberFirebaseAuthLauncher( onAuthComplete = { onBackClick() }, onAuthError = { it.printStackTrace() error = "Something went wrong" }, koinInject() ) val context = LocalContext.current Button( modifier = Modifier.align(Alignment.Center), onClick = { val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(context.getString(R.string.default_web_client_id)) .requestEmail() .build() val googleSignInClient = GoogleSignIn.getClient(context, gso) launcher.launch(googleSignInClient.signInIntent) } ) { Text(text = "Sign in with Google") } } }
29
Kotlin
14
223
78d0dcae0bfe4f51551f4ce223891bc99df30966
1,885
Confetti
Apache License 2.0
app/src/main/java/com/levis/nimblechallenge/data/repository/AuthRepositoryImpl.kt
LevisLuong
807,424,023
false
{"Kotlin": 158020}
package com.levis.nimblechallenge.data.repository import com.levis.nimblechallenge.core.utils.repoCall import com.levis.nimblechallenge.data.local.datastore.LocalDataSource import com.levis.nimblechallenge.data.network.Api import com.levis.nimblechallenge.data.network.dtos.LoginTokenDto import com.levis.nimblechallenge.data.network.request.ForgotPasswordRequest import com.levis.nimblechallenge.data.network.request.LoginRequest import com.levis.nimblechallenge.data.network.request.LogoutRequest import com.levis.nimblechallenge.data.network.response.ForgotPasswordResponse import com.levis.nimblechallenge.domain.repository.AuthRepository import javax.inject.Inject class AuthRepositoryImpl @Inject constructor( private val api: Api, private val localDataSource: LocalDataSource, ) : AuthRepository { override suspend fun login(payload: LoginRequest): LoginTokenDto = api.login(payload) .data .also { localDataSource.saveAccessToken(it.accessToken.orEmpty()) localDataSource.saveTokenType(it.tokenType.orEmpty()) localDataSource.saveRefreshToken(it.refreshToken.orEmpty()) } override suspend fun forgotPassword(payload: ForgotPasswordRequest): ForgotPasswordResponse { return repoCall { api.forgotPassword(payload) } } override suspend fun logout() { val tokenType = localDataSource.getTokenType() val accessToken = localDataSource.getAccessToken() api.logout( LogoutRequest( token = "$tokenType $accessToken" ) ) localDataSource.clearAll() } }
0
Kotlin
0
0
cb2e6ba5bb17d48d6e4732c0116ff125cab360c7
1,683
NimbleChallenge
Apache License 2.0
app/src/main/java/app/quiz/joaomartins/adapters/usersAdapters.kt
jlucas577
300,985,156
false
{"Kotlin": 20976}
package app.quiz.joaomartins.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import app.quiz.joaomartins.R import app.quiz.joaomartins.model.Users import kotlinx.android.synthetic.main.item_history.view.* class UsersAdapters(private val users: List<Users>) : RecyclerView.Adapter<UsersAdapters.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate( R.layout.item_history, parent, false ) return ViewHolder( view ) } override fun getItemCount() = users.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val user = users[position] val hitsPercent = user.hits.toInt() * 10 holder.name.text = user.user holder.hits.text = "Pontuação de $hitsPercent%" } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val name : TextView = itemView.name val hits : TextView = itemView.hits } }
0
Kotlin
0
1
f0b992e9125b675545eade01d14ca98036175185
1,192
DynaQuiz
MIT License
compiler/src/main/kotlin/com/r0adkll/kimchi/annotations/ContributesToAnnotation.kt
r0adkll
842,714,606
false
{"Kotlin": 208023, "Shell": 3091}
// Copyright (C) 2024 r0adkll // SPDX-License-Identifier: Apache-2.0 package com.r0adkll.kimchi.annotations import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSAnnotation import com.r0adkll.kimchi.util.KimchiException import com.r0adkll.kimchi.util.ksp.argumentAt import com.r0adkll.kimchi.util.ksp.isAnnotation import com.r0adkll.kimchi.util.ksp.valueAsClassName import com.r0adkll.kimchi.util.ksp.valueAsClassNameList import com.squareup.kotlinpoet.ClassName class ContributesToAnnotation private constructor( val scope: ClassName, override val replaces: List<ClassName>, ) : ReplaceableAnnotation { companion object { /** * Find the [ContributesTo] annotation on a given [annotated] element * that is scoped to [scope] * @param annotated The annotated element to pull from * @param scope The scope of the annotation we are looking for * @return the [ContributesToAnnotation] for the given scope, or throws [KimchiException] */ fun from(annotated: KSAnnotated, scope: ClassName): ContributesToAnnotation { annotated.annotations .filter { it.isAnnotation(ContributesTo::class) } .forEach { annotation -> val contributesToAnnotation = from(annotation) if (contributesToAnnotation.scope == scope) { return contributesToAnnotation } } throw KimchiException("Unable to find @ContributesTo annotation for $scope", annotated) } fun from(annotation: KSAnnotation): ContributesToAnnotation { val scope = annotation.argumentAt("scope", 0) ?.valueAsClassName ?: throw KimchiException("Unable to find `scope` on @ContributesMultibinding annotation", annotation.parent) val replaces = annotation.argumentAt("replaces", 2) ?.valueAsClassNameList ?: emptyList() return ContributesToAnnotation(scope, replaces) } } }
3
Kotlin
1
71
480a4963337cf42e3a5fd42b2918f5551a911791
1,934
kimchi
Apache License 2.0
app/src/main/java/com/z1/pokedex/feature/details/data/datasource/local/PokemonDetailsLocalDataSource.kt
zero1code
757,161,296
false
{"Kotlin": 245388}
package com.z1.pokedex.feature.details.data.datasource.local import kotlinx.coroutines.flow.Flow interface PokemonDetailsLocalDataSource { suspend fun getPokemonFavoritesName(userId: String): Flow<List<String>> }
0
Kotlin
0
7
320b1c045b313ce8ca419a12732b5d8926e9e7e9
218
pokedex-z1
Apache License 2.0
app/src/main/java/com/example/mytransactions/data/remote/TransactionRemoteDataSource.kt
zcufo123
463,680,121
false
{"Kotlin": 31968}
package com.example.mytransactions.data.remote import javax.inject.Inject class TransactionRemoteDataSource @Inject constructor( private val transactionService: TransactionService ): BaseDataSource() { suspend fun getAllTransactions() = getResult { transactionService.getAllTransactions() } }
0
Kotlin
0
0
52d22bfc68628cf94aa96f751b9a107a283bf6c0
303
MyTransactions
Apache License 2.0