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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
debugBanner/src/main/java/io/armcha/debugBanner/BannerGravity.kt
|
armcha
| 145,413,807
| false
| null |
package io.armcha.debugBanner
enum class BannerGravity {
START,
END
}
| 1
|
Kotlin
|
11
| 59
|
18e1894e27b24a500484144aac992933eb686a37
| 79
|
DebugBanner
|
Apache License 2.0
|
examples/basic-integration-jetpack-compose/app/src/main/java/com/deuna/compose_demo/MainActivity.kt
|
deuna-developers
| 718,859,364
| false
|
{"Kotlin": 75371}
|
package com.deuna.compose_demo
import android.os.*
import androidx.activity.*
import androidx.activity.compose.*
import androidx.compose.runtime.Composable
import androidx.navigation.compose.*
import com.deuna.compose_demo.screens.*
import com.deuna.compose_demo.view_models.home.HomeViewModel
import com.deuna.maven.*
import com.deuna.maven.shared.Environment
import com.deuna.maven.shared.Json
import com.deuna.maven.shared.toMap
import org.json.JSONObject
class MainActivity() : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// Define the navigation for the app
Navigator {
// Set up the navigation host, which manages navigation within the app
NavHost(
navController = LocalNavController.current,
startDestination = Screens.Home.route // Set the start destination to the home screen
) {
// Define the composable function for the home screen
composable(Screens.Home.route) {
HomeScreen(
// Initialize the view model with DeunaSDK configuration for sandbox environment
homeViewModel = HomeViewModel(
deunaSDK = DeunaSDK(
environment = Environment.SANDBOX,
publicApiKey = "YOUR_PUBLIC_API_KEY"
),
)
)
}
// Define the composable function for the success screen
composable(Screens.PaymentSuccessful.route) {
PaymentSuccessfulScreen(
json = JSONObject(it.arguments?.getString("jsonOrder")!!).toMap(),
)
}
composable(Screens.SavedCardSuccessful.route) {
NavigateToCardSavedSuccessfulScreen(it.arguments)
}
composable(Screens.ClickToPaySuccessful.route) {
NavigateToCardSavedSuccessfulScreen(it.arguments)
}
}
}
}
}
}
@Composable
fun NavigateToCardSavedSuccessfulScreen(arguments: Bundle?) {
val data = JSONObject(
arguments?.getString("data")!!
).toMap()
CardSavedSuccessfulScreen(
title = data["title"] as String,
savedCardData = data["savedCardData"] as Json
)
}
| 0
|
Kotlin
|
0
| 0
|
a6bbfe559f65037e5f29f4956cc1def3a6f0201e
| 2,648
|
deuna-sdk-android
|
MIT License
|
app/src/main/java/io/github/drumber/kitsune/data/source/local/library/dao/LibraryEntryDao.kt
|
Drumber
| 406,471,554
| false
|
{"Kotlin": 993796, "Ruby": 2109}
|
package io.github.drumber.kitsune.data.source.local.library.dao
import androidx.lifecycle.LiveData
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import io.github.drumber.kitsune.data.source.local.library.model.LocalLibraryEntry
import io.github.drumber.kitsune.data.source.local.library.model.LocalLibraryMedia
import io.github.drumber.kitsune.data.source.local.library.model.LocalLibraryStatus
@Dao
interface LibraryEntryDao {
companion object {
/** Order by status orderId (see [LocalLibraryStatus]) and update time */
const val ORDER_BY_STATUS = "ORDER BY status, DATETIME(updatedAt) DESC"
}
/* ===================
* All Library Status
* =================== */
@Query("SELECT * FROM library_entries $ORDER_BY_STATUS")
fun allLibraryEntriesPagingSource(): PagingSource<Int, LocalLibraryEntry>
@Query("SELECT * FROM library_entries WHERE media_type = :type $ORDER_BY_STATUS")
fun allLibraryEntriesByTypePagingSource(type: LocalLibraryMedia.MediaType): PagingSource<Int, LocalLibraryEntry>
/* ===================
* Filtered by Status
* =================== */
@Query("SELECT * FROM library_entries WHERE status IN (:status) $ORDER_BY_STATUS")
fun allLibraryEntriesByStatusPagingSource(status: List<LocalLibraryStatus>): PagingSource<Int, LocalLibraryEntry>
@Query("SELECT * FROM library_entries WHERE status IN (:status) AND media_type = :type $ORDER_BY_STATUS")
fun allLibraryEntriesByTypeAndStatusPagingSource(type: LocalLibraryMedia.MediaType, status: List<LocalLibraryStatus>): PagingSource<Int, LocalLibraryEntry>
/* ===================
* Non Paging Queries
* =================== */
@Query("SELECT * FROM library_entries $ORDER_BY_STATUS")
suspend fun getAllLibraryEntries(): List<LocalLibraryEntry>
@Query("SELECT * FROM library_entries WHERE media_type = :type $ORDER_BY_STATUS")
suspend fun getAllLibraryEntriesByType(type: LocalLibraryMedia.MediaType): List<LocalLibraryEntry>
@Query("SELECT * FROM library_entries WHERE status IN (:status) $ORDER_BY_STATUS")
suspend fun getAllLibraryEntriesByStatus(status: List<LocalLibraryStatus>): List<LocalLibraryEntry>
@Query("SELECT * FROM library_entries WHERE status IN (:status) AND media_type = :type $ORDER_BY_STATUS")
suspend fun getAllLibraryEntriesByTypeAndStatus(type: LocalLibraryMedia.MediaType, status: List<LocalLibraryStatus>): List<LocalLibraryEntry>
@Query("SELECT * FROM library_entries WHERE media_id = :mediaId")
suspend fun getLibraryEntryFromMedia(mediaId: String): LocalLibraryEntry?
@Query("SELECT * FROM library_entries WHERE media_id = :mediaId")
fun getLibraryEntryFromMediaAsLiveData(mediaId: String): LiveData<LocalLibraryEntry?>
@Query("SELECT * FROM library_entries WHERE id = :id")
suspend fun getLibraryEntry(id: String): LocalLibraryEntry?
@Query("SELECT EXISTS(SELECT 1 FROM library_entries WHERE id = :id AND DATETIME(updatedAt) > DATETIME(:updatedAt))")
suspend fun hasLibraryEntryWhereUpdatedAtIsAfter(id: String, updatedAt: String): Boolean
@Query("SELECT * FROM library_entries WHERE id = :id")
fun getLibraryEntryAsLiveData(id: String): LiveData<LocalLibraryEntry?>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(libraryEntry: List<LocalLibraryEntry>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertSingle(libraryEntry: LocalLibraryEntry)
@Update
suspend fun updateSingle(libraryEntry: LocalLibraryEntry)
@Delete
suspend fun deleteSingle(libraryEntry: LocalLibraryEntry)
@Query("DELETE FROM library_entries WHERE id = :id")
suspend fun deleteSingleById(id: String)
@Delete
suspend fun deleteAll(libraryEntries: List<LocalLibraryEntry>)
@Query("DELETE FROM library_entries")
suspend fun clearLibraryEntries()
}
| 6
|
Kotlin
|
4
| 92
|
ba6f2a69cb71a9fd71d4825921ff6d9b6300471e
| 4,064
|
Kitsune
|
Apache License 2.0
|
ui/src/main/java/es/marcrdz/ui/feature/main/MainViewModel.kt
|
marcRDZ
| 858,190,692
| false
|
{"Kotlin": 76785}
|
package es.marcrdz.ui.feature.main
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import es.marcrdz.presentation.handlers.MainData
import es.marcrdz.presentation.handlers.MainEvent
import es.marcrdz.presentation.handlers.MainEventHandler
import es.marcrdz.ui.base.BaseViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(
handler: MainEventHandler
) : BaseViewModel<MainEvent, MainData>(
initialState = MainData(users = emptyList()),
handler = handler
) {
init {
viewModelScope.launch {
handler.handleInit().collect {
processState(it)
}
}
}
override fun onEvent(event: MainEvent) {
viewModelScope.launch {
handler.handleEvent(event).collect { newState ->
processState(newState) {
when (event) {
is MainEvent.OnUserSelected -> this.copy(selectedUser = it.selectedUser)
else -> it
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1e9bd230cf866bfc91a32fddddf70d76ae6d3a67
| 1,157
|
RandomUserApp
|
Apache License 2.0
|
app/src/main/java/com/example/weatherapp/feature_weather/domain/repository/WeatherRepository.kt
|
VladShurakov
| 712,506,582
| false
|
{"Kotlin": 79527}
|
package com.example.weatherapp.feature_weather.domain.repository
import com.example.weatherapp.feature_weather.domain.model.CurrentWeather
import com.example.weatherapp.feature_weather.domain.model.DailyWeather
import com.example.weatherapp.feature_weather.domain.model.HourlyWeather
import com.example.weatherapp.util.NetworkResult
interface WeatherRepository {
suspend fun getCurrentWeather(
latitude: Double,
longitude: Double,
tempUnit: String,
windSpeedUnit: String,
precipitationUnit: String
): NetworkResult<CurrentWeather>
suspend fun getHourlyWeather(
latitude: Double,
longitude: Double,
tempUnit: String,
windSpeedUnit: String,
precipitationUnit: String
): NetworkResult<HourlyWeather>
suspend fun getDailyWeather(
latitude: Double,
longitude: Double,
tempUnit: String,
windSpeedUnit: String,
precipitationUnit: String
): NetworkResult<DailyWeather>
}
| 2
|
Kotlin
|
0
| 3
|
1cc923f3296f28dfe0d6750995f7d04131f2dae7
| 1,010
|
WeatherApp
|
MIT License
|
values4k/src/main/kotlin/dev/forkhandles/values/validation.kt
|
fork-handles
| 275,203,729
| false
| null |
package dev.forkhandles.values
/**
* Allows validation on values coming in to ensure only legal values construction.
*/
typealias Validation<T> = (T) -> Boolean
val Int.maxLength: Validation<String> get() = { it.length <= this@maxLength }
val Int.minLength: Validation<String> get() = { it.length >= this@minLength }
val Int.exactLength: Validation<String> get() = { it.length == this@exactLength }
val IntRange.length: Validation<String> get() = { this@length.contains(it.length) }
val Int.maxValue: Validation<Int> get() = { it <= this@maxValue }
val Int.minValue: Validation<Int> get() = { it >= this@minValue }
val IntRange.value: Validation<Number> get() = { this@value.contains(it) }
val Long.maxValue: Validation<Long> get() = { it <= this@maxValue }
val Long.minValue: Validation<Long> get() = { it >= this@minValue }
val LongRange.value: Validation<Number> get() = { this@value.contains(it) }
val Number.exactValue: Validation<Number> get() = { it == this@exactValue }
val String.regex: Validation<String> get() = toRegex().let { v -> { v.matches(it) } }
fun <T> Validation<T>.and(that: Validation<T>): Validation<T> = { this@and(it) && that(it) }
fun <T> Validation<T>.or(that: Validation<T>): Validation<T> = { this@or(it) || that(it) }
operator fun <T> Validation<T>.not(): Validation<T> = { !this@not(it) }
fun <T> Validation<T>.check(value: T) {
require(this(value))
{ "Validation failed for: ${this@check.javaClass.simpleName}(${value.toString().takeIf { it.isNotBlank() } ?: "\"\""})" }
}
| 11
| null |
27
| 221
|
fb43cb68201fea003260d57d2fb03bdb92df8085
| 1,523
|
forkhandles
|
Apache License 2.0
|
bannerx/src/main/kotlin/com/blueiobase/api/android/bannerx/enums/OverScrollMode.kt
|
IODevBlue
| 601,108,830
| false
| null |
package com.blueiobase.api.android.bannerx.enums
import com.blueiobase.api.android.bannerx.BannerX
/**
* Constants representing the over-scrolling behaviour of [BannerX] when it over-scrolls.
* @author IODevBlue
* @since 1.0.0
*/
enum class OverScrollMode {
/** Always allow over-scrolling. */
ALWAYS,
/** Over-scroll only if [BannerX] is large enough to scroll and show over-scroll effect. */
IF_CONTENT_SCROLLS,
/** Over-scrolling is disabled. */
NEVER
}
| 0
|
Kotlin
|
0
| 1
|
e61487dfee93ec3101a4dcfa5296f42aed3f5002
| 487
|
BannerX
|
Apache License 2.0
|
src/test/kotlin/de/clark/steps/ManagerPageSteps.kt
|
petrschitow
| 268,904,483
| false
| null |
package de.clark.steps
import de.clark.TestContext
import de.clark.pages.ManagerPage
import io.cucumber.java8.En
class ManagerPageSteps(private var testContext: TestContext) : En {
val managerPage: ManagerPage by lazy {
ManagerPage(testContext.driver)
}
init {
Then("I close popup") {
managerPage.closePopup()
}
And("I see my application") {
assert(managerPage.isMyApplicationDisplayed())
}
}
}
| 0
|
Kotlin
|
0
| 0
|
db8b91a8a7430f7f1a988ac86f9811f720a10c65
| 480
|
clark-tests-ui
|
Apache License 2.0
|
src/main/kotlin/org/halflife/clientmanager/util/GenderDetection.kt
|
xEnakil
| 793,054,418
| false
|
{"Kotlin": 72479}
|
package org.halflife.clientmanager.util
import org.halflife.clientmanager.dto.response.GenderResponse
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
@Component
class GenderDetection(private val restTemplate: RestTemplate) {
fun getGender(name: String): GenderResponse? {
val url = "https://api.genderize.io/?name=$name"
return restTemplate.getForObject(url, GenderResponse::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
763b04aa6046eaef1eb72ec6114233e8b621763a
| 468
|
ClientManager
|
MIT License
|
buildSrc/src/main/kotlin/Prop.kt
|
sadashi-ota
| 193,362,372
| false
| null |
import java.io.FileInputStream
import java.util.Properties
object Prop {
val map = mutableMapOf<String, String>()
fun loadProperties(filepath: String) {
val properties = Properties()
val inputStream = FileInputStream(filepath)
properties.load(inputStream)
properties.forEach {
map[it.key as String] = "${it.value}"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e4c76fd0c9333110f4548140ebb455275631de3c
| 387
|
narou-reader
|
Apache License 2.0
|
app/src/main/java/com/jonay/customcalendar/adapter/LogAdapter.kt
|
jonaysantana93
| 729,904,102
| false
|
{"Kotlin": 21518}
|
package com.jonay.customcalendar.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.jonay.customcalendar.databinding.LogItemBinding
class LogAdapter(private var list: List<String>): RecyclerView.Adapter<LogItem>() {
override fun getItemCount(): Int = list.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LogItem = LogItem.initialize(parent)
override fun onBindViewHolder(holder: LogItem, position: Int) {
holder.bindLogItem(list[position])
}
@SuppressLint("NotifyDataSetChanged")
fun updateList(newList: List<String>) {
list = newList
notifyDataSetChanged()
}
}
class LogItem(private val binding: LogItemBinding): RecyclerView.ViewHolder(binding.root){
companion object: InitializeItemInterface {
override fun initialize(parent: ViewGroup): LogItem =
LogItem(
LogItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false)
)
}
fun bindLogItem(txt: String) = binding.apply {
logTxt.text = txt
}
}
| 0
|
Kotlin
|
0
| 0
|
5954f3133d570a351d30a91fc82be4a69fad2d59
| 1,244
|
CustomCalendar
|
MIT License
|
magicindicator/src/main/java/net/lucode/hackware/magicindicator/buildins/commonnavigator/titles/badge/BadgePagerTitleView.kt
|
Yinzeyu
| 290,686,345
| true
|
{"Kotlin": 159908}
|
package net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge
import android.content.Context
import android.view.View
import android.widget.FrameLayout
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IMeasurablePagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
/**
* 支持显示角标的title,角标布局可自定义
* 博客: http://hackware.lucode.net
* Created by hackware on 2016/7/18.
*/
class BadgePagerTitleView(context: Context?) : FrameLayout(context!!), IMeasurablePagerTitleView {
var innerPagerTitleView: IPagerTitleView? = null
private set
private var mBadgeView: View? = null
var isAutoCancelBadge = true
private var mXBadgeRule: BadgeRule? = null
private var mYBadgeRule: BadgeRule? = null
override fun onSelected(index: Int, totalCount: Int) {
innerPagerTitleView?.onSelected(index, totalCount)
if (isAutoCancelBadge) {
badgeView = null
}
}
override fun onDeselected(index: Int, totalCount: Int) {
innerPagerTitleView?.onDeselected(index, totalCount)
}
override fun onLeave(index: Int, totalCount: Int, leavePercent: Float, leftToRight: Boolean) {
innerPagerTitleView?.onLeave(index, totalCount, leavePercent, leftToRight)
}
override fun onEnter(index: Int, totalCount: Int, enterPercent: Float, leftToRight: Boolean) {
innerPagerTitleView?.onEnter(index, totalCount, enterPercent, leftToRight)
}
fun setInnerPagerTitleView(innerPagerTitleView: IPagerTitleView) {
if (this.innerPagerTitleView === innerPagerTitleView) {
return
}
this.innerPagerTitleView = innerPagerTitleView
removeAllViews()
if (this.innerPagerTitleView is View) {
val lp = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
addView(this.innerPagerTitleView as View?, lp)
}
if (mBadgeView != null) {
val lp = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
addView(mBadgeView, lp)
}
}
var badgeView: View?
get() = mBadgeView
set(badgeView) {
if (mBadgeView === badgeView) {
return
}
mBadgeView = badgeView
removeAllViews()
if (innerPagerTitleView is View) {
val lp = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
addView(innerPagerTitleView as View?, lp)
}
if (mBadgeView != null) {
val lp = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
addView(mBadgeView, lp)
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
if (innerPagerTitleView is View && mBadgeView != null) {
val position = IntArray(14) // 14种角标定位方式
val v = innerPagerTitleView as View
position[0] = v.left
position[1] = v.top
position[2] = v.right
position[3] = v.bottom
if (innerPagerTitleView is IMeasurablePagerTitleView) {
val view = innerPagerTitleView as IMeasurablePagerTitleView
position[4] = view.contentLeft
position[5] = view.contentTop
position[6] = view.contentRight
position[7] = view.contentBottom
} else {
for (i in 4..7) {
position[i] = position[i - 4]
}
}
position[8] = v.width / 2
position[9] = v.height / 2
position[10] = position[4] / 2
position[11] = position[5] / 2
position[12] = position[6] + (position[2] - position[6]) / 2
position[13] = position[7] + (position[3] - position[7]) / 2
// 根据设置的BadgeRule调整角标的位置
mXBadgeRule?.let {
val x = position[it.anchor.ordinal]
val offset = it.offset
val newLeft = x + offset
mBadgeView?.offsetLeftAndRight(newLeft - mBadgeView!!.left)
}
mYBadgeRule?.let {
val y = position[it.anchor.ordinal]
val offset = it.offset
val newTop = y + offset
mBadgeView?.offsetTopAndBottom(newTop - mBadgeView!!.top)
}
}
}
override val contentLeft: Int = if (innerPagerTitleView is IMeasurablePagerTitleView) {
left + (innerPagerTitleView as IMeasurablePagerTitleView).contentLeft
} else left
override val contentTop: Int = if (innerPagerTitleView is IMeasurablePagerTitleView) {
(innerPagerTitleView as IMeasurablePagerTitleView).contentTop
} else top
override val contentRight: Int = if (innerPagerTitleView is IMeasurablePagerTitleView) {
left + (innerPagerTitleView as IMeasurablePagerTitleView).contentRight
} else right
override val contentBottom: Int = if (innerPagerTitleView is IMeasurablePagerTitleView) {
(innerPagerTitleView as IMeasurablePagerTitleView).contentBottom
} else bottom
var xBadgeRule: BadgeRule?
get() = mXBadgeRule
set(badgeRule) {
if (badgeRule != null) {
val anchor = badgeRule.anchor
require(!(anchor != BadgeAnchor.LEFT && anchor != BadgeAnchor.RIGHT && anchor != BadgeAnchor.CONTENT_LEFT && anchor != BadgeAnchor.CONTENT_RIGHT && anchor != BadgeAnchor.CENTER_X && anchor != BadgeAnchor.LEFT_EDGE_CENTER_X && anchor != BadgeAnchor.RIGHT_EDGE_CENTER_X)) { "x badge rule is wrong." }
}
mXBadgeRule = badgeRule
}
var yBadgeRule: BadgeRule?
get() = mYBadgeRule
set(badgeRule) {
if (badgeRule != null) {
val anchor = badgeRule.anchor
require(!(anchor != BadgeAnchor.TOP && anchor != BadgeAnchor.BOTTOM && anchor != BadgeAnchor.CONTENT_TOP && anchor != BadgeAnchor.CONTENT_BOTTOM && anchor != BadgeAnchor.CENTER_Y && anchor != BadgeAnchor.TOP_EDGE_CENTER_Y && anchor != BadgeAnchor.BOTTOM_EDGE_CENTER_Y)) { "y badge rule is wrong." }
}
mYBadgeRule = badgeRule
}
}
| 0
|
Kotlin
|
0
| 0
|
7ea750167fee6debd132e1f1928aa7e70a1eba3b
| 6,390
|
MagicIndicator
|
The Unlicense
|
app/src/main/java/psycho/mountain/tastinggenie/SakeReviewFragment.kt
|
pyth0n14n
| 229,515,435
| false
|
{"Kotlin": 103915}
|
package psycho.mountain.tastinggenie
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ExpandableListView
import android.widget.TextView
import kotlinx.android.synthetic.main.fragment_sake_detailed.*
import kotlinx.android.synthetic.main.fragment_sake_review.*
import kotlinx.android.synthetic.main.list_checklist_item.*
import psycho.mountain.tastinggenie.database.SakeReview
import psycho.mountain.tastinggenie.listview.ExpandableCheckListAdapter
import psycho.mountain.tastinggenie.utility.viewToInt
import psycho.mountain.tastinggenie.utility.viewToString
import java.lang.Math.round
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.LinkedHashMap
import kotlin.math.round
class SakeReviewFragment: Fragment() {
private var listener: SakeReviewFragmentListener? = null
private var sakeReview: SakeReview? = null // データ更新時は既存の値をBundleで渡される
private var sakeListId: Int? = null // データ初回設定時は既存の値をBundleで渡される
interface SakeReviewFragmentListener {
fun onClickReviewAddButton(sakeReview: SakeReview)
}
companion object {
fun newInstance(): SakeReviewFragment {
return SakeReviewFragment()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let{
// sakeReviewは更新時のみ渡され,それ以外では空っぽなので例外処理で対処する
try {
sakeReview = it.getParcelable("sakeReview") as SakeReview
}
catch (e: TypeCastException) {
Log.d("SakeReviewFragment", "new review")
sakeReview = null
}
sakeListId = it.getInt("sake_list_id")
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is SakeReviewFragmentListener) {
listener = context
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sake_review, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
context?.let{
if (sakeReview != null) {
setupView(sakeReview!!)
}
else {
// 日付の自動セット
initDate()
// sake_list_idの設定 (MEMO: これはsakeReviewの更新だろうがそうでなかろうが,常にやらないとダメな奴だった)
sake_review_hidden_id.text = sakeListId.toString()
}
// 日付のセット
sake_review_date.setOnTouchListener { v, event ->
if (event.action == MotionEvent.ACTION_UP) {
val sdf = SimpleDateFormat("yyyy/MM/dd(E)", Locale.US) // Week の形式に応じる
val text_date = sdf.parse(sake_review_date.text.toString())
val calendar = Calendar.getInstance()
calendar.time = text_date
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val date = calendar.get(Calendar.DAY_OF_MONTH)
val dtp = DatePickerDialog(
context!!, DatePickerDialog.OnDateSetListener { view, y, m, d ->
calendar.set(y, m, d)
val day = calendar.get(Calendar.DAY_OF_WEEK)
val week = arrayOf("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
sake_review_date.setText("%04d/%02d/%02d(%s)".format(y, m+1, d, week[day-1]))
}, year, month, date
)
dtp.show()
true
}
else {
false
}
}
// 温度
sake_review_temperature.setOnClickListener {
dialogSakeTemperature(context!!)
}
// 色
sake_review_color.setOnClickListener {
dialogSakeColor(context!!)
}
// 香り
sake_review_scent_intensity.setOnClickListener {
dialogSakeScentIntensity(context!!)
}
sake_review_scent_top.setOnClickListener {
dialogSakeScent(context!!, sake_review_scent_top)
}
sake_review_scent_mouth.setOnClickListener {
dialogSakeScent(context!!, sake_review_scent_mouth)
}
sake_review_scent_nose.setOnClickListener {
dialogSakeScent(context!!, sake_review_scent_nose)
}
// 味
sake_review_viscosity.setOnClickListener {
dialogSakeViscosity(context!!)
}
sake_review_sweet.setOnClickListener {
dialogSakeSweetSpicy(context!!)
}
sake_review_sour.setOnClickListener {
dialogSakeSour(context!!)
}
sake_review_bitter.setOnClickListener {
dialogSakeBitter(context!!)
}
sake_review_umami.setOnClickListener {
dialogSakeUmami(context!!)
}
sake_review_sharp.setOnClickListener {
dialogSakeSharp(context!!)
}
// 評価
sake_review_review.setOnClickListener {
dialogSakeReview(context!!)
}
// DBに追加する処理
button_sake_review_make.setOnClickListener {
val sakeReview = makeSakeReview()
listener?.onClickReviewAddButton(sakeReview)
}
}
}
private fun setupView(review: SakeReview) {
sake_review_hidden_review_id.text = review.review_id.toString()
sake_review_hidden_id.text = review.id.toString()
sake_review_date.setText(review.date)
sake_review_bar.setText(review.bar)
if (review.price >= 0) {sake_review_price.setText(review.price.toString())}
if (review.volume >= 0) {sake_review_volume.setText(review.volume.toString())}
sake_review_temperature.text = review.temp
sake_review_color.text = review.color
sake_review_viscosity.text = review.viscosity
sake_review_scent_intensity.text = review.intensity
sake_review_scent_top.text = review.scent_top
sake_review_scent_mouth.text = review.scent_mouth
sake_review_scent_nose.text = review.scent_nose
sake_review_sweet.text = review.sweet
sake_review_sour.text = review.sour
sake_review_bitter.text = review.bitter
sake_review_umami.text = review.umami
sake_review_sharp.text = review.sharp
sake_review_scene.setText(review.scene)
sake_review_dish.setText(review.dish)
sake_review_comment.setText(review.comment)
sake_review_review.text = review.review
button_sake_review_make.text = "更新"
}
private fun makeSakeReview(): SakeReview {
return SakeReview(
viewToInt(sake_review_hidden_review_id),
viewToInt(sake_review_hidden_id),
viewToString(sake_review_date),
viewToString(sake_review_bar),
viewToInt(sake_review_price),
viewToInt(sake_review_volume),
viewToString(sake_review_temperature),
viewToString(sake_review_color),
viewToString(sake_review_viscosity),
viewToString(sake_review_scent_intensity),
viewToString(sake_review_scent_top),
viewToString(sake_review_scent_mouth),
viewToString(sake_review_scent_nose),
viewToString(sake_review_sweet),
viewToString(sake_review_sour),
viewToString(sake_review_bitter),
viewToString(sake_review_umami),
viewToString(sake_review_sharp),
viewToString(sake_review_scene),
viewToString(sake_review_dish),
viewToString(sake_review_comment),
viewToString(sake_review_review)
)
}
private fun initDate() {
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val date = calendar.get(Calendar.DAY_OF_MONTH)
val day = calendar.get(Calendar.DAY_OF_WEEK)
val week = arrayOf("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
sake_review_date.setText("%04d/%02d/%02d(%s)".format(year, month+1, date, week[day-1]))
}
// ---------------------------------------------------
// ------------- Dialogs -------------------
// ---------------------------------------------------
private fun dialogSakeTemperature(context: Context) {
val temperatureList = arrayOf("飛び切り燗(55℃以上)", "熱燗(50℃)", "上燗(45℃)",
"ぬる燗(40℃)", "人肌燗(35℃)", "日向燗(30℃)", "常温(20℃)", "涼冷え(15℃)",
"花冷え(10℃)","雪冷え(5℃)")
var temp = temperatureList.indexOf(sake_review_temperature.text)
if (temp < 0) {temp = 0}
val dialog = AlertDialog.Builder(context)
.setTitle(R.string.temperature)
.setSingleChoiceItems(temperatureList, temp) { _, which ->
temp = which
}
.setPositiveButton("OK") { _, _ ->
sake_review_temperature.text = temperatureList[temp]
}
.show()
}
private fun dialogSakeColor(context: Context) {
val colorList = arrayOf("青冴え", "透明", "ほぼ透明", "やや黄色",
"山吹色", "琥珀色", "番茶色", "橙色", "白色", "白濁", "緑色")
var color = colorList.indexOf(sake_review_color.text)
if (color < 0) {color = 0}
val dialog = AlertDialog.Builder(context)
.setTitle(R.string.color)
.setSingleChoiceItems(colorList, color) { _, which ->
color = which
}
.setPositiveButton("OK") { _, _ ->
sake_review_color.text = colorList[color]
}
.show()
}
private fun dialogSakeScent(context: Context, textview: TextView) {
val listData = LinkedHashMap<String, List<String>>()
listData["フローラル"] = arrayListOf("梅の花", "桜", "クチナシ", "チューリップ",
"ライチ", "メロン", "バナナ", "洋ナシ", "桃")
listData["フレッシュ"] = arrayListOf("さざんか", "りんどう", "水仙", "藤",
"レモンバーム", "タイム",
"ラズベリー", "イチゴ", "レモン", "ライム", "オレンジ", "グレープフルーツ",
"クレソン", "三つ葉", "バジル",
"松の葉", "青竹", "新芽")
listData["穏やか"] = arrayListOf("ミネラル", "石", "木炭", "オイル",
"白菜", "菜の花", "人参", "ごぼう", "大根", "春菊",
"楓", "ヒノキ", "和紙",
"くるみ", "銀杏", "胡麻",
"ぶなしめじ", "エノキ", "まいたけ")
listData["ふくよか"] = arrayListOf("稲穂", "つきたての餅", "白米", "豆腐", "蕎麦",
"栗", "カシューナッツ", "ピーナッツ",
"バター", "カスタードクリーム", "ヨーグルト",
"磯の香", "ミズゴケ", "青のり", "カステラ", "昆布", "はちみつ", "干し椎茸")
listData["マイナス"] = arrayListOf("セメダイン", "カビ", "アルコール", "米酢", "ゴム",
"フィルタ紙", "炭")
val view = ExpandableListView(context)
val titleList: ArrayList<String> = ArrayList(listData.keys)
val adapter = ExpandableCheckListAdapter(context, titleList, listData, textview.text.split(","), null)
val dialog = AlertDialog.Builder(context)
.setTitle(R.string.label_scent)
.setView(view)
.setPositiveButton("OK") { _,_ ->
textview.text = adapter.getCheckedItems().joinToString()
}
.create()
view.setAdapter(adapter)
dialog.show()
}
private fun dialogSakeSelect(context: Context, list: Array<String>, textView: TextView, title: Int) {
var idx = list.indexOf(textView.text)
if (idx < 0) {idx = list.size/2}
var dialog = AlertDialog.Builder(context)
.apply{
setTitle(title)
setSingleChoiceItems(list, idx) { _, which ->
idx = which
}
setPositiveButton("OK") { _, _ ->
textView.text = list[idx]
}
show()
}
}
private fun dialogSakeViscosity(context: Context) {
val viscosityList = arrayOf("弱い", "中程度", "強い")
dialogSakeSelect(context, viscosityList, sake_review_viscosity, R.string.viscosity)
}
private fun dialogSakeScentIntensity(context: Context) {
dialogSakeSelect(context,
arrayOf("弱い", "やや弱い", "普通", "やや強い", "強い")
, sake_review_scent_intensity, R.string.label_scent_intensity)
}
private fun dialogSakeSweetSpicy(context: Context) {
dialogSakeSelect(context,
arrayOf("甘口", "やや甘口", "普通", "やや辛口", "辛口")
, sake_review_sweet, R.string.label_sweet_spicy)
}
private fun dialogSakeSour(context: Context) {
dialogSakeSelect(context,
arrayOf("弱い", "やや弱い", "普通", "やや強い", "強い")
, sake_review_sour, R.string.label_sour)
}
private fun dialogSakeBitter(context: Context) {
dialogSakeSelect(context,
arrayOf("弱い", "やや弱い", "普通", "やや強い", "強い")
, sake_review_bitter, R.string.label_bitter)
}
private fun dialogSakeUmami(context: Context) {
dialogSakeSelect(context,
arrayOf("淡麗", "やや淡麗", "普通", "やや濃醇", "濃醇")
, sake_review_umami, R.string.label_umami)
}
private fun dialogSakeSharp(context: Context) {
dialogSakeSelect(context,
arrayOf("短い", "やや短い", "普通", "やや長い", "長い")
, sake_review_sharp, R.string.label_sharp)
}
private fun dialogSakeReview(context: Context) {
dialogSakeSelect(context,
arrayOf("嫌い", "やや嫌い", "あまり好きでない",
"普通", "やや好き", "好き", "大好き")
, sake_review_review, R.string.label_review)
}
}
| 0
|
Kotlin
|
0
| 4
|
a8f537e723de7008ae8d12f1274781fcef79bbf0
| 14,271
|
TastingGenie
|
MIT License
|
samples/starter-projects/konsist-starter-multiplatform-gradle-kotlin-junit5/src/jvmTest/kotlin/com/sample/SampleKonsistTest.kt
|
LemonAppDev
| 621,181,534
| false
|
{"Kotlin": 2114775, "Python": 13962}
|
package com.sample
import com.lemonappdev.konsist.api.Konsist
import com.lemonappdev.konsist.api.ext.list.withNameEndingWith
import com.lemonappdev.konsist.api.verify.assert
import org.junit.jupiter.api.Test
class SampleKonsistTest {
@Test
fun `classes with 'UseCase' suffix should reside in 'domain' and 'usecase' package`() {
Konsist
.scopeFromProject()
.classes()
.withNameEndingWith("UseCase")
.assert { it.resideInPackage("..domain..") }
}
}
| 8
|
Kotlin
|
11
| 595
|
2e33b6f26741d709ad63fa8c637c57208330aea9
| 517
|
konsist
|
Apache License 2.0
|
app/src/main/java/com/breezebiolumeskincare/features/dashboard/presentation/api/dayStartEnd/DayStartEndRepoProvider.kt
|
DebashisINT
| 740,453,031
| false
|
{"Kotlin": 15911330, "Java": 1030912}
|
package com.breezebiolumeskincare.features.dashboard.presentation.api.dayStartEnd
import com.breezebiolumeskincare.features.stockCompetetorStock.api.AddCompStockApi
import com.breezebiolumeskincare.features.stockCompetetorStock.api.AddCompStockRepository
object DayStartEndRepoProvider {
fun dayStartRepositiry(): DayStartEndRepository {
return DayStartEndRepository(DayStartEndApi.create())
}
}
| 0
|
Kotlin
|
0
| 0
|
e25768e0e9490f0130635d614b8743b923f35a00
| 414
|
BIOLUMESKINSCIENCE
|
Apache License 2.0
|
examples/core/core_input_mouse.kt
|
Its-Kenta
| 690,260,636
| false
|
{"Kotlin": 257105, "Makefile": 2337}
|
import kaylibkit.kCore.*
import kaylibkit.kEnums.ConfigFlag
import kaylibkit.kEnums.MouseButton
import kaylibkit.kShapes.drawCircle
import kaylibkit.kText.drawText
import kaylibc.*
import kotlinx.cinterop.memScoped
const val SCREEN_WIDTH = 800
const val SCREEN_HEIGHT = 450
//------------------------------------------------------------------------------------
// Program main entry point
//------------------------------------------------------------------------------------
fun main() {
memScoped {
setConfigFlags(ConfigFlag.VSYNC_HINT) // Turn VSYNC On
initWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - mouse input")
var ballPosition: Vector2
var ballColor = darkBlue
//--------------------------------------------------------------------------------------
// Main game loop
while (!windowShouldClose) { // Detect window close button or ESC key
// Update
//----------------------------------------------------------------------------------
ballPosition = getMousePosition(allocator = this)
if (isMouseButtonPressed(MouseButton.LEFT)) ballColor = maroon
else if (isMouseButtonPressed(MouseButton.MIDDLE)) ballColor = lime
else if (isMouseButtonPressed(MouseButton.RIGHT)) ballColor = darkBlue
else if (isMouseButtonPressed(MouseButton.SIDE)) ballColor = purple
else if (isMouseButtonPressed(MouseButton.EXTRA)) ballColor = yellow
else if (isMouseButtonPressed(MouseButton.FORWARD)) ballColor = orange
else if (isMouseButtonPressed(MouseButton.BACK)) ballColor = beige
//----------------------------------------------------------------------------------
drawing {
// Draw
//----------------------------------------------------------------------------------
clearBackground(rayWhite)
drawText("move ball with mouse and click mouse button to change color", 10, 10, 20, darkGray)
drawCircle(ballPosition, 50F, ballColor)
//----------------------------------------------------------------------------------
}
}
// De-Initialization
//--------------------------------------------------------------------------------------
closeWindow() // Close window and OpenGL context
//-------------------------------------------------------------------------------------- }
}
}
| 0
|
Kotlin
|
0
| 0
|
ac1b1a0ec2f6f6f2f85cada81b27b50586069a6b
| 2,542
|
KaylibKit
|
zlib License
|
YAXH/src/main/java/io/github/duzhaokun123/yaxh/utils/Utils.kt
|
duzhaokun123
| 734,996,306
| false
|
{"Kotlin": 16577}
|
package io.github.duzhaokun123.yaxh.utils
| 0
|
Kotlin
|
0
| 0
|
b83140b0ee24fac5fc4ce368fe03e0072e463e83
| 43
|
YAXH
|
Apache License 2.0
|
app/src/main/java/chun/project/movieapp/screen/home/viewholder/TrendingViewHolder.kt
|
ChunJR
| 349,675,573
| false
| null |
package chun.project.movieapp.screen.home.viewholder
import android.content.Context
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.recyclerview.widget.LinearLayoutManager
import chun.project.movieapp.R
import chun.project.movieapp.databinding.ViewholderTrendingBinding
import chun.project.movieapp.model.Genres
import chun.project.movieapp.model.MovieModel
import chun.project.movieapp.screen.home.`interface`.HomeListener
import chun.project.movieapp.screen.home.adapter.HomeAdapter
import chun.project.movieapp.screen.home.adapter.TrendingAdapter
class TrendingViewHolder(
private val context: Context,
private val binding: ViewholderTrendingBinding,
private val listener: HomeListener,
private val lifecycle: Lifecycle
) : HomeAdapter.HomeViewModelV2<List<MovieModel>>(binding.root) {
private val recyclerView = binding.recyclerView
private var adapter: TrendingAdapter? = null
override fun bind(viewType: Int, data: Pair<PagingData<MovieModel>, List<Genres>>) {
adapter = TrendingAdapter(listener)
recyclerView.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
recyclerView.adapter = adapter
adapter?.submitData(lifecycle, data.first)
adapter?.addLoadStateListener { loadState ->
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
errorState?.let {
androidx.appcompat.app.AlertDialog.Builder(context)
.setTitle(R.string.txt_error)
.setMessage(it.error.localizedMessage)
.setNegativeButton(R.string.txt_cancel) { dialog, _ ->
dialog.dismiss()
}
.setPositiveButton(R.string.txt_retry) { _, _ ->
adapter?.retry()
}
.show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
50b58358d05feb255c256bc5dee04b14221e7f85
| 2,189
|
MovieApp
|
Academic Free License v1.1
|
src/main/kotlin/de/langerhans/discord/gitbot/handlers/CommitHandler.kt
|
ICannt
| 74,634,494
| true
|
{"Kotlin": 23602}
|
package de.langerhans.discord.gitbot.handlers
import de.langerhans.discord.gitbot.models.PullRequestEvent
import de.langerhans.discord.gitbot.models.PushEvent
import org.springframework.stereotype.Component
/**
* Created by maxke on 07.08.2016.
* handles new/closed PRs
*/
@Component
open class CommitHandler: AbstractHandler() {
override fun handle(payload: String) {
val event = gson.fromJson(payload, PushEvent::class.java)
val message = "[${event.repository.name}] Push by ${event.pusher.name}:"
client.getChannelByID(config.targetChannel).sendMessage(message)
for (commit in event.commits)
{
client.getChannelByID(config.targetChannel).sendMessage("(${commit.url})\n ```${commit.message}```")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
76175fdc5b0f183364a42266c49344b669a7e1e3
| 780
|
discord-github-webhooks
|
MIT License
|
src/test/kotlin/dev/iuhh/tictactoe/GameBoardTest.kt
|
jimmyiu
| 807,562,276
| false
|
{"Kotlin": 17035}
|
package dev.iuhh.tictactoe
import ArgProvider
import dev.iuhh.tictactoe.builder.GameBoardBuilder
import dev.iuhh.tictactoe.builder.GameBoardStringBuilder
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.catchException
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.ArgumentsSource
import org.junit.jupiter.params.provider.CsvSource
import org.junit.jupiter.params.provider.ValueSource
class GameBoardTest {
@ParameterizedTest
@ValueSource(strings = ["XO=", "XX==1==OO", "===XXXOOO="])
fun `given invalid string format, this game cannot be created`(invalidString: String) {
// when
val exception = catchException {
GameBoard.of(invalidString)
}
// then
assertThat(exception)
.isInstanceOf(IllegalStateException::class.java)
}
@ParameterizedTest
@ArgumentsSource(ValidGameBoardStringTestCases::class)
fun `given valid string representation, the game can be created with expected cell symbols`(gameBoardInString: String) {
// when
val board = GameBoard.of(gameBoardInString)
// then
assertThat(board[0, 0]).isEqualTo('X')
assertThat(board[0, 1]).isEqualTo('O')
assertThat(board[0, 2]).isEqualTo('X')
assertThat(board[1, 0]).isEqualTo('=')
assertThat(board[1, 1]).isEqualTo('O')
assertThat(board[1, 2]).isEqualTo('X')
assertThat(board[2, 0]).isEqualTo('=')
assertThat(board[2, 1]).isEqualTo('O')
assertThat(board[2, 2]).isEqualTo('=')
}
@ParameterizedTest
@CsvSource(
"X,3",
"O,2",
)
fun `count should return the number of symbols in the game board`(symbol: Char, expected: Int) {
// given
val board = GameBoardBuilder.ofRows(
"XOX",
"===",
"OX=",
)
// when
val actual = board.count(symbol)
// then
assertThat(actual).isEqualTo(expected)
}
@ParameterizedTest
@CsvSource(
"Row1,XXO",
"Row2,OO=",
"Row3,XOX",
"Col1,XOX",
"Col2,XOO",
"Col3,O=X",
"DiagonalTopLeft,XOX",
"DiagonalTopRight,OOX",
)
fun `getBy should return the game board current symbols of the given pattern`(
pattern: WinningPattern,
expected: String
) {
val actual = GameBoardBuilder.incomplete().getBy(pattern)
assertThat(actual).containsExactlyElementsOf(expected.toList())
}
private class ValidGameBoardStringTestCases : ArgProvider(
arguments(
GameBoardStringBuilder.ofRows(
"XOX",
"=OX",
"=O="
)
),
arguments(
GameBoardStringBuilder.ofCols(
"X==",
"OOO",
"XX="
)
)
)
}
| 2
|
Kotlin
|
0
| 0
|
1c4b20a69c2d549e79fdba6fbecd26c39c166ce4
| 2,694
|
tic-tac-toe-problem
|
Apache License 2.0
|
src/test/kotlin/dev/iuhh/tictactoe/GameBoardTest.kt
|
jimmyiu
| 807,562,276
| false
|
{"Kotlin": 17035}
|
package dev.iuhh.tictactoe
import ArgProvider
import dev.iuhh.tictactoe.builder.GameBoardBuilder
import dev.iuhh.tictactoe.builder.GameBoardStringBuilder
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.catchException
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.ArgumentsSource
import org.junit.jupiter.params.provider.CsvSource
import org.junit.jupiter.params.provider.ValueSource
class GameBoardTest {
@ParameterizedTest
@ValueSource(strings = ["XO=", "XX==1==OO", "===XXXOOO="])
fun `given invalid string format, this game cannot be created`(invalidString: String) {
// when
val exception = catchException {
GameBoard.of(invalidString)
}
// then
assertThat(exception)
.isInstanceOf(IllegalStateException::class.java)
}
@ParameterizedTest
@ArgumentsSource(ValidGameBoardStringTestCases::class)
fun `given valid string representation, the game can be created with expected cell symbols`(gameBoardInString: String) {
// when
val board = GameBoard.of(gameBoardInString)
// then
assertThat(board[0, 0]).isEqualTo('X')
assertThat(board[0, 1]).isEqualTo('O')
assertThat(board[0, 2]).isEqualTo('X')
assertThat(board[1, 0]).isEqualTo('=')
assertThat(board[1, 1]).isEqualTo('O')
assertThat(board[1, 2]).isEqualTo('X')
assertThat(board[2, 0]).isEqualTo('=')
assertThat(board[2, 1]).isEqualTo('O')
assertThat(board[2, 2]).isEqualTo('=')
}
@ParameterizedTest
@CsvSource(
"X,3",
"O,2",
)
fun `count should return the number of symbols in the game board`(symbol: Char, expected: Int) {
// given
val board = GameBoardBuilder.ofRows(
"XOX",
"===",
"OX=",
)
// when
val actual = board.count(symbol)
// then
assertThat(actual).isEqualTo(expected)
}
@ParameterizedTest
@CsvSource(
"Row1,XXO",
"Row2,OO=",
"Row3,XOX",
"Col1,XOX",
"Col2,XOO",
"Col3,O=X",
"DiagonalTopLeft,XOX",
"DiagonalTopRight,OOX",
)
fun `getBy should return the game board current symbols of the given pattern`(
pattern: WinningPattern,
expected: String
) {
val actual = GameBoardBuilder.incomplete().getBy(pattern)
assertThat(actual).containsExactlyElementsOf(expected.toList())
}
private class ValidGameBoardStringTestCases : ArgProvider(
arguments(
GameBoardStringBuilder.ofRows(
"XOX",
"=OX",
"=O="
)
),
arguments(
GameBoardStringBuilder.ofCols(
"X==",
"OOO",
"XX="
)
)
)
}
| 2
|
Kotlin
|
0
| 0
|
1c4b20a69c2d549e79fdba6fbecd26c39c166ce4
| 2,694
|
tic-tac-toe-problem
|
Apache License 2.0
|
Kotlin/four/src/test/kotlin/com/nlw/four/NextLevelWeekApplicationTests.kt
|
brunoredes
| 341,719,792
| false
|
{"TypeScript": 14215, "Kotlin": 10441}
|
package com.nlw.four
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class NextLevelWeekApplicationTests {
@Test
fun contextLoads() {
}
}
| 0
|
TypeScript
|
0
| 1
|
15127f00e24271ba9a81038c60b1f4e7528d1cd0
| 207
|
next-level-week-4
|
MIT License
|
app/src/main/java/com/example/fooddelivery/data/data_source/remote/dto/order/FoodDto.kt
|
spencer2k19
| 720,201,452
| false
|
{"Kotlin": 305089}
|
package com.example.fooddelivery.data.data_source.remote.dto.order
import com.google.gson.annotations.SerializedName
data class FoodDto(
@SerializedName("id")
val id: Int?,
@SerializedName("quantity")
val quantity: Int?
)
| 0
|
Kotlin
|
0
| 2
|
7be246eba97aa90740952a8bd85dbeb3229c826b
| 240
|
Food-Delivery-Android
|
MIT License
|
app/src/main/java/com/izhal/dicodingsubmission2/User.kt
|
izhal27
| 304,802,570
| false
| null |
package com.izhal.dicodingsubmission2
interface IUser {
val id: Int
val login: String
val avatar_url: String
val url: String
val html_url: String
}
class User(
override val id: Int,
override val login: String,
override val avatar_url: String,
override val url: String,
override val html_url: String
) : IUser
| 0
|
Kotlin
|
1
| 0
|
01f2ad6ab529e8ed95b2af43a4b1d465422d14b9
| 330
|
dicoding-submission-2
|
MIT License
|
app/src/main/java/com/izhal/dicodingsubmission2/User.kt
|
izhal27
| 304,802,570
| false
| null |
package com.izhal.dicodingsubmission2
interface IUser {
val id: Int
val login: String
val avatar_url: String
val url: String
val html_url: String
}
class User(
override val id: Int,
override val login: String,
override val avatar_url: String,
override val url: String,
override val html_url: String
) : IUser
| 0
|
Kotlin
|
1
| 0
|
01f2ad6ab529e8ed95b2af43a4b1d465422d14b9
| 330
|
dicoding-submission-2
|
MIT License
|
mmupnp/src/test/java/net/mm2d/upnp/internal/parser/ServiceParserTest.kt
|
ohmae
| 55,842,405
| false
|
{"Kotlin": 752707}
|
/*
* Copyright (c) 2019 大前良介 (OH<NAME>)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.parser
import io.mockk.mockk
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.IOException
@Suppress("TestFunctionName", "NonAsciiCharacters")
@RunWith(JUnit4::class)
class ServiceParserTest {
@Test(expected = IOException::class)
fun loadDescription_パラメータがとれないとException() {
ServiceParser.loadDescription(mockk(relaxed = true), mockk(relaxed = true), mockk(relaxed = true))
}
}
| 2
|
Kotlin
|
11
| 50
|
19ed97060e1cbda1990e747a216b94c4d3c1641b
| 621
|
mmupnp
|
MIT License
|
presentation/src/main/java/com/jinglebroda/presentation/singleActivity/mvvm/utils/letterLanguage/LetterRusAndEngLanguage.kt
|
jingleBroda
| 629,142,633
| false
| null |
package com.jinglebroda.presentation.singleActivity.mvvm.utils.letterLanguage
object LetterRusAndEngLanguage {
private val capsEngLetter = 'А'..'Z'
private val capsRuLetter = 'А'..'Я'
private val littleEngLetter = 'a'..'z'
private val littleRuLetter = 'а'..'я'
fun isEnglishLetter(ch: Char): Boolean = (ch in capsEngLetter) || (ch in littleEngLetter)
fun isRussianLetter(ch: Char): Boolean = (ch in capsRuLetter) || (ch in littleRuLetter)
}
| 0
|
Kotlin
|
0
| 0
|
acfa4d2443684c002b197ddf524a7afed1afe37c
| 466
|
Look_to_cook
|
MIT License
|
app/src/main/java/com/jeeps/gamecollector/remaster/data/repository/IgdbRepository.kt
|
JamesJose7
| 115,309,790
| false
| null |
package com.jeeps.gamecollector.remaster.data.repository
import com.jeeps.gamecollector.remaster.data.model.IgdbDao
import javax.inject.Inject
class IgdbRepository @Inject constructor(
private val igdbDao: IgdbDao
) {
suspend fun searchGames(query: String) =
igdbDao.searchGames(query)
suspend fun getGameCoverById(gameId: String) =
igdbDao.getGameCoverById(gameId)
}
| 0
|
Kotlin
|
0
| 0
|
67bfd2e487bc2e995c5f9f21718a0e729d17b8b8
| 399
|
GameCollector
|
Apache License 2.0
|
domain/src/main/kotlin/team/applemango/runnerbe/domain/register/runnerbe/repository/AccessTokenRepository.kt
|
ricky-buzzni
| 485,390,072
| false
|
{"Kotlin": 615137}
|
/*
* RunnerBe © 2022 Team AppleMango. all rights reserved.
* RunnerBe license is under the MIT.
*
* [NaverLoginRepository.kt] created by Ji Sungbin on 22. 2. 6. 오전 2:08
*
* Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE.
*/
package team.applemango.runnerbe.domain.register.runnerbe.repository
/**
* 소셜 로그인 액세스 토큰 발급 API -> 각 플랫폼별 로그인 SDK 사용
*/
interface AccessTokenRepository {
suspend fun getKakao(): String
suspend fun getNaver(): String
}
| 0
| null |
0
| 0
|
f48fb298c07732a9c32afcff0bddb16f9fe2e37a
| 500
|
RunnerBe-Android
|
MIT License
|
app/src/main/java/com/suret/moviesapp/domain/usecase/GetFavoriteMovieByIdUseCase.kt
|
Suret1
| 370,776,824
| false
| null |
package com.suret.moviesapp.domain.usecase
import com.suret.moviesapp.data.model.FavoriteMovieModel
import com.suret.moviesapp.domain.repository.MovieRepository
class GetFavoriteMovieByIdUseCase(private val movieRepository: MovieRepository) {
suspend fun execute(id: Int): FavoriteMovieModel = movieRepository.getFavoriteMovieById(id)
}
| 0
|
Kotlin
|
0
| 3
|
82e3d352775fc89d8d6e0506aa1bce977a7c5d12
| 342
|
MoviesApp
|
Apache License 2.0
|
y2018/src/main/kotlin/adventofcode/y2018/Day18.kt
|
Ruud-Wiegers
| 434,225,587
| false
|
{"Kotlin": 432181}
|
package adventofcode.y2018
import adventofcode.io.AdventSolution
import adventofcode.util.collections.takeWhileDistinct
object Day18 : AdventSolution(2018, 18, "Settlers of The North Pole") {
override fun solvePartOne(input: String) =
generateSequence(ConwayGrid(input), ConwayGrid::next)
.drop(10)
.first()
.resourceValue()
override fun solvePartTwo(input: String): Int {
val (steps, state) = generateSequence(ConwayGrid(input), ConwayGrid::next)
.takeWhileDistinct()
.withIndex()
.last()
val cycleLength = generateSequence(state, ConwayGrid::next)
.takeWhileDistinct()
.count()
val remainingSteps = (1_000_000_000 - steps) % cycleLength
return generateSequence(state, ConwayGrid::next)
.drop(remainingSteps)
.first()
.resourceValue()
}
}
private data class ConwayGrid(private val grid: List<List<Char>>) {
constructor(input: String) : this(input.lines().map(String::toList))
fun resourceValue() = count('|') * count('#')
private fun count(ch: Char) = grid.flatten().count { it == ch }
fun next() = grid.indices.map { y ->
grid[0].indices.map { x ->
typeInNextGeneration(x, y)
}
}.let(::ConwayGrid)
private fun typeInNextGeneration(x: Int, y: Int): Char =
when (grid[y][x]) {
'.' -> if (countNear(x, y, '|') >= 3) '|' else '.'
'|' -> if (countNear(x, y, '#') >= 3) '#' else '|'
'#' -> if (countNear(x, y, '|') == 0 || countNear(x, y, '#') <= 1) '.' else '#'
else -> throw IllegalStateException()
}
private fun countNear(x: Int, y: Int, c: Char): Int {
var count = 0
for (j in y - 1..y + 1)
for (i in x - 1..x + 1)
if (grid.getOrNull(j)?.getOrNull(i) == c)
count++
return count
}
}
| 0
|
Kotlin
|
0
| 3
|
ecff6ae4fbd89409d7fb7ffd229e7fc1ac96bfb6
| 2,059
|
advent-of-code
|
MIT License
|
asm-debuglog-plugin/src/main/java/it/sephiroth/android/library/asm/plugin/debuglog/DebugLogPluginInit.kt
|
sephiroth74
| 429,513,067
| false
|
{"Kotlin": 228380, "Java": 510}
|
package it.sephiroth.android.library.asm.plugin.debuglog
import it.sephiroth.android.library.asm.commons.Constants
import it.sephiroth.android.library.asm.commons.plugin.AsmBaseExtension
import it.sephiroth.android.library.asm.plugin.debuglog.asm.vo.MethodAnnotationData
import it.sephiroth.android.library.asm.plugin.debuglog.asm.vo.MethodParameter
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.logging.Logger
abstract class DebugLogPluginInit : Plugin<Project> {
private lateinit var logger: Logger
private val extensionName = BuildConfig.EXTENSION_NAME
fun getObjectMapping() = map
override fun apply(target: Project) {
logger = target.logger
logger.lifecycle("[DebugLogPluginInit] apply(${target.name})")
val base = if (target.extensions.findByName(Constants.BASE_EXTENSION_NAME) == null) {
logger.lifecycle("[DebugLogPluginInit] registering extension ${Constants.BASE_EXTENSION_NAME}")
target.extensions.create(Constants.BASE_EXTENSION_NAME, AsmBaseExtension::class.java)
} else {
logger.lifecycle("[DebugLogPluginInit] extension ${Constants.BASE_EXTENSION_NAME} already registered")
target.extensions.getByType(AsmBaseExtension::class.java)
}
logger.lifecycle("[DebugLogPluginInit] registering extension ${Constants.BASE_EXTENSION_NAME}.$extensionName")
base.extensions.create(extensionName, DebugLogPluginExtension::class.java)
// target.plugins.apply(DebugLogPluginPost::class.java)
// target.plugins.apply(DebugLogPlugin::class.java)
}
companion object {
val map = hashMapOf<String, HashMap<String, Pair<MethodAnnotationData, List<MethodParameter>>>>()
}
}
| 0
|
Kotlin
|
0
| 0
|
e99102cf0cc8f6328ea97161deb5ca2a787b6b0a
| 1,763
|
AndroidDebugLog
|
MIT License
|
ktfx-layouts/src/ktfx/layouts/scene/shape/MoveTo.kt
|
alilosoft
| 182,138,993
| true
|
{"Kotlin": 364065, "HTML": 1385, "Java": 682}
|
@file:Suppress("PackageDirectoryMismatch", "NOTHING_TO_INLINE")
package ktfx.layouts
import javafx.scene.shape.MoveTo
/** Creates a [MoveTo]. */
fun moveTo(
x: Double = 0.0,
y: Double = 0.0,
init: ((@LayoutDslMarker MoveTo).() -> Unit)? = null
): MoveTo = MoveTo(x, y).also { init?.invoke(it) }
/** Creates a [MoveTo] and add it to this manager. */
inline fun PathElementManager.moveTo(
x: Double = 0.0,
y: Double = 0.0,
noinline init: ((@LayoutDslMarker MoveTo).() -> Unit)? = null
): MoveTo = ktfx.layouts.moveTo(x, y, init).add()
| 0
|
Kotlin
|
0
| 0
|
f499c9d7abddb270f1946c0e9ffb9072e45cd625
| 560
|
ktfx
|
Apache License 2.0
|
data_source/message_data_source/src/main/java/com/can_apps/message_data_source/MessageDatabase.kt
|
loukwn
| 327,419,202
| true
|
{"Kotlin": 135661, "Shell": 322}
|
package com.can_apps.message_data_source
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [MessageEntity::class], version = 1)
internal abstract class MessageDatabase : RoomDatabase() {
abstract fun messageDao(): MessageDao
}
| 0
| null |
0
| 0
|
310249c542b746de6e6a868956a45e5b9fffb2dc
| 269
|
showcase
|
Freetype Project License
|
games-impl/src/commonMain/kotlin/net/zomis/games/impl/alchemists/TheoryBoard.kt
|
Zomis
| 125,767,793
| false
|
{"Kotlin": 1346310, "Vue": 212095, "JavaScript": 43020, "CSS": 4513, "HTML": 1459, "Shell": 801, "Dockerfile": 348}
|
package net.zomis.games.impl.alchemists
| 89
|
Kotlin
|
5
| 17
|
dd9f0e6c87f6e1b59b31c1bc609323dbca7b5df0
| 41
|
Games
|
MIT License
|
src/pl/shockah/aoc/y2015/Day24.kt
|
Shockah
| 159,919,224
| false
| null |
package pl.shockah.aoc.y2015
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import pl.shockah.aoc.AdventTask
import pl.shockah.unikorn.Ref
class Day24: AdventTask<List<Int>, Long, Long>(2015, 24) {
private data class Group(
val list: List<Int>
): List<Int> by list, Comparable<Group> {
val sum by lazy { sum() }
val product by lazy { list.map { it.toLong() }.reduce { acc, i -> acc * i} }
constructor(): this(emptyList())
operator fun plus(`package`: Int): Group {
return Group(list + `package`)
}
override fun compareTo(other: Group): Int {
if (size != other.size)
return size.compareTo(other.size)
if (product != other.product)
return product.compareTo(other.product)
return 0
}
}
private data class Grouping(
val groups: List<Group>
) {
val isValid: Boolean
get() = groups.map { it.sum }.toSet().size == 1
constructor(groupCount: Int): this(generateSequence { Group() }.take(groupCount).toList())
}
override fun parseInput(rawInput: String): List<Int> {
return rawInput.lines().map(String::toInt)
}
private fun getBestCombination(groupCount: Int, packages: List<Int>): Grouping {
val best = Ref<Grouping?>(null)
findBestCombination(packages.sortedDescending(), packages.sum() / groupCount, Grouping(groupCount), best)
return best.value!!
}
private fun findBestCombination(packages: List<Int>, target: Int, grouping: Grouping, best: Ref<Grouping?>) {
if (best.value != null) {
if (best.value!!.groups.first() < grouping.groups.first())
return
}
if (packages.isEmpty()) {
@Suppress("LiftReturnOrAssignment")
if (grouping.isValid) {
if (best.value == null || grouping.groups.first() < best.value!!.groups.first()) {
println("New best: $grouping")
best.value = grouping
}
}
return
}
val descending = grouping.groups.sortedByDescending { it.sum }
val delta = (descending[0].sum - descending[1].sum) + (descending[1].sum - descending[2].sum)
if (delta > packages.sum())
return
val `package` = packages.first()
val newPackages = packages.drop(1)
for (i in grouping.groups.indices) {
if (grouping.groups[i].sum + `package` <= target) {
val newGroups = grouping.groups.toMutableList()
newGroups[i] = newGroups[i] + `package`
findBestCombination(newPackages, target, Grouping(newGroups), best)
}
}
}
override fun part1(input: List<Int>): Long {
return getBestCombination(3, input).groups.first().product
}
// TODO: this takes way too long... find a faster way or some optimizations
override fun part2(input: List<Int>): Long {
return getBestCombination(4, input).groups.first().product
}
class Tests {
private val task = Day24()
private val input = (1..5) + (7..11)
@Test
fun part1() {
Assertions.assertEquals(99L, task.part1(input))
}
@Test
fun part2() {
Assertions.assertEquals(44L, task.part2(input))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
| 2,927
|
Advent-of-Code
|
Apache License 2.0
|
sdkpushexpress/src/main/java/com/pushexpress/sdk/models/DeviceConfigRequest.kt
|
pushexpress
| 600,907,986
| false
| null |
package com.pushexpress.sdk.models
data class DeviceConfigRequest(
val app_id: String,
val ic_token: String,
val ext_id: String,
val fcm_token: String,
val lang: String,
val ad_id: String,
val country_net: String,
val country_sim: String,
val timezone: Int,
val install_ts: Long,
val onscreen_cnt: Int,
val onscreen_sec: Long,
val droid_api_ver: Int,
val sdk_ver: String,
)
| 0
|
Kotlin
|
0
| 3
|
69ec0acc519cf805447e76745a7e3f868aedd173
| 431
|
pushexpress-android-sdk
|
Apache License 2.0
|
src/main/java/com/digital/signage/exceptions/InvalidRequestDataException.kt
|
Rocky-Saini
| 741,118,438
| false
|
{"Batchfile": 1, "Markdown": 2, "Shell": 1, "Maven POM": 1, "Dockerfile": 1, "XML": 9, "Java Properties": 4, "YAML": 2, "JSON": 8, "SQL": 2, "Java": 564, "Kotlin": 193, "Ignore List": 1}
|
package com.digital.signage.exceptions
/**
* @author -<NAME> created on 1/23/2023 4:05 PM
* @project - Digital Sign-edge
*/
class InvalidRequestDataException(val invalidDataLocalizedMessage: String) : Exception()
| 0
|
Java
|
0
| 0
|
7879fdf301f0d0545954bfed823de6b6cbd41b46
| 216
|
local-server
|
DOC License
|
components/proxy/src/test/kotlin/com/hotels/styx/routing/config/RouteHandlerFactoryTest.kt
|
pologood
| 182,489,218
| true
|
{"YAML": 44, "Markdown": 31, "Text": 17, "Maven POM": 22, "Ignore List": 1, "Makefile": 1, "Java": 727, "JSON": 4, "Kotlin": 13, "Scala": 103, "XML": 15, "Python": 8, "Lua": 1, "Shell": 9, "Dockerfile": 1, "SVG": 1, "Groovy": 1, "HTML": 6, "CSS": 1, "JavaScript": 5, "ANTLR": 1}
|
/*
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.routing.config
import com.fasterxml.jackson.databind.JsonNode
import com.hotels.styx.api.HttpHandler
import io.kotlintest.shouldBe
import io.kotlintest.shouldThrow
import io.kotlintest.specs.StringSpec
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import java.lang.IllegalArgumentException
class RouteHandlerFactoryTest : StringSpec({
val mockHandler = mockk<HttpHandler>()
val aHandlerInstance = mockk<HttpHandler>()
val handlers = mapOf("aHandler" to aHandlerInstance)
"Builds a new handler as per RouteHandlerDefinition" {
val routeDef = RouteHandlerDefinition("handler-def", "DelegateHandler", mockk<JsonNode>())
val handlerFactory = httpHandlerFactory(mockHandler)
val routeFactory = RouteHandlerFactory(mapOf("DelegateHandler" to handlerFactory), handlers)
val delegateHandler = routeFactory.build(listOf("parents"), routeDef)
(delegateHandler != null).shouldBe(true)
verify {
handlerFactory.build(listOf("parents"), routeFactory, routeDef)
}
}
"Doesn't accept unregistered types" {
val config = RouteHandlerDefinition("foo", "ConfigType", mockk())
val routeFactory = RouteHandlerFactory(mapOf(), handlers)
val e = shouldThrow<IllegalArgumentException> {
routeFactory.build(listOf(), config)
}
e.message.shouldBe("Unknown handler type 'ConfigType'")
}
"Returns handler from a configuration reference" {
val routeFactory = RouteHandlerFactory(mapOf(), handlers)
val handler = routeFactory.build(listOf(), RouteHandlerReference("aHandler"))
handler.shouldBe(aHandlerInstance)
}
"Throws exception when it refers a non-existent object" {
val routeFactory = RouteHandlerFactory(mapOf(), handlers)
val e = shouldThrow<IllegalArgumentException> {
routeFactory.build(listOf(), RouteHandlerReference("non-existent"))
}
e.message.shouldBe("Non-existent handler instance: 'non-existent'")
}
})
fun httpHandlerFactory(handler: HttpHandler): HttpHandlerFactory {
val factory: HttpHandlerFactory = mockk()
every {
factory.build(any(), any(), any())
} returns handler
return factory
}
| 0
|
Java
|
0
| 0
|
a016e9d9ce5cd698e73110789cc8fb3acc43d360
| 2,885
|
styx
|
Apache License 2.0
|
airbyte-commons-worker/src/main/kotlin/io/airbyte/workers/workload/JobOutputDocStore.kt
|
jxqlovejava
| 790,575,401
| true
|
{"Java Properties": 3, "Gradle Kotlin DSL": 50, "Shell": 55, "Markdown": 71, "Batchfile": 1, "Kotlin": 509, "Dockerfile": 26, "Java": 1550, "INI": 10, "JavaScript": 21, "TypeScript": 421, "HTML": 5, "CSS": 7, "Python": 7, "Makefile": 2, "Go": 9, "SQL": 14}
|
package io.airbyte.workers.workload
import io.airbyte.commons.json.Jsons
import io.airbyte.config.ConnectorJobOutput
import io.airbyte.config.ReplicationOutput
import io.airbyte.metrics.lib.MetricAttribute
import io.airbyte.metrics.lib.MetricClient
import io.airbyte.metrics.lib.MetricTags
import io.airbyte.metrics.lib.OssMetricsRegistry
import io.airbyte.workers.storage.StorageClient
import io.airbyte.workers.workload.exception.DocStoreAccessException
import jakarta.inject.Named
import jakarta.inject.Singleton
import java.util.Optional
@Singleton
class JobOutputDocStore(
@Named("outputDocumentStore") val storageClient: StorageClient,
val metricClient: MetricClient,
) {
@Throws(DocStoreAccessException::class)
fun read(workloadId: String): Optional<ConnectorJobOutput> {
val output: String? =
try {
storageClient.read(workloadId)
} catch (e: Exception) {
throw DocStoreAccessException("Unable to read output for $workloadId", e)
}
return Optional.ofNullable(output?.let { Jsons.deserialize(it, ConnectorJobOutput::class.java) })
}
@Throws(DocStoreAccessException::class)
fun write(
workloadId: String,
connectorJobOutput: ConnectorJobOutput,
) {
try {
storageClient.write(workloadId, Jsons.serialize(connectorJobOutput))
metricClient.count(OssMetricsRegistry.JOB_OUTPUT_WRITE, 1, MetricAttribute(MetricTags.STATUS, "success"))
} catch (e: Exception) {
metricClient.count(OssMetricsRegistry.JOB_OUTPUT_WRITE, 1, MetricAttribute(MetricTags.STATUS, "error"))
throw DocStoreAccessException("Unable to write output for $workloadId", e)
}
}
@Throws(DocStoreAccessException::class)
fun readSyncOutput(workloadId: String): Optional<ReplicationOutput> {
val output: String? =
try {
storageClient.read(workloadId).also {
metricClient.count(OssMetricsRegistry.JOB_OUTPUT_READ, 1, MetricAttribute(MetricTags.STATUS, "success"))
}
} catch (e: Exception) {
metricClient.count(OssMetricsRegistry.JOB_OUTPUT_READ, 1, MetricAttribute(MetricTags.STATUS, "error"))
throw DocStoreAccessException("Unable to read output for $workloadId", e)
}
return Optional.ofNullable(output?.let { Jsons.deserialize(it, ReplicationOutput::class.java) })
}
@Throws(DocStoreAccessException::class)
fun writeSyncOutput(
workloadId: String,
connectorJobOutput: ReplicationOutput,
) {
try {
storageClient.write(workloadId, Jsons.serialize(connectorJobOutput))
metricClient.count(OssMetricsRegistry.JOB_OUTPUT_WRITE, 1, MetricAttribute(MetricTags.STATUS, "success"))
} catch (e: Exception) {
metricClient.count(OssMetricsRegistry.JOB_OUTPUT_WRITE, 1, MetricAttribute(MetricTags.STATUS, "error"))
throw DocStoreAccessException("Unable to write output for $workloadId", e)
}
}
}
| 0
| null |
0
| 0
|
d4e64e0a64c6f7ff72e19d6890be5c747f902f70
| 2,880
|
airbyte-platform
|
MIT License
|
pop-miners/altchain-pop-miner/src/main/kotlin/org/veriblock/miners/pop/shell/commands/DebugCommands.kt
|
paucasafont
| 270,580,517
| false
|
{"INI": 2, "Gradle Kotlin DSL": 20, "Shell": 1, "Markdown": 7, "Batchfile": 1, "Kotlin": 316, "Java": 431, "Dockerfile": 4, "Java Properties": 1}
|
// VeriBlock Blockchain Project
// Copyright 2017-2018 VeriBlock, Inc
// Copyright 2018-2020 <NAME>
// All rights reserved.
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
package org.veriblock.miners.pop.shell.commands
import io.grpc.StatusRuntimeException
import kotlinx.coroutines.runBlocking
import org.veriblock.lite.NodeCoreLiteKit
import org.veriblock.lite.core.Context
import org.veriblock.miners.pop.service.MinerConfig
import org.veriblock.miners.pop.service.MinerService
import org.veriblock.miners.pop.util.formatCoinAmount
import org.veriblock.sdk.alt.plugin.PluginService
import org.veriblock.sdk.models.Coin
import org.veriblock.shell.CommandFactory
import org.veriblock.shell.command
import org.veriblock.shell.core.success
fun CommandFactory.debugCommands(
config: MinerConfig,
context: Context,
minerService: MinerService,
pluginService: PluginService,
nodeCoreLiteKit: NodeCoreLiteKit
) {
command(
name = "Get Debug Information",
form = "getdebuginfo",
description = "Collect information about the application for troubleshooting"
) {
printInfo("Running several checks, this may take a few moments...")
if (nodeCoreLiteKit.network.isHealthy()) {
printInfo("SUCCESS - NodeCore connection: Connected")
val nodeCoreSyncStatus = nodeCoreLiteKit.network.getNodeCoreSyncStatus()
if (nodeCoreLiteKit.network.isSynchronized()) {
printInfo("SUCCESS - NodeCore synchronization status: Synchronized (LocalHeight=${nodeCoreSyncStatus.localBlockchainHeight} NetworkHeight=${nodeCoreSyncStatus.networkHeight})")
} else {
printInfo("FAIL - NodeCore synchronization status: Not synchronized. ${nodeCoreSyncStatus.blockDifference} blocks left (LocalHeight=${nodeCoreSyncStatus.localBlockchainHeight} NetworkHeight=${nodeCoreSyncStatus.networkHeight})")
}
} else {
printInfo("FAIL - NodeCore connection: Not connected")
printInfo("FAIL - Unable to determine the NodeCore synchronization status")
}
val plugins = pluginService.getPlugins().filter { it.key != "test" }
if (plugins.isNotEmpty()) {
runBlocking {
plugins.forEach {
if (it.value.isConnected()) {
printInfo("SUCCESS - ${it.value.name} connection: Connected")
val chainSyncStatus = it.value.getSynchronizedStatus()
if (chainSyncStatus.isSynchronized) {
printInfo("SUCCESS - ${it.value.name} synchronization status: Synchronized (LocalHeight=${chainSyncStatus.localBlockchainHeight} NetworkHeight=${chainSyncStatus.networkHeight})")
} else {
printInfo("FAIL- ${it.value.name} synchronization status: Not synchronized, ${chainSyncStatus.blockDifference} blocks left (LocalHeight=${chainSyncStatus.localBlockchainHeight} NetworkHeight=${chainSyncStatus.networkHeight})")
}
} else {
printInfo("FAIL - ${it.value.name} connection: Not connected")
printInfo("FAIL - Unable to determine the ${it.value.name} synchronization status")
}
}
}
} else {
printInfo("FAIL - There are no plugins loaded")
}
try {
val currentBalance = minerService.getBalance()?.confirmedBalance ?: Coin.ZERO
if (nodeCoreLiteKit.network.isHealthy()) {
if (currentBalance.atomicUnits > config.maxFee) {
printInfo("SUCCESS - The PoP wallet contains sufficient funds, current balance: ${currentBalance.atomicUnits.formatCoinAmount()} ${context.vbkTokenName}")
} else {
printInfo("FAIL - The VBK PoP wallet does not contain sufficient funds: current balance: ${currentBalance.atomicUnits.formatCoinAmount()} ${context.vbkTokenName}, minimum required: ${config.maxFee.formatCoinAmount()}, need ${(config.maxFee - currentBalance.atomicUnits).formatCoinAmount()} more. See: https://wiki.veriblock.org/index.php/Get_VBK")
}
} else {
printInfo("FAIL - Unable to determine the PoP balance.")
}
} catch(e: StatusRuntimeException) {
printInfo("FAIL - Unable to determine the PoP balance.")
}
success()
}
}
| 1
| null |
1
| 1
|
904f69339e8e152ac54f8f5a63aea6eddfaba27b
| 4,630
|
nodecore
|
MIT License
|
src/kotlin/de/monticore/lang/montisecarc/visualization/GraphDatabase.kt
|
MontiSecArc
| 82,662,403
| false
| null |
package de.monticore.lang.montisecarc.visualization
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import de.tbuning.neo4j.graphdatabase.Neo4JGraphDatabase
import org.neo4j.graphdb.GraphDatabaseService
/**
* Copyright 2016 thomasbuning
*
* 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.
*/
class GraphDatabase(private val project: Project) : ProjectComponent, Disposable {
val instance = Logger.getInstance(GraphDatabase::class.java)
override fun disposeComponent() {
dispose()
}
override fun projectClosed() {
dispose()
}
override fun initComponent() {
}
private var arrayOfNeo4JGraphDatabases: Array<out Neo4JGraphDatabase>? = null
override fun projectOpened() {
try {
arrayOfNeo4JGraphDatabases = ApplicationManager.getApplication().getExtensions(Neo4JGraphDatabase.EP_NAME)
arrayOfNeo4JGraphDatabases?.forEach {
it.startDatabase(project.basePath.orEmpty())
}
} catch (ex: Exception) {
Logger.getInstance(GraphDatabase::class.java).info("Graph Database Plugin not installed")
}
}
override fun dispose() {
arrayOfNeo4JGraphDatabases?.forEach(Neo4JGraphDatabase::dispose)
}
fun isAvailable():Boolean {
if(arrayOfNeo4JGraphDatabases == null) {
return false
} else {
return arrayOfNeo4JGraphDatabases!!.isNotEmpty()
}
}
override fun getComponentName(): String = javaClass.name
fun createDatabase(graphQuery: String, forDir: String = "graph_editor"): GraphDatabaseService? {
instance.info("Create Database $graphQuery in $forDir")
val database = arrayOfNeo4JGraphDatabases?.find { it.databaseFolder == forDir }
if (database != null) {
return database.createDatabase(graphQuery)
}
return null
}
}
| 0
|
Kotlin
|
2
| 1
|
82d80a3d587a3f47e961034cf7e496f7149fd912
| 2,592
|
intellij_msa_language_plugin
|
Apache License 2.0
|
App News - Android + Kotlin + Retrofit + Coroutines + Room/app_news_mvvm/app/src/main/java/com/lvb/projects/app_news_mvvm/util/InternetChecker.kt
|
Velosofurioso
| 454,964,649
| false
| null |
package com.lvb.projects.app_news_mvvm.util
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
class InternetChecker {
companion object {
fun checkForInternetConnection(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
val activeNetwork = connectivityManager.activeNetwork ?: return false
val capabilities =
connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
return when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> true
else -> false
}
return connectivityManager.activeNetworkInfo?.isAvailable ?: false
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d7d97f11c24d6a736b9603184b003a53a5eca099
| 1,128
|
Mobile-Development-Courses
|
MIT License
|
app/src/main/java/com/example/test/di/NetworkModule.kt
|
rahman248
| 504,381,047
| false
| null |
package com.example.test.di
import com.example.test.BuildConfig
import com.example.test.data.remote.ApiService
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
/* Services */
@Provides
@Singleton
fun provideGsonConverterFactory(): GsonConverterFactory {
return GsonConverterFactory.create(GsonBuilder().create())
}
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.build()
@ApiServices
@Provides
@Singleton
fun provideRetrofitServices(gsonConverterFactory: GsonConverterFactory,
okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(gsonConverterFactory)
.client(okHttpClient)
.build()
}
@Provides
@Singleton
fun provideApiService(@ApiServices retrofit: Retrofit): ApiService = retrofit.create(
ApiService::class.java)
}
| 0
|
Kotlin
|
0
| 0
|
f1cc20afffeed786d514bdffa5ad56b4a6eddd37
| 1,581
|
pjs
|
The Unlicense
|
emojipicker/src/main/java/com/kazumaproject/emojipicker/other/EmojiTypes.kt
|
KazumaProject
| 599,677,394
| false
|
{"Kotlin": 257606, "Java": 153764}
|
package com.kazumaproject.emojipicker.other
sealed class EmojiTypes{
object SmileysAndPeople : EmojiTypes()
object AnimalsAndNature : EmojiTypes()
object FoodAndDrink : EmojiTypes()
object Activity : EmojiTypes()
object TravelAndPlaces : EmojiTypes()
object Objects : EmojiTypes()
object Symbols : EmojiTypes()
}
| 0
|
Kotlin
|
0
| 0
|
17ac7b5bfa58223eb87c9c360a1e6ec335683fcf
| 342
|
MarkdownNote
|
MIT License
|
app/src/main/java/me/zhaoweihao/hnuplus/WeatherActivity.kt
|
zhaoweih
| 128,950,368
| false
| null |
package me.zhaoweihao.hnuplus
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.github.pwittchen.weathericonview.WeatherIconView
import com.taishi.flipprogressdialog.FlipProgressDialog
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import java.io.IOException
import butterknife.BindView
import butterknife.ButterKnife
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.current.*
import me.zhaoweihao.hnuplus.Gson.Channel
import me.zhaoweihao.hnuplus.Gson.Forecast
import me.zhaoweihao.hnuplus.Gson.Weather
import me.zhaoweihao.hnuplus.Utils.HttpUtil
import me.zhaoweihao.hnuplus.Utils.Utility
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
class WeatherActivity : AppCompatActivity(), TencentLocationListener {
private var latitudeStr: String? = null
private var longitudeStr: String? = null
private var addressStr: String? = null
private var icon: Int = 0
private var flipProgressDialog: FlipProgressDialog? = null
companion object {
private val TAG = "WeatherActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_weather)
ButterKnife.bind(this)
flipProgressDialog = Utility.myDialog()
flipProgressDialog!!.show(fragmentManager, "")
if (Build.VERSION.SDK_INT >= 23) {
val permissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (checkSelfPermission(permissions[0]) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, 0)
} else {
val request = TencentLocationRequest.create()
val locationManager = TencentLocationManager.getInstance(this)
val error = locationManager.requestLocationUpdates(request, this)
}
}
}
private fun requestWeather(latitude: String, longitude: String) {
val url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(SELECT%20woeid%20FROM%20geo.places%20WHERE%20text%3D%22($latitude%2C$longitude)%22)%20and%20u%3D'c'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
HttpUtil.sendOkHttpRequest(url, object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val responseData = response.body().string()
val weather = Utility.handleWeatherResponse(responseData)
val channel = weather!!.query!!.results!!.channel
val location = channel!!.location!!.city + "," + channel.location!!.region + "," + channel.location!!.country
Log.d(TAG, location)
runOnUiThread {
if (weather != null) {
showWeatherInfo(weather)
} else {
Log.d(TAG, "获取天气信息失败")
}
}
}
})
}
private fun showWeatherInfo(weather: Weather?) {
val channel = weather!!.query!!.results!!.channel
val locationStr = channel!!.location!!.city + "," + channel.location!!.region + "," + channel.location!!.country
val statusStr = channel.item!!.condition!!.text
val degreeStr = channel.item!!.condition!!.temp
val humidityStr = channel.atmosphere!!.humidity
val speedStr = channel.wind!!.speed
val sunriseStr = channel.astronomy!!.sunrise
val sunsetStr = channel.astronomy!!.sunset
val chillStr = channel.wind!!.chill
val directionStr = channel.wind!!.direction
val pressureStr = channel.atmosphere!!.pressure
val risingStr = channel.atmosphere!!.rising
val visibilityStr = channel.atmosphere!!.visibility
val code = channel.item!!.condition!!.code
title = locationStr
status!!.text = statusStr
degree!!.text = degreeStr!! + " C"
humidity!!.text = humidityStr!! + " %"
speed!!.text = speedStr!! + " km/h"
sunrise!!.text = sunriseStr
sunset!!.text = sunsetStr
forecast_layout!!.removeAllViews()
chill!!.text = chillStr
direction!!.text = directionStr
speed_detail!!.text = speedStr + " km/h"
humidity_detail!!.text = humidityStr + " %"
pressure!!.text = pressureStr!! + " mb"
rising!!.text = risingStr
visibility!!.text = visibilityStr!! + " km"
latitude!!.text = latitudeStr
longitude!!.text = longitudeStr
address!!.text = addressStr
setWeatherIcon(code)
my_weather_icon!!.setIconResource(getString(icon))
my_weather_icon!!.setIconSize(80)
my_weather_icon!!.setIconColor(Color.GRAY)
for (forecast in channel.item!!.forecastList!!) {
val view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecast_layout, false)
val date = view.findViewById<TextView>(R.id.date)
val day = view.findViewById<TextView>(R.id.day)
val statusForecast = view.findViewById<TextView>(R.id.status_forecast)
val high = view.findViewById<TextView>(R.id.high)
val low = view.findViewById<TextView>(R.id.low)
val dateStr = forecast.date
val dayStr = forecast.day
val statusForecastStr = forecast.text
val highStr = forecast.high
val lowStr = forecast.low
date.text = dateStr
day.text = dayStr
statusForecast.text = statusForecastStr
high.text = highStr
low.text = lowStr
forecast_layout!!.addView(view)
}
flipProgressDialog!!.dismiss()
}
private fun setWeatherIcon(code: String?) {
when (code) {
"0" -> icon = R.string.wi_tornado
"1" -> icon = R.string.wi_storm_showers
"2" -> icon = R.string.wi_tornado
"3" -> icon = R.string.wi_thunderstorm
"4" -> icon = R.string.wi_thunderstorm
"5" -> icon = R.string.wi_snow
"6" -> icon = R.string.wi_rain_mix
"7" -> icon = R.string.wi_rain_mix
"8" -> icon = R.string.wi_sprinkle
"9" -> icon = R.string.wi_sprinkle
"10" -> icon = R.string.wi_hail
"11" -> icon = R.string.wi_showers
"12" -> icon = R.string.wi_showers
"13" -> icon = R.string.wi_snow
"14" -> icon = R.string.wi_storm_showers
"15" -> icon = R.string.wi_snow
"16" -> icon = R.string.wi_snow
"17" -> icon = R.string.wi_hail
"18" -> icon = R.string.wi_hail
"19" -> icon = R.string.wi_cloudy_gusts
"20" -> icon = R.string.wi_fog
"21" -> icon = R.string.wi_fog
"22" -> icon = R.string.wi_fog
"23" -> icon = R.string.wi_cloudy_gusts
"24" -> icon = R.string.wi_cloudy_windy
"25" -> icon = R.string.wi_thermometer
"26" -> icon = R.string.wi_cloudy
"27" -> icon = R.string.wi_night_cloudy
"28" -> icon = R.string.wi_day_cloudy
"29" -> icon = R.string.wi_night_cloudy
"30" -> icon = R.string.wi_day_cloudy
"31" -> icon = R.string.wi_night_clear
"32" -> icon = R.string.wi_day_sunny
"33" -> icon = R.string.wi_night_clear
"34" -> icon = R.string.wi_day_sunny_overcast
"35" -> icon = R.string.wi_hail
"36" -> icon = R.string.wi_day_sunny
"37" -> icon = R.string.wi_thunderstorm
"38" -> icon = R.string.wi_thunderstorm
"39" -> icon = R.string.wi_thunderstorm
"40" -> icon = R.string.wi_storm_showers
"41" -> icon = R.string.wi_snow
"42" -> icon = R.string.wi_snow
"43" -> icon = R.string.wi_snow
"44" -> icon = R.string.wi_cloudy
"45" -> icon = R.string.wi_lightning
"46" -> icon = R.string.wi_snow
"47" -> icon = R.string.wi_thunderstorm
"3200" -> icon = R.string.wi_cloud
else -> icon = R.string.wi_cloud
}
}
override fun onLocationChanged(tencentLocation: TencentLocation, error: Int, reason: String) {
if (TencentLocation.ERROR_OK == error) {
// 定位成功
Log.d(TAG, tencentLocation.address)
latitudeStr = tencentLocation.latitude.toString()
longitudeStr = tencentLocation.longitude.toString()
addressStr = tencentLocation.address
requestWeather(latitudeStr!!, longitudeStr!!)
val locationManager = TencentLocationManager.getInstance(this)
locationManager.removeUpdates(this)
} else {
// 定位失败
}
}
override fun onStatusUpdate(s: String, i: Int, s1: String) {
}
}
| 0
|
Kotlin
|
0
| 13
|
73f2e2b5467c0010f2cb8852c306b0fe0ef95617
| 9,665
|
Nice-Trader
|
MIT License
|
app/src/test/java/com/realtimemap/presentation/process/MapViewIntentProcessorTest.kt
|
rahmatya685
| 312,604,137
| false
| null |
package com.realtimemap.presentation.process
import com.google.common.truth.Truth
import com.realtimemap.presentation.map.MapViewAction
import com.realtimemap.presentation.map.MapViewIntent
import com.realtimemap.repo.model.MapModelMapper
import com.realtimemap.repo.remote.DummyData
import org.junit.Test
class MapViewIntentProcessorTest {
val mapViewIntentProcessor = MapViewIntentProcessor(MapModelMapper())
@Test
fun `check if LoadInitialViewIntent is converted to the LoadLocationsAction`() {
val action = mapViewIntentProcessor.intentToAction(MapViewIntent.LoadInitialViewIntent)
Truth.assertThat(action).isEqualTo(MapViewAction.LoadLocationsAction)
}
@Test
fun `check if GetLocationUpdatesIntent is converted to GetLocationUpdatesAction`() {
val action = mapViewIntentProcessor.intentToAction(MapViewIntent.GetLocationUpdatesIntent)
Truth.assertThat(action).isEqualTo(MapViewAction.GetLocationUpdatesAction)
}
@Test
fun `check if RetryFetchAction is converted to RetryFetchAction`() {
val action = mapViewIntentProcessor.intentToAction(MapViewIntent.RetryFetchViewIntent)
Truth.assertThat(action).isEqualTo(MapViewAction.RetryFetchAction)
}
@Test
fun `check if ShowLocationDetailIntent is converted to RetryFetchAction`() {
val intent = MapViewIntent.ShowLocationDetailIntent(DummyData.userLocation)
val action = mapViewIntentProcessor.intentToAction(intent)
Truth.assertThat(action).isInstanceOf(MapViewAction.ShowLocationDetailAction::class.java)
val showLocationDetailAction = action as MapViewAction.ShowLocationDetailAction
Truth.assertThat(showLocationDetailAction.userLocationModel)
.isEqualTo(DummyData.userLocationModel)
}
}
| 0
|
Kotlin
|
0
| 3
|
199b6c16d989d640ad88e98803745ab160e6ae91
| 1,802
|
RealtimeLocation
|
Apache License 2.0
|
app/src/main/java/com/example/careerboast/view/screens/login/LoginScreen.kt
|
Ev4esem
| 771,869,351
| false
|
{"Kotlin": 90779}
|
package com.example.careerboast.view.screens.login
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.careerboast.common.composable.BasicButton
import com.example.careerboast.common.composable.EmailField
import com.example.careerboast.common.composable.PasswordField
import com.example.careerboast.common.ext.basicButton
import com.example.careerboast.common.ext.fieldModifier
import com.example.careerboast.ui.theme.Black
import com.example.careerboast.ui.theme.CareerBoastTheme
import com.example.careerboast.R.string as AppText
@Composable
fun LoginScreen(
openAndPopUp : (String, String) -> Unit,
viewModel : LoginViewModel,
uiState : LoginUiState
) {
LoginScreenContent(
uiState = uiState,
onEmailChange = viewModel::onEmailChange,
onPasswordChange = viewModel::onPasswordChange,
onSignInClick = { viewModel.onSingInClick(openAndPopUp) }
)
}
@Composable
fun LoginScreenContent(
modifier: Modifier = Modifier,
uiState: LoginUiState,
onEmailChange: (String) -> Unit,
onPasswordChange: (String) -> Unit,
onSignInClick: () -> Unit,
) {
Column(
modifier = modifier
.fillMaxWidth()
.fillMaxHeight()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = modifier.fillMaxWidth().basicButton(),
horizontalArrangement = Arrangement.Start
) {
Text(
text = stringResource(AppText.sign_up),
color = Black,
fontSize = 32.sp,
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.height(20.dp))
EmailField(uiState.email, onEmailChange, Modifier.fieldModifier())
PasswordField(uiState.password, onPasswordChange, Modifier.fieldModifier())
BasicButton(
text = AppText.register,
modifier = Modifier
.basicButton()
.height(61.dp)
) {
onSignInClick()
}
}
}
@Preview(showBackground = true)
@Composable
fun LoginScreenPreview() {
val uiState = LoginUiState(
email = "email@test.com"
)
CareerBoastTheme {
LoginScreenContent(
uiState = uiState,
onEmailChange = { },
onPasswordChange = { },
onSignInClick = { },
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1239403f5ae15e7ab81e3e48a01b083b73284582
| 3,355
|
CareerBoast
|
Apache License 2.0
|
typescript-kotlin/src/main/kotlin/typescript/LiteralExpression.kt
|
turansky
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
package typescript
external interface LiteralExpression : LiteralLikeNode, PrimaryExpression {
/*
_literalExpressionBrand: any;
*/
}
| 0
|
Kotlin
|
1
| 10
|
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
| 191
|
react-types-kotlin
|
Apache License 2.0
|
solar/src/main/java/com/chiksmedina/solar/bold/businessstatistic/Chart.kt
|
CMFerrer
| 689,442,321
| false
|
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.bold.businessstatistic
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.bold.BusinessStatisticGroup
val BusinessStatisticGroup.Chart: ImageVector
get() {
if (_chart != null) {
return _chart!!
}
_chart = Builder(
name = "Chart", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(20.0f, 13.75f)
curveTo(20.0f, 13.3358f, 19.6642f, 13.0f, 19.25f, 13.0f)
horizontalLineTo(16.25f)
curveTo(15.8358f, 13.0f, 15.5f, 13.3358f, 15.5f, 13.75f)
verticalLineTo(20.5f)
horizontalLineTo(14.0f)
verticalLineTo(4.25f)
curveTo(14.0f, 3.5217f, 13.9984f, 3.0509f, 13.9518f, 2.704f)
curveTo(13.908f, 2.3787f, 13.8374f, 2.2768f, 13.7803f, 2.2197f)
curveTo(13.7232f, 2.1626f, 13.6213f, 2.092f, 13.296f, 2.0482f)
curveTo(12.9491f, 2.0016f, 12.4783f, 2.0f, 11.75f, 2.0f)
curveTo(11.0217f, 2.0f, 10.5509f, 2.0016f, 10.204f, 2.0482f)
curveTo(9.8787f, 2.092f, 9.7768f, 2.1626f, 9.7197f, 2.2197f)
curveTo(9.6626f, 2.2768f, 9.592f, 2.3787f, 9.5482f, 2.704f)
curveTo(9.5016f, 3.0509f, 9.5f, 3.5217f, 9.5f, 4.25f)
verticalLineTo(20.5f)
horizontalLineTo(8.0f)
verticalLineTo(8.75f)
curveTo(8.0f, 8.3358f, 7.6642f, 8.0f, 7.25f, 8.0f)
horizontalLineTo(4.25f)
curveTo(3.8358f, 8.0f, 3.5f, 8.3358f, 3.5f, 8.75f)
verticalLineTo(20.5f)
horizontalLineTo(2.0f)
horizontalLineTo(1.75f)
curveTo(1.3358f, 20.5f, 1.0f, 20.8358f, 1.0f, 21.25f)
curveTo(1.0f, 21.6642f, 1.3358f, 22.0f, 1.75f, 22.0f)
horizontalLineTo(21.75f)
curveTo(22.1642f, 22.0f, 22.5f, 21.6642f, 22.5f, 21.25f)
curveTo(22.5f, 20.8358f, 22.1642f, 20.5f, 21.75f, 20.5f)
horizontalLineTo(21.5f)
horizontalLineTo(20.0f)
verticalLineTo(13.75f)
close()
}
}
.build()
return _chart!!
}
private var _chart: ImageVector? = null
| 0
|
Kotlin
|
0
| 0
|
3414a20650d644afac2581ad87a8525971222678
| 3,092
|
SolarIconSetAndroid
|
MIT License
|
Unpack/src/me/anno/io/zip/internal/TarArchiveIterator.kt
|
AntonioNoack
| 456,513,348
| false
|
{"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698}
|
package me.anno.io.zip.internal
import me.anno.utils.structures.NextEntryIterator
import org.apache.commons.compress.archivers.ArchiveEntry
import org.apache.commons.compress.archivers.ArchiveInputStream
class TarArchiveIterator(val file: ArchiveInputStream) : NextEntryIterator<ArchiveEntry>() {
override fun nextEntry(): ArchiveEntry? = file.nextEntry
}
| 0
|
Kotlin
|
3
| 24
|
013af4d92e0f89a83958008fbe1d1fdd9a10e992
| 361
|
RemsEngine
|
Apache License 2.0
|
src/main/kotlin/com/vepanimas/intellij/prisma/ide/schema/definitions/PrismaSchemaKeywords.kt
|
vepanimas
| 527,378,342
| false
|
{"Kotlin": 303241, "HTML": 7321, "Lex": 2375, "JavaScript": 1076}
|
package com.vepanimas.intellij.prisma.ide.schema.definitions
import com.vepanimas.intellij.prisma.ide.schema.types.PrismaDatasourceType
import com.vepanimas.intellij.prisma.ide.schema.PrismaSchemaKind
import com.vepanimas.intellij.prisma.ide.schema.schema
val PRISMA_SCHEMA_KEYWORDS = schema {
group(PrismaSchemaKind.KEYWORD) {
element {
label = "datasource"
documentation = "The datasource block tells the schema where the models are backed."
}
element {
label = "generator"
documentation =
"Generator blocks configure which clients are generated and how they're generated. Language preferences and binary configuration will go in here."
}
element {
label = "model"
documentation =
"Models represent the entities of your application domain. They are defined using model blocks in the data model."
}
element {
label = "enum"
documentation =
"Enums are defined via the enum block. You can define enums in your data model if they're supported by the datasource you use (e.g SQLite: not supported)."
datasources = PrismaDatasourceType.except(PrismaDatasourceType.SQLITE)
}
element {
label = "type"
documentation = "Composite types are available for MongoDB only."
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f98b18d5f9f451d70994ebe672ab9a584f184b73
| 1,436
|
intellij-prisma
|
Apache License 2.0
|
app/src/main/java/com/wnc21/logger/analytics/AnalyticsEvent.kt
|
sarathkumar-optisol
| 362,393,072
| true
|
{"Kotlin": 17942}
|
package com.wnc21.logger.analytics
class AnalyticsEvent(msg: String)
| 0
| null |
0
| 0
|
c6d866ba1e513d20f26160926908a3a95af14afb
| 69
|
Logger
|
Apache License 2.0
|
src/obdKotlin/encoders/SpecialEncoder.kt
|
PavelB24
| 508,802,157
| false
| null |
package obdKotlin.encoders
import kotlinx.coroutines.flow.MutableSharedFlow
import obdKotlin.decoders.EncodingState
import obdKotlin.hexToInt
import obdKotlin.messages.Message
import obdKotlin.profiles.Profile
import obdKotlin.toHex
import java.lang.IllegalStateException
import java.nio.ByteBuffer
abstract class SpecialEncoder {
var buffer: ByteBuffer? = null
var cc = 0
var expectedFrames = 0
var eventFlow: MutableSharedFlow<Message?>? = null
open suspend fun handleBytes(message: ByteArray): EncodingState {
return when (message.first().toHex()) {
ByteMessageType.SINGLE.hex -> {
decodeSingleMessage(message)
}
ByteMessageType.FIRST.hex -> {
decodeFirstMessage(message)
}
ByteMessageType.SECONDARY.hex -> {
decodeSecondaryMessage(message)
}
else -> { EncodingState.Unsuccessful(message.decodeToString()) }
}
}
abstract suspend fun decodeSingleMessage(message: ByteArray): EncodingState
private suspend fun decodeFirstMessage(message: ByteArray): EncodingState {
if (message.size > 16) return EncodingState.Unsuccessful(message.decodeToString())
val expect = message.decodeToString(1, 4).hexToInt()
expectedFrames = if ((expect - 6) % 7 == 0) (expect - 6) / 7 else (expect - 6) / 7 + 1
buffer = ByteBuffer.allocate(expect * 2)
val cleanData = message.copyOfRange(5, message.size)
buffer?.put(cleanData)
cc += cleanData.size
return EncodingState.WaitNext
}
private suspend fun decodeSecondaryMessage(message: ByteArray): EncodingState {
if (buffer == null) {
throw IllegalStateException()
} else {
buffer?.put(message.copyOfRange(3, message.size))
buffer?.let {
return if (it.hasRemaining()) {
EncodingState.WaitNext
} else {
decodeBufferedMessage()
}
}
throw IllegalStateException("Message Buffer is null")
}
}
abstract suspend fun decodeBufferedMessage(): EncodingState
fun bindMessagesFlow(flow: MutableSharedFlow<Message?>) {
eventFlow = flow
}
companion object {
fun getInstance(type: Profile.Profiles): SpecialEncoder {
return when (type) {
Profile.Profiles.BYD_F3 -> TODO()
Profile.Profiles.BYD_F3_ABS -> TODO()
Profile.Profiles.CHERRY_TIGO_DELPHI -> TODO()
Profile.Profiles.PEUGEOT_308_20120 -> TODO()
Profile.Profiles.BMW320E91AT -> TODO()
Profile.Profiles.FIAT_PRE_OBD -> TODO()
Profile.Profiles.YANVAR_72 -> TODO()
Profile.Profiles.YANVAR_5_11 -> TODO()
Profile.Profiles.ACCORD_24 -> TODO()
Profile.Profiles.LEXUS_RX330 -> TODO()
Profile.Profiles.UAZ_1797 -> TODO()
}
}
}
}
| 2
|
Kotlin
|
0
| 0
|
aeb6027cdc48a1f1d76e25d258abc36562f04176
| 3,073
|
OBDKotlin
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/com/belveth/bullettime/BulletTimeApplication.kt
|
belveth
| 482,193,761
| false
| null |
package com.belveth.bullettime
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
import org.springframework.boot.runApplication
@SpringBootApplication(exclude = [SecurityAutoConfiguration::class])
class BulletTimeApplication
fun main(args: Array<String>) {
runApplication<BulletTimeApplication>(*args)
}
| 0
|
Kotlin
|
0
| 1
|
83fecf1962934d35eceeb5542c005c56f7135f54
| 415
|
bullet-time
|
MIT License
|
Retos/Reto #13 - ADIVINA LA PALABRA [Media]/kotlin/Mariopolonia0.kt
|
mouredev
| 581,049,695
| false
|
{"Python": 4194087, "JavaScript": 1590517, "Java": 1408944, "C#": 782329, "Kotlin": 533858, "TypeScript": 479964, "Rust": 357628, "Go": 322940, "PHP": 288620, "Swift": 278290, "C": 223896, "Jupyter Notebook": 221090, "C++": 175187, "Dart": 159755, "Ruby": 71132, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 33508, "Haskell": 27994, "Shell": 27979, "R": 19771, "Lua": 16964, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12839, "F#": 12816, "Pascal": 12673, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Carbon": 2611, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1394, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "Haxe": 112, "HolyC": 110, "OpenEdge ABL": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "TeX": 72, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Mojo": 37, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
|
package EjercicioKotlin.Mouredev
/*
* Crea un pequeño juego que consista en adivinar palabras en un número máximo de intentos:
* - El juego comienza proponiendo una palabra aleatoria incompleta
* - Por ejemplo "m_ur_d_v", y el número de intentos que le quedan
* - El usuario puede introducir únicamente una letra o una palabra (de la misma longitud que
* la palabra a adivinar)
* - Si escribe una letra y acierta, se muestra esa letra en la palabra. Si falla, se resta
* uno al número de intentos
* - Si escribe una resolución y acierta, finaliza el juego, en caso contrario, se resta uno
* al número de intentos
* - Si el contador de intentos llega a 0, el jugador pierde
* - La palabra debe ocultar de forma aleatoria letras, y nunca puede comenzar
* ocultando más del 60%
* - Puedes utilizar las palabras que quieras y el número de intentos que consideres
*/
class reto13 {
private var word = listOf("evening", "friend", "because", "waiting", "please", "tomorrow", "time").random()
//el posiento de las palabra que estaran oculta
private var attempts = (word.length * 0.6).toInt()
private var wordDisguise = word
init {
disguiseWord()
begin()
}
private fun begin() {
var stop = false
while (!stop) {
print()
val char = readln()[0]
if (word.contains(char)) {
val replace = wordDisguise.toCharArray()
for (item in replace.indices) {
if (word[item] == char)
replace[item] = char
}
wordDisguise = String(replace)
} else {
println("\n========================")
println("it is not in the word")
println("========================")
attempts--
if (attempts == 0) {
stop = true
println("\n==============")
println("you have lost")
println("==============")
}
}
if (!wordDisguise.contains('_')) {
stop = true
println("\n==============")
println("to cattle")
println("==============")
}
}
}
private fun print() {
println("==================================")
println("the word is : $wordDisguise")
println("have $attempts available")
print("select letter:")
}
private fun disguiseWord() {
val position = Array(attempts, { 0 })
for (item in 0..attempts - 1) {
var positionToHide = 0
var stop = false
do {
positionToHide = (0..word.length - 1).random()
if (!position.contains(positionToHide))
stop = true
} while (!stop)
position[item] = positionToHide
val replace = wordDisguise.toCharArray()
replace[positionToHide] = '_'
wordDisguise = String(replace)
}
}
}
fun main() {
reto13()
}
| 1
|
Python
|
2974
| 5,192
|
f8c44ac12756b14a32abf57cbf4e0cd06ad58088
| 3,191
|
retos-programacion-2023
|
Apache License 2.0
|
app/src/main/java/com/example/deportesdalda/Users.kt
|
FerCobo
| 519,836,349
| false
|
{"Kotlin": 80944}
|
package com.example.deportesdalda
import com.google.firebase.database.Exclude
class Users {
private var email: String? = null
private var name: String? = null
private var lastname: String? = null
private var points: String? = null
private var phone: String? = null
private var date: String? = null
@Exclude
fun getEmail(): String? {
return email
}
fun setEmail(email: String?) {
this.email = email
}
fun setName(name: String?) {
this.name = name
}
fun getName(): String? {
return name
}
fun setLastname(lastname: String?) {
this.lastname = lastname
}
fun getLastname(): String? {
return lastname
}
fun setPoints(points: String?) {
this.points = points
}
fun getPoints(): String? {
return points
}
fun setPhone(phone: String?) {
this.phone = phone
}
fun getPhone(): String? {
return phone
}
fun setDate(date: String?) {
this.date = date
}
fun getDate(): String? {
return date
}
}
| 0
|
Kotlin
|
0
| 0
|
e849ce50dfd5026607105dbcc665ef238004f072
| 1,112
|
AppDalda
|
MIT License
|
src/main/kotlin/no/njoh/pulseengine/core/window/Window.kt
|
NiklasJohansen
| 239,208,354
| false
| null |
package no.njoh.pulseengine.core.window
interface Window
{
var title: String
val width: Int
val height: Int
val screenMode: ScreenMode
val wasResized: Boolean
fun updateScreenMode(mode: ScreenMode)
fun close()
}
interface WindowInternal : Window
{
override var wasResized: Boolean
val windowHandle: Long
fun init(initWidth: Int, initHeight: Int, screenMode: ScreenMode, gameName: String)
fun cleanUp()
fun setOnResizeEvent(callback: (width: Int, height: Int, windowRecreated: Boolean) -> Unit)
fun swapBuffers()
fun isOpen(): Boolean
}
| 0
|
Kotlin
|
0
| 1
|
0233386dfca8a4ae6a990cd3dffe47db05e82319
| 595
|
PulseEngine
|
MIT License
|
app/src/main/java/dev/pinaki/desipe/di/InjectionConstants.kt
|
Pinaki93
| 276,979,416
| false
| null |
/*
* MIT License
*
* Copyright (c) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package dev.pinaki.desipe.di
object InjectionConstants {
const val KEY_DATABASE_NAME = "database_name"
const val KEY_IS_DEBUG_BUILD = "is_debug"
const val KEY_BASE_URL = "base_url"
const val KEY_PREFERENCES_NAME = "shared_preferences_name"
const val KEY_OS_VERSION = "os_version"
}
| 0
|
Kotlin
|
4
| 25
|
c62e337d8bfacdc9a7e2a26b7fbdbbe320c43f60
| 1,435
|
Desipe
|
MIT License
|
View-common/src/main/kotlin/view/utils/mapBased/keys/delegates/AbstractRWKey.kt
|
mzaart
| 160,253,085
| false
| null |
package view.utils.mapBased.keys.delegates
import view.utils.mapBased.keys.HasKeys
import view.utils.mapBased.keys.MapInterface
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* A delegate for mutable properties that are based on maps.
*/
abstract class AbstractRWKey<T>: ReadWriteProperty<HasKeys, T> {
/**
* Defines the value retrieval stategy of the property
*/
protected abstract val getterStrategy: List<MapInterface.Strategy>
override fun setValue(thisRef: HasKeys, property: KProperty<*>, value: T) {
mapInterface(thisRef.keys).setValue(property.name, value)
}
/**
* Returns the [MapInterface] used to communicate with the map.
*
* @param keys The map that contains the values
* @return The [MapInterface] used to communicate with the map.
*/
protected open fun mapInterface(keys: MutableMap<String, Any?>) = MapInterface<T>(keys, getterStrategy)
}
| 0
|
Kotlin
|
1
| 2
|
b374346a2a17dca51ecbabc00e058eaeb286ae6f
| 961
|
View
|
Apache License 2.0
|
apzkr-pzpi-21-11-kokhanevych-pavlo/Task4-MobileClient/src/main/java/com/animal/hotel/presentation/ui/models/HotelUI.kt
|
NureKokhanevychPavlo
| 810,819,177
| false
|
{"Kotlin": 196074, "Java": 178994, "C++": 2061}
|
package com.animal.hotel.presentation.ui.models
import android.os.Parcelable
import com.animal.hotel.domain.models.user.Hotel
import kotlinx.parcelize.Parcelize
@Parcelize
data class HotelUI(
val hotelId: Int,
var name: String,
val region: String,
val district: String,
val city: String,
val street: String,
val numberHouse: String
): Parcelable {
fun toHotel(): Hotel {
return Hotel(hotelId, name, region, district, city, street, numberHouse)
}
companion object {
fun toHotelUI(hotel: Hotel) = HotelUI (
hotel.hotelId,
hotel.name,
hotel.region,
hotel.district,
hotel.city,
hotel.street,
hotel.numberHouse
)
}
}
| 0
|
Kotlin
|
0
| 0
|
19d108f579c254e76375a995e3ae366bccfe143a
| 767
|
apzkr-pzpi-21-11-kokhanevych-pavlo
|
Apache License 2.0
|
KotlinMultiplatform/XFullStack/server/src/main/kotlin/com/pradyotprakash/xfullstack/features/tags/resource/TagsResource.kt
|
pradyotprksh
| 385,586,594
| false
|
{"Kotlin": 2877106, "Dart": 1066884, "Python": 319400, "Rust": 180589, "Swift": 147761, "C++": 113494, "CMake": 94132, "Go": 45704, "HTML": 21089, "Ruby": 12424, "C": 8043, "Shell": 5675, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "JavaScript": 781, "CSS": 588, "Objective-C": 380, "Dockerfile": 32}
|
package com.pradyotprakash.xfullstack.features.tags.resource
import io.ktor.resources.Resource
import utils.Constants.Paths.Tags.TAGS
import utils.Constants.Paths.Tags.TRENDING
@Resource(TAGS)
class TagsResource {
@Resource(TRENDING)
data class Trending(
private val parent: TagsResource = TagsResource(),
)
}
| 0
|
Kotlin
|
11
| 23
|
c11b01fb3bdec4af906f390aede1f38eca74b31a
| 332
|
development_learning
|
MIT License
|
LeetCode/ThreeSum.kt
|
MartinWie
| 702,541,017
| false
|
{"Kotlin": 65168}
|
class ThreeSum {
fun threeSum(nums: IntArray): List<List<Int>> {
val targetSum = 0
val resultsList = mutableListOf<List<Int>>()
val numsList = nums.toMutableList()
for (outerNum in numsList) {
for (midNum in numsList.minus(outerNum)) {
for (innerNum in numsList.minus(outerNum).minus(midNum)) {
if (innerNum + midNum + outerNum == targetSum) {
resultsList.add(listOf(innerNum, midNum, outerNum).sorted())
}
}
}
}
return resultsList.distinct()
}
fun threeSum2(nums: IntArray): List<List<Int>> {
val resultList = mutableListOf<List<Int>>()
nums.sort()
for (index in nums.indices) {
if (index > 0 && nums[index] == nums[index - 1]) continue
var leftPointer = index + 1
var rightPointer = nums.size - 1
while (leftPointer < rightPointer) {
val sum = nums[index] + nums[leftPointer] + nums[rightPointer]
when {
sum == 0 -> {
resultList.add(listOf(nums[index], nums[leftPointer], nums[rightPointer]))
leftPointer++
rightPointer--
while (leftPointer < rightPointer && nums[leftPointer] == nums[leftPointer - 1]) leftPointer++
while (leftPointer < rightPointer && nums[rightPointer] == nums[rightPointer + 1]) rightPointer--
}
sum < 0 -> {
leftPointer++
}
sum > 0 -> {
rightPointer--
}
}
}
}
return resultList
}
fun threeSum3(nums: IntArray): List<List<Int>> {
nums.sort()
val resultList = mutableListOf<List<Int>>()
for (index in nums.indices) {
// Avoid duplicate triplets
if (index == 0 || nums[index] != nums[index - 1]) {
twoSum(nums, index, -nums[index], resultList)
}
}
return resultList
}
private fun twoSum(
nums: IntArray,
startIndex: Int,
target: Int,
resultList: MutableList<List<Int>>,
) {
val seen = HashSet<Int>()
for (i in startIndex + 1 until nums.size) {
if (seen.contains(target - nums[i])) {
val triplet = listOf(-target, target - nums[i], nums[i])
// Add the triplet if it's not already in the list to avoid duplicates
if (!resultList.contains(triplet)) {
resultList.add(triplet)
}
}
seen.add(nums[i])
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a2c6172fd8dbd18de7d87a1ee73d730314effed2
| 2,846
|
KotlinCodeJourney
|
MIT License
|
app/src/main/java/com/teamaad34/polls/di/AppModule.kt
|
muhundet
| 274,891,779
| true
|
{"Kotlin": 32629}
|
package com.teamaad34.polls.di
import com.teamaad34.polls.data.source.IChoiceDataSource
import com.teamaad34.polls.data.source.IQuestionDataSource
import com.teamaad34.polls.data.source.IVoterDataSource
import com.teamaad34.polls.data.source.local.ChoiceLocalDataSource
import com.teamaad34.polls.data.source.local.QuestionLocalDataSource
import com.teamaad34.polls.data.source.local.VoterLocalDataSource
import com.teamaad34.polls.data.source.local.dao.ChoicesDao
import com.teamaad34.polls.data.source.local.dao.QuestionsDao
import com.teamaad34.polls.data.source.remote.ChoiceRemoteDataSource
import com.teamaad34.polls.data.source.remote.QuestionRemoteDataSource
import com.teamaad34.polls.data.source.remote.VoterRemoteDataSource
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import javax.inject.Qualifier
import javax.inject.Singleton
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class LocalVoterDataSource
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class RemoteVoterDataSource
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class LocalQuestionDataSource
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class RemoteQuestionDataSource
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class LocalChoiceDataSource
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class RemoteChoiceDataSource
@Provides
@Singleton
@LocalVoterDataSource
fun provideVoterLocalDataSource(): IVoterDataSource = VoterLocalDataSource()
@Provides
@Singleton
@RemoteVoterDataSource
fun provideVoterRemoteDataSource(): IVoterDataSource = VoterRemoteDataSource()
@Provides
@Singleton
@LocalQuestionDataSource
fun provideQuestionLocalDataSource(dao: QuestionsDao): IQuestionDataSource =
QuestionLocalDataSource(dao)
@Provides
@Singleton
@RemoteQuestionDataSource
fun provideQuestionRemoteDataSource(): IQuestionDataSource = QuestionRemoteDataSource()
@Provides
@Singleton
@LocalChoiceDataSource
fun provideChoiceLocalDataSource(dao: ChoicesDao): IChoiceDataSource =
ChoiceLocalDataSource(dao)
@Provides
@Singleton
@RemoteChoiceDataSource
fun provideChoiceRemoteDataSource(): IChoiceDataSource = ChoiceRemoteDataSource()
}
| 0
| null |
0
| 0
|
2bc0e087b64664f02a4f25d210f60a1d23441f59
| 2,668
|
PollsApp
|
MIT License
|
app/src/main/kotlin/com/konifar/materialcat/_di/ActivityModule.kt
|
konifar
| 40,127,425
| false
| null |
package com.konifar.materialcat._di
import android.support.v7.app.AppCompatActivity
import dagger.Module
import dagger.Provides
import io.reactivex.disposables.CompositeDisposable
@Module
class ActivityModule(private val activity: AppCompatActivity) {
@ActivityScope
@Provides
fun provideCompositeDisposable() = CompositeDisposable()
@Provides
fun provideActivity(): AppCompatActivity = activity
}
| 12
|
Kotlin
|
82
| 397
|
6b47aef9fae8ad3de32a897b9dede729b28c1580
| 422
|
material-cat
|
Apache License 2.0
|
app/src/main/java/com/ztgeng/smssenderkotlin/MyFirebaseMessagingService.kt
|
ZTGeng
| 166,071,264
| false
| null |
package com.ztgeng.smssenderkotlin
import android.net.Uri
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
private const val FETCH_SMS_KEY = "fetch_sms"
private const val SMS_NUMBER_KEY = "number"
private const val SERVER_IP_KEY = "server"
private const val DEFAULT_SMS_NUMBER = 5
class MyFirebaseMessagingService : FirebaseMessagingService() {
/**
* 当获取新的FCM Token,则向服务端更新。
*/
override fun onNewToken(token: String?) {
Log.d("gengz", "On new token: $token")
if (!token.isNullOrBlank()) {
NetworkClient.getInstance(this.applicationContext).sendToken(this, token)
}
}
/**
* 处理{@code remoteMessage.collapseKey}值为“fetch_sms”的消息:
* - 若{@code remoteMessage.data}存在“server”键,则以其值更新储存在SharedPreferences中的服务器地址;
* - 若{@code remoteMessage.data}存在“number”键,则以其值作为读取短信条数,否则默认读取5条;
* - 读取短信并发送到储存的服务器地址。
*/
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
Log.d("gengz", "From: ${remoteMessage?.from}")
remoteMessage?.data?.isNotEmpty()?.let { Log.d("gengz", "Data: ${remoteMessage.data}") }
remoteMessage?.notification?.let { Log.d("gengz", "Message: ${it.title} - ${it.body}") }
when (remoteMessage?.collapseKey) {
FETCH_SMS_KEY -> {
val url = remoteMessage.data?.get(SERVER_IP_KEY)
url?.let { saveServerName(this, it) }
NetworkClient.getInstance(this.applicationContext).sendSms(
this, readSms(remoteMessage.data?.get(SMS_NUMBER_KEY)?.toInt() ?: DEFAULT_SMS_NUMBER))
}
}
}
/**
* 读取最多{@code number}条最新短信,转为JSON。格式为:
* ```
* [
* {
* number: ..., // 短信发送方号码
* time: ..., // 发送时间,格式为:dow mon dd hh:mm:ss zzz yyyy
* message: ... // 短信文本
* },
* ...
* ]
* ```
*/
private fun readSms(number: Int): JSONArray {
val msgs = JSONArray()
val cursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null) ?: return msgs
if (cursor.moveToFirst()) {
do {
val msg = JSONObject()
for (i in 0 until cursor.columnCount) {
when (cursor.getColumnName(i)) {
"address" -> msg.put("number", cursor.getString(i))
"date" -> msg.put("time", Date(cursor.getLong(i)).toString())
"body" -> msg.put("message", cursor.getString(i))
}
}
msgs.put(msg)
} while (cursor.moveToNext() && msgs.length() < number)
}
cursor.close()
return msgs
}
}
| 0
|
Kotlin
|
0
| 1
|
3bdfa3cefa56ca6fee5852e3770d3d675b0473d0
| 2,879
|
sms-sender-android
|
MIT License
|
feature-authentication/src/main/java/com/standup/app/authentication/intro/IntroFragment.kt
|
kevalpatel2106
| 109,775,416
| false
| null |
/*
* Copyright 2018 <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.standup.app.authentication.intro
import android.os.Bundle
import android.support.annotation.DrawableRes
import android.support.annotation.StringRes
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.kevalpatel2106.common.base.uiController.BaseFragment
import com.kevalpatel2106.utils.annotations.UIController
import com.standup.app.authentication.R
import kotlinx.android.synthetic.main.fragment_intro.*
/**
* A simple [Fragment] subclass to display the introduction text and image into the [IntroActivity].
*
* @see [IntroPagerAdapter]
* @author <a href="https://github.com/kevalpatel2106">kevalpatel2106</a>
*/
@UIController
class IntroFragment : BaseFragment() {
companion object {
private val ARG_CAPTION = "ARG_CAPTION"
private val ARG_IMAGE = "ARG_IMAGE"
/**
* Get the new instance of the fragment [IntroFragment].
*
* @param caption String resource for the text to display as the caption.
* @param image Drawable resource for the image to display.
* @return [IntroFragment]
*/
internal fun newInstance(@StringRes caption: Int, @DrawableRes image: Int): IntroFragment {
val introFragment = IntroFragment()
val bundle = Bundle()
bundle.putInt(ARG_CAPTION, caption)
bundle.putInt(ARG_IMAGE, image)
introFragment.arguments = bundle
return introFragment
}
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.fragment_intro, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
intro_tv.setText(arguments!!.getInt(ARG_CAPTION))
intro_iv.setImageResource(arguments!!.getInt(ARG_IMAGE))
}
}
}
| 18
|
Kotlin
|
1
| 3
|
d4d0313062118521621da5dac90e836f512ddd54
| 2,708
|
Stand-Up
|
Apache License 2.0
|
src/test/kotlin/adventofcode/year2020/Day22CrabCombatSpec.kt
|
pfolta
| 573,956,675
| false
|
{"Kotlin": 189633, "Dockerfile": 227}
|
package adventofcode.year2020
import adventofcode.PuzzleBaseSpec
class Day22CrabCombatSpec : PuzzleBaseSpec(306, 291)
| 0
|
Kotlin
|
0
| 0
|
20b8e19ed81a018b866290c6be6df7ec22afb454
| 120
|
AdventOfCode
|
MIT License
|
app/src/main/java/org/p2p/wallet/common/ui/recycler/EndlessScrollListener.kt
|
p2p-org
| 306,035,988
| false
| null |
package org.p2p.wallet.common.ui.recycler
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
private const val VISIBLE_THRESHOLD = 11
class EndlessScrollListener(
private val layoutManager: LinearLayoutManager,
private val onYScroll: ((Int) -> Unit)? = null,
private val loadNextPage: (Int) -> Unit,
) : RecyclerView.OnScrollListener() {
private var isLoading = true
private var totalLoadedItems = 0
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
onYScroll?.invoke(dy)
val visibleItemCount = layoutManager.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
if (totalItemCount == visibleItemCount) return
if (totalItemCount > totalLoadedItems) {
isLoading = false
totalLoadedItems = totalItemCount
return
}
val smth = totalItemCount - visibleItemCount <= firstVisibleItem + VISIBLE_THRESHOLD
if (!isLoading && smth) {
loadNextPage(totalItemCount)
isLoading = true
}
}
fun reset() {
isLoading = false
totalLoadedItems = 0
}
}
| 9
|
Kotlin
|
14
| 23
|
2badf683d824c57654b12ea0c023f96e1a5d0c19
| 1,325
|
key-app-android
|
MIT License
|
src/main/kotlin/io/github/pandier/intellijdiscordrp/listener/RichPresenceFileListener.kt
|
pandier
| 768,334,300
| false
|
{"Kotlin": 52560}
|
package io.github.pandier.intellijdiscordrp.listener
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import io.github.pandier.intellijdiscordrp.service.DiscordService
class RichPresenceFileListener : FileEditorManagerListener {
override fun selectionChanged(event: FileEditorManagerEvent) {
val newFile = event.newFile
val discordService = DiscordService.getInstance()
discordService.changeActivityBackground(event.manager.project, newFile)
}
}
| 11
|
Kotlin
|
0
| 8
|
384d8354c59e1ffdb4053852630d6862e71b7802
| 558
|
intellij-discord-rp
|
MIT License
|
framework/src/main/kotlin/pt/isel/SHORT/html/element/Wbr.kt
|
48276AntonioMarques
| 762,862,793
| false
|
{"Kotlin": 290899, "CSS": 6361, "JavaScript": 2091, "HTML": 587}
|
package pt.isel.SHORT.html.element
import pt.isel.SHORT.html.base.attribute.Attribute
import pt.isel.SHORT.html.base.element.HtmlReceiver
import pt.isel.SHORT.html.base.element.Tag
import pt.isel.SHORT.html.base.element.VoidTag
/**
* Represents the HTML <wbr> tag.
* Description: Represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.
*/
fun Tag.Wbr(attributes: List<Attribute> = emptyList(), content: HtmlReceiver? = null): Tag = apply {
appendChild(VoidTag("wbr", attributes, scope))
}
| 0
|
Kotlin
|
0
| 1
|
0457515ab97855e4f42f7eeacec53f2919908918
| 632
|
short
|
Apache License 2.0
|
workshop/spring-data/redis-examples-demo/src/test/kotlin/io/bluetape4k/workshop/redis/examples/reactive/ReactiveRedisConfiguration.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.workshop.redis.examples.reactive
import io.bluetape4k.junit5.faker.Fakers
import io.bluetape4k.logging.KLogging
import io.bluetape4k.support.uninitialized
import io.bluetape4k.testcontainers.storage.RedisServer
import io.bluetape4k.workshop.redis.examples.reactive.model.Person
import jakarta.annotation.PreDestroy
import kotlinx.coroutines.reactor.awaitSingleOrNull
import kotlinx.coroutines.runBlocking
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Bean
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory
import org.springframework.data.redis.core.ReactiveRedisTemplate
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.RedisSerializationContext
import org.springframework.data.redis.serializer.RedisSerializer
/**
* [RedisApplication] 과 분리해서 독립적으로 테스트하기 위해서 [SpringBootApplication] 을 선언합니다.
*/
@SpringBootApplication
class ReactiveRedisConfiguration {
companion object: KLogging() {
@JvmStatic
val redis = RedisServer.Launcher.redis
@JvmStatic
val faker = Fakers.faker
}
@Autowired
private val reactiveRedisConnectionFactory: ReactiveRedisConnectionFactory = uninitialized()
/**
* Configures a [ReactiveRedisTemplate] with [String] keys and a typed [Jackson2JsonRedisSerializer].
*/
@Bean
fun reactiveJsonPersonRedisTemplate(factory: ReactiveRedisConnectionFactory): ReactiveRedisTemplate<String, Person> {
val valueSerializer = Jackson2JsonRedisSerializer(Person::class.java)
val context = RedisSerializationContext
.newSerializationContext<String, Person>(RedisSerializer.string())
.value(valueSerializer)
.build()
return ReactiveRedisTemplate(factory, context)
}
/**
* Configures a [ReactiveRedisTemplate] with [String] keys and [GenericJackson2JsonRedisSerializer].
*
* NOTE: Value에 해당하는 Object 는 `@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)` 를 선언해야 한다.
* 참고: [io.bluetape4k.workshop.redis.examples.reactive.model.EmailAddress]
*/
@Bean
fun reactiveJsonObjectRedisTemplate(factory: ReactiveRedisConnectionFactory): ReactiveRedisTemplate<String, Any?> {
// Value에 해당하는 Object 는 `@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)` 가 선언되어 있어야만 Class 정보를 알 수 있다
val valueSerializer = GenericJackson2JsonRedisSerializer("@class")
val context = RedisSerializationContext
.newSerializationContext<String, Any?>(RedisSerializer.string())
.value(valueSerializer)
.build()
return ReactiveRedisTemplate(factory, context)
}
@PreDestroy
fun flushTestDb() {
runBlocking {
reactiveRedisConnectionFactory.reactiveConnection.serverCommands().flushDb().awaitSingleOrNull()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 3,097
|
bluetape4k
|
MIT License
|
workshop/spring-data/redis-examples-demo/src/test/kotlin/io/bluetape4k/workshop/redis/examples/reactive/ReactiveRedisConfiguration.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.workshop.redis.examples.reactive
import io.bluetape4k.junit5.faker.Fakers
import io.bluetape4k.logging.KLogging
import io.bluetape4k.support.uninitialized
import io.bluetape4k.testcontainers.storage.RedisServer
import io.bluetape4k.workshop.redis.examples.reactive.model.Person
import jakarta.annotation.PreDestroy
import kotlinx.coroutines.reactor.awaitSingleOrNull
import kotlinx.coroutines.runBlocking
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.context.annotation.Bean
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory
import org.springframework.data.redis.core.ReactiveRedisTemplate
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.RedisSerializationContext
import org.springframework.data.redis.serializer.RedisSerializer
/**
* [RedisApplication] 과 분리해서 독립적으로 테스트하기 위해서 [SpringBootApplication] 을 선언합니다.
*/
@SpringBootApplication
class ReactiveRedisConfiguration {
companion object: KLogging() {
@JvmStatic
val redis = RedisServer.Launcher.redis
@JvmStatic
val faker = Fakers.faker
}
@Autowired
private val reactiveRedisConnectionFactory: ReactiveRedisConnectionFactory = uninitialized()
/**
* Configures a [ReactiveRedisTemplate] with [String] keys and a typed [Jackson2JsonRedisSerializer].
*/
@Bean
fun reactiveJsonPersonRedisTemplate(factory: ReactiveRedisConnectionFactory): ReactiveRedisTemplate<String, Person> {
val valueSerializer = Jackson2JsonRedisSerializer(Person::class.java)
val context = RedisSerializationContext
.newSerializationContext<String, Person>(RedisSerializer.string())
.value(valueSerializer)
.build()
return ReactiveRedisTemplate(factory, context)
}
/**
* Configures a [ReactiveRedisTemplate] with [String] keys and [GenericJackson2JsonRedisSerializer].
*
* NOTE: Value에 해당하는 Object 는 `@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)` 를 선언해야 한다.
* 참고: [io.bluetape4k.workshop.redis.examples.reactive.model.EmailAddress]
*/
@Bean
fun reactiveJsonObjectRedisTemplate(factory: ReactiveRedisConnectionFactory): ReactiveRedisTemplate<String, Any?> {
// Value에 해당하는 Object 는 `@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)` 가 선언되어 있어야만 Class 정보를 알 수 있다
val valueSerializer = GenericJackson2JsonRedisSerializer("@class")
val context = RedisSerializationContext
.newSerializationContext<String, Any?>(RedisSerializer.string())
.value(valueSerializer)
.build()
return ReactiveRedisTemplate(factory, context)
}
@PreDestroy
fun flushTestDb() {
runBlocking {
reactiveRedisConnectionFactory.reactiveConnection.serverCommands().flushDb().awaitSingleOrNull()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 3,097
|
bluetape4k
|
MIT License
|
cacheable-compiler/src/main/kotlin/com/moriatsushi/cacheable/compiler/CacheableIrElementTransformer.kt
|
mori-atsushi
| 713,685,225
| false
|
{"Kotlin": 49048}
|
package com.moriatsushi.cacheable.compiler
import com.moriatsushi.cacheable.compiler.declaration.CacheableDeclarations
import com.moriatsushi.cacheable.compiler.factory.IrActualFunctionFactory
import com.moriatsushi.cacheable.compiler.factory.IrCacheStoreFieldFactory
import com.moriatsushi.cacheable.compiler.factory.IrCacheableFunctionBodyFactory
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrDeclarationContainer
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
class CacheableIrElementTransformer(
private val cacheableDeclarations: CacheableDeclarations,
private val irCacheStoreFieldFactory: IrCacheStoreFieldFactory,
private val irActualFunctionFactory: IrActualFunctionFactory,
private val irCacheableFunctionBodyFactory: IrCacheableFunctionBodyFactory,
) : IrElementTransformerVoid() {
override fun visitSimpleFunction(declaration: IrSimpleFunction): IrStatement {
if (!cacheableDeclarations.cacheableAnnotationDeclaration.hasAnnotation(declaration)) {
return declaration
}
val parent = (declaration.parent as? IrDeclarationContainer)
?: error("Unexpected function parent type")
val irCacheStoreField = irCacheStoreFieldFactory.create(declaration)
parent.declarations.add(irCacheStoreField)
val actualFunction = irActualFunctionFactory.create(declaration)
parent.declarations.add(actualFunction)
declaration.body = irCacheableFunctionBodyFactory.create(
originalFunction = declaration,
actualFunction = actualFunction,
cacheStoreField = irCacheStoreField,
)
return declaration
}
}
| 11
|
Kotlin
|
2
| 98
|
fe25a47fd6194fe33d928fbafef38a44feac6353
| 1,780
|
kotlin-cacheable
|
Apache License 2.0
|
app/api/src/main/java/com/thechance/api/utils/ConvertDate.kt
|
TheChance101
| 642,833,370
| false
|
{"Kotlin": 344872, "Dockerfile": 185}
|
package com.thechance.api.utils
import java.time.LocalDateTime
fun LocalDateTime.convertDateToMillis(): Long {
return this.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()
}
| 1
|
Kotlin
|
6
| 22
|
aad54550989c7eb8b75c256c36d2d9f795cbb189
| 198
|
Honey-Mart-Server
|
Apache License 2.0
|
feature3-no-ui/src/main/java/com/example/feature3_no_ui/internal/di/NotifierComponent.kt
|
zagayevskiy
| 356,612,646
| false
| null |
package com.example.feature3_no_ui.internal.di
import com.example.feature3_no_ui.api.NotifierDependencies
import com.example.feature3_no_ui.internal.NotifierImpl
import dagger.Component
@Component(dependencies = [NotifierDependencies::class])
internal interface NotifierComponent {
@Component.Factory
interface Factory {
fun create(deps: NotifierDependencies): NotifierComponent
}
val impl: NotifierImpl
}
| 0
|
Kotlin
|
7
| 38
|
68f5a3aa82ac0b219264ee661d4a2f47971dd72b
| 432
|
android-multimodule-di-example
|
MIT License
|
GuessTheWord-Starter/app/src/main/java/com/example/android/guesstheword/screens/game/GameViewModel.kt
|
edwardotis
| 228,745,768
| true
|
{"Kotlin": 445557}
|
package com.example.android.guesstheword.screens.game
import android.os.CountDownTimer
import android.text.format.DateUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import timber.log.Timber
class GameViewModel : ViewModel() {
//event which triggers end of the game
private val _eventGameFinished = MutableLiveData<Boolean>()
val eventGameFinished: LiveData<Boolean>
get() = _eventGameFinished
// The current word
private val _word = MutableLiveData<String>()
val word: LiveData<String>
//kotlin backing property
get() = _word
// The current score
//keep mutable score private
//basically LiveData version of getter/setter access modifiers
private val _score = MutableLiveData<Int>()
val score: LiveData<Int>
//kotlin backing property
get() = _score
private val _timeLeft = MutableLiveData<Long>()
val timeLeft: LiveData<Long>
//kotlin backing property
get() = _timeLeft
//INSTEAD OF THIS
// private val _timeLeftStr = MutableLiveData<String>()
// val timeLeftStr: LiveData<String>
// //kotlin backing property
// get() = _timeLeftStr
//WE USE Transformations.map to convert one LiveData object to another.
val timeLeftStr = Transformations.map(timeLeft){ time ->
DateUtils.formatElapsedTime(time)
}
val hint = Transformations.map(word){ selectedWord ->
"The current word has ${selectedWord.length} letters. " +
"\n And the first letter is ${selectedWord.get(0)}"
}
private val timer: CountDownTimer
// The list of words - the front of the list is the next word to guess
lateinit var wordList: MutableList<String>
init {
_word.value = ""
_score.value = 0
_eventGameFinished.value = false
resetList()
nextWord()
timer = object : CountDownTimer(COUNTDOWN_TIME, ONE_SECOND){
override fun onFinish() {
onGameFinish()
}
override fun onTick(millisUntilFinished: Long) {
_timeLeft.value = (millisUntilFinished /ONE_SECOND)
Timber.i(_timeLeft.value.toString())
}
}
timer.start()
Timber.i("GameViewModel created!")
}
companion object {
// Time when the game is over
private const val DONE = 0L
// Countdown time interval
private const val ONE_SECOND = 1000L
// Total time for the game
private const val COUNTDOWN_TIME = 60000L
}
/**
* Moves to the next word in the list
*/
private fun nextWord() {
if (!wordList.isEmpty()) {
//Select and remove a _word from the list
_word.value = wordList.removeAt(0)
}else{
resetList()
}
}
fun onGameFinish(){
//game over man
_eventGameFinished.value = true
}
fun onGameFinishComplete(){
_eventGameFinished.value = false
}
/**
* Resets the list of words and randomizes the order
*/
private fun resetList() {
wordList = mutableListOf(
"queen",
"hospital",
"basketball",
"cat",
"change",
"snail",
"soup",
"calendar",
"sad",
"desk",
"guitar",
"home",
"railway",
"zebra",
"jelly",
"car",
"crow",
"trade",
"bag",
"roll",
"bubble"
)
wordList.shuffle()
}
/** Methods for buttons presses **/
fun onSkip() {
if (!wordList.isEmpty()) {
_score.value = _score.value?.minus(1)
}
nextWord()
}
fun onCorrect() {
if (!wordList.isEmpty()) {
_score.value = score.value?.plus(1)
}
nextWord()
}
override fun onCleared() {
super.onCleared()
timer.cancel()
Timber.i("GameViewModel destroyed!")
}
}
| 0
|
Kotlin
|
0
| 0
|
b6e3263b6fb2d4e4bdadeb9a2812c7e0c8300f1c
| 4,300
|
android-kotlin-fundamentals-starter-apps
|
Apache License 2.0
|
app/src/main/java/com/breezefieldsalesbaishalii/features/dashboard/presentation/api/dashboardApi/DashboardRepoProvider.kt
|
DebashisINT
| 764,495,414
| false
|
{"Kotlin": 16305966, "Java": 1023113}
|
package com.breezefieldsalesbaishalii.features.dashboard.presentation.api.dashboardApi
import com.breezefieldsalesbaishalii.features.login.api.LoginApi
import com.breezefieldsalesbaishalii.features.login.api.LoginRepository
/**
* Created by Saikat on 26-Jun-20.
*/
object DashboardRepoProvider {
fun provideDashboardImgRepository(): DashboardRepo {
return DashboardRepo(DashboardApi.img())
}
fun provideDashboardRepository(): DashboardRepo {
return DashboardRepo(DashboardApi.create())
}
}
| 0
|
Kotlin
|
0
| 0
|
1706fa9ae7d427280d4c6c04955a081f9fd99ec7
| 526
|
BaishaliiTanksFSM
|
Apache License 2.0
|
mobile/FeedbackApp/app/src/main/java/br/com/rocketseat/nlw/impulse/feedbackapp/models/Feedback.kt
|
Henrique-Santos-da-Silva
| 533,898,807
| false
| null |
package br.com.rocketseat.nlw.impulse.feedbackapp.models
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class Feedback(
val type: String,
val comment: String,
@SerializedName("screenshot") val screenShot: String? = null,
@SerializedName("screenshotbase64") val screenShotBase64: String? = null
) : Serializable
| 0
|
Kotlin
|
0
| 1
|
ceef8fd5803e8a88f75c7898cd435a6822562cc7
| 366
|
nlw-return-impulse-kotlin
|
MIT License
|
app/src/main/java/net/pfiers/osmfocus/osmdroid/overlays/GeometryOverlay.kt
|
EasyVector
| 401,386,836
| true
|
{"Kotlin": 195964, "Ruby": 583}
|
package net.pfiers.osmfocus.osmdroid.overlays
import android.graphics.Canvas
import androidx.annotation.ColorInt
import net.pfiers.osmfocus.osmdroid.toOverlay
import org.locationtech.jts.geom.Geometry
import org.locationtech.jts.geom.GeometryFactory
import org.osmdroid.views.Projection
import org.osmdroid.views.overlay.Overlay
class GeometryOverlay constructor(
@ColorInt private val color: Int,
private val factory: GeometryFactory
) : Overlay() {
private var overlay: Overlay? = null
private var _geometry: Geometry? = null
var geometry: Geometry?
get() = _geometry
set(value) {
_geometry = value
overlay = value?.toOverlay(factory, color)
}
override fun draw(pCanvas: Canvas?, pProjection: Projection?) {
overlay?.draw(pCanvas, pProjection)
}
}
| 0
|
Kotlin
|
0
| 0
|
5e1050578690d1267493720506b44528204b9154
| 838
|
osmfocus
|
Apache License 2.0
|
platform/android/goldengate/RxFitbitGatt/src/main/java/com/fitbit/bluetooth/fbgatt/rx/scanner/DeviceAddressPeripheralScannerFilter.kt
|
Fitbit
| 252,750,226
| false
|
{"C": 2519513, "Kotlin": 897890, "Swift": 806092, "C++": 805305, "CMake": 121256, "Python": 115131, "Objective-C": 88567, "JavaScript": 20929, "HTML": 13841, "Shell": 2041, "Dockerfile": 1379, "Ruby": 252}
|
// Copyright 2017-2020 Fitbit, Inc
// SPDX-License-Identifier: Apache-2.0
package com.fitbit.bluetooth.fbgatt.rx.scanner
import com.fitbit.bluetooth.fbgatt.FitbitGatt
/**
* Add a single filter for scanning peripheral by device adddress
*
* @param deviceAddress device address to add for scanning filter
*/
class DeviceAddressPeripheralScannerFilter(
private val deviceAddress: String
) : PeripheralScannerFilter {
override fun add(fitbitGatt: FitbitGatt) {
fitbitGatt.addDeviceAddressFilter(deviceAddress)
}
}
| 14
|
C
|
32
| 290
|
417aad0080bdc8b20c27cf8fff2455c20e6f3adb
| 542
|
golden-gate
|
Apache License 2.0
|
app/src/main/java/dev/lucianosantos/exerciseplanner/data/ExercisesRepository.kt
|
lucianosantosdev
| 579,394,983
| false
| null |
package dev.lucianosantos.exerciseplanner.repositories
import androidx.lifecycle.LiveData
import dev.lucianosantos.exerciseplanner.data.Exercise
import dev.lucianosantos.exerciseplanner.data.ExerciseDao
class ExercisesRepository(private val exercisesDao: ExerciseDao) : IExercisesRepository {
override suspend fun getById(exerciseId: String) = exercisesDao.getById(exerciseId)
override suspend fun addExercise(exercise: Exercise) {
exercisesDao.insert(exercise)
}
override fun fetchExercises(routineId: String?) : LiveData<List<Exercise>> =
if (routineId == null) {
exercisesDao.getAll()
} else {
exercisesDao.getAllByRoutineId(routineId)
}
}
| 4
|
Kotlin
|
0
| 0
|
b0f7a10b64fb55a2f2c52267b65935ab580cb37f
| 699
|
ExercisePlanner
|
Apache License 2.0
|
aws/sdk-codegen/src/main/kotlin/software/amazon/smithy/rustsdk/customize/ec2/EC2MakePrimitivesOptional.kt
|
smithy-lang
| 308,027,791
| false
|
{"Rust": 4428309, "Kotlin": 3842117, "Smithy": 151231, "Python": 62946, "Shell": 49728, "TypeScript": 30713, "Dockerfile": 9790, "JavaScript": 5975, "Harbour": 5848, "Makefile": 5633, "CSS": 982, "RenderScript": 116}
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package software.amazon.smithy.rustsdk.customize.ec2
import software.amazon.smithy.model.Model
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.model.traits.ClientOptionalTrait
import software.amazon.smithy.model.transform.ModelTransformer
object EC2MakePrimitivesOptional {
fun processModel(model: Model): Model {
val updates = arrayListOf<Shape>()
for (struct in model.structureShapes) {
for (member in struct.allMembers.values) {
updates.add(member.toBuilder().addTrait(ClientOptionalTrait()).build())
}
}
return ModelTransformer.create().replaceShapes(model, updates)
}
}
| 300
|
Rust
|
188
| 504
|
8d8e7ab7aa6c3b388ffb2365a29ab03f87c24507
| 805
|
smithy-rs
|
Apache License 2.0
|
unrealengine/src/main/kotlin/dev/dexsr/gmod/palworld/trainer/ue/gvas/rawdata/WorkerDirector.kt
|
flammky
| 758,310,188
| false
|
{"Kotlin": 483889}
|
package dev.dexsr.gmod.palworld.trainer.ue.gvas.rawdata
import dev.dexsr.gmod.palworld.trainer.ue.gvas.*
import dev.dexsr.gmod.palworld.trainer.ue.util.cast
import java.nio.ByteBuffer
import java.nio.ByteOrder
object WorkerDirector
sealed class WorkerDirectorDict() : OpenGvasDict()
class WorkerDirectorData(
val id: String,
val spawnTransform: GvasTransform,
val currentOrderType: Byte,
val currentBattleType: Byte,
val containerId: String
) : WorkerDirectorDict()
fun WorkerDirector.decode(
reader: GvasReader,
typeName: String,
size: Int,
path: String
) : GvasProperty {
check(typeName == "ArrayProperty") {
"WorkerDirector_decode: expected ArrayProperty, got=$typeName"
}
val value = reader.property(typeName, size, path, nestedCallerPath = path)
val arrayDict = value
.value
.cast<GvasArrayDict>()
val dataBytes = arrayDict.value
.cast<GvasAnyArrayPropertyValue>().values
.cast<GvasByteArrayValue>().value
value.value = CustomByteArrayRawData(
customType = path,
id = arrayDict.id,
value = GvasArrayDict(
arrayType = arrayDict.arrayType,
id = arrayDict.id,
value = GvasTransformedArrayValue(decodeBytes(reader, dataBytes))
)
)
return value
}
private fun WorkerDirector.decodeBytes(
parentReader: GvasReader,
dataBytes: ByteArray
): WorkerDirectorData {
val reader = parentReader.copy(ByteBuffer.wrap(dataBytes).order(ByteOrder.LITTLE_ENDIAN))
val data = WorkerDirectorData(
id = reader.uuid().toString(),
spawnTransform = reader.ftransform(),
currentOrderType = reader.readByte(),
currentBattleType = reader.readByte(),
containerId = reader.uuid().toString()
)
check(reader.isEof()) {
"WorkerDirector_decodeBytes: EOF not reached"
}
return data
}
fun WorkerDirector.encode(
writer: GvasWriter,
typeName: String,
data: GvasProperty
): Int {
TODO()
}
| 0
|
Kotlin
|
0
| 4
|
38cb678968e49372a2e304b46a60a2f6310767ed
| 2,035
|
PalToolbox
|
Apache License 2.0
|
app/src/main/java/it/andrearosa/kickstarter/dto/Geo.kt
|
andrea-rosa
| 149,014,587
| false
| null |
package it.andrearosa.kickstarter.dto
data class Geo(
val lat: String,
val lon: String
)
| 0
|
Kotlin
|
0
| 0
|
d80652bc50999e78e8a13a7e67a6a219fc6ba640
| 105
|
kickstarter-android-kt
|
MIT License
|
src/main/kotlin/com/rhseung/blueprint/tooltip/data/BundleTooltipData.kt
|
minecraft-stuffs
| 675,141,654
| false
|
{"Kotlin": 163498, "Java": 2919}
|
package com.rhseung.blueprint.tooltip.data
import net.minecraft.item.BlockItem
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.nbt.NbtCompound
import net.minecraft.util.collection.DefaultedList
import java.util.*
import java.util.stream.Stream
/**
* [net.minecraft.item.BundleItem.getTooltipData]
*/
class BundleTooltipData(
stack: ItemStack
) : AbstractTooltipData(stack) {
val inventory: DefaultedList<ItemStack>;
val bundleOccupancy: Int;
init {
val defaultedList: DefaultedList<ItemStack> = DefaultedList.of();
val stream = getBundledStacks(stack);
Objects.requireNonNull(defaultedList);
stream.forEach(defaultedList::add);
this.inventory = defaultedList;
this.bundleOccupancy = getBundleOccupancy(stack);
}
private fun getBundledStacks(stack: ItemStack): Stream<ItemStack> {
val nbtCompound = stack.nbt;
return if (nbtCompound == null) {
Stream.empty();
} else {
val nbtList = nbtCompound.getList("Items", 10);
Objects.requireNonNull(NbtCompound::class.java);
nbtList.stream()
.map { NbtCompound::class.java.cast(it) }
.map { ItemStack.fromNbt(it) };
}
}
private fun getItemOccupancy(stack: ItemStack): Int {
if (stack.isOf(Items.BUNDLE)) {
return 4 + getBundleOccupancy(stack)
} else {
if ((stack.isOf(Items.BEEHIVE) || stack.isOf(Items.BEE_NEST)) && stack.hasNbt()) {
val nbtCompound = BlockItem.getBlockEntityNbt(stack)
if (nbtCompound != null && !nbtCompound.getList("Bees", 10).isEmpty()) {
return 64
}
}
return 64 / stack.maxCount
}
}
private fun getBundleOccupancy(stack: ItemStack): Int {
return getBundledStacks(stack).mapToInt { getItemOccupancy(it) * it.count }.sum()
}
}
| 0
|
Kotlin
|
0
| 0
|
56eee22a4ce6b14bd833fab986f19b11c45c3223
| 1,992
|
blueprint
|
MIT License
|
android/design/src/main/kotlin/io/chefbook/design/components/switches/Switch.kt
|
mephistolie
| 379,951,682
| false
|
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
|
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import io.chefbook.core.android.compose.providers.theme.LocalTheme
@Composable
fun Switch(
isChecked: Boolean,
) {
val density = LocalDensity.current
val colors = LocalTheme.colors
val width = 40.dp
val height = 24.dp
val gap = 3.dp
val thumbRadius = (height / 2) - gap
val animatePosition = animateFloatAsState(
label = "switch",
targetValue = with(density) {
if (isChecked)
(width - thumbRadius - gap).toPx()
else
(thumbRadius + gap).toPx()
}
)
Canvas(
modifier = Modifier.size(width = width, height = height)
) {
drawRoundRect(
color = if (isChecked) colors.tintPrimary else colors.backgroundTertiary,
cornerRadius = CornerRadius(x = 28.dp.toPx(), y = 28.dp.toPx()),
)
drawCircle(
color = colors.backgroundPrimary,
radius = thumbRadius.toPx(),
center = Offset(
x = animatePosition.value,
y = size.height / 2
)
)
}
}
| 0
|
Kotlin
|
0
| 12
|
ddaf82ee3142f30aee8920d226a8f07873cdcffe
| 1,365
|
chefbook-mobile
|
Apache License 2.0
|
airwallex/src/main/java/com/airwallex/android/AirwallexSecurityConnector.kt
|
sihuicai
| 343,422,189
| true
|
{"Kotlin": 383342}
|
package com.airwallex.android
import android.content.Context
import com.airwallex.android.model.PaymentIntent
import com.threatmetrix.TrustDefender.Config
import com.threatmetrix.TrustDefender.Profile
import com.threatmetrix.TrustDefender.ProfilingOptions
import com.threatmetrix.TrustDefender.TrustDefender
/**
* The implementation of [SecurityConnector] to retrieve the Device Fingerprinting token
*/
internal class AirwallexSecurityConnector : SecurityConnector {
private var profilingHandle: Profile.Handle? = null
/**
* Retrieve SecurityToken listener
*/
interface SecurityTokenListener {
fun onResponse(deviceId: String)
}
/**
* Retrieve the SecurityToken from Cardinals under the ID of [PaymentIntent]
*
* @param paymentIntentId ID of [PaymentIntent]
* @param applicationContext The Context of Application
* @param securityTokenListener The listener of when retrieved the SecurityToken
*/
override fun retrieveSecurityToken(
paymentIntentId: String,
applicationContext: Context,
securityTokenListener: SecurityTokenListener
) {
Logger.debug(
TAG,
"Start init TrustDefender " + TrustDefender.version
)
val config = Config().setOrgId(BuildConfig.DEVICE_FINGERPRINT_ORG_ID)
.setContext(applicationContext)
TrustDefender.getInstance().init(config)
Logger.debug(TAG, "Successfully init init-ed")
doProfile(paymentIntentId, securityTokenListener)
}
/**
* Init was successful or there is a valid instance to be used for further calls. Fire a profile request
*/
private fun doProfile(paymentIntentId: String, securityTokenListener: SecurityTokenListener) {
val fraudSessionId = "$paymentIntentId${System.currentTimeMillis()}"
var sessionID = "${BuildConfig.DEVICE_FINGERPRINT_MERCHANT_ID}$fraudSessionId"
val options = ProfilingOptions().setSessionID(sessionID)
// Fire off the profiling request.
profilingHandle = TrustDefender.getInstance().doProfileRequest(options) { result ->
Logger.debug(
TAG,
"Session id: ${result.sessionID}, Session status: ${result.status}"
)
if (result.sessionID != null) {
sessionID = result.sessionID
}
profilingHandle?.cancel()
profilingHandle = null
securityTokenListener.onResponse(sessionID)
}
}
companion object {
private const val TAG = "TrustDefender"
}
}
| 0
| null |
0
| 0
|
9a8ea62d5c5d45d09b81ae3cba4141cb76537bf2
| 2,612
|
airwallex-payment-android
|
MIT License
|
med-app-android/app/src/main/java/dts/app/med_app_android/Fragment/EditProfileClientFragment.kt
|
Timo4ka016
| 623,606,328
| false
| null |
package dts.app.med_app_android.Fragment
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import dts.app.med_app_android.Model.UpdateClientRequest
import dts.app.med_app_android.R
import dts.app.med_app_android.Retrofit.RetrofitClient
import dts.app.med_app_android.Retrofit.TokenManager
import dts.app.med_app_android.Service.ClientService
import dts.app.med_app_android.databinding.EditProfileClientBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class EditProfileClientFragment : Fragment() {
private lateinit var binding: EditProfileClientBinding
private lateinit var clientService: ClientService
private lateinit var tokenManager: TokenManager
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = EditProfileClientBinding.inflate(inflater, container, false)
tokenManager = TokenManager(requireContext())
val retrofit = RetrofitClient.getRetrofitClient(tokenManager)
clientService = retrofit.create(ClientService::class.java)
header()
navigation()
updateClient()
return binding.root
}
private fun updateClient() = with(binding) {
btnSave.setOnClickListener {
val callUpdateClient = clientService.updateClient(requestBody())
callUpdateClient.enqueue(object : Callback<Void> {
override fun onResponse(call: Call<Void>, response: Response<Void>) {
if (response.isSuccessful) {
findNavController().navigate(R.id.profileClientFragment, null)
} else {
Log.i(
"Response Error",
"Failed to update user: ${response.code()} ${response.message()}"
)
}
}
override fun onFailure(call: Call<Void>, t: Throwable) {
Log.i("Response Error", "Failed to update user: ${t.message}")
}
})
}
}
private fun requestBody(): UpdateClientRequest {
return UpdateClientRequest(
firstname = binding.inputFirstname.text?.trim().toString(),
lastname = binding.inputLastname.text?.trim().toString(),
password = binding.inputPassword.text?.trim().toString()
)
}
private fun navigation() = with(binding) {
myHeader.imgBack.setOnClickListener { findNavController().navigate(R.id.profileClientFragment) }
}
private fun header() = with(binding) {
myHeader.relativeHeader.visibility = View.GONE
myHeader.imgFavorite.visibility = View.GONE
myHeader.txtPageName.visibility = View.VISIBLE
myHeader.txtPageName.text = "Редактировать профиль"
}
}
| 0
|
Kotlin
|
0
| 2
|
e5e399a293063dd144ad3f12ea0d5e164eb373e1
| 3,062
|
medical-service-app
|
Apache License 2.0
|
applications/data-collector-server/src/main/kotlin/io/collective/start/collector/App.kt
|
obaro
| 729,811,598
| false
|
{"Kotlin": 54775, "CSS": 8759, "FreeMarker": 7381, "JavaScript": 848, "Shell": 556, "Dockerfile": 214, "Procfile": 90}
|
package io.collective.start.collector
import io.collective.database.getDbCollector
import io.collective.rabbitsupport.*
import io.collective.workflow.WorkScheduler
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import java.net.URI
import java.util.*
fun Application.module() {
install(DefaultHeaders)
install(CallLogging)
install(Routing) {
get("/") {
call.respondText("hi!", ContentType.Text.Html)
}
}
val dbUser = System.getenv("DB_USER")
?: throw RuntimeException("Please set the DB_USER environment variable")
val dbPassword = System.getenv("DB_PASS")
?: throw RuntimeException("Please set the DB_PASS environment variable")
val dbUrl = System.getenv("DB_URL")
?: throw RuntimeException("Please set the DB_URL environment variable")
val dbPort = System.getenv("DB_PORT")
?: throw RuntimeException("Please set the DB_PORT environment variable")
val dbCollector = getDbCollector(dbUser, dbPassword, dbUrl, dbPort)
val apiKey = System.getenv("WEATHER_API_KEY")
var weatherFetchDelay = System.getenv("WEATHER_FETCH_DELAY")?.toLong() ?: 120
if(weatherFetchDelay < 60)
weatherFetchDelay = 60
val rabbitString = System.getenv("RABBIT_URL")
?: throw RuntimeException("Please set the RABBIT_URL environment variable")
val connectionFactory = buildConnectionFactory(rabbitString.let(::URI)
?: throw RuntimeException("$rabbitString is NOT a valid URI"))
val registrationNotificationExchange = RabbitExchange(
name = "collection-exchange",
type = "direct",
routingKeyGenerator = { _: String -> "42" },
)
val registrationNotificationQueue = RabbitQueue("collection-notification")
connectionFactory.declareAndBind(exchange = registrationNotificationExchange, queue = registrationNotificationQueue, routingKey = "42")
val publishFunction = publish(connectionFactory, registrationNotificationExchange)
val collectorPublisher = CollectorMessagePublisher(publishFunction)
val scheduler = WorkScheduler<ExampleTask>(ExampleWorkFinder(),
mutableListOf(ExampleWorker(collectorPublisher, dbCollector, apiKey)), weatherFetchDelay)
scheduler.start()
}
fun main() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"))
val port = System.getenv("PORT")?.toInt() ?: 8889
embeddedServer(Netty, port, watchPaths = listOf("data-collector-server"),
module = {
module()
}).start()
}
| 0
|
Kotlin
|
0
| 0
|
7e41573c0eaccf2d069c6cbe2badee7dae0eae68
| 2,644
|
Weather5028
|
Apache License 2.0
|
app/src/main/java/br/com/programadorthi/anarchtecturetry/feature/blockchain/data/local/BlockchainLocalMapper.kt
|
programadorthi
| 165,963,379
| false
| null |
package br.com.programadorthi.anarchtecturetry.feature.blockchain.data.local
import br.com.programadorthi.anarchtecturetry.feature.blockchain.domain.Blockchain
import io.reactivex.functions.Function
import java.util.*
class BlockchainLocalMapper : Function<List<BlockchainEntity>, List<Blockchain>> {
override fun apply(items: List<BlockchainEntity>): List<Blockchain> {
if (items.isEmpty()) {
return emptyList()
}
return items.map { entity ->
Blockchain(
date = Date(entity.timestamp),
value = entity.value
)
}
}
}
| 0
|
Kotlin
|
0
| 12
|
3547af32de09f6dbdaf22c921c0e9c63421d327e
| 627
|
Anarchitecturetry
|
MIT License
|
app/src/main/java/io/github/takusan23/komadroid/ui/theme/Type.kt
|
takusan23
| 817,421,552
| false
|
{"Kotlin": 186890}
|
package io.github.takusan23.komadroid.ui.theme
import androidx.compose.material3.Typography
val AppTypography = Typography()
| 0
|
Kotlin
|
0
| 0
|
f567a3002adc15643b51546e0808dc004c46b8e2
| 127
|
KomaDroid
|
Apache License 2.0
|
commons/src/main/java/com/cyberkey/commons/compose/theme/DynamicTheme.kt
|
Damayantha
| 785,721,725
| false
|
{"Kotlin": 1621089, "Java": 379060}
|
package com.cyberkey.commons.compose.theme
import android.content.Context
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import com.cyberkey.commons.compose.extensions.config
import com.cyberkey.commons.compose.theme.model.Theme
import com.cyberkey.commons.extensions.getProperTextColor
import com.cyberkey.commons.extensions.isBlackAndWhiteTheme
import com.cyberkey.commons.extensions.isWhiteTheme
fun getTheme(context: Context, materialYouTheme: Theme.SystemDefaultMaterialYou): Theme {
val baseConfig = context.config
val primaryColorInt = baseConfig.primaryColor
val isSystemInDarkTheme = context.isDarkMode()
val accentColor = baseConfig.accentColor
val backgroundColorTheme = if (baseConfig.isUsingSystemTheme || baseConfig.isUsingAutoTheme) {
if (isSystemInDarkTheme) theme_dark_background_color else Color.White
} else {
Color(baseConfig.backgroundColor)
}
val backgroundColor = backgroundColorTheme.toArgb()
val appIconColor = baseConfig.appIconColor
val textColor = context.getProperTextColor()
val theme = when {
baseConfig.isUsingSystemTheme -> materialYouTheme
context.isBlackAndWhiteTheme() -> Theme.BlackAndWhite(
accentColor = accentColor,
primaryColorInt = primaryColorInt,
backgroundColorInt = backgroundColor,
appIconColorInt = appIconColor,
textColorInt = textColor
)
context.isWhiteTheme() -> Theme.White(
accentColor = accentColor,
primaryColorInt = primaryColorInt,
backgroundColorInt = backgroundColor,
appIconColorInt = appIconColor,
textColorInt = textColor
)
else -> {
val customPrimaryColor = when (primaryColorInt) {
-12846 -> md_red_100
-1074534 -> md_red_200
-1739917 -> md_red_300
-1092784 -> md_red_400
-769226 -> md_red_500
-1754827 -> md_red_600
-2937041 -> md_red_700
-3790808 -> md_red_800
-4776932 -> md_red_900
-476208 -> md_pink_100
-749647 -> md_pink_200
-1023342 -> md_pink_300
-1294214 -> md_pink_400
-1499549 -> md_pink_500
-2614432 -> md_pink_600
-4056997 -> md_pink_700
-5434281 -> md_pink_800
-7860657 -> md_pink_900
-1982745 -> md_purple_100
-3238952 -> md_purple_200
-4560696 -> md_purple_300
-5552196 -> md_purple_400
-6543440 -> md_purple_500
-7461718 -> md_purple_600
-8708190 -> md_purple_700
-9823334 -> md_purple_800
-11922292 -> md_purple_900
-3029783 -> md_deep_purple_100
-5005861 -> md_deep_purple_200
-6982195 -> md_deep_purple_300
-8497214 -> md_deep_purple_400
-10011977 -> md_deep_purple_500
-10603087 -> md_deep_purple_600
-11457112 -> md_deep_purple_700
-12245088 -> md_deep_purple_800
-13558894 -> md_deep_purple_900
-3814679 -> md_indigo_100
-6313766 -> md_indigo_200
-8812853 -> md_indigo_300
-10720320 -> md_indigo_400
-12627531 -> md_indigo_500
-13022805 -> md_indigo_600
-13615201 -> md_indigo_700
-14142061 -> md_indigo_800
-15064194 -> md_indigo_900
-4464901 -> md_blue_100
-7288071 -> md_blue_200
-10177034 -> md_blue_300
-12409355 -> md_blue_400
-14575885 -> md_blue_500
-14776091 -> md_blue_600
-15108398 -> md_blue_700
-15374912 -> md_blue_800
-15906911 -> md_blue_900
-4987396 -> md_light_blue_100
-8268550 -> md_light_blue_200
-11549705 -> md_light_blue_300
-14043396 -> md_light_blue_400
-16537100 -> md_light_blue_500
-16540699 -> md_light_blue_600
-16611119 -> md_light_blue_700
-16615491 -> md_light_blue_800
-16689253 -> md_light_blue_900
-5051406 -> md_cyan_100
-8331542 -> md_cyan_200
-11677471 -> md_cyan_300
-14235942 -> md_cyan_400
-16728876 -> md_cyan_500
-16732991 -> md_cyan_600
-16738393 -> md_cyan_700
-16743537 -> md_cyan_800
-16752540 -> md_cyan_900
-5054501 -> md_teal_100
-8336444 -> md_teal_200
-11684180 -> md_teal_300
-14244198 -> md_teal_400
-16738680 -> md_teal_500
-16742021 -> md_teal_600
-16746133 -> md_teal_700
-16750244 -> md_teal_800
-16757440 -> md_teal_900
-2691126 -> md_green_100
-4528984 -> md_green_200
-6366844 -> md_green_300
-7810712 -> md_green_400
-9254834 -> md_green_500
-10176442 -> md_green_600
-11492293 -> md_green_700
-12808398 -> md_green_800
-15700705 -> md_green_900
-2298424 -> md_light_green_100
-3808859 -> md_light_green_200
-5319295 -> md_light_green_300
-6501275 -> md_light_green_400
-7617718 -> md_light_green_500
-8604862 -> md_light_green_600
-9920712 -> md_light_green_700
-11171025 -> md_light_green_800
-13407970 -> md_light_green_900
-985917 -> md_lime_100
-1642852 -> md_lime_200
-2300043 -> md_lime_300
-2825897 -> md_lime_400
-3285959 -> md_lime_500
-4142541 -> md_lime_600
-5983189 -> md_lime_700
-6382300 -> md_lime_800
-8227049 -> md_lime_900
-1596 -> md_yellow_100
-2672 -> md_yellow_200
-3722 -> md_yellow_300
-4520 -> md_yellow_400
-5317 -> md_yellow_500
-141259 -> md_yellow_600
-278483 -> md_yellow_700
-415707 -> md_yellow_800
-688361 -> md_yellow_900
-4941 -> md_amber_100
-8062 -> md_amber_200
-10929 -> md_amber_300
-13784 -> md_amber_400
-16121 -> md_amber_500
-19712 -> md_amber_600
-24576 -> md_amber_700
-28928 -> md_amber_800
-37120 -> md_amber_900
-8014 -> md_orange_100
-13184 -> md_orange_200
-18611 -> md_orange_300
-22746 -> md_orange_400
-26624 -> md_orange_500
-291840 -> md_orange_600
-689152 -> md_orange_700
-1086464 -> md_orange_800
-1683200 -> md_orange_900
-13124 -> md_deep_orange_100
-21615 -> md_deep_orange_200
-30107 -> md_deep_orange_300
-36797 -> md_deep_orange_400
-43230 -> md_deep_orange_500
-765666 -> md_deep_orange_600
-1684967 -> md_deep_orange_700
-2604267 -> md_deep_orange_800
-4246004 -> md_deep_orange_900
-2634552 -> md_brown_100
-4412764 -> md_brown_200
-6190977 -> md_brown_300
-7508381 -> md_brown_400
-8825528 -> md_brown_500
-9614271 -> md_brown_600
-10665929 -> md_brown_700
-11652050 -> md_brown_800
-12703965 -> md_brown_900
-3155748 -> md_blue_grey_100
-5194811 -> md_blue_grey_200
-7297874 -> md_blue_grey_300
-8875876 -> md_blue_grey_400
-10453621 -> md_blue_grey_500
-11243910 -> md_blue_grey_600
-12232092 -> md_blue_grey_700
-13154481 -> md_blue_grey_800
-14273992 -> md_blue_grey_900
-1 -> md_grey_black_dark
-1118482 -> md_grey_200
-2039584 -> md_grey_300
-4342339 -> md_grey_400
-6381922 -> md_grey_500
-9079435 -> md_grey_600
-10395295 -> md_grey_700
-12434878 -> md_grey_800
-16777216 -> md_grey_black_dark
else -> md_green_900
}
Theme.Custom(
primaryColorInt = customPrimaryColor.toArgb(),
backgroundColorInt = backgroundColor,
appIconColorInt = appIconColor,
textColorInt = textColor
)
}
}
return theme
}
| 0
|
Kotlin
|
0
| 0
|
757f3ab319b9f15b96444143c1dfcd619c703294
| 9,399
|
VideoPlayer
|
The Unlicense
|
article_module/src/main/java/com/aj/article_module/adapter/SystemTreeFMAdapter.kt
|
HoyeZhang
| 264,694,354
| false
|
{"Kotlin": 149612}
|
package com.aj.article_module.adapter
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.util.TypedValue
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.aj.article_module.R
import com.aj.article_module.bean.*
import com.aj.article_module.databinding.ArticleItemSystemTreeItemBinding
import com.aj.base_module.utils.ContextCompatUtils
import com.aj.base_module.utils.ScreenUtils
import com.aj.data_service.ArouterPageManger
import com.aj.data_service.ArouterUrlManage
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.flexbox.FlexboxLayout
import kotlin.random.Random
/**
*
* @Package: com.aj.article_module.adapter
* @ClassName: OfficialAccountListAdapter
* @Description: 体系列表
* @Author: zhy
* @CreateDate: 2020/8/03 11:12
*/
class SystemTreeFMAdapter : BaseQuickAdapter<SystemTreeBean, BaseViewHolder> {
private val colors = intArrayOf(
R.color.base_color_gray,
R.color.base_color_757575,
R.color.base_color_455A64,
R.color.base_color_9E9E9E,
R.color.base_color_BDBDBD
)
constructor(layoutResId: Int = R.layout.article_item_system_tree_item) : super(
layoutResId
)
override fun onItemViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
super.onItemViewHolderCreated(viewHolder, viewType)
DataBindingUtil.bind<ViewDataBinding>(viewHolder.itemView)
setOnItemClickListener { _, _, position ->
val bundle = Bundle()
bundle.putString(PageDataInfo.systemTreeName, data[position].name)
bundle.putParcelable(PageDataInfo.systemTreeBean, data[position])
ArouterPageManger.navigationWithParams(
context,
ArouterUrlManage.ARTICLE_SYSTEM_CLASSIFY_ACTIVITY,
bundle
)
}
}
override fun convert(holder: BaseViewHolder, item: SystemTreeBean) {
//获取 Binding
val articleItemSystemTreeItemBinding: ArticleItemSystemTreeItemBinding? =
DataBindingUtil.getBinding(holder.itemView)
if (articleItemSystemTreeItemBinding != null) {
articleItemSystemTreeItemBinding.systemTreeBean = item
}
var flexLayout: FlexboxLayout = holder.getView(R.id.fbl_tab)
if ( item.children.isNotEmpty()) {
flexLayout.removeAllViews()
item.children.forEach { systemTreeChildren ->
val tabItem = TextView(context)
tabItem.text = systemTreeChildren.name
tabItem.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
context.resources.getDimension(R.dimen.base_text_sp_14)
)
val gradientDrawable : GradientDrawable = ContextCompatUtils.getDrawable(context,R.drawable.article_bg_theme_round_2) as GradientDrawable
gradientDrawable.setColor(ContextCompatUtils.getColor(context,colors[Random.nextInt(colors.size )]))
tabItem.background =gradientDrawable
tabItem.setTextColor( ContextCompatUtils.getColor(context,R.color.base_colorWhite))
var vlp: FlexboxLayout.LayoutParams = FlexboxLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
vlp.setMargins(
ScreenUtils.dp2px(context, 2f),
ScreenUtils.dp2px(context, 1f),
ScreenUtils.dp2px(context, 2f),
ScreenUtils.dp2px(context, 1f)
)
tabItem.setPadding(
ScreenUtils.dp2px(context, 2.5f),
ScreenUtils.dp2px(context, 2f),
ScreenUtils.dp2px(context, 2.5f),
ScreenUtils.dp2px(context, 2f)
)
tabItem.layoutParams = vlp
flexLayout.addView(tabItem)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4a891208699ad4bda6697e10cd960bbf685f840d
| 4,205
|
wanandroid
|
Apache License 2.0
|
src/main/kotlin/com/velocitypowered/api/kt/event/connection/ProxyPingEvent.kt
|
VelocityPowered
| 367,863,490
| false
| null |
package com.velocitypowered.api.kt.event.connection
import com.velocitypowered.api.event.connection.ProxyPingEvent
import com.velocitypowered.api.proxy.connection.InboundConnection
import com.velocitypowered.api.proxy.server.ServerPing
inline val ProxyPingEvent.connection: InboundConnection
get() = connection()
inline var ProxyPingEvent.ping: ServerPing
get() = ping()
set(value) {
setPing(value)
}
| 2
|
Kotlin
|
6
| 6
|
3f457b9f0a73d086fae7f7d12ec770d8c3cde1c2
| 416
|
velocity-language-kotlin
|
MIT License
|
core/src/main/java/com/viniciusjanner/desafio/core/domain/model/EventCheckinResponse.kt
|
viniciusjanner
| 693,962,041
| false
|
{"Kotlin": 93899, "Java": 115}
|
package com.viniciusjanner.desafio.core.domain.model
data class EventCheckinResponse(
val code: Int
)
| 0
|
Kotlin
|
0
| 0
|
6a66a9a4d5a125b9212dfc62bf0325698f4fc502
| 107
|
android_desafio_tecnico_empresa_sicredi
|
Apache License 2.0
|
src/main/kotlin/com/mt/notion/common/request/parent/WithParentRequest.kt
|
motui
| 479,945,371
| false
| null |
package com.mt.notion.common.request.parent
/**
* Database
*
* @author it.motui
*/
interface WithParentRequest {
val type: ParentType
}
| 0
|
Kotlin
|
0
| 1
|
80b7b256d8d7c34b15cf79d1e5f539c8ef4736b4
| 145
|
notion-sdk-kotlin
|
MIT License
|
app/src/main/java/com/example/matchmentor/view/ProfileAdapter.kt
|
RodrigoJrDev
| 795,927,508
| false
|
{"Kotlin": 80720}
|
package com.example.matchmentor.view
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.matchmentor.R
import com.example.matchmentor.model.Profile
class ProfileAdapter(private var profiles: List<Profile>) : RecyclerView.Adapter<ProfileAdapter.ProfileViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProfileViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_profile, parent, false)
return ProfileViewHolder(view)
}
override fun onBindViewHolder(holder: ProfileViewHolder, position: Int) {
val profile = profiles[position]
holder.bind(profile)
}
override fun getItemCount(): Int = profiles.size
fun updateProfiles(newProfiles: List<Profile>) {
profiles = newProfiles
notifyDataSetChanged()
}
class ProfileViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val nameTextView: TextView = itemView.findViewById(R.id.name_text_view)
private val ageTextView: TextView = itemView.findViewById(R.id.age_text_view)
private val cityTextView: TextView = itemView.findViewById(R.id.city_text_view)
private val infoTextView: TextView = itemView.findViewById(R.id.info_text_view)
private val photoImageView: ImageView = itemView.findViewById(R.id.photo_image_view)
fun bind(profile: Profile) {
val fullName = "${profile.nome} ${profile.sobrenome}"
nameTextView.text = fullName
ageTextView.text = profile.idade?.toString() ?: "N/A"
cityTextView.text = "Cidade: ${profile.cidade}"
val info = StringBuilder()
profile.area_de_interesse?.let { info.append("Interesse: $it\n") }
profile.profissao?.let { info.append("Profissão: $it\n") }
profile.area_de_atuacao?.let { info.append("Área de Atuação: $it\n") }
profile.descricao_pessoal?.let { info.append("Descrição: $it\n") }
infoTextView.text = info.toString().trim()
val imageUrl = "https://focus-clientes.com.br/MatchMentorBackEnd/icons-users/${profile.foto}"
if (!profile.foto.isNullOrEmpty()) {
Glide.with(itemView.context).load(imageUrl).centerCrop().into(photoImageView)
} else {
photoImageView.setImageResource(R.drawable.image1)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
424b3963b6e230f40d29a6e42bb7f0cf501c842c
| 2,614
|
MatchTech
|
MIT License
|
app/src/main/java/com/example/chatgpttest/ChatGPTApplication.kt
|
DaedricKnight
| 629,326,747
| false
| null |
package com.example.chatgpttest
import android.app.Application
import com.example.chatgpttest.di.AppModule
import com.example.chatgpttest.di.ApplicationComponent
import com.example.chatgpttest.di.DaggerApplicationComponent
class ChatGPTApplication : Application() {
lateinit var appComponent: ApplicationComponent
private set
override fun onCreate() {
super.onCreate()
appComponent = DaggerApplicationComponent.create()
DaggerApplicationComponent.builder()
.appModule(AppModule())
.build()
}
}
| 0
|
Kotlin
|
0
| 0
|
4b4857dfdb355ac0702fc329070850770a531866
| 565
|
ChatGPTTest
|
MIT License
|
src/jsMain/kotlin/dev/valvavassori/compose/sweeper/ui/containers/GameMenu.kt
|
faogustavo
| 720,502,762
| false
|
{"Kotlin": 31505, "CSS": 544, "HTML": 437}
|
package dev.valvavassori.compose.sweeper.ui.containers
import androidx.compose.runtime.Composable
import dev.valvavassori.compose.sweeper.ui.components.nineeightcss.CloseButton
import dev.valvavassori.compose.sweeper.ui.components.nineeightcss.TitleBar
import dev.valvavassori.compose.sweeper.ui.components.nineeightcss.Window
@Composable
fun GameMenu(
onCloseClick: () -> Unit,
) {
Window(
viewId = "game-menu",
draggable = true,
attrs = { classes("game-menu") },
) {
TitleBar(
title = "Minesweeper Menu",
buttons = {
CloseButton(attrs = {
onClick { onCloseClick() }
})
}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
08f610238a60e213407b25c189a4781b5b59db8f
| 724
|
compose-sweeper
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.