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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Utils.kt
|
bienenjakob
| 573,125,960
| false
|
{"Kotlin": 53763}
|
import java.io.File
fun inputTextOfDay(n: Int): String {
return File("src/day$n/input$n.txt").readText()
}
fun testTextOfDay(n: Int): String {
return File("src/day$n/test$n.txt").readText()
}
| 0
|
Kotlin
|
0
| 0
|
6ff34edab6f7b4b0630fb2760120725bed725daa
| 202
|
aoc-2022-in-kotlin
|
Apache License 2.0
|
src/main/kotlin/kkon_warmup/Quicksort.kt
|
jdinkla
| 354,538,950
| false
| null |
package kkon_warmup
import kotlinx.coroutines.*
import utilities.measure
import kotlin.random.Random
const val BUCKET_SIZE = 2048
fun <T> List<T>.pivot(): T = this[Random.nextInt(0, size)]
suspend fun <T : Comparable<T>> coquicksort(ls: List<T>): List<T> = coroutineScope {
if (ls.size <= BUCKET_SIZE) {
ls.sorted()
} else {
val pivot = ls.pivot()
val (lower, higher) = ls.partition { it < pivot }
val sortedLower = async { coquicksort(lower) }
val sortedHigher = async { coquicksort(higher) }
sortedLower.await() + sortedHigher.await()
}
}
fun <T : Comparable<T>> quicksort(ls: List<T>): List<T> {
if (ls.size <= BUCKET_SIZE) {
return ls.sorted()
}
val pivot = ls.pivot()
val (lower, higher) = ls.partition { it < pivot }
return quicksort(lower) + quicksort(higher)
}
fun main() {
val ls = (1..5_000_000).map { Random.nextInt() }
measure("sorted") {
ls.sorted()
}
measure("sequential") {
quicksort(ls)
}
measure("coroutines") {
runBlocking(Dispatchers.Default) {
coquicksort(ls)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
99bd6583d20b7cef8c06cdcbb2e2708c25d6dede
| 1,153
|
2021_kkon_warmup
|
MIT License
|
src/main/kotlin/kkon_warmup/Quicksort.kt
|
jdinkla
| 354,538,950
| false
| null |
package kkon_warmup
import kotlinx.coroutines.*
import utilities.measure
import kotlin.random.Random
const val BUCKET_SIZE = 2048
fun <T> List<T>.pivot(): T = this[Random.nextInt(0, size)]
suspend fun <T : Comparable<T>> coquicksort(ls: List<T>): List<T> = coroutineScope {
if (ls.size <= BUCKET_SIZE) {
ls.sorted()
} else {
val pivot = ls.pivot()
val (lower, higher) = ls.partition { it < pivot }
val sortedLower = async { coquicksort(lower) }
val sortedHigher = async { coquicksort(higher) }
sortedLower.await() + sortedHigher.await()
}
}
fun <T : Comparable<T>> quicksort(ls: List<T>): List<T> {
if (ls.size <= BUCKET_SIZE) {
return ls.sorted()
}
val pivot = ls.pivot()
val (lower, higher) = ls.partition { it < pivot }
return quicksort(lower) + quicksort(higher)
}
fun main() {
val ls = (1..5_000_000).map { Random.nextInt() }
measure("sorted") {
ls.sorted()
}
measure("sequential") {
quicksort(ls)
}
measure("coroutines") {
runBlocking(Dispatchers.Default) {
coquicksort(ls)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
99bd6583d20b7cef8c06cdcbb2e2708c25d6dede
| 1,153
|
2021_kkon_warmup
|
MIT License
|
fluentui_core/src/main/java/com/microsoft/fluentui/util/Utils.kt
|
anthonysidesap
| 454,785,267
| true
|
{"Kotlin": 2243120, "Shell": 8996}
|
package com.microsoft.fluentui.util
import android.content.res.Resources
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
fun pxToDp(value: Float) = (value / Resources
.getSystem()
.displayMetrics.density).dp
fun dpToPx(value: Dp) = (value * Resources
.getSystem()
.displayMetrics.density).value
| 1
|
Kotlin
|
2
| 7
|
2b0d10f7b754c189fea210d279487617e5661eaa
| 351
|
fluentui-android
|
MIT License
|
server/src/main/com/broll/gainea/server/core/objects/Soldier.kt
|
Rolleander
| 253,573,579
| false
|
{"Kotlin": 426720, "Java": 265966, "HTML": 1714, "CSS": 1069, "JavaScript": 24}
|
package com.broll.gainea.server.core.objects
import com.broll.gainea.server.core.battle.BattleContext
import com.broll.gainea.server.core.battle.FightingPower
import com.broll.gainea.server.core.fractions.Fraction
import com.broll.gainea.server.core.player.Player
import com.broll.gainea.server.core.player.isNeutral
open class Soldier(owner: Player) : Unit(owner) {
var fraction: Fraction? = null
var isCommander = false
init {
if (!owner.isNeutral()) {
fraction = owner.fraction
}
}
override fun calcFightingPower(context: BattleContext): FightingPower {
return if (fraction == null) {
super.calcFightingPower(context)
} else fraction!!.calcFightingPower(this, context)
}
}
| 0
|
Kotlin
|
1
| 3
|
35593a78a4b81e1758cc9bca23e78fb14b427334
| 760
|
Gainea
|
MIT License
|
SmartWindowdevice/app/src/main/java/com/hsj/SmartWindowdevice/data/services/VillageForecastApiService.kt
|
gksl2577
| 350,228,145
| false
| null |
package com.hsj.SmartWindowdevice.data.services
import com.hsj.SmartWindowdevice.BuildConfig
import com.hsj.SmartWindowdevice.data.models.villageforecast.VillageForecastResponse
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface VillageForecastApiService {
@GET(
"1360000/VilageFcstInfoService/getUltraSrtNcst" +
"?serviceKey=${BuildConfig.VILLAGE_FORECAST_API_KEY}" +
"&numOfRows=10" +
"&pageNo=1" +
"&dataType=json"
)
suspend fun getDateNLocation(
@Query("base_date") base_date: String,
@Query("base_time") base_time: String,
@Query("nx") nx: Int,
@Query("ny") ny: Int
):Response<VillageForecastResponse>
}
| 0
|
Kotlin
|
0
| 1
|
28a200bb9c05c82ff3a764e6f9c2d96f466248c9
| 770
|
monday
|
MIT License
|
src/otherTest/kotlin/AssertionFailedErrorTest4js.kt
|
romanart
| 224,223,786
| true
|
{"Kotlin": 27716}
|
package com.willowtreeapps.opentest4k
actual typealias Serialized = Any
actual inline fun <reified T : Any> deserialize(bytes: Serialized): T = bytes as T
actual fun serialize(`object`: Any): Serialized = `object`
| 0
| null |
0
| 0
|
77e9a33fb79a27ba76770f2f39b2d8d49969dff0
| 217
|
opentest4k
|
Apache License 2.0
|
android/app/src/main/java/com/fabirt/weatherforecast/data/models/WeatherResponse.kt
|
fabirt
| 256,286,254
| false
| null |
package com.fabirt.weatherforecast.data.models
import com.google.gson.annotations.SerializedName
data class WeatherResponse(
@SerializedName("current")
val currentWeather: CurrentWeatherModel,
@SerializedName("location")
val location: WeatherLocation,
@SerializedName("request")
val request: WeatherRequest
) {
companion object {
// weatherIcons = listOf("https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"),
// weatherDescriptions = listOf("Sunny"),
fun getFixed(): WeatherResponse {
return WeatherResponse(
CurrentWeatherModel(
observationTime = "12:14 PM",
temperature = 13,
weatherCode = 113,
windSpeed = 0,
windDegree = 349,
windDir = "N",
pressure = 1010,
precip = 0.0,
humidity = 90,
cloudcover = 0,
feelslike = 13,
uvIndex = 4,
visibility = 16,
weatherDescriptions = listOf("Description")
),
WeatherLocation(
name = "New York",
country = "United States of America",
region = "New York",
lat = "40.714",
lon = "-74.006",
timezoneId = "America/New_York",
localtime = "2019-09-07 08:14",
localtimeEpoch = 1587144047703,
utcOffset = "-4.0"
),
WeatherRequest(
type = "City",
query = "New York, United States of America",
language = "en",
unit = "m"
)
)
}
}
}
/*
{
"request": {
"type": "City",
"query": "New York, United States of America",
"language": "en",
"unit": "m"
},
"location": {
"name": "New York",
"country": "United States of America",
"region": "New York",
"lat": "40.714",
"lon": "-74.006",
"timezone_id": "America/New_York",
"localtime": "2019-09-07 08:14",
"localtime_epoch": 1567844040,
"utc_offset": "-4.0"
},
"current": {
"observation_time": "12:14 PM",
"temperature": 13,
"weather_code": 113,
"weather_icons": [
"https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
],
"weather_descriptions": [
"Sunny"
],
"wind_speed": 0,
"wind_degree": 349,
"wind_dir": "N",
"pressure": 1010,
"precip": 0,
"humidity": 90,
"cloudcover": 0,
"feelslike": 13,
"uv_index": 4,
"visibility": 16
}
}
*/
| 0
|
Kotlin
|
6
| 9
|
d42a921ada74911d811dceae6eec80f7c6f325ae
| 2,974
|
weather-forecast-app
|
MIT License
|
app/src/main/java/vn/tiki/android/androidhometestclone/data/api/GetDealsAsynTask.kt
|
txtd1993
| 139,110,366
| false
|
{"Kotlin": 13684}
|
package vn.tiki.android.androidhometestclone.data.api
import android.os.AsyncTask
import vn.tiki.android.androidhometestclone.data.api.response.Deal
import vn.tiki.android.androidhometestclone.presenter.DealCountDownContract
class GetDealsAsyncTask(private val apiServices: ApiServices, private val callback: DealCountDownContract.View) : AsyncTask<Unit, Unit, List<Deal>>() {
override fun onPreExecute() {
super.onPreExecute()
callback.showLoadingDialog()
}
override fun doInBackground(vararg params: Unit?): List<Deal> {
return apiServices.getDeals()
}
override fun onPostExecute(result: List<Deal>?) {
super.onPostExecute(result)
callback.showDeals(result)
callback.hideLoadingDialog()
}
}
| 0
|
Kotlin
|
0
| 0
|
23b2d4eccd9d77204ff5f6b63388346c27b96728
| 769
|
dattran__deals_count_down
|
Apache License 2.0
|
Edu-Android/branches/222/src/com/jetbrains/edu/android/compatibilityUtils.kt
|
JetBrains
| 43,696,115
| false
| null |
package com.jetbrains.edu.android
import com.android.tools.idea.sdk.IdeSdks
import java.io.File
fun setAndroidSdkPath(sdkLocation: File) {
IdeSdks.getInstance().setAndroidSdkPath(sdkLocation, null)
}
| 5
|
Kotlin
|
43
| 118
|
f9a96276d53cc1fca004f302e0aabde9e4b7548b
| 203
|
educational-plugin
|
Apache License 2.0
|
definitions/src/main/kotlin-gen/com/divpundir/mavlink/definitions/uavionix/UavionixAdsbTransceiverHealthReport.kt
|
divyanshupundir
| 484,943,163
| false
| null |
package com.divpundir.mavlink.definitions.uavionix
import com.divpundir.mavlink.api.GeneratedMavField
import com.divpundir.mavlink.api.GeneratedMavMessage
import com.divpundir.mavlink.api.MavBitmaskValue
import com.divpundir.mavlink.api.MavDeserializer
import com.divpundir.mavlink.api.MavMessage
import com.divpundir.mavlink.serialization.decodeBitmaskValue
import com.divpundir.mavlink.serialization.encodeBitmaskValue
import com.divpundir.mavlink.serialization.truncateZeros
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.Byte
import kotlin.ByteArray
import kotlin.Int
import kotlin.UInt
import kotlin.Unit
/**
* Transceiver heartbeat with health report (updated every 10s)
*/
@GeneratedMavMessage(
id = 10_003u,
crcExtra = 4,
)
public data class UavionixAdsbTransceiverHealthReport(
/**
* ADS-B transponder messages
*/
@GeneratedMavField(type = "uint8_t")
public val rfhealth: MavBitmaskValue<UavionixAdsbRfHealth> = MavBitmaskValue.fromValue(0u),
) : MavMessage<UavionixAdsbTransceiverHealthReport> {
public override val instanceMetadata: MavMessage.Metadata<UavionixAdsbTransceiverHealthReport> =
METADATA
public override fun serializeV1(): ByteArray {
val outputBuffer = ByteBuffer.allocate(SIZE_V1).order(ByteOrder.LITTLE_ENDIAN)
outputBuffer.encodeBitmaskValue(rfhealth.value, 1)
return outputBuffer.array()
}
public override fun serializeV2(): ByteArray {
val outputBuffer = ByteBuffer.allocate(SIZE_V2).order(ByteOrder.LITTLE_ENDIAN)
outputBuffer.encodeBitmaskValue(rfhealth.value, 1)
return outputBuffer.array().truncateZeros()
}
public companion object {
private const val ID: UInt = 10_003u
private const val CRC_EXTRA: Byte = 4
private const val SIZE_V1: Int = 1
private const val SIZE_V2: Int = 1
private val DESERIALIZER: MavDeserializer<UavionixAdsbTransceiverHealthReport> =
MavDeserializer { bytes ->
val inputBuffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val rfhealth = inputBuffer.decodeBitmaskValue(1).let { value ->
val flags = UavionixAdsbRfHealth.getFlagsFromValue(value)
if (flags.isNotEmpty()) MavBitmaskValue.of(flags) else MavBitmaskValue.fromValue(value)
}
UavionixAdsbTransceiverHealthReport(
rfhealth = rfhealth,
)
}
private val METADATA: MavMessage.Metadata<UavionixAdsbTransceiverHealthReport> =
MavMessage.Metadata(ID, CRC_EXTRA, DESERIALIZER)
public val classMetadata: MavMessage.Metadata<UavionixAdsbTransceiverHealthReport> = METADATA
public fun builder(builderAction: Builder.() -> Unit): UavionixAdsbTransceiverHealthReport =
Builder().apply(builderAction).build()
}
public class Builder {
public var rfhealth: MavBitmaskValue<UavionixAdsbRfHealth> = MavBitmaskValue.fromValue(0u)
public fun build(): UavionixAdsbTransceiverHealthReport = UavionixAdsbTransceiverHealthReport(
rfhealth = rfhealth,
)
}
}
| 0
|
Kotlin
|
3
| 13
|
6a19cc374482310c9753c72b4df92a3be2cdc6d1
| 2,995
|
mavlink-kotlin
|
Apache License 2.0
|
app-android/app/src/main/java/com/snap/camerakitsamples/unity/android/UnityPlayerFragment.kt
|
Snapchat
| 692,140,343
| false
|
{"JavaScript": 679134, "C#": 239219, "ShaderLab": 80492, "Swift": 29359, "Kotlin": 21854, "HLSL": 13994, "Objective-C++": 2785, "Objective-C": 1432, "Ruby": 1170, "Java": 1039}
|
package com.snap.camerakitsamples.unity.android
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.DialogFragment
import com.unity3d.player.UnityPlayer
import com.fictionalcompany.mygame.R
class UnityPlayerFragment : DialogFragment(R.layout.fragment_unity_player) {
lateinit var mUnityPlayer: UnityPlayer;
lateinit var fl_forUnity : FrameLayout;
override fun onStart() {
super.onStart()
setWindowParams()
}
private fun setWindowParams(){
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog?.window?.setLayout(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
mUnityPlayer = UnityPlayer(activity)
val view : FrameLayout = inflater.inflate(R.layout.fragment_unity_player, container, false) as FrameLayout
view.addView(mUnityPlayer.view, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
mUnityPlayer.requestFocus()
mUnityPlayer.windowFocusChanged(true)
return view
}
override fun onDestroy() {
mUnityPlayer.quit()
super.onDestroy()
}
override fun onPause() {
super.onPause()
mUnityPlayer.pause()
}
override fun onResume() {
super.onResume()
mUnityPlayer.resume()
}
}
| 0
|
JavaScript
|
3
| 23
|
d9caa60b667822280c13c3ca373000677ae1d0b3
| 1,795
|
camera-kit-unity-sample
|
MIT License
|
core/src/main/kotlin/com/piotrwalkusz/smartlaw/core/model/presentation/SectionPresentationElement.kt
|
piotrwalkusz1
| 293,285,610
| false
| null |
package com.piotrwalkusz.smartlaw.core.model.presentation
data class SectionPresentationElement(
val presentationElements: List<PresentationElement> = listOf()
) : PresentationElement
| 0
|
Kotlin
|
0
| 0
|
235354ac0469d5ba9630b91124f6fcc4481dad34
| 192
|
SmartLaw
|
MIT License
|
io/okio/src/main/kotlin/io/bluetape4k/okio/SinkSupport.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.okio
import okio.BufferedSink
import okio.Sink
import okio.buffer
/**
* [Sink]를 [BufferedSink]로 변환합니다.
*/
fun Sink.buffered(): BufferedSink = buffer()
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 177
|
bluetape4k
|
MIT License
|
feature-dapp-impl/src/main/java/com/edgeverse/wallet/feature_dapp_impl/presentation/addToFavourites/di/AddToFavouritesComponent.kt
|
finn-exchange
| 512,140,809
| false
|
{"Kotlin": 2956205, "Java": 14536, "JavaScript": 399}
|
package com.edgeverse.wallet.feature_dapp_impl.presentation.addToFavourites.di
import androidx.fragment.app.Fragment
import dagger.BindsInstance
import dagger.Subcomponent
import com.edgeverse.wallet.common.di.scope.ScreenScope
import com.edgeverse.wallet.feature_dapp_impl.presentation.addToFavourites.AddToFavouritesFragment
import com.edgeverse.wallet.feature_dapp_impl.presentation.addToFavourites.AddToFavouritesPayload
@Subcomponent(
modules = [
AddToFavouritesModule::class
]
)
@ScreenScope
interface AddToFavouritesComponent {
@Subcomponent.Factory
interface Factory {
fun create(
@BindsInstance fragment: Fragment,
@BindsInstance payload: AddToFavouritesPayload,
): AddToFavouritesComponent
}
fun inject(fragment: AddToFavouritesFragment)
}
| 0
|
Kotlin
|
1
| 0
|
03229c4188cb56b0fb0340e60d60184c7afa2c75
| 827
|
edgeverse-wallet
|
Apache License 2.0
|
feature-dapp-impl/src/main/java/com/edgeverse/wallet/feature_dapp_impl/presentation/addToFavourites/di/AddToFavouritesComponent.kt
|
finn-exchange
| 512,140,809
| false
|
{"Kotlin": 2956205, "Java": 14536, "JavaScript": 399}
|
package com.edgeverse.wallet.feature_dapp_impl.presentation.addToFavourites.di
import androidx.fragment.app.Fragment
import dagger.BindsInstance
import dagger.Subcomponent
import com.edgeverse.wallet.common.di.scope.ScreenScope
import com.edgeverse.wallet.feature_dapp_impl.presentation.addToFavourites.AddToFavouritesFragment
import com.edgeverse.wallet.feature_dapp_impl.presentation.addToFavourites.AddToFavouritesPayload
@Subcomponent(
modules = [
AddToFavouritesModule::class
]
)
@ScreenScope
interface AddToFavouritesComponent {
@Subcomponent.Factory
interface Factory {
fun create(
@BindsInstance fragment: Fragment,
@BindsInstance payload: AddToFavouritesPayload,
): AddToFavouritesComponent
}
fun inject(fragment: AddToFavouritesFragment)
}
| 0
|
Kotlin
|
1
| 0
|
03229c4188cb56b0fb0340e60d60184c7afa2c75
| 827
|
edgeverse-wallet
|
Apache License 2.0
|
app/src/main/java/com/inging/notis/ui/search/SearchViewModel.kt
|
prdotk
| 372,680,673
| false
| null |
package com.inging.notis.ui.search
import androidx.core.app.NotificationCompat.CATEGORY_MESSAGE
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.inging.notis.constant.NotiViewType
import com.inging.notis.data.room.entity.NotiInfo
import com.inging.notis.repository.NotiRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class SearchViewModel @Inject constructor(
private val repository: NotiRepository
) : ViewModel() {
// 검색어
var word = ""
// 히스토리에서 선택한 검색어
var wordHistory = MutableLiveData<String>()
// 노티 검색
fun searchNotiInfoList(word: String) = Pager(
config = PagingConfig(pageSize = 20)
) {
repository.searchNotiInfoList(word)
}.flow
.cachedIn(viewModelScope)
var deleteInfo = NotiInfo(-1, senderType = NotiViewType.LEFT)
// 임시 삭제
suspend fun undoDelete() {
withContext(Dispatchers.IO) {
repository.updateNotiDeleted(listOf(deleteInfo.notiId), true)
}
}
// 임시 삭제 복구
suspend fun undoRestore() {
withContext(Dispatchers.IO) {
repository.updateNotiDeleted(listOf(deleteInfo.notiId), false)
}
}
// 삭제
fun delete(info: NotiInfo) {
CoroutineScope(Dispatchers.IO).launch {
when (info.category) {
CATEGORY_MESSAGE ->
repository.deleteMsgNotiListAndUpdateSummary(
info.notiId,
info.pkgName,
info.summaryText
)
else ->
repository.deleteNotiAndUpdatePkgNoti(info)
}
}
}
// 검색 히스토리 목록
val searchHistoryList = Pager(
config = PagingConfig(pageSize = 30)
) {
repository.getSearchHistoryList()
}.flow
.cachedIn(viewModelScope)
// 검색 히스토리 저장
fun saveSearchHistory(word: String) {
CoroutineScope(Dispatchers.IO).launch {
repository.saveSearchHistory(word)
}
}
// 검색 히스토리 삭제
fun deleteSearchHistory(word: String) {
CoroutineScope(Dispatchers.IO).launch {
repository.deleteSearchHistory(word)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
15101b8f1a844adc892c2b4ce04a39790b41738d
| 2,560
|
notis
|
MIT License
|
drafter/src/commonMain/kotlin/io/androidpoet/drafter/bars/GroupedBarChartRenderer.kt
|
AndroidPoet
| 861,638,856
| false
|
{"Kotlin": 139232}
|
/*
* Designed and developed by 2024 androidpoet (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.androidpoet.drafter.bars
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
public class GroupedBarChartRenderer : BarChartRenderer<GroupedBarChartData> {
override fun calculateMaxValue(data: GroupedBarChartData): Float =
data.groupedValues.flatten().maxOrNull() ?: 0f
override fun calculateBarAndSpacing(
chartWidth: Float,
dataSize: Int,
barsPerGroup: Int,
): Pair<Float, Float> {
val totalGroupSpacing = chartWidth * 0.1f
val groupSpacing = totalGroupSpacing / (dataSize + 1)
val availableWidth = chartWidth - totalGroupSpacing
val totalBarSpacingPerGroup = (barsPerGroup - 1) * 4f
val barWidth = (availableWidth / dataSize - totalBarSpacingPerGroup) / barsPerGroup
return Pair(barWidth, groupSpacing)
}
override fun calculateGroupWidth(
barWidth: Float,
barsPerGroup: Int,
): Float {
val totalBarSpacingPerGroup = (barsPerGroup - 1) * 4f
return barWidth * barsPerGroup + totalBarSpacingPerGroup
}
override fun drawBars(
drawScope: DrawScope,
data: GroupedBarChartData,
index: Int,
left: Float,
barWidth: Float,
groupSpacing: Float,
chartBottom: Float,
chartHeight: Float,
maxValue: Float,
animationProgress: Float,
) {
val groupValues = data.groupedValues[index]
val barsPerGroup = groupValues.size
val barSpacing = 4f
var currentLeft = left
groupValues.forEachIndexed { barIndex, value ->
val barHeight = (value / maxValue) * chartHeight * animationProgress
val barColor = data.colors.getOrElse(barIndex) { Color.Gray }
drawScope.drawRect(
color = barColor,
topLeft = Offset(currentLeft, chartBottom - barHeight),
size = Size(barWidth, barHeight),
)
currentLeft += barWidth + barSpacing
}
}
}
| 0
|
Kotlin
|
1
| 8
|
cb004a03c481fb21ce22d81889bcf83e5090154d
| 2,556
|
Drafter
|
Apache License 2.0
|
app/src/main/java/com/example/pictotalk/game/SettingsManager.kt
|
Raynou
| 782,802,602
| false
|
{"Kotlin": 86125}
|
package com.example.pictotalk.game
import android.content.Context
import android.content.SharedPreferences
/**
* Singleton class that stores values that are intended to be used in various parts of the app.
* @property context
*/
class SettingsManager(private val context: Context) {
companion object {
private const val PREFS_NAME = "pictotalk"
private const val PREFS_DIFFICULTY = "difficulty"
}
private fun getPreference(key: String, defaultValue: String): String {
val preferences: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
return preferences.getString(key, defaultValue) ?: defaultValue
}
private fun setPreference(key: String, value: String) {
val preferences: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
with(preferences.edit()) {
putString(key, value)
apply()
}
}
fun getDifficulty(): Difficulty {
val difficulty = getPreference(PREFS_DIFFICULTY, Difficulty.EASY.name)
return Difficulty.valueOf(difficulty)
}
fun setDifficulty(difficulty: Difficulty) {
setPreference(PREFS_DIFFICULTY, difficulty.name)
}
}
| 0
|
Kotlin
|
0
| 1
|
0cce6d6b284311e8675e320d3302c15beb71167c
| 1,245
|
PictoTalk
|
MIT License
|
AcornUiCore/src/com/acornui/gl/component/text/TfPartBuilder.kt
|
konsoletyper
| 105,533,124
| false
| null |
/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.gl.component.text
import com.acornui.component.layout.LayoutContainer
import com.acornui.component.layout.algorithm.FlowLayoutData
//fun LayoutContainer<*, FlowLayoutData>.add(text: String) {
// val span = TextSpanElement(this)
// val words = span.createWords(text)
//
// for (word in words) {
// val lastChar = word.chars.last().char
// if (lastChar == '\n') {
// word layout {
// clearsLine = true
// }
// } else if (lastChar == '\t') {
// word layout {
// clearsTabstop = true
// }
// } else if (lastChar == ' ') {
// word layout {
// overhangs = true
// }
// }
// span.addElement(word)
// }
// addElement(span)
//}
//
//private fun TextSpanElement.createWords(text: String): List<TfWord> {
// val words = ArrayList<TfWord>()
// if (text.isEmpty()) return words
// var word = TfWord(this)
// for (i in 0..text.lastIndex) {
// val char = text[i]
// val tfChar = char(char)
// if (!word.canAddChar(char)) {
// // Need a new word
// words.add(word)
// word = TfWord(this)
// }
// word.chars.add(tfChar)
// }
// if (word.isNotEmpty())
// words.add(word)
//
// return words
//}
//
//private fun TfWord.canAddChar(char: Char): Boolean {
// val last = chars.lastOrNull() ?: return true
// val lastC = last.char
// if (lastC.isBreaking()) return false
// return (lastC == ' ') == (char == ' ')
//}
| 0
|
Kotlin
|
3
| 0
|
a84b559fe1d1cad01eb9223ad9af73b4d5fb5bc8
| 1,946
|
Acorn
|
Apache License 2.0
|
src/commonMain/kotlin/com/beetroot/server/entity/player/StaticPlayer.kt
|
BeetrootPowered
| 255,452,972
| false
| null |
package com.beetroot.server.entity.player
class StaticPlayer : Player() {
}
| 0
|
Kotlin
|
0
| 5
|
0e141ff3a2c32a7eb6c49867517e11830938ebc8
| 76
|
Beetroot
|
MIT License
|
app/src/main/java/com/example/dotoring_neoul/navigation/RootNavigationGraph.kt
|
Team-Neoul
| 678,390,604
| false
| null |
package com.example.dotoring_neoul.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.dotoring_neoul.ui.home.HomeScreen
@Composable
fun RootNavigationGraph(navController: NavHostController) {
NavHost(
navController = navController,
route = Graph.ROOT,
startDestination = Graph.AUTHENTICATION
) {
com.example.dotoring_neoul.authNavGraph(navController = navController)
composable(route = Graph.HOME) {
HomeScreen()
}
}
}
object Graph {
const val ROOT = "root_graph"
const val AUTHENTICATION = "auth_graph"
const val HOME = "home_graph"
const val MENTI_DETAILS = "menti_details_graph"
const val MESSAGE_DETAILS = "message_detail_graph"
}
| 6
|
Kotlin
|
2
| 0
|
fb7eb022c0cf1fff26f780282d32624665f1255f
| 885
|
Neoul_Dotoring-AOS
|
MIT License
|
video/src/main/java/com/brins/video/fragment/VideoFragment.kt
|
BrinsLee
| 297,821,918
| false
| null |
package com.brins.video.fragment
import android.content.res.ColorStateList
import android.graphics.Typeface
import android.os.Bundle
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.brins.baselib.config.*
import com.brins.baselib.fragment.BaseFragment
import com.brins.baselib.utils.UIUtils
import com.brins.video.R
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.android.synthetic.main.fragment_video.*
class VideoFragment : BaseFragment() {
private val changeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
val count = tab_layout.tabCount
for (i in 0 until count) {
val tab = tab_layout.getTabAt(i)
val textView = tab?.customView as TextView
if (tab.getPosition() == position) {
textView.setTextSize(13f)
textView.setTypeface(Typeface.DEFAULT_BOLD)
} else {
textView.setTextSize(13f)
textView.setTypeface(Typeface.DEFAULT)
}
}
}
}
private var mediator: TabLayoutMediator? = null
private var list = mutableListOf<Fragment>(
VideoCategoryFragment.getInstance(MAINLAND),
VideoCategoryFragment.getInstance(HONGKONG_TAIWAN),
VideoCategoryFragment.getInstance(EUROPE_AMERICA),
VideoCategoryFragment.getInstance(JAPAN),
VideoCategoryFragment.getInstance(KOREA)
)
private var titleList = mutableListOf<String>(
MAINLAND,
HONGKONG_TAIWAN,
EUROPE_AMERICA,
JAPAN,
KOREA
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun getLayoutResID(): Int {
return R.layout.fragment_video
}
override fun reLoad() {
}
override fun init(savedInstanceState: Bundle?) {
vp_video.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
vp_video.adapter = object : FragmentStateAdapter(childFragmentManager, getLifecycle()) {
override fun getItemCount(): Int {
return list.size
}
override fun createFragment(position: Int): Fragment {
return list[position]
}
}
vp_video.registerOnPageChangeCallback(changeCallback)
mediator = TabLayoutMediator(
tab_layout,
vp_video,
TabLayoutMediator.TabConfigurationStrategy { tab, position ->
val textView = TextView(getMyContext())
val states = arrayOfNulls<IntArray>(2)
states[0] = intArrayOf(android.R.attr.state_selected)
states[1] = intArrayOf()
val colors = intArrayOf(
UIUtils.getColor(R.color.black),
UIUtils.getColor(R.color.default_btn_text)
)
val colorStateList = ColorStateList(states, colors)
textView.setText(titleList[position])
textView.setTextSize(13f)
textView.setTextColor(colorStateList)
tab.setCustomView(textView)
})
mediator?.attach()
}
companion object {
fun getInstance(): VideoFragment {
return VideoFragment()
}
}
override fun onDestroy() {
mediator?.detach()
vp_video?.unregisterOnPageChangeCallback(changeCallback)
super.onDestroy()
}
}
| 0
|
Kotlin
|
0
| 1
|
37cbd7448ebfc23475c00462018f6d70c74631e1
| 3,689
|
Music
|
Apache License 2.0
|
no-waste-auth-manager/src/main/kotlin/edu/ubb/micro/nowaste/authmanager/repository/UserRepository.kt
|
kissbudai
| 192,089,735
| false
| null |
package edu.ubb.micro.nowaste.authmanager.repository
import edu.ubb.micro.nowaste.authmanager.model.User
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.stereotype.Repository
@Repository
interface UserRepository : MongoRepository<User, String> {
fun findUserByUserName(userName: String): User?
}
| 0
|
Kotlin
|
0
| 0
|
25afa71e987fcbfb85bf6f2588d7654b98e1e0c5
| 345
|
no-waste-api
|
Apache License 2.0
|
android/src/debug/kotlin/org/acyb/sayit/app/atom/TextPreview.kt
|
a-cyborg
| 766,941,087
| false
|
{"Kotlin": 165341}
|
/*
* Copyright (c) 2024 Mima Kang / All rights reserved.
*
* Use of this source code is governed by Apache v2.0
*/
package org.acyb.sayit.app.atom
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
@Preview
@Composable
fun TextDisplayStandardLargePreview() {
TextDisplayStandardLarge(text = "SayIt")
}
@Preview
@Composable
fun TextHeadlineStandardPreview() {
TextHeadlineStandardSmall(text = "SayIt")
}
@Preview
@Composable
fun TextTitleStandardLargePreview() {
TextTitleStandardLarge(text = "SayIt")
}
@Preview
@Composable
fun TextTitleSubtleMediumPreview() {
TextTitleSubtleMedium(text = "TitleSubtleMedium")
}
@Preview
@Composable
fun TextLabelAttentionLargePreview() {
TextLabelAttentionLarge(text = "SayIt")
}
@Preview
@Composable
fun TextBodyStandardLargePreview() {
TextBodyStandardLarge(text = "SayIt")
}
@Preview
@Composable
fun TextBodyStandardMediumPreview() {
TextBodyStandardSmall(text = "SayIt")
}
| 0
|
Kotlin
|
0
| 0
|
dc69c992895d0377dc6cc499dfc3e9e876758873
| 996
|
SayItAlarmMP
|
Apache License 2.0
|
shared/src/commonMain/kotlin/ui/features/slidingDrawerUi.kt
|
youranshul
| 652,226,399
| false
| null |
package ui.features
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
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.unit.dp
import com.seiko.imageloader.rememberAsyncImagePainter
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
@Composable
fun UserImageArea() {
Box(
modifier = Modifier
.fillMaxWidth()
.height(150.dp)
.border(2.dp, Color.Gray)
) {
Row(
) {
val painterResource = rememberAsyncImagePainter("https://www.themoviedb.org/t/p/w600_and_h900_bestv2/rQtUWshSz2no41OXniyNJxSoBhf.jpg")
Image(
painter = painterResource,
modifier = Modifier
.width(120.dp)
.height(150.dp),
contentScale = ContentScale.Crop,
contentDescription = ""
)
Spacer(modifier = Modifier.fillMaxHeight().width(2.dp))
Column {
Text("Anshul Upadhyay")
Text("Joined on : 03 Mar 2021")
}
}
}
}
private val options = arrayListOf("Favorite", "Settings","Dark theme", "Actors","Watchlist", "Settings")
@Composable
fun DrawerOptions() {
Column {
options.forEach {
OptionItem(it)
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun OptionItem(name: String) {
Row(
modifier =
Modifier
.fillMaxWidth()
.height(60.dp)
.clickable { },
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource("outline_home.xml"),
contentDescription = null
)
Spacer(modifier = Modifier.fillMaxHeight().width(10.dp))
Text(name)
}
}
| 1
|
Kotlin
|
0
| 0
|
f702c1a174a967a30d2bce2471a7b28515b28336
| 2,191
|
KmmMovieBuff
|
Apache License 2.0
|
multi-search/src/main/kotlin/co/anitrend/multisearch/ui/MultiSearch.kt
|
AniTrend
| 225,128,246
| false
|
{"Kotlin": 37296}
|
package co.anitrend.multisearch.ui
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import co.anitrend.multisearch.R
import co.anitrend.multisearch.model.MultiSearchChangeListener
import co.anitrend.multisearch.presenter.MultiSearchPresenter
import kotlinx.android.synthetic.main.search_view.view.*
class MultiSearch @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
): FrameLayout(context, attrs, defStyleAttr) {
private val presenter by lazy {
MultiSearchPresenter(context)
}
init {
val typedArray = context.theme.obtainStyledAttributes(
attrs, R.styleable.MultiSearch, defStyleAttr, defStyleAttr
)
presenter.createConfiguration(typedArray)
onInitializeComponent()
}
private fun onInitializeComponent() {
LayoutInflater.from(context).inflate(
R.layout.search_view,
this,
true
)
presenter.configureSearchAction(
multiSearchActionIcon
)
multiSearchContainer.presenter = presenter
multiSearchActionIcon.setOnClickListener {
if (!presenter.isInSearchMode)
multiSearchContainer.search()
else
multiSearchContainer.completeSearch()
}
}
fun setSearchViewListener(multiSearchChangeListener: MultiSearchChangeListener) {
multiSearchContainer.multiSearchChangeListener = multiSearchChangeListener
}
}
| 2
|
Kotlin
|
2
| 3
|
f6dd78e63c416304d1765c696126be912c4caada
| 1,592
|
material-multi-search
|
Apache License 2.0
|
app/src/main/java/social/entourage/android/groups/create/CommunicationHandlerViewModel.kt
|
ReseauEntourage
| 30,242,877
| false
|
{"Kotlin": 2176686}
|
package social.entourage.android.groups.create
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import social.entourage.android.api.model.Group
class CommunicationHandlerViewModel : ViewModel() {
var clickNext = MutableLiveData<Boolean>()
var isCondition = MutableLiveData<Boolean>()
var isButtonClickable = MutableLiveData<Boolean>()
var canExitGroupCreation: Boolean = true
var group: Group = Group()
fun resetValues() {
isCondition.value = false
isButtonClickable.value = false
clickNext.value = false
}
}
| 2
|
Kotlin
|
2
| 9
|
29edfb57c6d62db7a89307be9fa87aa7d5d56431
| 593
|
entourage-android
|
MIT License
|
service/src/commonMain/kotlin/ServiceConfiguration.kt
|
sellmair
| 322,400,648
| false
| null |
package io.sellmair.ionos.dyndns.service
import io.sellmair.ionos.dyndns.cli.DomainConfiguration
import io.sellmair.ionos.dyndns.cli.DomainConfigurationDTO
import io.sellmair.ionos.dyndns.cli.toDuration
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlin.time.Duration
@Serializable
data class ServiceConfigurationDTO(
val ipRefreshInterval: String,
val domains: List<DomainConfigurationDTO>
) {
fun toServiceConfiguration() = ServiceConfiguration(
ipRefreshInterval.toDuration(),
domains = domains.map { it.toArguments() }
)
fun toJson(): String {
return Json.encodeToString(serializer(), this)
}
companion object {
fun fromJson(json: String): ServiceConfigurationDTO {
return Json.decodeFromString(serializer(), json)
}
}
}
data class ServiceConfiguration(
val ipRefreshInterval: Duration,
val forceRefreshInterval: Duration? = null,
val domains: List<DomainConfiguration> = emptyList()
)
| 1
|
Kotlin
|
0
| 1
|
6c3cddb41d93c1a4f15259a59dd101f2565fd554
| 1,036
|
ionos-dyndns
|
MIT License
|
src/main/kotlin/xyz/mahasamut/gun_game/runnable/RunnableManager.kt
|
M4h45amu7x
| 619,067,634
| false
| null |
package xyz.mahasamut.gun_game.runnable
import xyz.mahasamut.gun_game.GunGame
import xyz.mahasamut.gun_game.config.ConfigManager
import xyz.mahasamut.gun_game.runnable.runnables.ScoreboardRunnable
import xyz.mahasamut.gun_game.runnable.runnables.SetTimeRunnable
object RunnableManager {
fun initRunnables() {
ScoreboardRunnable().runTaskTimer(GunGame.instance, 0L, ConfigManager.config.scoreboard.interval)
SetTimeRunnable().runTaskTimer(GunGame.instance, 20L, 200L)
}
}
| 0
|
Kotlin
|
0
| 1
|
854a37f1bbc2a57fcbe76b731471d4a1cad44010
| 497
|
gun-game
|
Apache License 2.0
|
k4kotlin/src/main/java/com/livinglifetechway/k4kotlin/Number.kt
|
priya5713
| 100,002,986
| true
|
{"Kotlin": 7410, "Java": 1196}
|
@file:Suppress("NOTHING_TO_INLINE")
package com.livinglifetechway.k4kotlin
/**
* Returns Zero (0) if it is null
*/
fun Number?.orZero(): Number = if (this != null) this else 0
fun Int?.orZero(): Int = if (this != null) this else 0
fun Float?.orZero(): Float = if (this != null) this else 0.0f
fun Double?.orZero(): Double = if (this != null) this else 0.0
| 0
|
Kotlin
|
0
| 1
|
3138961164b17c52cb005e6e5a1df2f3b9640229
| 363
|
K4Kotlin
|
Apache License 2.0
|
app/src/main/java/com/developerbreach/developerbreach/repository/AppRepository.kt
|
RajashekarRaju
| 285,625,118
| false
|
{"Kotlin": 164789}
|
package com.developerbreach.developerbreach.repository
import android.content.Context
import com.developerbreach.developerbreach.repository.database.DatabaseRepository
import com.developerbreach.developerbreach.repository.database.getDatabaseInstance
import com.developerbreach.developerbreach.repository.local.LocalRepository
import com.developerbreach.developerbreach.repository.network.NetworkRepository
import com.developerbreach.developerbreach.repository.network.NetworkService
class AppRepository(
context: Context
) {
val databaseRepository = DatabaseRepository(getDatabaseInstance(context))
val networkRepository = NetworkRepository(NetworkService())
val localRepository = LocalRepository(context)
}
| 0
|
Kotlin
|
0
| 0
|
65e3019f6babda8ca722a734f5d5b23012b5f7e9
| 727
|
developers-breach-android
|
Apache License 2.0
|
buildSrc/src/main/java/Versions.kt
|
Nanamare
| 502,257,230
| false
|
{"Kotlin": 79604}
|
object Versions {
const val compile_sdk_version = 32
const val min_sdk_version = 21
const val gradle_version = "7.1.2"
const val kotlin_version = "1.6.10"
const val kotlinx_coroutines_version = "1.6.0"
object Retrofit {
const val retrofit_version = "2.9.0"
const val ok_http_version = "4.9.3"
}
object KotlinxSerialization {
const val json_version = "1.2.2"
const val converter_version = "0.8.0"
const val core_version = "1.3.0"
}
object Hilt {
const val dagger_hilt_version = "2.40.5"
const val hilt_lifecycle_viewmodel_version = "1.0.0-alpha03"
}
const val coil_version = "2.0.0-rc03"
const val room_version = "2.4.2"
const val timber_version = "5.0.1"
const val androidx_ktx_version = "1.4.0"
const val material_version = "1.5.0"
object Androidx {
const val startup_version = "1.1.1"
const val paging_version = "3.1.1"
const val lifecycle_version = "2.4.1"
const val core_ktx_version = "1.7.0"
}
const val subsampling_scale_iv_versions = "3.10.0"
}
| 0
|
Kotlin
|
0
| 5
|
c152ec31739b460eb5ca53dcf43910f8fdcffdd8
| 1,127
|
Picsum-photos
|
MIT License
|
app/src/main/java/com/mobilecoronatracker/data/persistence/dao/CountryDataDao.kt
|
m1awicki
| 247,331,176
| false
| null |
package com.mobilecoronatracker.data.persistence.dao
import androidx.room.Dao
import androidx.room.Query
import com.mobilecoronatracker.data.persistence.entity.CountryData
import com.mobilecoronatracker.data.persistence.entity.CountryDataWithCountryInfo
import kotlinx.coroutines.flow.Flow
@Dao
abstract class CountryDataDao : BaseDao<CountryData> {
@Query(
"""
SELECT country_data.*, country.name, country.iso2, country.country_flag_path
FROM country_data
INNER JOIN country ON country_data.country_id = country.id
WHERE entry_date=:timestamp
ORDER BY cases DESC
"""
)
abstract fun getAllCountriesByTimestampFlow(timestamp: Long): Flow<List<CountryDataWithCountryInfo>>
@Query(
"""
SELECT COUNT(*)
FROM country_data
WHERE entry_date=:timestamp
"""
)
abstract suspend fun getAllCountriesCountByTimestamp(timestamp: Long): Int
@Query(
"""
SELECT *
FROM country_data
WHERE entry_date>=:timestampStart AND entry_date<=:timestampEnd AND country_id=:countryId
"""
)
abstract fun getCountryDataForTimeRange(
timestampStart: Long,
timestampEnd: Long,
countryId: Long
): Flow<List<CountryData>>
@Query(
"""
SELECT *
FROM country_data
WHERE entry_date = :todayTimestamp AND country_id = :countryId
"""
)
abstract fun getCountryByTimestamp(countryId: Long, todayTimestamp: Long): CountryData?
@Query(
"""
SELECT country_data.*
FROM country_data
INNER JOIN country ON country_data.country_id = country.id
WHERE name=:countryName
ORDER BY entry_date ASC
"""
)
abstract fun getAllCountryEntries(countryName: String): Flow<List<CountryData>>
}
| 0
|
Kotlin
|
3
| 2
|
0b4ed179e97c3141fc99698511fcecff93b590e6
| 1,864
|
mobilecoronatracker
|
Apache License 2.0
|
pipeline-core/src/main/kotlin/io/inapinch/pipeline/http/Http.kt
|
magicfoodhand
| 174,868,832
| false
|
{"Kotlin": 52220, "JavaScript": 12797, "HTML": 1590, "Dockerfile": 1137, "CSS": 98}
|
package io.inapinch.pipeline.http
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import okhttp3.OkHttpClient
import okhttp3.Request
interface HttpClient {
fun objectMapper(): ObjectMapper
fun get(url: String) : String
fun getJson(url: String) : Map<String, Any> = objectMapper().readValue(get(url))
}
private class OkHttp(private val okhttp: OkHttpClient = OkHttpClient.Builder().build(),
private val objectMapper: ObjectMapper = jacksonObjectMapper()) : HttpClient {
override fun objectMapper(): ObjectMapper = objectMapper
override fun get(url: String) : String {
return okhttp.newCall(Request.Builder().url(url).get().build())
.execute()
.body()!!
.string()
}
}
object Http{
private val client : HttpClient = OkHttp()
fun get(url: String) : String = client.get(url)
fun getJson(url: String) : Map<String, Any> = client.getJson(url)
fun url(baseUrl: String, params: Map<String, Any>) : String =
"$baseUrl${params.entries.stream()
.map{ "${it.key}=${it.value}" }
.reduce("", { key, value -> "$key&$value" }, { t, _ -> t })
.replaceFirst('&', '?')}"
}
| 0
|
Kotlin
|
0
| 0
|
8f02a5abedefb3c8253b9f538bcc0871f9fc43e3
| 1,372
|
pipeline
|
MIT License
|
app/src/main/java/com/crrl/beatplayer/utils/QueueUtils.kt
|
bg-write
| 391,164,835
| true
|
{"Kotlin": 507543}
|
/*
* Copyright (c) 2020. <NAME>. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.crrl.beatplayer.utils
import android.app.Application
import android.support.v4.media.session.MediaSessionCompat
import com.crrl.beatplayer.R
import com.crrl.beatplayer.extensions.*
import com.crrl.beatplayer.models.Song
import com.crrl.beatplayer.repository.SongsRepository
import com.google.gson.Gson
interface QueueUtils {
var currentSongId: Long
var queue: LongArray
var queueTitle: String
var currentSong: Song
val previousSongId: Long?
val nextSongId: Long?
fun setMediaSession(session: MediaSessionCompat)
fun playNext(id: Long)
fun remove(id: Long)
fun swap(from: Int, to: Int)
fun queue(): String
fun clear()
fun clearPlayedSongs()
fun shuffleQueue(isShuffle: Boolean = false)
}
class QueueUtilsImplementation(
private val context: Application,
private val songsRepository: SongsRepository,
private val settingsUtility: SettingsUtility
) : QueueUtils {
private lateinit var mediaSession: MediaSessionCompat
private val playedSongs = mutableListOf<Int>()
private val auxQueue = mutableListOf<Long>()
private val currentSongIndex
get() = queue.indexOf(currentSongId)
override var currentSongId: Long = -1
override var queue: LongArray = longArrayOf()
set(value) {
field = value
if (value.isNotEmpty()) {
mediaSession.setQueue(value.toQueue(songsRepository))
auxQueue.setAll(settingsUtility.originalQueueList.toQueueList().toMutableList())
}
}
override var queueTitle: String = ""
set(value) {
field = if (value.isNotEmpty()) {
value
} else context.getString(R.string.all_songs)
mediaSession.setQueueTitle(value)
}
override var currentSong: Song = Song()
get() = if (field.id != currentSongId) songsRepository.getSongForId(currentSongId) else field
override val previousSongId: Long?
get() {
if (mediaSession.position() >= 5000) return currentSongId
val previousIndex = currentSongIndex - 1
return when {
previousIndex >= 0 -> {
queue[previousIndex]
}
else -> null
}
}
override val nextSongId: Long?
get() {
val nextIndex = currentSongIndex + 1
return when {
nextIndex < queue.size -> queue[nextIndex]
else -> null
}
}
override fun setMediaSession(session: MediaSessionCompat) {
mediaSession = session
}
override fun playNext(id: Long) {
val nextIndex = currentSongIndex + 1
swap(queue.indexOf(id), nextIndex)
}
override fun remove(id: Long) {
queue = queue.toMutableList().apply { delete(id) }.toLongArray()
}
override fun swap(from: Int, to: Int) {
queue = queue.toMutableList().moveElement(from, to).toLongArray()
}
override fun queue(): String {
return "${currentSongIndex + 1}/${queue.size}"
}
override fun clear() {
queue = longArrayOf()
queueTitle = ""
currentSongId = 0
}
override fun clearPlayedSongs() {
playedSongs.clear()
}
override fun shuffleQueue(isShuffle: Boolean) {
if (isShuffle)
mediaSession.setQueue(shuffleQueue())
else
restoreQueueOrder()
}
private fun shuffleQueue(): List<MediaSessionCompat.QueueItem> {
val sQueue = mediaSession.controller.queue.shuffled()
val realQueue = sQueue.moveElement(sQueue.indexOfFirst { it.queueId == currentSongId }, 0)
auxQueue.setAll(queue.toList())
settingsUtility.originalQueueList = Gson().toJson(auxQueue)
queue = realQueue.toIdList()
return realQueue
}
private fun restoreQueueOrder() {
queue = auxQueue.toLongArray()
settingsUtility.originalQueueList = "[]"
auxQueue.clear()
}
}
| 0
| null |
0
| 1
|
3daa6902cdaa51837669b7916b362da429e23959
| 4,653
|
BeatPlayer
|
Apache License 2.0
|
kotlin/graphs/flows/MaxFlowFordFulkersonSimple.kt
|
polydisc
| 281,633,906
| true
|
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
|
package graphs.flows
// https://en.wikipedia.org/wiki/Ford–Fulkerson_algorithm in O(V^2 * flow)
object MaxFlowFordFulkersonSimple {
fun maxFlow(cap: Array<IntArray>, s: Int, t: Int): Int {
var flow = 0
while (true) {
if (!augmentPath(cap, BooleanArray(cap.size), s, t)) return flow
++flow
}
}
fun augmentPath(cap: Array<IntArray>, vis: BooleanArray, i: Int, t: Int): Boolean {
if (i == t) return true
vis[i] = true
for (j in vis.indices) if (!vis[j] && cap[i][j] > 0 && augmentPath(cap, vis, j, t)) {
--cap[i][j]
++cap[j][i]
return true
}
return false
}
// Usage example
fun main(args: Array<String?>?) {
val capacity =
arrayOf(intArrayOf(0, 1, 1, 0), intArrayOf(1, 0, 1, 1), intArrayOf(1, 1, 0, 1), intArrayOf(0, 1, 1, 0))
System.out.println(2 == maxFlow(capacity, 0, 3))
}
}
| 1
|
Java
|
0
| 0
|
4566f3145be72827d72cb93abca8bfd93f1c58df
| 960
|
codelibrary
|
The Unlicense
|
app/src/main/java/com/example/ghiblifilms/features/film_detail/ui/GhibliFilmDetailViewModel.kt
|
rmiguel1985
| 769,203,810
| false
|
{"Kotlin": 178102}
|
package com.example.ghiblifilms.features.film_detail.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.ghiblifilms.features.film_detail.domain.GetGhibliFilmUseCase
import com.example.ghiblifilms.features.film_detail.domain.entities.FilmEntity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import timber.log.Timber
class GhibliFilmDetailViewModel(
private val movieId: String,
private val ghibliFilmUseCaseImpl: GetGhibliFilmUseCase
) : ViewModel() {
private val _state = MutableStateFlow(DetailUiState())
val state = _state.asStateFlow()
init {
getFilm()
}
fun getFilm() {
viewModelScope.launch {
_state.value = DetailUiState(loading = true)
ghibliFilmUseCaseImpl.execute(movieId).fold(
onSuccess = {
_state.value = DetailUiState(film = it)
},
onFailure = {
_state.value = DetailUiState(error = it.message ?: "")
Timber.e("Error: ${it.message}")
}
)
}
}
data class DetailUiState(
val loading: Boolean = false,
val film: FilmEntity = FilmEntity(),
val error: String = ""
)
}
| 0
|
Kotlin
|
0
| 1
|
de5d1775cc19684131a3bb964178edcb24cfbaf4
| 1,355
|
GhibliFilms
|
The Unlicense
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsdocumentmanagementapi/config/DocumentRequestContextConfiguration.kt
|
ministryofjustice
| 714,999,059
| false
|
{"Kotlin": 261375, "Dockerfile": 1356, "Shell": 1316}
|
package uk.gov.justice.digital.hmpps.hmppsdocumentmanagementapi.config
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import uk.gov.justice.digital.hmpps.hmppsdocumentmanagementapi.resource.SERVICE_NAME
import uk.gov.justice.digital.hmpps.hmppsdocumentmanagementapi.resource.USERNAME
@Configuration
class DocumentRequestContextConfiguration(private val documentRequestContextInterceptor: DocumentRequestContextInterceptor) : WebMvcConfigurer {
override fun addInterceptors(registry: InterceptorRegistry) {
log.info("Adding document request context interceptor")
registry.addInterceptor(documentRequestContextInterceptor).addPathPatterns("/documents/**")
}
companion object {
private val log = LoggerFactory.getLogger(this::class.java)
}
}
@Configuration
class DocumentRequestContextInterceptor : HandlerInterceptor {
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
val serviceName = request.getHeader(SERVICE_NAME)?.trim()
require(!serviceName.isNullOrEmpty()) {
"$SERVICE_NAME header is required"
}
val username = request.getHeader(USERNAME)?.trim()?.takeUnless(String::isBlank)
request.setAttribute(DocumentRequestContext::class.simpleName, DocumentRequestContext(serviceName, username))
return true
}
}
| 0
|
Kotlin
|
0
| 0
|
462faeae4623738a21d8964dd83001f624ca4e21
| 1,674
|
hmpps-document-management-api
|
MIT License
|
app/src/main/java/com/cleveroad/phone_example/ValidatorFactory.kt
|
Cleveroad
| 114,619,348
| false
| null |
package com.cleveroad.phone_example
import android.content.Context
import com.cleveroad.bootstrap.kotlin_validators.PhoneValidatorImpl
import com.cleveroad.bootstrap.kotlin_validators.R
fun getPhoneValidator(context: Context) = with(context) {
PhoneValidatorImpl
.builder(this)
.emptyErrorMessage(getString(R.string.phone_is_invalid))
.invalidErrorMessage(getString(R.string.phone_is_invalid))
.build()
}
| 3
|
Kotlin
|
6
| 38
|
7bc51f35e26b1f0ca600422a57fc37b2231b726a
| 459
|
Bootstrap
|
The Unlicense
|
aoc-2018/src/test/kotlin/nl/jstege/adventofcode/aoc2018/days/Day22Test.kt
|
JStege1206
| 92,714,900
| false
| null |
package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.utils.DayTester
class Day22Test : DayTester(Day22())
| 0
|
Kotlin
|
0
| 0
|
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
| 139
|
AdventOfCode
|
MIT License
|
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/visualStudio/VisualStudioPackagesRegistryLocator.kt
|
JetBrains
| 49,584,664
| false
| null |
/*
* Copyright 2000-2023 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.visualStudio
import jetbrains.buildServer.agent.*
import jetbrains.buildServer.agent.Logger
class VisualStudioPackagesRegistryLocator(
private val _windowsRegistry: WindowsRegistry)
: VisualStudioPackagesLocator {
override fun tryGetPackagesPath(): String? {
var packagesPath: String? = null;
for (key in RegKeys) {
_windowsRegistry.accept(
key,
object : WindowsRegistryVisitor {
override fun visit(key: WindowsRegistryKey) = false
override fun visit(value: WindowsRegistryValue): Boolean {
if (value.type == WindowsRegistryValueType.Str && "CachePath".equals(value.key.parts.lastOrNull(), true)) {
packagesPath = value.text
LOG.debug("Using Visual Studio packages cache directory \"$packagesPath\"");
return false
}
return true
}
},
false)
}
return packagesPath
}
companion object {
private val LOG = Logger.getLogger(VisualStudioPackagesRegistryLocator::class.java)
internal val RegKeys =
WindowsRegistryBitness
.values()
.asSequence()
.map {
WindowsRegistryKey.create(
it,
WindowsRegistryHive.LOCAL_MACHINE,
"SOFTWARE",
"Microsoft",
"VisualStudio",
"Setup")
}
}
}
| 15
|
Kotlin
|
23
| 91
|
0a941fa071470657d160150dfebe866587fd5198
| 2,481
|
teamcity-dotnet-plugin
|
Apache License 2.0
|
src/main/kotlin/com/amazon/elasticsearch/replication/action/repository/TransportGetFileChunkAction.kt
|
opendistro-for-elasticsearch
| 368,213,608
| false
| null |
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.elasticsearch.replication.action.repository
import com.amazon.elasticsearch.replication.repository.RemoteClusterRestoreLeaderService
import com.amazon.elasticsearch.replication.util.performOp
import org.apache.logging.log4j.LogManager
import org.elasticsearch.action.support.ActionFilters
import org.elasticsearch.action.support.single.shard.TransportSingleShardAction
import org.elasticsearch.cluster.ClusterState
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver
import org.elasticsearch.cluster.routing.ShardsIterator
import org.elasticsearch.cluster.service.ClusterService
import org.elasticsearch.common.bytes.BytesArray
import org.elasticsearch.common.inject.Inject
import org.elasticsearch.common.io.stream.StreamInput
import org.elasticsearch.common.io.stream.Writeable
import org.elasticsearch.index.shard.ShardId
import org.elasticsearch.indices.IndicesService
import org.elasticsearch.threadpool.ThreadPool
import org.elasticsearch.transport.TransportActionProxy
import org.elasticsearch.transport.TransportService
class TransportGetFileChunkAction @Inject constructor(threadPool: ThreadPool, clusterService: ClusterService,
transportService: TransportService, actionFilters: ActionFilters,
indexNameExpressionResolver: IndexNameExpressionResolver,
private val indicesService: IndicesService,
private val restoreLeaderService: RemoteClusterRestoreLeaderService) :
TransportSingleShardAction<GetFileChunkRequest, GetFileChunkResponse>(GetFileChunkAction.NAME,
threadPool, clusterService, transportService, actionFilters,
indexNameExpressionResolver, ::GetFileChunkRequest, ThreadPool.Names.GET) {
init {
TransportActionProxy.registerProxyAction(transportService, GetFileChunkAction.NAME, ::GetFileChunkResponse)
}
companion object {
private val log = LogManager.getLogger(TransportGetFileChunkAction::class.java)
}
override fun shardOperation(request: GetFileChunkRequest, shardId: ShardId): GetFileChunkResponse {
log.debug(request.toString())
val indexShard = indicesService.indexServiceSafe(shardId.index).getShard(shardId.id)
val store = indexShard.store()
val buffer = ByteArray(request.length)
var bytesRead = 0
store.performOp({
val fileMetaData = request.storeFileMetadata
val currentInput = restoreLeaderService.openInputStream(request.restoreUUID, request,
fileMetaData.name(), fileMetaData.length())
val offset = request.offset
if (offset < fileMetaData.length()) {
currentInput.skip(offset)
bytesRead = currentInput.read(buffer)
}
})
return GetFileChunkResponse(request.storeFileMetadata, request.offset, BytesArray(buffer, 0, bytesRead))
}
override fun resolveIndex(request: GetFileChunkRequest): Boolean {
return true
}
override fun getResponseReader(): Writeable.Reader<GetFileChunkResponse> {
return Writeable.Reader { inp: StreamInput -> GetFileChunkResponse(inp) }
}
override fun shards(state: ClusterState, request: InternalRequest): ShardsIterator? {
return state.routingTable().shardRoutingTable(request.request().leaderShardId).primaryShardIt()
}
}
| 3
|
Kotlin
|
2
| 8
|
e89a9dd57895b0bd3f813afd0a8ee17b5196d16e
| 4,164
|
cross-cluster-replication
|
Apache License 2.0
|
arsceneview/src/main/java/io/github/sceneview/ar/arcore/Camera.kt
|
SceneView
| 426,414,439
| false
| null |
package io.github.sceneview.ar.arcore
import com.google.ar.core.Camera
import com.google.ar.core.TrackingState
/**
* Keep the screen unlocked while tracking, but allow it to lock when tracking stops.
*/
val Camera.isTracking get() = trackingState == TrackingState.TRACKING
| 28
|
Kotlin
|
90
| 440
|
9bd1e3dd6a51c8de36cf1a86db20f44bc63861fb
| 276
|
sceneview-android
|
Apache License 2.0
|
src/test/kotlin/br/com/zupacademy/find/FindPixKeyEndpointTest.kt
|
GabrielDiasgd
| 395,062,747
| true
|
{"Kotlin": 55968, "Smarty": 2022, "Dockerfile": 179}
|
package br.com.zupacademy.find
import br.com.zupacademy.FindPixKeyRequest
import br.com.zupacademy.FindPixKeyResponse
import br.com.zupacademy.KeyManagerFindServiceGrpc
import br.com.zupacademy.integration.bcb.BcbClient
import br.com.zupacademy.integration.bcb.PixKeyDetailsResponse
import br.com.zupacademy.integration.bcb.register.BcbBankAccountResponse
import br.com.zupacademy.integration.bcb.register.BcbOwnerResponse
import br.com.zupacademy.register.Account
import br.com.zupacademy.register.KeyPix
import br.com.zupacademy.register.KeyPixRepository
import br.com.zupacademy.register.KeyType
import io.grpc.ManagedChannel
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.annotation.GrpcChannel
import io.micronaut.grpc.server.GrpcServerChannel
import io.micronaut.http.HttpResponse
import io.micronaut.test.annotation.MockBean
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.Mockito
import java.time.LocalDateTime
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@MicronautTest(transactional = false)
internal class FindPixKeyEndpointTest(
private val clientGrpc: KeyManagerFindServiceGrpc.KeyManagerFindServiceBlockingStub,
private val keyPixRepository: KeyPixRepository
) {
@field:Inject
lateinit var bcbClient: BcbClient
private val keyPix = createKeyPix()
@BeforeEach
internal fun setUp() {
keyPixRepository.deleteAll()
keyPixRepository.save(keyPix)
}
@Test
internal fun `deve buscar uma chave por pixId e clientId`() {
val requestGrpc = FindPixKeyRequest.newBuilder()
.setPixId(FindPixKeyRequest.FilterByPixId
.newBuilder().setPixId(keyPix.pixId)
.setClientId(keyPix.clientId)
.build())
.build()
val responseGrpc = clientGrpc.findKey(requestGrpc)
assertNotNull(responseGrpc)
assertEquals(keyPix.type.name, responseGrpc.typeKey.name)
assertEquals(keyPix.keyValue, responseGrpc.keyValue)
assertEquals(keyPix.pixId, responseGrpc.pixId)
}
@Test
internal fun `nao deve encontrar chave por pixId e clientId quando registro nao existir`() {
val requestGrpc = FindPixKeyRequest.newBuilder()
.setPixId(FindPixKeyRequest.FilterByPixId
.newBuilder().setPixId(UUID.randomUUID().toString())
.setClientId(keyPix.clientId)
.build())
.build()
val error = assertThrows<StatusRuntimeException> {
clientGrpc.findKey(requestGrpc)
}
with(error) {
assertEquals(Status.NOT_FOUND.code, status.code)
assertEquals("Chave pix não encontrada ou não pertence ao cliente", status.description)
}
}
@Test
internal fun `deve encontrar uma chave por valor da chave quando registro existir localmente`() {
val requestGrpc = FindPixKeyRequest.newBuilder()
.setKey(keyPix.keyValue)
.build()
val responseGrpc = clientGrpc.findKey(requestGrpc)
assertEquals(keyPix.type.name, responseGrpc.typeKey.name)
assertEquals(keyPix.keyValue, responseGrpc.keyValue)
}
@Test
internal fun `deve encontrar chave por valor da chave quando registro existir somente no bcb`() {
val requestGrpc = FindPixKeyRequest.newBuilder()
.setKey("anotherBank@gmail.com")
.build()
val bcbResponse = createdPixKeyDetailsReponse()
Mockito.`when`(bcbClient.findByKeyBcb("anotherBank@gmail.com"))
.thenReturn(HttpResponse.ok(bcbResponse))
val responseGrpc: FindPixKeyResponse = clientGrpc.findKey(requestGrpc)
assertNotNull(responseGrpc)
assertEquals("", responseGrpc.pixId)
assertEquals("", responseGrpc.clientId)
assertEquals(bcbResponse.key, responseGrpc.keyValue)
assertEquals(bcbResponse.keyType, responseGrpc.typeKey.name)
}
@Test
internal fun `nao deve encontrar a chave por valor da chave no sistema local nem no bcb`() {
val requestGrpc = FindPixKeyRequest.newBuilder()
.setKey("notExist@email.com")
.build()
Mockito.`when`(bcbClient.findByKeyBcb("notExist@email.com")).thenReturn(HttpResponse.notFound())
val error = assertThrows<StatusRuntimeException> {
clientGrpc.findKey(requestGrpc)
}
with(error) {
assertEquals(Status.NOT_FOUND.code, status.code)
assertEquals("Chave Pix não encontrada no banco central", status.description)
}
}
@Test
internal fun `nao deve encontrar chave quando filtro invalido`() {
val requestGrpc = FindPixKeyRequest.newBuilder()
.build()
val error = assertThrows<StatusRuntimeException> {
clientGrpc.findKey(requestGrpc)
}
with(error) {
assertEquals(Status.FAILED_PRECONDITION.code, status.code)
assertEquals("Chave Pix inválida ou não informada", status.description)
}
}
@MockBean(BcbClient::class)
fun bcbClientMock(): BcbClient {
return Mockito.mock(BcbClient::class.java)
}
}
@Factory
class ClientGrpc() {
@Singleton
fun blokingStub(@GrpcChannel(GrpcServerChannel.NAME) channel: ManagedChannel): KeyManagerFindServiceGrpc.KeyManagerFindServiceBlockingStub? {
return KeyManagerFindServiceGrpc.newBlockingStub(channel)
}
}
fun createKeyPix(): KeyPix {
return KeyPix(UUID.randomUUID().toString(),KeyType.EMAIL,"gabriel@gmail.com","0001", "44719190839",
"Itau", "Gabriel", "123456", Account.CONTA_CORRENTE)
}
fun createdPixKeyDetailsReponse(): PixKeyDetailsResponse {
return PixKeyDetailsResponse(KeyType.EMAIL.name,"anotherBank@gmail.com",
BcbBankAccountResponse("Itau","0001", "123456", "CACC"),
BcbOwnerResponse("NATURAL_PERSON", "Gabriel", "44719190839"), LocalDateTime.now())
}
| 0
|
Kotlin
|
0
| 0
|
ab924216a36e3099f81267d4d6bc822b89b266e9
| 6,207
|
orange-talents-06-template-pix-keymanager-grpc
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/ui/navigation/AppNavigationHost.kt
|
ryanw-mobile
| 794,752,204
| false
|
{"Kotlin": 518481, "Swift": 693}
|
/*
* Copyright (c) 2024. <NAME>
* https://github.com/ryanw-mobile
* Sponsored by RW MobiMedia UK Limited
*
*/
package com.rwmobi.kunigami.ui.navigation
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.rwmobi.kunigami.ui.destinations.account.AccountScreen
import com.rwmobi.kunigami.ui.destinations.account.AccountUIEvent
import com.rwmobi.kunigami.ui.destinations.agile.AgileScreen
import com.rwmobi.kunigami.ui.destinations.agile.AgileUIEvent
import com.rwmobi.kunigami.ui.destinations.tariffs.TariffsScreen
import com.rwmobi.kunigami.ui.destinations.tariffs.TariffsUIEvent
import com.rwmobi.kunigami.ui.destinations.usage.UsageScreen
import com.rwmobi.kunigami.ui.destinations.usage.UsageUIEvent
import com.rwmobi.kunigami.ui.utils.collectAsStateMultiplatform
import com.rwmobi.kunigami.ui.utils.getScreenSizeInfo
import com.rwmobi.kunigami.ui.viewmodels.AccountViewModel
import com.rwmobi.kunigami.ui.viewmodels.AgileViewModel
import com.rwmobi.kunigami.ui.viewmodels.TariffsViewModel
import com.rwmobi.kunigami.ui.viewmodels.UsageViewModel
import org.koin.mp.KoinPlatform.getKoin
@Composable
fun AppNavigationHost(
modifier: Modifier = Modifier,
navController: NavHostController,
windowSizeClass: WindowSizeClass,
lastDoubleTappedNavItem: AppNavigationItem?,
onShowSnackbar: suspend (String) -> Unit,
onScrolledToTop: (AppNavigationItem) -> Unit,
) {
NavHost(
modifier = modifier,
navController = navController,
startDestination = AppNavigationItem.USAGE.name,
) {
composable(route = AppNavigationItem.USAGE.name) {
val viewModel: UsageViewModel = viewModel { getKoin().get() }
val uiState by viewModel.uiState.collectAsStateMultiplatform()
// workaround: Issue with iOS we have to do it here
val screenSizeInfo = getScreenSizeInfo()
viewModel.notifyScreenSizeChanged(screenSizeInfo = screenSizeInfo)
LaunchedEffect(lastDoubleTappedNavItem) {
val enabled = lastDoubleTappedNavItem?.equals(AppNavigationItem.USAGE) ?: false
viewModel.requestScrollToTop(enabled = enabled)
}
UsageScreen(
modifier = Modifier.fillMaxSize(),
uiState = uiState,
uiEvent = UsageUIEvent(
onInitialLoad = viewModel::initialLoad,
onSwitchPresentationStyle = viewModel::onSwitchPresentationStyle,
onPreviousTimeFrame = viewModel::onPreviousTimeFrame,
onNextTimeFrame = viewModel::onNextTimeFrame,
onErrorShown = viewModel::errorShown,
onScrolledToTop = { onScrolledToTop(AppNavigationItem.USAGE) },
onShowSnackbar = onShowSnackbar,
),
)
}
composable(route = AppNavigationItem.AGILE.name) {
val viewModel: AgileViewModel = viewModel { getKoin().get() }
val uiState by viewModel.uiState.collectAsStateMultiplatform()
// workaround: Issue with iOS we have to do it here
val screenSizeInfo = getScreenSizeInfo()
viewModel.notifyScreenSizeChanged(screenSizeInfo = screenSizeInfo)
LaunchedEffect(lastDoubleTappedNavItem) {
val enabled = lastDoubleTappedNavItem?.equals(AppNavigationItem.AGILE) ?: false
viewModel.requestScrollToTop(enabled = enabled)
}
AgileScreen(
modifier = Modifier.fillMaxSize(),
uiState = uiState,
uiEvent = AgileUIEvent(
onRefresh = viewModel::refresh,
onErrorShown = viewModel::errorShown,
onScrolledToTop = { onScrolledToTop(AppNavigationItem.AGILE) },
onShowSnackbar = onShowSnackbar,
),
)
}
composable(route = AppNavigationItem.TARIFFS.name) {
val viewModel: TariffsViewModel = viewModel { getKoin().get() }
val uiState by viewModel.uiState.collectAsStateMultiplatform()
LaunchedEffect(lastDoubleTappedNavItem) {
val enabled = lastDoubleTappedNavItem?.equals(AppNavigationItem.TARIFFS) ?: false
viewModel.requestScrollToTop(enabled = enabled)
}
TariffsScreen(
modifier = Modifier.fillMaxSize(),
uiState = uiState,
uiEvent = TariffsUIEvent(
onRefresh = viewModel::refresh,
onProductItemClick = {}, // TODO: Not sure where to go
onErrorShown = viewModel::errorShown,
onScrolledToTop = { onScrolledToTop(AppNavigationItem.TARIFFS) },
onShowSnackbar = onShowSnackbar,
),
)
}
composable(route = AppNavigationItem.ACCOUNT.name) {
val viewModel: AccountViewModel = viewModel { getKoin().get() }
val uiState by viewModel.uiState.collectAsStateMultiplatform()
viewModel.notifyWindowSizeClassChanged(windowSizeClass = windowSizeClass)
LaunchedEffect(lastDoubleTappedNavItem) {
val enabled = lastDoubleTappedNavItem?.equals(AppNavigationItem.ACCOUNT) ?: false
viewModel.requestScrollToTop(enabled = enabled)
}
AccountScreen(
modifier = Modifier.fillMaxSize(),
uiState = uiState,
uiEvent = AccountUIEvent(
onRefresh = viewModel::refresh,
onUpdateApiKeyClicked = {}, // TODO: Dialog
onClearCredentialButtonClicked = viewModel::clearCredentials,
onSubmitCredentials = viewModel::submitCredentials,
onMeterSerialNumberSelected = viewModel::updateMeterSerialNumber,
onErrorShown = viewModel::errorShown,
onScrolledToTop = { onScrolledToTop(AppNavigationItem.ACCOUNT) },
onShowSnackbar = onShowSnackbar,
),
)
}
}
}
| 24
|
Kotlin
|
0
| 2
|
241e0ea08e92d663e8c9fb2732627dc054e24db6
| 6,614
|
OctoMeter
|
MIT License
|
product-group-common/src/commonMain/kotlin/models/PrgrpGroupLock.kt
|
crowdproj
| 508,540,199
| false
|
{"Kotlin": 270309}
|
package models
import kotlin.jvm.JvmInline
@JvmInline
value class PrgrpGroupLock(private val id: String) {
fun asString() = id
companion object {
val NONE = PrgrpGroupLock("")
}
}
| 0
|
Kotlin
|
3
| 1
|
dd2ee2aa0c4c3e0e3cabcdf3db42fcd8304b093f
| 202
|
crowdproj-product-groups
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnAnalysisGeospatialMapStyleOptionsPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.quicksight
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.quicksight.CfnAnalysis
/**
* The map style options of the geospatial map.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.quicksight.*;
* GeospatialMapStyleOptionsProperty geospatialMapStyleOptionsProperty =
* GeospatialMapStyleOptionsProperty.builder()
* .baseMapStyle("baseMapStyle")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-geospatialmapstyleoptions.html)
*/
@CdkDslMarker
public class CfnAnalysisGeospatialMapStyleOptionsPropertyDsl {
private val cdkBuilder: CfnAnalysis.GeospatialMapStyleOptionsProperty.Builder =
CfnAnalysis.GeospatialMapStyleOptionsProperty.builder()
/** @param baseMapStyle The base map style of the geospatial map. */
public fun baseMapStyle(baseMapStyle: String) {
cdkBuilder.baseMapStyle(baseMapStyle)
}
public fun build(): CfnAnalysis.GeospatialMapStyleOptionsProperty = cdkBuilder.build()
}
| 4
| null |
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 1,477
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/famas/doodlekingkmm/presentation/screen_game/GameScreen.kt
|
rvenky125
| 610,919,955
| false
|
{"Kotlin": 94142, "Ruby": 2308, "Swift": 771}
|
package com.famas.doodlekingkmm.presentation.screen_game
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Button
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import com.famas.doodlekingkmm.core.util.asFormattedDate
import com.famas.doodlekingkmm.core.util.getScreenModel
import com.famas.doodlekingkmm.data.models.Announcement
import com.famas.doodlekingkmm.data.models.ChatMessage
import com.famas.doodlekingkmm.presentation.components.canvas.CanvasBox
import com.famas.doodlekingkmm.presentation.screen_game.components.ChatItem
import com.famas.doodlekingkmm.presentation.screen_game.components.PlayerScores
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class GameScreen(
private val roomId: String
) : Screen {
@Composable
override fun Content() {
val viewModel = getScreenModel<GameScreenVM>()
val state = viewModel.gameScreenState.value
val navigator = LocalNavigator.current
val focusManager = LocalFocusManager.current
val animatedProgress = remember {
Animatable(1f)
}
val drawerState = rememberDrawerState(DrawerValue.Closed)
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(Unit) {
delay(1000)
viewModel.connectToRoom(roomId, navigator)
}
LaunchedEffect(state.totalTime, state.time) {
if (state.totalTime != 0L || state.time != 0L) {
animatedProgress.animateTo(state.time.toFloat() / state.totalTime.toFloat())
}
}
ModalNavigationDrawer(drawerContent = {
PlayerScores(state.playersList)
}, drawerState = drawerState, modifier = Modifier.fillMaxSize()) {
if (state.showChooseWordsView) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
state.newWords.forEach {
Button(onClick = {
viewModel.onEvent(GameScreenEvent.OnSelectWord(it))
}, modifier = Modifier.padding(bottom = 10.dp)) {
Text(it)
}
}
Text(
(state.time / 1000L).toString(),
style = MaterialTheme.typography.displayLarge,
modifier = Modifier.padding(top = 20.dp)
)
}
} else {
Column {
CanvasBox(
canvasController = viewModel.canvasController,
modifier = Modifier.fillMaxWidth().fillMaxHeight(0.55f).onPlaced {
viewModel.onEvent(
GameScreenEvent.OnLayout(
it.size.width,
it.size.height
)
)
},
onGoBack = {
navigator?.pop()
},
drawingEnabled = state.drawingPlayer == state.username
)
Text(
state.statusText ?: "",
modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp),
textAlign = TextAlign.Center
)
LinearProgressIndicator(
progress = animatedProgress.value,
modifier = Modifier.fillMaxWidth().padding(bottom = 12.dp)
)
Column(modifier = Modifier.pointerInput(Unit) { detectTapGestures { } }) {
Row(modifier = Modifier.weight(1f)) {
IconButton(onClick = {
coroutineScope.launch {
drawerState.open()
}
}) {
Icon(Icons.Default.Person, null)
}
LazyColumn(
modifier = Modifier.weight(1f),
horizontalAlignment = Alignment.End,
reverseLayout = true
) {
items(state.messages) {
when (it) {
is Announcement -> {
Surface(
color = MaterialTheme.colorScheme.tertiaryContainer,
modifier = Modifier.padding(vertical = 10.dp)
.padding(horizontal = 16.dp),
shape = RoundedCornerShape(25)
) {
Column(modifier = Modifier.padding(10.dp)) {
Text(
it.message,
modifier = Modifier.padding(vertical = 5.dp)
)
Text(
it.timestamp.asFormattedDate(),
modifier = Modifier.padding(vertical = 5.dp),
style = MaterialTheme.typography.labelSmall
)
}
}
}
is ChatMessage -> {
ChatItem(
message = it.message,
name = it.from,
timestamp = it.timestamp,
modifier = Modifier.padding(
horizontal = 16.dp,
vertical = 4.dp
).padding(bottom = 16.dp)
)
}
else -> Text(
it.toString(),
modifier = Modifier.padding(vertical = 5.dp)
)
}
}
}
}
if (state.drawingPlayer != state.username) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(
state.textInputValue,
onValueChange = {
viewModel.onEvent(GameScreenEvent.OnChangeTextInputValue(it))
},
modifier = Modifier.weight(1f),
keyboardOptions = KeyboardOptions(
autoCorrect = false,
imeAction = ImeAction.Done
),
maxLines = 1
)
IconButton(onClick = {
viewModel.onEvent(GameScreenEvent.OnSendMessage)
focusManager.clearFocus()
}) {
Icon(imageVector = Icons.Default.Send, null)
}
}
}
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 28
|
0966d0f4540c1a3d8ef6d6360111404378cb0fa8
| 10,473
|
DoodleKingKMM
|
MIT License
|
app/src/main/java/space/taran/arknavigator/mvp/model/repo/extra/ImageMetaExtra.kt
|
ARK-Builders
| 394,855,699
| false
| null |
package space.taran.arknavigator.mvp.model.repo.extra
import java.nio.file.Path
import space.taran.arknavigator.mvp.model.repo.index.ResourceMetaExtra
import space.taran.arknavigator.utils.extension
object ImageMetaExtra {
val ACCEPTED_EXTENSIONS: Set<String> =
setOf("jpg", "jpeg", "png")
fun extract(path: Path): ResourceMetaExtra? = null
fun isImage(path: Path): Boolean =
ACCEPTED_EXTENSIONS.contains(extension(path))
}
| 103
|
Kotlin
|
12
| 4
|
1d6cfa9a15d95a2ca1d7628042142f972931393f
| 456
|
ARK-Navigator
|
MIT License
|
extension/src/main/java/com/stanfit/android/extension/library/date/Date+Utils.kt
|
stanfit
| 258,159,175
| false
| null |
package com.stanfit.android.extension.library.date
import android.text.format.DateUtils
import java.util.*
/**
* Check today.
*
* @return Boolean
*/
fun Date.isToday(): Boolean {
return DateUtils.isToday(time)
}
/**
* Check yesterday.
*
* @return Boolean
*/
fun Date.isYesterday(): Boolean {
return DateUtils.isToday(time + DateUtils.DAY_IN_MILLIS)
}
/**
* Check tomorrow.
*
* @return Boolean
*/
fun Date.isTomorrow(): Boolean {
return DateUtils.isToday(time - DateUtils.DAY_IN_MILLIS)
}
/**
* Check this month.
*
* @return Boolean
*/
fun Date.isThisMonth(): Boolean {
val target = Calendar.getInstance()
target.time = this
val current = Calendar.getInstance()
return target.get(Calendar.MONTH) == current.get(Calendar.MONTH)
}
/**
* Check this year.
*
* @return Boolean
*/
fun Date.isThisYear(): Boolean {
val target = Calendar.getInstance()
target.time = this
val current = Calendar.getInstance()
return target.get(Calendar.YEAR) == current.get(Calendar.YEAR)
}
| 1
|
Kotlin
|
0
| 1
|
d188377ea090777a5d591fc72d19b5b32fddd6e3
| 1,033
|
android-extension
|
MIT License
|
Dr Cat/app/src/main/java/com/sapplication/app/modules/guideselfnotespage/data/model/ListdrlivingstoneRowModel.kt
|
QwertyFusion
| 744,446,675
| false
|
{"Kotlin": 86043}
|
package com.sapplication.app.modules.guideselfnotespage.`data`.model
import com.sapplication.app.R
import com.sapplication.app.appcomponents.di.MyApp
import kotlin.String
data class ListdrlivingstoneRowModel(
/**
* TODO Replace with dynamic value
*/
var txtDrLivingstone: String? =
MyApp.getInstance().resources.getString(R.string.lbl_dr_livingstone)
,
/**
* TODO Replace with dynamic value
*/
var txtTherapistBoo: String? = MyApp.getInstance().resources.getString(R.string.msg_therapist_boo)
)
| 0
|
Kotlin
|
1
| 0
|
8a9af6d4ee80d130f2f494a0b838b4f53c43f755
| 526
|
SIH-2023
|
MIT License
|
core/src/org/river/exertion/ai/noumena/group/RedHandNoumenon.kt
|
exertionriver
| 345,650,250
| false
| null |
package org.river.exertion.ai.noumena.group
import org.river.exertion.ai.attribute.Trait.Companion.mergeOverrideTraits
import org.river.exertion.ai.internalFacet.InternalFacetAttribute
import org.river.exertion.ai.noumena.GroupNoumenon
import org.river.exertion.ai.noumena.core.IAttributeable
import org.river.exertion.ai.noumena.core.INoumenon
import org.river.exertion.ai.noumena.core.NoumenonType
class RedHandNoumenon : INoumenon, IAttributeable {
override fun type() = NoumenonType.RED_HAND
override fun types() = GroupNoumenon.types().toMutableList().apply { this.add( type() ) }.toList()
override fun traits() = GroupNoumenon.traits().mergeOverrideTraits(listOf())
override fun facetAttributes() = mutableSetOf<InternalFacetAttribute>()
}
| 0
|
Kotlin
|
0
| 2
|
058c7ec60da78953c3141a7e866047eb2f453a3b
| 764
|
koboldCave
|
MIT License
|
contributor-api/src/main/java/com/anand/contributor/contributor/api/IBottomNavigationContribution.kt
|
microsoft
| 561,173,246
| false
|
{"Kotlin": 14422}
|
/*
* Copyright (c) Microsoft Corporation. Licensed under the MIT license.
*/
package com.anand.contributor.contributor.api
import androidx.annotation.DrawableRes
import androidx.fragment.app.Fragment
interface IBottomNavigationContribution: IContribution {
val state: BottomNavigationContributionState
fun fragment(): Class<out Fragment>
}
data class BottomNavigationContributionState(
val text: String,
@DrawableRes val icon: Int,
val order: Int
)
| 0
|
Kotlin
|
1
| 6
|
382974651b7d357d4d9630499f54dc6ffe2f20db
| 473
|
contributor-design-pattern-sample
|
MIT License
|
app/src/main/java/chenmc/sms/transaction/service/SetReadService.kt
|
zhidao8
| 105,611,156
| false
| null |
package chenmc.sms.transaction.service
import android.app.Service
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.support.v4.content.ContextCompat
/**
* @author Carter
* Created on 2018-04-21
*/
class SetReadService : Service() {
private val handler: Handler = object : Handler(Looper.myLooper()) {
override fun handleMessage(msg: Message) {
val sms = msg.obj as String
val newValues = ContentValues()
newValues.put("read", 1)
contentResolver.update(Uri.parse("content://sms/"), newValues, "body like ?", arrayOf("%$sms%"))
stopSelf(msg.what)
}
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
if (ContextCompat.checkSelfPermission(this, "android.permission.WRITE_SMS") ==
PackageManager.PERMISSION_GRANTED) {
val message = handler.obtainMessage(startId, intent.getStringExtra(EXTRA_SMS))
// 延迟 3 秒,等待短信写入数据库
handler.sendMessageDelayed(message, 3 * 1000)
} else stopSelf(startId)
return Service.START_NOT_STICKY
}
companion object {
const val EXTRA_SMS = "EXTRA_SMS"
}
}
| 3
|
Kotlin
|
10
| 69
|
8c83419e2574c464be5cdd7d2e7a50e4beb08ee9
| 1,490
|
SmsCodeHelper
|
Apache License 2.0
|
app/src/main/java/chenmc/sms/transaction/service/SetReadService.kt
|
zhidao8
| 105,611,156
| false
| null |
package chenmc.sms.transaction.service
import android.app.Service
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.support.v4.content.ContextCompat
/**
* @author Carter
* Created on 2018-04-21
*/
class SetReadService : Service() {
private val handler: Handler = object : Handler(Looper.myLooper()) {
override fun handleMessage(msg: Message) {
val sms = msg.obj as String
val newValues = ContentValues()
newValues.put("read", 1)
contentResolver.update(Uri.parse("content://sms/"), newValues, "body like ?", arrayOf("%$sms%"))
stopSelf(msg.what)
}
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
if (ContextCompat.checkSelfPermission(this, "android.permission.WRITE_SMS") ==
PackageManager.PERMISSION_GRANTED) {
val message = handler.obtainMessage(startId, intent.getStringExtra(EXTRA_SMS))
// 延迟 3 秒,等待短信写入数据库
handler.sendMessageDelayed(message, 3 * 1000)
} else stopSelf(startId)
return Service.START_NOT_STICKY
}
companion object {
const val EXTRA_SMS = "EXTRA_SMS"
}
}
| 3
|
Kotlin
|
10
| 69
|
8c83419e2574c464be5cdd7d2e7a50e4beb08ee9
| 1,490
|
SmsCodeHelper
|
Apache License 2.0
|
InstaTask/app/src/main/java/com/example/instatask/model/JobCreator.kt
|
linpeterk
| 472,551,243
| false
| null |
package com.example.instatask.model
data class JobCreator (
val id:Int,
val name:String,
val hourlyRate:Int = 25,
val description:String,
val imageRes:Int,
val available:String = "Monday-Friday",
val workLocation:String = "Orange County Area"
)
| 0
|
Kotlin
|
0
| 0
|
fd9fd4723b8180a5b19e40bb43ae822e1418b0ff
| 279
|
Insta-Task
|
Apache License 2.0
|
key-manager-grpc/src/main/kotlin/br/com/zup/orange/pix/TipoChave.kt
|
jpauloleao
| 396,783,482
| true
|
{"Kotlin": 63764}
|
package br.com.zup.orange.pix
import org.hibernate.validator.internal.constraintvalidators.hv.br.CPFValidator
enum class TipoChave {
CPF {
override fun validaChave(chave: String?) : Boolean{
if (chave.isNullOrBlank()) {
throw IllegalArgumentException("Chave não deve ser nula")
}
if (!chave.matches("^[0-9]{11}\$".toRegex())) {
throw IllegalArgumentException("Chave não segue o padrão. Ex: 12345678901")
}
val retornoValidacao = CPFValidator().run {
initialize(null)
isValid(chave, null) }
if(!retornoValidacao){
throw IllegalArgumentException("CPF Invalido")
}
return true
}
},
CELULAR {
override fun validaChave(chave: String?) : Boolean{
if (chave.isNullOrBlank()) {
throw IllegalArgumentException("Chave não deve ser nula")
}
if (!chave.matches("^\\+[1-9][0-9]\\d{1,14}\$".toRegex())) {
throw IllegalArgumentException("Chave não segue o padrão. Ex: +5585988714077")
}
return true
}
},
EMAIL {
override fun validaChave(chave: String?) : Boolean{
if (chave.isNullOrBlank()) {
throw IllegalArgumentException("Chave não deve ser nula")
}
if(!chave.matches("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})\$".toRegex())){
throw IllegalArgumentException("Email em formato Invalido")
}
return true
}
},
ALEATORIA {
override fun validaChave(chave: String?) : Boolean{
//Requisito: Quando a chave for aleatoria, o sistema que gera
if(!chave.isNullOrBlank()){
throw IllegalArgumentException("Chave Aleatoria é gerada pelo sistema, não deve ser preenchida")
}
return true
}
};
abstract fun validaChave(chave: String?) : Boolean
}
| 0
|
Kotlin
|
0
| 0
|
979b76f910178cdc0514bb56241263bf8fcc4fbe
| 2,130
|
orange-talents-06-template-pix-keymanager-grpc
|
Apache License 2.0
|
app/src/main/java/br/com/ernanilima/jinventario/data/result/IResult.kt
|
ernanilima
| 370,795,646
| false
| null |
package br.com.ernanilima.jinventario.data.result;
/**
* Usada para receber os resultados
*/
interface IResult {
fun setResult(iResult: IResultType)
fun setResultFirebaseError(errorCode: String)
}
| 0
|
Kotlin
|
0
| 2
|
8b98c69920f6bbc963f2f9ab926bda374f274dd1
| 207
|
jinventario
|
MIT License
|
app/src/main/java/com/imcys/bilibilias/home/ui/model/UserCreateCollectionBean.kt
|
1250422131
| 280,332,208
| false
|
{"Kotlin": 580556, "Java": 28319}
|
package com.imcys.bilibilias.home.ui.model
import kotlinx.serialization.Serializable
/**
* 用户创建收藏夹数据
*/
@Serializable
data class UserCreateCollectionBean(
val code: Int = 0,
val message: String = "",
val ttl: Int = 0,
val data: DataBean = DataBean(),
) {
@Serializable
data class DataBean(val list: List<ListBean> = emptyList()) {
@Serializable
data class ListBean(
val id: Long = 0,
val mid: Long = 0,
val attr: Int = 0,
val title: String = "",
val media_count: Int = 0,
var selected: Int = 0,
)
}
}
| 11
|
Kotlin
|
51
| 849
|
4dff7fbbcffeead83d0d3881bb3782857f08b830
| 629
|
bilibilias
|
Apache License 2.0
|
app/src/main/java/com/cookiedinner/boxanizer/core/components/CameraComponent.kt
|
CookieDinner
| 782,371,313
| false
|
{"Kotlin": 237478}
|
package com.cookiedinner.boxanizer.core.components
import android.Manifest
import android.content.res.Configuration
import android.graphics.Bitmap
import android.widget.LinearLayout
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis.Analyzer
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.ImageProxy
import androidx.camera.view.LifecycleCameraController
import androidx.camera.view.PreviewView
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterExitState
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PhotoCamera
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.cookiedinner.boxanizer.core.data.DataStoreManager
import com.cookiedinner.boxanizer.core.models.CameraDialogState
import com.cookiedinner.boxanizer.core.models.CameraPhotoPhase
import com.cookiedinner.boxanizer.core.models.CameraType
import com.cookiedinner.boxanizer.core.utilities.BarcodeAnalyzer
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import org.koin.compose.koinInject
import java.io.ByteArrayOutputStream
import java.util.concurrent.Executors
object CameraComponentDefaults {
@Composable
fun Overlay() {
val dividerColor = MaterialTheme.colorScheme.surface
Column(
modifier = Modifier.height(180.dp),
verticalArrangement = Arrangement.SpaceBetween
) {
HorizontalDivider(
thickness = Dp.Hairline,
color = dividerColor
)
HorizontalDivider(
thickness = Dp.Hairline,
color = dividerColor
)
}
Row(
modifier = Modifier.width(180.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
VerticalDivider(
thickness = Dp.Hairline,
color = dividerColor
)
VerticalDivider(
thickness = Dp.Hairline,
color = dividerColor
)
}
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun CameraDialog(
state: CameraDialogState,
onScanned: (String) -> Unit = {},
takePhoto: (ByteArray?) -> Unit = {},
dataStoreManager: DataStoreManager = koinInject(),
overlay: @Composable BoxScope.() -> Unit = {}
) {
val orientation = LocalConfiguration.current.orientation
val scannableBarcodes = dataStoreManager.collectBarcodeTypesWithLifecycle()
var canScan = remember {
true
}
LaunchedEffect(state.visible, state.scannerFlag) {
if (state.visible)
canScan = true
}
AnimatedVisibility(
visible = state.visible,
enter = fadeIn(tween(50)),
exit = fadeOut(tween(300, 300))
) {
Dialog(
onDismissRequest = {
state.hide()
},
properties = DialogProperties(
usePlatformDefaultWidth = false
)
) {
AnimatedVisibility(
visible = state.visible && transition.currentState == EnterExitState.Visible,
enter = fadeIn(tween(700)) + scaleIn(tween(700)),
exit = fadeOut(tween(500)) + scaleOut(tween(700))
) {
OutlinedCard(
modifier = Modifier
.padding(8.dp)
.then(
if (orientation == Configuration.ORIENTATION_PORTRAIT)
Modifier
.fillMaxWidth(0.95f)
.aspectRatio(3f / 4)
else
Modifier
.fillMaxHeight(0.95f)
.aspectRatio(4f / 3)
)
) {
if (state.visible && !transition.isRunning) {
Box(
modifier = Modifier.padding(4.dp),
contentAlignment = Alignment.Center
) {
CameraComponent(
imageAnalyzer = if (state.type == CameraType.SCANNER) {
BarcodeAnalyzer(
barcodeListener = {
canScan = false
onScanned(it)
},
scannableBarcodes = scannableBarcodes.value,
canScan = canScan
)
} else null,
takePhoto = if (state.type == CameraType.PHOTO) {
{ phase, byteArray ->
when (phase) {
CameraPhotoPhase.TAKING -> {
state.hide()
}
CameraPhotoPhase.DONE -> {
takePhoto(byteArray)
}
CameraPhotoPhase.ERROR -> {
//TODO Camera error handling
}
}
}
} else null
)
overlay()
}
}
}
}
}
}
}
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun CameraComponent(
modifier: Modifier = Modifier,
imageAnalyzer: Analyzer? = null,
takePhoto: ((CameraPhotoPhase, ByteArray?) -> Unit)? = null
) {
val cameraPermissionState = rememberPermissionState(permission = Manifest.permission.CAMERA)
Surface(
modifier = Modifier.then(modifier),
shape = MaterialTheme.shapes.small
) {
if (cameraPermissionState.status.isGranted) {
CameraPreview(
imageAnalyzer = imageAnalyzer,
takePhoto = takePhoto
)
} else {
NoPermissionScreen(cameraPermissionState::launchPermissionRequest)
}
}
}
@Composable
private fun CameraPreview(
imageAnalyzer: Analyzer?,
takePhoto: ((CameraPhotoPhase, ByteArray?) -> Unit)?
) {
val lifecycleOwner = LocalLifecycleOwner.current
val context = LocalContext.current
val cameraController = remember {
LifecycleCameraController(context)
}
val cameraExecutor = remember {
Executors.newSingleThreadExecutor()
}
Box(contentAlignment = Alignment.BottomCenter) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = {
PreviewView(context).apply {
layoutParams = LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT)
setBackgroundColor(android.graphics.Color.BLACK)
scaleType = PreviewView.ScaleType.FIT_CENTER
}.also { previewView ->
cameraController.unbind()
cameraController.bindToLifecycle(lifecycleOwner)
cameraController.cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
previewView.controller = cameraController
if (imageAnalyzer != null)
cameraController.setImageAnalysisAnalyzer(cameraExecutor, imageAnalyzer)
}
}
)
var photoTaken by rememberSaveable {
mutableStateOf(false)
}
if (takePhoto != null) {
FloatingActionButton(
modifier = Modifier.padding(bottom = 16.dp),
shape = CircleShape,
onClick = {
if (!photoTaken) {
photoTaken = true
cameraController.takePicture(
cameraExecutor,
object : ImageCapture.OnImageCapturedCallback() {
override fun onCaptureSuccess(imageProxy: ImageProxy) {
super.onCaptureSuccess(imageProxy)
takePhoto(CameraPhotoPhase.TAKING, null)
val bitmap = imageProxy.toBitmap()
val byteStream = ByteArrayOutputStream()
val aspectRatio = bitmap.width.toFloat() / bitmap.height
val resizedBitmap = Bitmap.createScaledBitmap(bitmap, (800 * aspectRatio).toInt(), 800, true)
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream)
bitmap.recycle()
resizedBitmap.recycle()
imageProxy.close()
takePhoto(CameraPhotoPhase.DONE, byteStream.toByteArray())
}
override fun onError(exception: ImageCaptureException) {
super.onError(exception)
exception.printStackTrace()
takePhoto(CameraPhotoPhase.ERROR, null)
}
}
)
}
}
) {
AnimatedContent(
targetState = photoTaken
) {
if (it) {
CircularProgressIndicator()
} else {
Icon(
imageVector = Icons.Default.PhotoCamera,
contentDescription = ""
)
}
}
}
}
}
}
@Composable
private fun NoPermissionScreen(askForPermission: () -> Unit) {
LaunchedEffect(Unit) {
askForPermission()
}
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black),
contentAlignment = Alignment.Center
) {
Text(
text = "Brak uprawnień do korzystania z kamery",
style = MaterialTheme.typography.titleMedium.copy(color = Color.White)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
d719b28665f3f9bdb52bfa53f0e6448a04c3cd04
| 13,259
|
Boxanizer
|
MIT License
|
src/main/java/challenges/cracking_coding_interview/object_oriented_design/othello/Piece.kt
|
MalekKamel
| 342,007,920
| false
|
{"Kotlin": 835312}
|
package challenges.cracking_coding_interview.object_oriented_design.othello
class Piece(var color: Color) {
fun flip() {
color = if (color == Color.Black) {
Color.White
} else {
Color.Black
}
}
}
| 0
|
Kotlin
|
0
| 1
|
3282a5d6f1906582a8194ff3c8cf3b7530c7a16d
| 252
|
ProblemSolving
|
Apache License 2.0
|
app/src/main/java/com/example/vigilanceai/facedetection/FaceDetectionActivity.kt
|
muhammad-mobeen
| 648,892,682
| false
| null |
package com.example.vigilanceai.facedetection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.vigilanceai.R
class FaceDetectionActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_face_detection)
}
}
| 0
|
Kotlin
|
0
| 0
|
63278d674530a6872211f250c942511e4890ffe3
| 370
|
Vigilance-AI-App
|
MIT License
|
app/src/main/java/ru/llxodz/pizzahouse/api/data/ApiMenuCategory.kt
|
llxodz
| 412,611,087
| false
| null |
package ru.llxodz.pizzahouse.api.data
import java.net.URL
data class ApiMenuCategory(
var id: Int,
var name: String,
var image: Int
)
val ApiMenuCategory.url: URL
get() {
return URL(this.id.toString())
}
| 0
|
Kotlin
|
0
| 0
|
a8f170996f8308c649aad6b065ad18b30c5306be
| 234
|
PizzaHouseAndroid
|
Apache License 2.0
|
main/java/com/example/login_page/localData/ReservationDatabase.kt
|
Wail-Sr
| 547,840,618
| false
|
{"Kotlin": 72508}
|
package com.example.login_page.localData
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Reserv::class], version = 1, exportSchema = false)
abstract class ReservationDatabase: RoomDatabase() {
abstract fun reservationDao(): ReservationDao
companion object {
// ReservationDatabase is a singleton
@Volatile
private var INSTANCE: ReservationDatabase? = null
fun getDatabase(context: Context): ReservationDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
ReservationDatabase::class.java,
"reservation_database"
).build()
INSTANCE = instance
return instance
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3b624307a86536586cdd06a9804ce0e3bb84801a
| 1,040
|
GARRU
|
MIT License
|
aTalk/src/main/java/net/java/sip/communicator/impl/provdisc/mdns/ProvisioningDiscoveryServiceMDNSImpl.kt
|
cmeng-git
| 704,328,019
| false
|
{"Kotlin": 14364024, "Java": 2718723, "C": 275021, "Shell": 49203, "Makefile": 28273, "C++": 13642, "HTML": 7793, "CSS": 3127, "JavaScript": 2758, "AIDL": 375}
|
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* 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 net.java.sip.communicator.impl.provdisc.mdns
import net.java.sip.communicator.service.provdisc.AbstractProvisioningDiscoveryService
import net.java.sip.communicator.service.provdisc.event.DiscoveryEvent
import net.java.sip.communicator.service.provdisc.event.DiscoveryListener
import timber.log.Timber
/**
* Class that uses mDNS to retrieve provisioning URL.
*
* @author <NAME>
* @author <NAME>
*/
class ProvisioningDiscoveryServiceMDNSImpl constructor() : AbstractProvisioningDiscoveryService(), DiscoveryListener {
/**
* MDNS provisioning discover object.
*/
private var discover: MDNSProvisioningDiscover? = null
/**
* Constructor.
*/
init {
try {
discover = MDNSProvisioningDiscover()
discover!!.addDiscoveryListener(this)
} catch (e: Exception) {
Timber.w(e, "Cannot create JmDNS instance")
}
}
/**
* Get the name of the method name used to retrieve provisioning URL.
*
* @return method name
*/
public override fun getMethodName(): String? {
return METHOD_NAME
}
/**
* Launch a discovery for a provisioning URL. This method is synchronous and
* may block for some time. Note that you don't have to call
* `startDiscovery` method prior to this one to retrieve URL.
*
* @return provisioning URL
*/
public override fun discoverURL(): String? {
if (discover != null) {
return discover!!.discoverProvisioningURL()
}
return null
}
/**
* Launch a mDNS discovery for a provisioning URL.
*
* This method is asynchronous, the response will be notified to any
* `ProvisioningListener` registered.
*/
public override fun startDiscovery() {
if (discover != null) {
Thread(discover).start()
}
}
/**
* Notify the provisioning URL.
*
* @param event provisioning event
*/
public override fun notifyProvisioningURL(event: DiscoveryEvent?) {
fireDiscoveryEvent(event)
}
companion object {
/**
* Name of the method used to retrieve provisioning URL.
*/
private val METHOD_NAME = "Bonjour"
}
}
| 0
|
Kotlin
|
0
| 0
|
90e83dd8c054a5f480d03e8b0b1912b41bd79b0c
| 2,893
|
atalk-hmos_kotlin
|
Apache License 2.0
|
presentation/src/main/java/com/zlagi/presentation/viewmodel/blog/feed/FeedContract.kt
|
Zlagi
| 475,379,557
| false
|
{"Kotlin": 496613}
|
package com.zlagi.presentation.viewmodel.blog.feed
import com.zlagi.presentation.model.BlogPresentationModel
class FeedContract {
sealed class FeedEvent {
object Initialization : FeedEvent()
object NextPage : FeedEvent()
object SwipeRefresh : FeedEvent()
object CreateBlogButtonClicked : FeedEvent()
data class BlogItemClicked(val blogPk: Int?) : FeedEvent()
}
sealed class FeedViewEffect {
data class Navigate(val blogPk: Int?) : FeedViewEffect()
data class ShowSnackBarError(val error: Int) : FeedViewEffect()
}
data class FeedViewState(
val loading: Boolean = false,
val noResults: Boolean = false,
val results: List<BlogPresentationModel> = emptyList()
)
}
| 0
|
Kotlin
|
12
| 63
|
dffd07e8533c285bb5ca9de4e9676985aa0e87cc
| 770
|
Blogfy
|
Apache License 2.0
|
tooling/compose-intellij-platform/sample/plugin-2/src/main/kotlin/org/jetbrains/compose/intellij/platform/sample/ComposeDemoAction2.kt
|
JetBrains
| 293,498,508
| false
| null |
package org.jetbrains.compose.intellij.platform.sample
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
class ComposeDemoAction2 : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
ComposeDemoDialog2(e.project).show()
}
}
class ComposeDemoDialog2(project: Project?) : AbstractComposeDemoDialog(project) {
init {
title = "Demo Dialog 2"
}
@Composable
override fun dialogContent() {
Row {
Box(
modifier = Modifier.fillMaxHeight().weight(1f)
) {
LazyScrollable()
}
}
}
}
| 668
|
Kotlin
|
645
| 9,090
|
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
| 948
|
compose-jb
|
Apache License 2.0
|
features/dd-sdk-android-session-replay/src/main/kotlin/com/datadog/android/sessionreplay/internal/recorder/mapper/CheckedTextViewMapper.kt
|
DataDog
| 219,536,756
| false
|
{"Kotlin": 7473590, "Java": 236752, "C": 79252, "Shell": 63057, "C++": 31838, "Python": 18744, "CMake": 2676}
|
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.sessionreplay.internal.recorder.mapper
import android.widget.CheckedTextView
import com.datadog.android.sessionreplay.internal.recorder.GlobalBounds
import com.datadog.android.sessionreplay.internal.recorder.densityNormalized
import com.datadog.android.sessionreplay.utils.StringUtils
import com.datadog.android.sessionreplay.utils.UniqueIdentifierGenerator
import com.datadog.android.sessionreplay.utils.ViewUtils
internal open class CheckedTextViewMapper(
textWireframeMapper: TextViewMapper,
private val stringUtils: StringUtils = StringUtils,
uniqueIdentifierGenerator: UniqueIdentifierGenerator = UniqueIdentifierGenerator,
viewUtils: ViewUtils = ViewUtils
) : CheckableTextViewMapper<CheckedTextView>(
textWireframeMapper,
stringUtils,
uniqueIdentifierGenerator,
viewUtils
) {
// region CheckableTextViewMapper
override fun resolveCheckableColor(view: CheckedTextView): String {
view.checkMarkTintList?.let {
return stringUtils.formatColorAndAlphaAsHexa(
it.defaultColor,
OPAQUE_ALPHA_VALUE
)
}
return stringUtils.formatColorAndAlphaAsHexa(view.currentTextColor, OPAQUE_ALPHA_VALUE)
}
override fun resolveCheckableBounds(view: CheckedTextView, pixelsDensity: Float): GlobalBounds {
val viewGlobalBounds = resolveViewGlobalBounds(view, pixelsDensity)
val textViewPaddingRight =
view.totalPaddingRight.toLong().densityNormalized(pixelsDensity)
var checkBoxHeight = 0L
val checkMarkDrawable = view.checkMarkDrawable
if (checkMarkDrawable != null && checkMarkDrawable.intrinsicHeight > 0) {
val height = checkMarkDrawable.intrinsicHeight -
view.totalPaddingTop -
view.totalPaddingBottom
checkBoxHeight = height.toLong().densityNormalized(pixelsDensity)
}
return GlobalBounds(
x = viewGlobalBounds.x + viewGlobalBounds.width - textViewPaddingRight,
y = viewGlobalBounds.y,
width = checkBoxHeight,
height = checkBoxHeight
)
}
// endregion
}
| 54
|
Kotlin
|
51
| 130
|
c925c5207edd70301f93dda432e3caba14e1a8d2
| 2,444
|
dd-sdk-android
|
Apache License 2.0
|
src/main/kotlin/com/between_freedom_and_space/mono_backend/posts/internal/tags/services/InteractionPostToTagService.kt
|
Between-Freedom-and-Space
| 453,797,438
| false
|
{"Kotlin": 614504, "HTML": 8733, "Dockerfile": 503, "Shell": 166}
|
package com.between_freedom_and_space.mono_backend.posts.internal.tags.services
import com.between_freedom_and_space.mono_backend.posts.internal.tags.services.model.BaseTagModel
import com.between_freedom_and_space.mono_backend.posts.internal.tags.services.model.TagId
interface InteractionPostToTagService {
fun deleteAllPostTags(postId: Long): List<BaseTagModel>
fun addTagsToPost(postId: Long, tags: Collection<TagId>): List<BaseTagModel>
}
| 0
|
Kotlin
|
0
| 1
|
812d8257e455e7d5b1d0c703a66b55ed2e1dcd35
| 455
|
Mono-Backend
|
Apache License 2.0
|
layout-inspector/src/com/android/tools/idea/layoutinspector/pipeline/foregroundprocessdetection/DeviceModel.kt
|
JetBrains
| 60,701,247
| false
|
{"Kotlin": 43855938, "Java": 36698280, "HTML": 1216565, "Starlark": 735324, "C++": 216476, "Python": 101594, "C": 71515, "Lex": 66026, "NSIS": 58516, "AIDL": 32502, "Shell": 28591, "CMake": 21034, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
|
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.layoutinspector.pipeline.foregroundprocessdetection
import com.android.tools.idea.appinspection.api.process.ProcessesModel
import com.android.tools.idea.appinspection.inspector.api.process.DeviceDescriptor
import com.android.tools.idea.appinspection.inspector.api.process.ProcessDescriptor
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.CopyOnWriteArraySet
/**
* Keeps track of the currently selected device.
*
* The selected device is controlled by [ForegroundProcessDetection],
* and it is used by [SelectedDeviceAction].
*/
class DeviceModel(parentDisposable: Disposable, private val processesModel: ProcessesModel): Disposable {
@TestOnly
constructor(
parentDisposable: Disposable,
processesModel: ProcessesModel,
foregroundProcessDetectionSupportedDeviceTest: Set<DeviceDescriptor>
) : this(parentDisposable, processesModel) {
foregroundProcessDetectionSupportedDevices.addAll(foregroundProcessDetectionSupportedDeviceTest)
}
init {
Disposer.register(parentDisposable, this)
ForegroundProcessDetection.addDeviceModel(this)
}
override fun dispose() {
ForegroundProcessDetection.removeDeviceModel(this)
}
/**
* The device on which the on-device library is polling for foreground process.
* When null, it means that we are not polling on any device.
*
* [selectedDevice] should only be set by [ForegroundProcessDetection],
* this is to make sure that there is consistency between the [selectedDevice] and the device we are polling on.
*/
var selectedDevice: DeviceDescriptor? = null
internal set(value) {
// each time the selected device changes, the selected process should be reset
// If selectedDevice is null, no device was selected. So we should not reset the process,
// because selectedProcess might be set by the user from the process picker.
if (selectedDevice != null) {
processesModel.selectedProcess = null
}
newSelectedDeviceListeners.forEach { it.invoke(value) }
field = value
}
@TestOnly
fun setSelectedDevice(device: DeviceDescriptor?) {
selectedDevice = device
}
val newSelectedDeviceListeners = CopyOnWriteArraySet<(DeviceDescriptor?) -> Unit>()
/**
* The set of connected devices that support foreground process detection.
*/
internal val foregroundProcessDetectionSupportedDevices = mutableSetOf<DeviceDescriptor>()
val devices: Set<DeviceDescriptor>
get() {
return processesModel.devices
}
val selectedProcess: ProcessDescriptor?
get() {
return processesModel.selectedProcess
}
val processes: Set<ProcessDescriptor>
get() {
return processesModel.processes
}
fun supportsForegroundProcessDetection(device: DeviceDescriptor): Boolean {
return foregroundProcessDetectionSupportedDevices.contains(device)
}
}
| 2
|
Kotlin
|
230
| 876
|
9c0a89784cca3c01ab99cf251b71a26cdb87cc47
| 3,602
|
android
|
Apache License 2.0
|
android/app/src/main/kotlin/de/julianassmann/flutter_gauges/MainActivity.kt
|
JulianAssmann
| 378,205,254
| false
| null |
package de.julianassmann.flutter_gauges
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 5
|
Dart
|
10
| 11
|
e405ae45be634d6940876e77bcafa86d987fe536
| 136
|
flutter_gauges
|
MIT License
|
retrofitfileuploadkit/src/main/java/com/dakshsemwal/retrofitfileuploadkit/FileUploadManagerProvider.kt
|
DAKSHSEMWAL
| 714,609,390
| false
|
{"Kotlin": 49218}
|
package com.dakshsemwal.retrofitfileuploadkit
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
/**
* A module for providing the FileUploadManager instance.
*
* This module uses the Hilt library to set up dependency injection, which makes it easier
* to manage the creation and provisioning of FileUploadManager instances across the app.
* By declaring the provider within an object annotated with @Module and @InstallIn,
* we ensure that Hilt treats this provider as a part of the dependency graph.
*
* @InstallIn(SingletonComponent::class) specifies that the provided instances will
* behave as singletons within the scope of the SingletonComponent, which typically
* lives for the duration of the application's lifecycle.
*/
@Module
@InstallIn(SingletonComponent::class)
object FileUploadManagerProvider {
/**
* Provides a singleton instance of FileUploadManager.
*
* The function is annotated with @Provides and @Singleton to indicate that it is a
* provider function and should only instantiate a single instance of FileUploadManager
* to be used wherever FileUploadManager is injected within the SingletonComponent scope.
*
* The FileUploadManagerImpl is created by passing the FileUploadApi instance which is required
* by the implementation. This allows for the separation of concerns, where the FileUploadManager
* implementation details are abstracted away from the consumers.
*
* @param fileUploadApi An instance of FileUploadApi to be used by the FileUploadManager for
* handling file upload operations.
* @return An instance of FileUploadManager that can be used for uploading files.
*/
@Provides
@Singleton
fun provideFileUploadManager(fileUploadApi: FileUploadApi): FileUploadManager =
FileUploadManagerImpl(fileUploadApi = fileUploadApi)
}
| 0
|
Kotlin
|
0
| 0
|
b943f3f893a4046cdc9818f0dabca288584f8c5b
| 1,966
|
RetrofitUploadKit
|
Apache License 2.0
|
networklib/src/main/java/com/brins/networklib/model/like/LikeMusicResult.kt
|
BrinsLee
| 297,821,918
| false
| null |
package com.brins.networklib.model.like
/**
* Created by lipeilin
* on 2020/10/21
*/
class LikeMusicResult {
var playlistId = ""
var code = 0
}
| 0
|
Kotlin
|
0
| 1
|
37cbd7448ebfc23475c00462018f6d70c74631e1
| 157
|
Music
|
Apache License 2.0
|
app/src/main/java/com/ebnrdwan/task/data/sources/articles/ArticleDataSource.kt
|
ebnrdwan
| 236,335,124
| false
| null |
package com.ebnrdwan.task.data.sources.articles
import com.ebnrdwan.task.BuildConfig
import com.ebnrdwan.task.data.dto.articles.ArticlesEntity
import com.ebnrdwan.task.data.service.ArticlesApi
import io.reactivex.Single
open class ArticleDataSource constructor(private val service: ArticlesApi) :
IArticlesDataSource {
override fun getArticles(): Single<ArticlesEntity> {
return service.getArticlesNews(BuildConfig.API_KEY)
}
}
| 0
|
Kotlin
|
1
| 1
|
9090b4b9a1f6d6ee7541b86bc9610e97bad403fa
| 449
|
NY-Times
|
Apache License 2.0
|
browser-kotlin/src/main/kotlin/js/intl/DisplayNamesFallback.kt
|
karakum-team
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
)
package js.intl
// language=JavaScript
@JsName("""(/*union*/{code: 'code', none: 'none'}/*union*/)""")
external enum class DisplayNamesFallback {
code,
none,
;
}
| 0
|
Kotlin
|
5
| 18
|
83aa7866b2353ee7daf1521611bf7f91ea8b0a9b
| 275
|
types-kotlin
|
Apache License 2.0
|
app/src/main/java/com/olucasmoro/movieapp/feature_watchlist/presentation/WatchListFragment.kt
|
olucasmoro
| 345,404,400
| false
| null |
package com.olucasmoro.movieapp.feature_watchlist.presentation
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.olucasmoro.movieapp.app.service.model.CallResults
import com.olucasmoro.movieapp.app.service.utils.Toast
import com.olucasmoro.movieapp.app.service.utils.Constants
import com.olucasmoro.movieapp.databinding.FragmentWatchlistBinding
import com.olucasmoro.movieapp.feature_user.data.local.SecurityPreferences
import org.koin.androidx.viewmodel.ext.android.viewModel
class WatchListFragment : Fragment() {
private lateinit var mSharedPreferences: SecurityPreferences
private val viewModel: WatchListViewModel by viewModel()
private var _binding: FragmentWatchlistBinding? = null
private val binding get() = _binding!!
private lateinit var watchlistAdapter: WatchListAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentWatchlistBinding.inflate(layoutInflater)
mSharedPreferences = SecurityPreferences(requireContext())
val userId = mSharedPreferences.get(Constants.AUTHENTICATION.USER_ID).toInt()
val sessionId = mSharedPreferences.get(Constants.AUTHENTICATION.SESSION_ID)
getWatchlist(userId, sessionId)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun getWatchlist(userId: Int, sessionId: String) {
viewModel.watchlistMovies(userId, sessionId).observe(viewLifecycleOwner) {
it?.let { response ->
when (response) {
is CallResults.Success -> {
response.data?.let { movie ->
watchlistAdapter = WatchListAdapter(movie, findNavController())
updateAdapter()
watchlistAdapter.notifyDataSetChanged()
true
}
}
is CallResults.Error -> {
Toast.toastDisplay(
requireContext(),
Constants.MESSAGE.FAILURE_CONNECTION
)
}
}
}
}
}
private fun updateAdapter() {
binding.rvMylist.apply {
layoutManager =
GridLayoutManager(requireContext(), 3)
adapter = watchlistAdapter
}
}
}
| 0
|
Kotlin
|
0
| 4
|
a298e7db82645f29b2f20bb6017b95336e5dc825
| 2,763
|
movie-app
|
The Unlicense
|
app/src/main/java/com/tw/auction_demo/net/RemoteBFFService.kt
|
moushao
| 643,272,418
| false
| null |
package com.tw.auction_demo.net
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer
import java.lang.Thread.sleep
/**
* Creates an OkHttp Interceptor that parses a request to dynamically
*/
class RemoteBFFService : Interceptor {
companion object {
const val VALUE_DEFAULT = "default.json"
const val COMBINE_KEY_LIST = "formId"
}
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
var resourceFileContent: String? = null
val operationName =
// request.url.pathSegments.last()+"/$VALUE_DEFAULT"
request.url.pathSegments.joinToString("_").plus(".json")
run getContent@{
val currentContent = readResourceFile(operationName)
if (currentContent != null) {
resourceFileContent = currentContent
return@getContent
}
}
return if (resourceFileContent == null) {
chain.proceed(request)
} else {
Response.Builder()
.code(200)
.protocol(Protocol.HTTP_2)
.message("Mock response")
.body(
resourceFileContent!!
.toByteArray()
.toResponseBody("application/json".toMediaTypeOrNull())
)
.addHeader("content-type", "application/json")
.request(request)
.build()
}
}
private fun readResourceFile(fileName: String) =
javaClass.classLoader
?.getResourceAsStream(fileName)
?.bufferedReader()
?.readText()
private fun JsonElement.toMap(
map: MutableMap<String, String>,
key: String?
): MutableMap<String, String> {
when (this) {
is JsonArray -> {
this.forEach { element ->
element.toMap(map, null)
}
}
is JsonObject -> {
this.keys.forEach { key ->
this[key]?.toMap(map, key)
}
}
else -> {
key?.let {
map[it] = this.toString().replace("\"", "")
}
}
}
return map
}
}
| 0
|
Kotlin
|
0
| 0
|
24f832ce1b74c538dc730e0b1a3632d0cc1f0c6b
| 2,765
|
dark-horse
|
Apache License 2.0
|
spring-pulsar-test/src/test/kotlin/com/intuit/pulsar/tests/consumers/SharedConsumer.kt
|
intuit
| 577,001,055
| false
| null |
package com.intuit.pulsar.tests.consumers
import com.intuit.pulsar.tests.utils.TestConstants
import com.intuit.spring.pulsar.client.annotations.consumer.PulsarConsumer
import com.intuit.spring.pulsar.client.annotations.consumer.Subscription
import com.intuit.spring.pulsar.client.annotations.consumer.Topic
import org.apache.pulsar.client.api.Consumer
import org.apache.pulsar.client.api.Message
import org.springframework.stereotype.Component
@Component(TestConstants.SHARED_CONSUMER)
@PulsarConsumer(
topic = Topic(topicNames = "shared_topic_01"),
subscription = Subscription(
subscriptionName = "shared_sub_01",
subscriptionType = "Shared"
),
count = "2"
)
class SharedConsumer: BaseTestConsumer<ByteArray>() {
override fun received(consumer: Consumer<ByteArray>?, message: Message<ByteArray>?) {
super.messageStore.incrementMessageCount(consumer!!)
consumer.acknowledge(message)
}
}
| 8
|
Kotlin
|
4
| 9
|
fff7f2041724ceeb688a15f39df5b7130a7f598a
| 947
|
spring-pulsar
|
MIT License
|
app/src/main/java/com/unlim/lib/ActivityMain.kt
|
cyxm
| 724,647,363
| false
|
{"Kotlin": 4078}
|
package com.unlim.lib
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.unlim.lib.databinding.ActivityMainBinding
class ActivityMain : AppCompatActivity() {
private lateinit var mViewBinding: ActivityMainBinding
private var mData = arrayListOf(
arrayListOf(
"1",
"2",
"3"
),
arrayListOf(
"4",
"5",
"6"
),
arrayListOf(
"7",
"8",
"9"
)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mViewBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mViewBinding.root)
mViewBinding.vTab.addTab(mViewBinding.vTab.newTab().setText("tab0"))
mViewBinding.vTab.addTab(mViewBinding.vTab.newTab().setText("tab1"))
mViewBinding.vTab.addTab(mViewBinding.vTab.newTab().setText("tab2"))
mViewBinding.vPage.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
mViewBinding.vPage.adapter = AdapterPage(this, mData)
}
class AdapterPage(
private val context: Context,
private val pageData: ArrayList<ArrayList<String>>
) :
RecyclerView.Adapter<VhPage>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VhPage {
return VhPage(
LayoutInflater.from(parent.context).inflate(R.layout.item_page, parent, false)
)
}
override fun getItemCount(): Int {
return pageData.size
}
override fun onBindViewHolder(holder: VhPage, position: Int) {
holder.vOnePage.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
holder.vOnePage.adapter = AdapterItem(pageData[position])
}
}
class VhPage(itemView: View) : RecyclerView.ViewHolder(itemView) {
val vOnePage: RecyclerView = itemView.findViewById(R.id.vOnePage)
}
class AdapterItem(private val itemData: ArrayList<String>) :
RecyclerView.Adapter<VhItem>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VhItem {
return VhItem(
LayoutInflater.from(parent.context).inflate(R.layout.item_func, parent, false)
)
}
override fun getItemCount(): Int {
return itemData.size
}
override fun onBindViewHolder(holder: VhItem, position: Int) {
holder.vItem.text = itemData[position]
}
}
class VhItem(itemView: View) : RecyclerView.ViewHolder(itemView) {
val vItem: AppCompatTextView = itemView.findViewById(R.id.vItem)
}
}
| 0
|
Kotlin
|
0
| 0
|
ba6307942807c8f341d41df702426d16fbca0f8f
| 3,088
|
AndroidLib
|
Apache License 2.0
|
app/src/main/java/aodev/blue/rxsandbox/model/operator/observable/filter/ObservableDistinctUntilChanged.kt
|
esnaultdev
| 146,037,889
| false
| null |
package aodev.blue.rxsandbox.model.operator.observable.filter
import aodev.blue.rxsandbox.model.Config
import aodev.blue.rxsandbox.model.ObservableT
import aodev.blue.rxsandbox.model.operator.Operator
class ObservableDistinctUntilChanged<T : Any> : Operator {
fun apply(input: ObservableT<T>): ObservableT<T> {
val events = when (input.events.size) {
0 -> emptyList()
1 -> listOf(input.events.first())
else -> {
val firstEvent = input.events.first()
val otherEvents = input.events.drop(1)
.zip(input.events)
.filter { it.first.value != it.second.value }
.map { it.first }
mutableListOf(firstEvent).apply { addAll(otherEvents) }
}
}
return ObservableT(
events = events,
termination = input.termination
)
}
override val expression: String = "distinctUntilChanged"
override val docUrl: String? = "${Config.operatorDocUrlPrefix}distinct.html"
}
| 0
|
Kotlin
|
0
| 1
|
57579e059dca90ea2b10e818a478ce391c1fd07f
| 1,096
|
RxSandbox
|
MIT License
|
media/src/main/java/com/cysion/media/net/BaseResp.kt
|
chenyao1208
| 166,728,303
| true
|
{"Kotlin": 132334, "Java": 20717}
|
package com.cysion.media.net
import com.cysion.ktbox.net.ApiException
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
/**
* 数据基类;若字段不一致,可仿照再写一个
*/
data class BaseResp<T>(val code: Int, val msg: String, val result: T) {
fun isSuccessful(): Boolean {
return code == 200
}
}
object BaseRespRx {
// 当T为null时,不能调用map方法,应使用BaseResponseRx.validateToMain2();此时,code完全能表明结果状态
fun <T> validateToMain(): ObservableTransformer<BaseResp<T>, T> {
return ObservableTransformer { observable ->
observable.map(validate()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
}
}
fun <T> validate(): Function<BaseResp<T>, T> {
return Function {
if (!it.isSuccessful()) {
throw ApiException(it.code, it.msg)
}
it.result
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0c85f2725447802b749c249d98b09a628e1901ae
| 998
|
KtDevBox
|
Apache License 2.0
|
core/src/main/kotlin/de/darkatra/bfme2/Vector3.kt
|
DarkAtra
| 325,887,805
| false
|
{"Kotlin": 263823}
|
package de.darkatra.bfme2
data class Vector3(
val x: Float,
val y: Float,
val z: Float
)
| 2
|
Kotlin
|
0
| 3
|
e602ba2bfdff6d627860d20e2093d483de055772
| 102
|
bfme2-modding-utils
|
MIT License
|
parcelable/src/notParcelableMain/kotlin/com/arkivanov/essenty/parcelable/ParcelReader.kt
|
arkivanov
| 385,374,863
| false
|
{"Kotlin": 178160}
|
package com.arkivanov.essenty.parcelable
import com.arkivanov.essenty.utils.internal.ExperimentalEssentyApi
import com.arkivanov.essenty.utils.internal.PARCELABLE_DEPRECATED_MESSAGE
import kotlin.reflect.KClass
/**
* Allows serializing [Parcelable] classes when implementing custom parcelers using [CommonParceler].
*/
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual class ParcelReader private constructor()
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual fun ParcelReader.readBoolean(): Boolean =
error("Not yet supported")
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual fun ParcelReader.readInt(): Int =
error("Not yet supported")
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual fun ParcelReader.readLong(): Long =
error("Not yet supported")
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual fun ParcelReader.readFloat(): Float =
error("Not yet supported")
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual fun ParcelReader.readDouble(): Double =
error("Not yet supported")
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual fun ParcelReader.readStringOrNull(): String? =
error("Not yet supported")
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual fun <T : Parcelable> ParcelReader.readParcelableOrNull(clazz: KClass<T>): T? =
error("Not yet supported")
@Deprecated(PARCELABLE_DEPRECATED_MESSAGE)
@ExperimentalEssentyApi
actual fun ParcelReader.readByteArray(): ByteArray =
error("Not yet supported")
| 3
|
Kotlin
|
11
| 342
|
c625395cdf916b831f66d57ad2c7fa11f65bb4ae
| 1,648
|
Essenty
|
Apache License 2.0
|
lib_common/src/main/java/com/app/lib_common/util/StatusBarUtil.kt
|
ldk123456
| 648,167,522
| false
| null |
package com.app.lib_common.util
import android.graphics.Color
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
object StatusBarUtil {
fun fitSystemBar(activity: AppCompatActivity) {
val window = activity.window
val decorView = window?.decorView
if (window == null || decorView == null) {
return
}
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = Color.TRANSPARENT
}
}
| 0
|
Kotlin
|
0
| 0
|
5631f4b6d681374dc7d8fccc3574f9cca4795476
| 736
|
JetpackApp
|
Apache License 2.0
|
t-tasks/src/main/java/com/teo/ttasks/ui/views/TasksContainerView.kt
|
teobaranga
| 28,672,362
| false
| null |
package com.teo.ttasks.ui.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import com.teo.ttasks.R
import com.teo.ttasks.R.layout
import com.teo.ttasks.data.model.Task
import com.teo.ttasks.util.DateUtils
import org.threeten.bp.ZonedDateTime
/**
*/
class TasksContainerView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr, defStyleRes) {
companion object {
private val currentYear by lazy { ZonedDateTime.now().year }
}
var showMonth: Boolean = false
var date: ZonedDateTime? = null
set(value) {
if (value == null) {
taskDateView.visibility = View.GONE
monthView.visibility = View.GONE
} else {
with(taskDateView) {
date = value
visibility = View.VISIBLE
}
with(monthView) {
if (showMonth) {
text = when {
value.year == currentYear -> value.format(DateUtils.formatterMonth)
else -> value.format(DateUtils.formatterMonthYear)
}
visibility = View.VISIBLE
} else {
visibility = View.GONE
}
}
}
field = value
}
var tasks: List<Task>? = null
set(tasks) {
if (!tasks.isNullOrEmpty()) {
for (task in tasks) {
val taskView = getInnerTaskItemView(task)
taskView.setOnClickListener { println("click") }
taskListView.addView(taskView)
}
taskListView.post {
if (taskListView.bottom > taskDateView.bottom) {
with(ConstraintSet()) {
clone(this@TasksContainerView)
connect(R.id.separator, ConstraintSet.BOTTOM, R.id.task_list, ConstraintSet.BOTTOM)
applyTo(this@TasksContainerView)
}
} else {
with(ConstraintSet()) {
clone(this@TasksContainerView)
connect(R.id.task_list, ConstraintSet.BOTTOM, R.id.task_date, ConstraintSet.BOTTOM)
applyTo(this@TasksContainerView)
}
}
}
} else {
taskListView.removeAllViewsInLayout()
with(ConstraintSet()) {
clone(this@TasksContainerView)
// Separator view
connect(R.id.separator, ConstraintSet.BOTTOM, R.id.task_date, ConstraintSet.BOTTOM)
applyTo(this@TasksContainerView)
}
}
field = tasks
}
private val taskDateView: TaskDateView
private val monthView: TextView
private val taskListView: LinearLayout
init {
View.inflate(context, layout.item_tasks_container, this)
taskDateView = findViewById(R.id.task_date)
monthView = findViewById(R.id.month)
taskListView = findViewById(R.id.task_list)
}
private fun getInnerTaskItemView(task: Task): View {
val view = LayoutInflater.from(context).inflate(layout.item_task_inner, taskListView, false)
val title = view.findViewById<TextView>(R.id.task_title)
val description = view.findViewById<TextView>(R.id.task_description)
val reminder = view.findViewById<TextView>(R.id.reminder)
title.text = task.title
if (task.notes.isNullOrBlank()) {
description.visibility = View.GONE
} else {
description.text = task.notes
description.visibility = View.VISIBLE
}
if (task.reminderDate == null) {
reminder.visibility = View.GONE
} else {
reminder.text = task.reminderDate!!.format(DateUtils.formatterTime)
reminder.visibility = View.VISIBLE
}
return view
}
}
| 1
|
Kotlin
|
3
| 7
|
04da2bc5ae76a165f9ebff00093c048923f87bf2
| 4,534
|
T-Tasks
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/presentation/AppTheme.kt
|
ParkJong-Hun
| 794,024,590
| false
|
{"Kotlin": 55052, "Swift": 594}
|
package presentation
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import presentation.navigation.AppNavigator
import presentation.navigation.LocalNavigator
@Composable
fun AppTheme(
content: @Composable () -> Unit,
) {
CompositionLocalProvider(
LocalNavigator provides AppNavigator(),
) {
MaterialTheme {
content()
}
}
}
| 6
|
Kotlin
|
0
| 1
|
6241d3ba5591ca8ff6e784630f4b0ffb8fe98a26
| 476
|
compose-multiplatform-test-airfield
|
Apache License 2.0
|
src/191/main/kotlin/org/rust/ide/actions/runAnything/RunAnythingCargoItem.kt
|
lundibundi
| 196,070,202
| true
|
{"Kotlin": 4655671, "Rust": 103690, "Python": 48426, "Lex": 20296, "HTML": 13447, "Shell": 760, "Java": 586, "RenderScript": 318}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions.runAnything
import java.awt.Component
import javax.swing.Icon
class RunAnythingCargoItem(command: String, icon: Icon) : RunAnythingCargoItemBase(command, icon) {
override fun createComponent(pattern: String?, isSelected: Boolean, hasFocus: Boolean): Component {
return super.createComponent(pattern, isSelected, hasFocus).also(this@RunAnythingCargoItem::customizeComponent)
}
}
| 0
|
Kotlin
|
0
| 1
|
51e8843a408612d6a89661f1aa7fb9ae2042f3ba
| 533
|
intellij-rust
|
MIT License
|
src/main/kotlin/me/melijn/melijnbot/commands/music/PrivateGainProfileCommand.kt
|
ToxicMushroom
| 107,187,088
| false
| null |
package me.melijn.melijnbot.commands.music
const val PRIVATE_GAIN_PROFILES_LIMIT = 3
const val PREMIUM_PRIVATE_GAIN_PROFILES_LIMIT = 30
const val PRIVATE_GAIN_PROFILES_LIMIT_PATH = "premium.feature.privategainprofiles.limit"
const val PRIVATE_GAIN_PROFILES_PREMIUM_LIMIT_PATH = "premium.feature.privategainprofiles.premiumlimit"
class PrivateGainProfileCommand : AbstractGainProfileCommand(
"command.privategainprofile", { context ->
context.authorId
}) {
init {
name = "privateGainProfile"
aliases = arrayOf("pgp")
}
}
| 5
|
Kotlin
|
22
| 80
|
01107bbaad0e343d770b1e4124a5a9873b1bb5bd
| 562
|
Melijn
|
MIT License
|
app/src/main/java/com/feelsokman/coroutineplayground/di/module/AppModule.kt
|
CostaFot
| 234,777,998
| false
| null |
package com.feelsokman.coroutineplayground.di.module
import android.app.Application
import android.content.Context
import android.content.res.Resources
import com.feelsokman.coroutineplayground.BuildConfig
import com.feelsokman.coroutineplayground.coroutine.DefaultDispatcherProvider
import com.feelsokman.coroutineplayground.coroutine.DispatcherProvider
import com.feelsokman.coroutineplayground.repos.RedditRepository
import com.google.firebase.analytics.FirebaseAnalytics
import com.squareup.otto.Bus
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class AppModule {
@Provides
@Singleton
fun providesApplicationContext(application: Application): Context {
return application
}
@Provides
@Singleton
fun providesApplicationResources(context: Context): Resources {
return context.resources
}
@Provides
@Singleton
fun providesBus(): Bus = Bus()
@Provides
fun providesFirebaseAnalytics(applicationContext: Context): FirebaseAnalytics {
return FirebaseAnalytics.getInstance(applicationContext)
}
@Provides
fun providesDebugFlag(): Boolean {
return BuildConfig.DEBUG
}
@Singleton
@Provides
internal fun providesDispatcherProvider(): DispatcherProvider {
return DefaultDispatcherProvider()
}
@Provides
fun providesRedditRepository(dispatcherProvider: DispatcherProvider): RedditRepository {
return RedditRepository(dispatcherProvider)
}
}
| 0
|
Kotlin
|
0
| 0
|
2f6ec7a768c57afd7c3b6e27d9a33b25b5f96c90
| 1,521
|
coroutine-playground
|
Apache License 2.0
|
demo-app-shared/src/main/java/ru/ar2code/demo_app_shared/GreetingResult.kt
|
ar2code
| 431,859,450
| false
| null |
package ru.ar2code.demo_app_shared
sealed class GreetingResult {
data class GreetingFieldInvalid(val error: String) : GreetingResult()
data class NameFieldInvalid(val error: String) : GreetingResult()
data class Hello(val greeting: String, val name: String) : GreetingResult()
}
| 0
|
Kotlin
|
0
| 0
|
6c0bca24dd0576088b0907919d67b8e9c4508b5f
| 291
|
mvilite-android-demo
|
MIT License
|
nebulosa-imaging/src/main/kotlin/nebulosa/imaging/algorithms/Debayer.kt
|
tiagohm
| 568,578,345
| false
| null |
package nebulosa.imaging.algorithms
import nebulosa.imaging.Image
class Debayer(val pattern: CfaPattern = CfaPattern.GRGB) : TransformAlgorithm {
private var cachedRed = FloatArray(0) // Prevent clone image.
override fun transform(source: Image): Image {
cachedRed = FloatArray(source.width * source.height)
if (source.mono) {
TODO("") // create RGB image, copy gray to red channel e call transform.
} else {
process(source)
}
return source
}
private fun process(source: Image) {
val width = source.width
val height = source.height
val widthM1 = width - 1
val heightM1 = height - 1
val rgbValues = FloatArray(3)
val rgbCounters = IntArray(3)
for (y in 0 until height) {
for (x in 0 until width) {
val index = y * source.stride + x * source.pixelStride
rgbValues.fill(0f)
rgbCounters.fill(0)
var bayerIndex = pattern[y and 1, x and 1]
rgbValues[bayerIndex.ordinal] += source.data[index]
rgbCounters[bayerIndex.ordinal]++
if (x != 0) {
bayerIndex = pattern[y and 1, x - 1 and 1]
rgbValues[bayerIndex.ordinal] += source.data[index - source.pixelStride]
rgbCounters[bayerIndex.ordinal]++
}
if (x != widthM1) {
bayerIndex = pattern[y and 1, x + 1 and 1]
rgbValues[bayerIndex.ordinal] += source.data[index + source.pixelStride]
rgbCounters[bayerIndex.ordinal]++
}
if (y != 0) {
bayerIndex = pattern[y - 1 and 1, x and 1]
rgbValues[bayerIndex.ordinal] += source.data[index - source.stride]
rgbCounters[bayerIndex.ordinal]++
if (x != 0) {
bayerIndex = pattern[y - 1 and 1, x - 1 and 1]
rgbValues[bayerIndex.ordinal] += source.data[index - source.stride - source.pixelStride]
rgbCounters[bayerIndex.ordinal]++
}
if (x != widthM1) {
bayerIndex = pattern[y - 1 and 1, x + 1 and 1]
rgbValues[bayerIndex.ordinal] += source.data[index - source.stride + source.pixelStride]
rgbCounters[bayerIndex.ordinal]++
}
}
if (y != heightM1) {
bayerIndex = pattern[y + 1 and 1, x and 1]
rgbValues[bayerIndex.ordinal] += source.data[index + source.stride]
rgbCounters[bayerIndex.ordinal]++
if (x != 0) {
bayerIndex = pattern[y + 1 and 1, x - 1 and 1]
rgbValues[bayerIndex.ordinal] += source.data[index + source.stride - source.pixelStride]
rgbCounters[bayerIndex.ordinal]++
}
if (x != widthM1) {
bayerIndex = pattern[y + 1 and 1, x + 1 and 1]
rgbValues[bayerIndex.ordinal] += source.data[index + source.stride + source.pixelStride]
rgbCounters[bayerIndex.ordinal]++
}
}
cachedRed[index / 3] = rgbValues[0] / rgbCounters[0]
source.data[index + 1] = rgbValues[1] / rgbCounters[1]
source.data[index + 2] = rgbValues[2] / rgbCounters[2]
}
}
for (i in cachedRed.indices) source.data[i * source.pixelStride] = cachedRed[i]
}
}
| 0
|
Kotlin
|
0
| 0
|
57780ec339ff4e3ec8d1965b7ddef7879861a814
| 3,755
|
nebulosa
|
MIT License
|
app/src/main/java/com/goldze/mvvmhabit/aioui/test/content/TestContentActivity.kt
|
fengao1004
| 505,038,355
| false
|
{"Java Properties": 2, "Gradle": 6, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Text": 4, "Ignore List": 4, "Proguard": 3, "Java": 214, "XML": 141, "Kotlin": 158}
|
package com.goldze.mvvmhabit.aioui.test.content
import android.os.Bundle
import android.util.Log
import com.goldze.mvvmhabit.BR
import com.goldze.mvvmhabit.R
import com.goldze.mvvmhabit.aioui.test.bean.FunnyTestBean
import com.goldze.mvvmhabit.aioui.test.bean.ScaDetailsResponseBean
import com.goldze.mvvmhabit.databinding.ActivityTestContentBinding
import me.goldze.mvvmhabit.base.BaseActivity
class TestContentActivity : BaseActivity<ActivityTestContentBinding, TestContentModel>() {
lateinit var detail: ScaDetailsResponseBean
lateinit var detail2: FunnyTestBean
lateinit var marry: String
lateinit var type: String
lateinit var name: String
lateinit var sex: String
override fun initContentView(savedInstanceState: Bundle?): Int {
return R.layout.activity_test_content
}
override fun initVariableId(): Int {
return BR.viewModel
}
override fun initData() {
super.initData()
type = intent.getStringExtra("type")
name = intent.getStringExtra("name")
if (type == "normal") {
detail = intent.getSerializableExtra("bean") as ScaDetailsResponseBean
binding.brRootView.setPageTitle(detail.data.scaVo.name)
} else {
detail2 = intent.getSerializableExtra("bean") as FunnyTestBean
binding.brRootView.setPageTitle(detail2.data.name)
}
marry = intent.getStringExtra("marry")
sex = intent.getStringExtra("sex")
if (type == "normal") {
viewModel.detail = detail
} else {
viewModel.detail2 = detail2
}
viewModel.type = type
viewModel.marry = marry
viewModel.name = name
viewModel.sex = sex
Log.i("fengao_xiaomi", "marry: $marry ")
Log.i("fengao_xiaomi", "sex: $sex")
viewModel.init()
}
}
| 1
| null |
1
| 1
|
1099bd7bfcf8a81d545567ae875b3528aa5fb1cd
| 1,862
|
AIO
|
Apache License 2.0
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/TrajAuto.kt
|
Petelax
| 671,336,777
| false
|
{"Gradle": 6, "Java Properties": 1, "Shell": 1, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Markdown": 7, "INI": 1, "XML": 20, "Java": 67, "Kotlin": 66}
|
package org.firstinspires.ftc.teamcode.drive.opmode
import com.acmerobotics.dashboard.FtcDashboard
import com.acmerobotics.dashboard.telemetry.MultipleTelemetry
import com.acmerobotics.dashboard.telemetry.TelemetryPacket
import com.arcrobotics.ftclib.command.CommandOpMode
import com.arcrobotics.ftclib.command.InstantCommand
import com.arcrobotics.ftclib.command.ParallelCommandGroup
import com.arcrobotics.ftclib.command.SequentialCommandGroup
import com.arcrobotics.ftclib.command.WaitCommand
import com.arcrobotics.ftclib.gamepad.GamepadEx
import com.arcrobotics.ftclib.geometry.Pose2d
import com.arcrobotics.ftclib.geometry.Rotation2d
import com.qualcomm.robotcore.eventloop.opmode.Autonomous
import com.qualcomm.robotcore.hardware.VoltageSensor
import org.firstinspires.ftc.teamcode.constants.DrivebaseConstants
import org.firstinspires.ftc.teamcode.drive.commands.ArmPIDCommand
import org.firstinspires.ftc.teamcode.drive.commands.ClawCommand
import org.firstinspires.ftc.teamcode.drive.commands.DriveToPosition
import org.firstinspires.ftc.teamcode.drive.commands.ElevatorNoVeloCommand
import org.firstinspires.ftc.teamcode.drive.commands.ElevatorPIDCommand
import org.firstinspires.ftc.teamcode.drive.commands.PathFollowing
import org.firstinspires.ftc.teamcode.drive.commands.TurnInPlace
import org.firstinspires.ftc.teamcode.drive.commands.WristCommand
import org.firstinspires.ftc.teamcode.drive.test.CommandBasedNotBasedTest
import org.firstinspires.ftc.teamcode.subsystems.Arm
import org.firstinspires.ftc.teamcode.subsystems.Claw
import org.firstinspires.ftc.teamcode.subsystems.Elevator
import org.firstinspires.ftc.teamcode.subsystems.Intake
import org.firstinspires.ftc.teamcode.subsystems.SwerveDrivebase
import org.firstinspires.ftc.teamcode.subsystems.Wrist
import kotlin.math.PI
@Autonomous
class TrajAuto: CommandOpMode() {
private lateinit var drivebase: SwerveDrivebase
private lateinit var intake: Intake
private lateinit var elevator: Elevator
private lateinit var wrist: Wrist
private lateinit var claw: Claw
private lateinit var arm: Arm
private var lastTime: Long = 0
private lateinit var dashboard: FtcDashboard
private lateinit var voltage: VoltageSensor
//private val startPose = Pose2d(-65.0, 12.0, Rotation2d(-PI/2))
override fun initialize() {
telemetry = MultipleTelemetry(telemetry, FtcDashboard.getInstance().telemetry)
dashboard = FtcDashboard.getInstance()
drivebase = SwerveDrivebase(hardwareMap)
elevator = Elevator(hardwareMap, Elevator.Mode.RAW)
wrist = Wrist(hardwareMap)
claw = Claw(hardwareMap)
arm = Arm(hardwareMap)
intake = Intake(hardwareMap)
voltage = hardwareMap.get(VoltageSensor::class.java, "Control Hub")
//drivebase.setPose(startPose)
//drivebase.setPose(Pose2d(0.0, 0.0, Rotation2d(-PI/2)))
val pose = drivebase.getPose()
val packet = TelemetryPacket()
packet.fieldOverlay().setFill("blue").setRotation(pose.heading).fillRect(pose.x-7.0, pose.y-7.0, 14.0, 14.0)
packet.put("x", pose.x)
packet.put("y", pose.y)
packet.put("heading", pose.heading)
dashboard.sendTelemetryPacket(packet)
schedule(
SequentialCommandGroup(
//TurnInPlace(drivebase, Rotation2d(PI/2), voltage::getVoltage),
PathFollowing(drivebase, Pose2d(12.0, 0.0, Rotation2d(0.0)))
)
)
}
override fun run() {
val currentTime = System.nanoTime()
val pose = drivebase.getPose()
val packet = TelemetryPacket()
packet.fieldOverlay().setFill("blue").setRotation(pose.heading).fillRect(pose.x-7.0, pose.y-7.0, 14.0, 14.0)
packet.put("hz", 1E9/(currentTime-lastTime))
packet.put("voltage", voltage.voltage)
packet.put("speed", drivebase.getAngularVelocity())
packet.put("degrees", drivebase.getHeading())
packet.put("x", pose.x)
packet.put("y", pose.y)
packet.put("heading", pose.heading)
dashboard.sendTelemetryPacket(packet)
//telemetry.addData("hz ", 1E9/(currentTime-lastTime))
//telemetry.update()
lastTime = currentTime
super.run()
}
}
| 0
|
Java
|
0
| 0
|
a66accb94638fb15c099bf5a86a2938c348881b9
| 4,268
|
FTC16413-CenterStage
|
BSD 3-Clause Clear License
|
api-editor/backend/src/test/kotlin/com/larsreimann/apiEditor/server/ApplicationTest.kt
|
Safe-DS
| 365,253,624
| false
| null |
package com.larsreimann.apiEditor.server
import com.larsreimann.apiEditor.model.BoundaryAnnotation
import com.larsreimann.apiEditor.model.CalledAfterAnnotation
import com.larsreimann.apiEditor.model.ComparisonOperator
import com.larsreimann.apiEditor.model.ConstantAnnotation
import com.larsreimann.apiEditor.model.DefaultNumber
import com.larsreimann.apiEditor.model.DefaultString
import com.larsreimann.apiEditor.model.EnumAnnotation
import com.larsreimann.apiEditor.model.EnumPair
import com.larsreimann.apiEditor.model.GroupAnnotation
import com.larsreimann.apiEditor.model.MoveAnnotation
import com.larsreimann.apiEditor.model.OptionalAnnotation
import com.larsreimann.apiEditor.model.PureAnnotation
import com.larsreimann.apiEditor.model.PythonFromImport
import com.larsreimann.apiEditor.model.PythonImport
import com.larsreimann.apiEditor.model.PythonParameterAssignment
import com.larsreimann.apiEditor.model.RemoveAnnotation
import com.larsreimann.apiEditor.model.RenameAnnotation
import com.larsreimann.apiEditor.model.RequiredAnnotation
import com.larsreimann.apiEditor.model.SerializablePythonClass
import com.larsreimann.apiEditor.model.SerializablePythonFunction
import com.larsreimann.apiEditor.model.SerializablePythonModule
import com.larsreimann.apiEditor.model.SerializablePythonPackage
import com.larsreimann.apiEditor.model.SerializablePythonParameter
import com.larsreimann.apiEditor.model.SerializablePythonResult
import io.ktor.client.call.body
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.server.testing.testApplication
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
class ApplicationTest {
@Test
fun testEcho() {
testApplication {
val testPythonPackage = SerializablePythonPackage(
distribution = "test-distribution",
name = "test-package",
version = "1.0.0",
modules = mutableListOf(
SerializablePythonModule(
name = "test-module",
imports = mutableListOf(
PythonImport(
module = "test-import",
alias = "test-alias",
),
),
fromImports = mutableListOf(
PythonFromImport(
module = "test-from-import",
declaration = "test-declaration",
alias = null,
),
),
classes = mutableListOf(
SerializablePythonClass(
name = "test-class",
qualifiedName = "test-module.test-class",
decorators = listOf("test-decorator"),
superclasses = listOf("test-superclass"),
methods = mutableListOf(),
isPublic = true,
description = "Lorem ipsum",
fullDocstring = "Lorem ipsum",
annotations = mutableListOf(),
),
),
functions = mutableListOf(
SerializablePythonFunction(
name = "test-function",
qualifiedName = "test-module.test-function",
decorators = listOf("test-decorator"),
parameters = mutableListOf(
SerializablePythonParameter(
name = "test-parameter",
qualifiedName = "test-module.test-function.test-parameter",
defaultValue = "42",
assignedBy = PythonParameterAssignment.NAME_ONLY,
isPublic = true,
typeInDocs = "str",
description = "Lorem ipsum",
annotations = mutableListOf(),
),
),
results = mutableListOf(
SerializablePythonResult(
name = "test-result",
type = "str",
typeInDocs = "str",
description = "Lorem ipsum",
annotations = mutableListOf(),
),
),
isPublic = true,
description = "Lorem ipsum",
fullDocstring = "Lorem ipsum",
annotations = mutableListOf(),
),
),
annotations = mutableListOf(),
),
),
annotations = mutableListOf(
BoundaryAnnotation(
isDiscrete = false,
lowerIntervalLimit = 0.0,
lowerLimitType = ComparisonOperator.LESS_THAN_OR_EQUALS,
upperIntervalLimit = 1.0,
upperLimitType = ComparisonOperator.LESS_THAN,
),
CalledAfterAnnotation("test-other-function"),
ConstantAnnotation(DefaultNumber(0.1)),
EnumAnnotation(
enumName = "test-enum",
pairs = listOf(
EnumPair("test-value", "TEST_VALUE"),
),
),
GroupAnnotation(
groupName = "test-group",
parameters = mutableListOf(
"test-parameter",
),
),
MoveAnnotation("test-destination-module"),
OptionalAnnotation(DefaultString("bla")),
PureAnnotation,
RenameAnnotation("test-new-name"),
RequiredAnnotation,
RemoveAnnotation,
),
)
val requestBody = Json.encodeToString(testPythonPackage)
val response = client.post("/api-editor/echo") {
contentType(ContentType.Application.Json)
setBody(requestBody)
}
assertEquals(HttpStatusCode.OK, response.status)
assertEquals(requestBody, response.body())
}
}
}
| 31
|
TypeScript
|
1
| 11
|
73c541b15fad2e67a0726a1b62c1f55f6e970a56
| 7,239
|
API-Editor
|
MIT License
|
app/src/main/java/com/example/booklibrary/splashscreen/onboarding/screen/ThirdScreen.kt
|
NoBody313
| 573,783,064
| false
|
{"Kotlin": 37355}
|
package com.example.booklibrary.splashscreen.onboarding.screen
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.booklibrary.R
class ThirdScreen : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_third_screen, container, false)
// Next button
val finish : Button = view.findViewById(R.id.btn_next)
finish.setOnClickListener{
findNavController().navigate(R.id.action_viewPagerFragment_to_loginActivity)
onBoardingFinished()
}
return view
}
private fun onBoardingFinished() {
val sharedPref = requireActivity().getSharedPreferences("onBoarding", Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putBoolean("Finished", true)
editor.apply()
}
}
| 0
|
Kotlin
|
0
| 2
|
113e96b6045aaac927bc0b7e1917603409c04550
| 1,204
|
Book_Library
|
MIT License
|
app/src/main/java/com/penpab/postsanitizer/dto/PostItem.kt
|
Acekhing
| 525,073,312
| false
| null |
package com.penpab.postsanitizer.dto
data class PostItem(
val _links: Links?,
val author: Int?,
val categories: List<Int>?,
val comment_status: String?,
val content: Content?,
val date: String?,
val date_gmt: String?,
val excerpt: Excerpt?,
val featured_media: Int?,
val format: String?,
val guid: Guid?,
val id: Int?,
val link: String?,
val meta: List<Any>?,
val modified: String?,
val modified_gmt: String?,
val ping_status: String?,
val slug: String?,
val status: String?,
val sticky: Boolean?,
val tags: List<Any>?,
val template: String?,
val title: Title?,
val type: String?,
val yoast_head: String?,
val yoast_head_json: YoastHeadJson?
)
| 0
|
Kotlin
|
0
| 0
|
a8394d9684148a1f99706515f144cccd4cd55b82
| 748
|
WorkManager
|
Apache License 2.0
|
packages/canvas/src-native/canvas-android/canvas/src/main/java/org/nativescript/canvas/GC.kt
|
NativeScript
| 293,639,798
| false
|
{"C++": 4259365, "JavaScript": 3250075, "Rust": 1485388, "TypeScript": 1321578, "C": 788864, "Kotlin": 138438, "Swift": 98341, "Objective-C": 67481, "Java": 25041, "Shell": 21984, "PLSQL": 12630, "Vue": 9098, "CMake": 7562, "Ruby": 4922, "SCSS": 3202, "HTML": 2271, "Objective-C++": 2078, "CSS": 1564, "Python": 1140}
|
package org.nativescript.canvas
import java.lang.ref.PhantomReference
import java.lang.ref.ReferenceQueue
import java.nio.ByteBuffer
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
class GC {
interface Object {
fun dispose()
}
class BufferWrapper(private val nativePtr: Long, val value: Any) : Object {
override fun dispose() {
disposeByteBufMut(nativePtr)
}
}
private var executor = Executors.newSingleThreadExecutor()
private val monitoring = AtomicBoolean()
private fun startWatch() {
if (monitoring.get()) {
return
}
monitoring.set(true)
executor.execute {
while (monitoring.get()) {
val tmp = bufferRefQue.poll()
tmp?.get()?.dispose()
}
}
}
private fun stopWatch() {
monitoring.set(false)
executor.shutdown()
}
fun restartWatch() {
stopWatch()
executor = Executors.newSingleThreadExecutor()
startWatch()
}
fun watchItem(value: Object) {
PhantomReference(value, bufferRefQue)
}
companion object {
@JvmStatic
val bufferRefQue: ReferenceQueue<Object> = ReferenceQueue()
@JvmStatic
val instance = GC()
init {
instance.startWatch()
}
@JvmStatic
fun watchObject(key: Long, value: ByteBuffer) {
PhantomReference(BufferWrapper(key, value), bufferRefQue)
}
@JvmStatic
private external fun disposeByteBufMut(buffer: Long)
}
}
| 21
|
C++
|
18
| 88
|
5b3672d275a0f14eee68257352f8141c1faebc77
| 1,367
|
canvas
|
Apache License 2.0
|
backend/data/src/main/kotlin/io/tolgee/service/export/ExportService.kt
|
tolgee
| 303,766,501
| false
| null |
package io.tolgee.service.export
import io.tolgee.constants.Message
import io.tolgee.dtos.request.export.ExportParams
import io.tolgee.exceptions.NotFoundException
import io.tolgee.model.Language
import io.tolgee.service.export.dataProvider.ExportDataProvider
import io.tolgee.service.export.dataProvider.ExportTranslationView
import io.tolgee.service.project.ProjectService
import org.springframework.stereotype.Service
import java.io.InputStream
import javax.persistence.EntityManager
@Service
class ExportService(
private val fileExporterFactory: FileExporterFactory,
private val projectService: ProjectService,
private val entityManager: EntityManager
) {
fun export(projectId: Long, exportParams: ExportParams): Map<String, InputStream> {
val data = getDataForExport(projectId, exportParams)
val baseLanguage = getProjectBaseLanguage(projectId)
val baseTranslationsProvider = getBaseTranslationsProvider(
exportParams = exportParams,
projectId = projectId,
baseLanguage = baseLanguage
)
return fileExporterFactory.create(
data = data,
exportParams = exportParams,
baseTranslationsProvider = baseTranslationsProvider,
baseLanguage
).produceFiles()
}
/**
* Base translations are not required for all Formatters.
* So formatters which need them can call the provider.
*/
private fun getBaseTranslationsProvider(
exportParams: ExportParams,
projectId: Long,
baseLanguage: Language
): () -> List<ExportTranslationView> {
return {
getDataForExport(projectId, exportParams.copy(languages = setOf(baseLanguage.tag), filterState = null))
}
}
private fun getDataForExport(projectId: Long, exportParams: ExportParams): List<ExportTranslationView> {
return ExportDataProvider(
entityManager = entityManager,
exportParams = exportParams,
projectId = projectId
).getData()
}
private fun getProjectBaseLanguage(projectId: Long): Language {
return projectService.getOrCreateBaseLanguage(projectId)
?: throw NotFoundException(Message.CANNOT_FIND_BASE_LANGUAGE)
}
}
| 48
| null |
8
| 666
|
38c1064783f3ec5d60d0502ec0420698395af539
| 2,122
|
tolgee-platform
|
Apache License 2.0
|
buildSrc/src/main/kotlin/korlibs/korge/gradle/util/NamedDomainObjectContainerExt.kt
|
korlibs
| 80,095,683
| false
|
{"Kotlin": 4210038, "C": 105670, "C++": 20878, "HTML": 3853, "Swift": 1371, "JavaScript": 1068, "Shell": 439, "CMake": 202, "Batchfile": 41, "CSS": 33}
|
package korlibs.korge.gradle.util
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectContainer
fun <T> NamedDomainObjectContainer<T>.createOnce(name: String, configureAction: T.() -> Unit): T {
val item = findByName(name)
if (item != null) return item
return create(name, configureAction)
}
| 464
|
Kotlin
|
123
| 2,497
|
1a565007ab748e00a4d602fcd78f7d4032afaf0b
| 322
|
korge
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.