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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
neat-form-core/src/main/java/com/nerdstone/neatformcore/views/handlers/ViewDispatcher.kt | kakavi | 265,782,204 | true | {"Kotlin": 252355} | package com.nerdstone.neatformcore.views.handlers
import android.view.View
import androidx.appcompat.view.ContextThemeWrapper
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import com.nerdstone.neatformcore.domain.listeners.DataActionListener
import com.nerdstone.neatformcore.domain.model.NFormViewData
import com.nerdstone.neatformcore.domain.model.NFormViewDetails
import com.nerdstone.neatformcore.domain.view.NFormView
import com.nerdstone.neatformcore.rules.RulesFactory
import com.nerdstone.neatformcore.utils.Utils
import com.nerdstone.neatformcore.viewmodel.DataViewModel
class ViewDispatcher private constructor() : DataActionListener {
val rulesFactory: RulesFactory = RulesFactory.INSTANCE
/**
* Dispatches an action when view value changes. If value is the same as what had already been
* dispatched then do nothing
* @param viewDetails the details of the view that has just dispatched a value
*/
override fun onPassData(viewDetails: NFormViewDetails) {
val context = viewDetails.view.context
var activityContext = context
if (context is ContextThemeWrapper) {
activityContext = context.baseContext
}
val viewModel = ViewModelProvider(activityContext as FragmentActivity)[DataViewModel::class.java]
if (viewModel.details[viewDetails.name] != viewDetails.value) {
viewModel.details[viewDetails.name] =
NFormViewData(viewDetails.view.javaClass.simpleName, viewDetails.value, viewDetails.metadata)
val nFormView = viewDetails.view as NFormView
nFormView.validateValue()
//Fire rules for calculations and other fields watching on this current field
val calculations = (viewDetails.view as NFormView).viewProperties.calculations
if (rulesFactory.subjectsRegistry.containsKey(viewDetails.name.trim()) || calculations != null) {
rulesFactory.updateFactsAndExecuteRules(viewDetails)
}
if (viewDetails.value == null && Utils.isFieldRequired(nFormView)
&& viewDetails.view.visibility == View.VISIBLE
) {
nFormView.formValidator.requiredFields.add(viewDetails.name)
}
}
}
companion object {
@Volatile
private var instance: ViewDispatcher? = null
val INSTANCE: ViewDispatcher
get() = instance ?: synchronized(this) {
ViewDispatcher().also {
instance = it
}
}
}
}
| 0 | null | 0 | 0 | c820144e15325572bba9a570066082ac5be61c33 | 2,621 | neat-form | Apache License 2.0 |
src/main/kotlin/com/dannybierek/tools/hmc/model/RepositoryId.kt | dbierek | 630,756,451 | false | null | package com.dannybierek.tools.hmc.model
data class RepositoryId(
val type: String = "",
val value: String = ""
) | 0 | Kotlin | 0 | 0 | 37f9aedaefbc617d640769a40c1684a21be52cef | 121 | HitmanModCreator | Apache License 2.0 |
feature/newsfeed/src/main/kotlin/com/finwise/feature/newsfeed/NewsFeedViewModel.kt | nimaiwalsh | 757,345,803 | false | {"Kotlin": 71169, "Shell": 2385} | package com.finwise.feature.newsfeed
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.finwise.data.remote.api.AllNewsResponse
import com.finwise.data.repository.GetFinancialNews
import com.finwise.data.repository.GetFinancialNews.Companion.invoke
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
data class NewsFeedUiState(
val newsItems: List<String>,
)
@HiltViewModel
class NewsFeedViewModel @Inject constructor(
getNews: GetFinancialNews
) : ViewModel() {
private val _state = MutableStateFlow(NewsFeedUiState(listOf("")))
val state get() = _state.asStateFlow()
init {
viewModelScope.launch {
val newsResponse = getNews()
_state.update { it.copy(newsItems = newsResponse.mapTpState()) }
}
}
private fun AllNewsResponse?.mapTpState(): List<String> {
if (this == null) return listOf()
return this.data.map {
it.title
}
}
} | 0 | Kotlin | 0 | 0 | 8eddda4d09145dbc081790fe0001886ab1e8360c | 1,167 | finwise | Apache License 2.0 |
src/main/kotlin/me/chill/database/operations/InviteWhitelistOperations.kt | woojiahao | 145,920,296 | false | null | package me.chill.database.operations
import me.chill.database.InviteWhitelist
import me.chill.database.Preference
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.transactions.transaction
fun addToWhitelist(serverId: String, inviteLink: String) =
transaction {
InviteWhitelist.insert {
it[InviteWhitelist.serverId] = serverId
it[InviteWhitelist.inviteLink] = inviteLink
}
}
fun hasInviteInWhitelist(serverId: String, inviteLink: String) =
transaction {
!InviteWhitelist.select { (InviteWhitelist.serverId eq serverId) and (InviteWhitelist.inviteLink eq inviteLink) }.empty()
}
fun removeFromWhitelist(serverId: String, inviteLink: String) =
transaction {
InviteWhitelist.deleteWhere { (InviteWhitelist.inviteLink eq inviteLink) and (InviteWhitelist.serverId eq serverId) }
}
fun getWhitelist(serverId: String) =
transaction {
InviteWhitelist.select { InviteWhitelist.serverId eq serverId }.joinToString("\n") {
"- ${it[InviteWhitelist.inviteLink]}"
}
}
fun getInviteExcluded(serverId: String) = getPreference(serverId, Preference.inviteRoleExcluded) as String?
fun editInviteExcluded(serverId: String, roleId: String) = updatePreferences(serverId) { it[inviteRoleExcluded] = roleId } | 10 | Kotlin | 12 | 19 | f55e6dc4897096b40c77580b5a4f3417ca563b34 | 1,394 | Taiga | MIT License |
src/main/kotlin/data/EncryptParameter.kt | Tlaster | 180,539,760 | false | null | package moe.tlaster.kotlinpgp.data
import org.bouncycastle.bcpg.CompressionAlgorithmTags
data class EncryptParameter(
val message: String,
val publicKey: List<PublicKeyData> = emptyList(),
val enableSignature: Boolean = false,
val privateKey: String = "",
val password: String = "",
val compressionAlgorithm: Int = CompressionAlgorithmTags.ZIP
)
data class PublicKeyData(
val key: String,
val isHidden: Boolean = false
)
data class PrivateKeyData(
val key: String,
val password: String
) | 2 | Kotlin | 0 | 9 | bbcf73a2fbbe7923142066b89ab343a2a28ec99a | 531 | KotlinPGP | MIT License |
ktor/src/main/kotlin/config/PostgresConfig.kt | crowdproj | 600,730,971 | false | null | package ru.music.discussions.ru.music.discussions.configs
import io.ktor.server.config.*
data class PostgresConfig(
val url: String = "jdbc:postgresql://localhost:5432/discussions",
val user: String = "postgres",
val password: String = "<PASSWORD>",
val schema: String = "discussions",
) {
constructor(config: ApplicationConfig): this(
url = config.property("$PATH.url").getString(),
user = config.property("$PATH.user").getString(),
password = config.property("$PATH.password").getString(),
schema = config.property("$PATH.schema").getString(),
)
companion object {
const val PATH = "discussions.repository.psql"
}
}
| 1 | Kotlin | 2 | 0 | 680c52b3be9161b699c635fc032a0289ce71a239 | 693 | music | Apache License 2.0 |
app/src/main/kotlin/com/hana053/micropost/domain/RelatedUser.kt | springboot-angular2-tutorial | 52,337,279 | false | null | package com.hana053.micropost.domain
data class RelatedUser(
val id: Long,
val name: String,
val email: String?,
override val avatarHash: String,
val isFollowedByMe: Boolean,
val userStats: UserStats,
val relationshipId: Long
) : Avatar {
fun toUser() = User(id, name, email, avatarHash, isFollowedByMe, userStats)
} | 0 | Kotlin | 5 | 11 | c609bfdaa867bd20a29fd4f64ab3a2b159e8c023 | 352 | android-app | MIT License |
app/src/main/kotlin/com/zgsbrgr/demo/fiba/ui/detail/GameInfo.kt | zgsbrgr | 542,563,023 | false | {"Kotlin": 121906, "Shell": 558} | package com.zgsbrgr.demo.fiba.ui.detail
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.zgsbrgr.demo.fiba.databinding.GameInfoBinding
import com.zgsbrgr.demo.fiba.domain.Match
import com.zgsbrgr.demo.fiba.domain.MatchEvent
import com.zgsbrgr.demo.fiba.ui.adapter.MatchEventAdapter
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
@AndroidEntryPoint
class GameInfo : Fragment() {
private var _viewBinding: GameInfoBinding? = null
private val viewBinding get() = _viewBinding!!
private val viewModel by viewModels<GameInfoViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_viewBinding = GameInfoBinding.inflate(inflater, container, false)
viewBinding.eventRv.apply {
layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
addItemDecoration(DividerItemDecoration(requireActivity(), DividerItemDecoration.HORIZONTAL))
}
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val eventList = mutableListOf<MatchEvent>()
val adapter = MatchEventAdapter()
viewBinding.eventRv.adapter = adapter
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect {
it.data?.let { event ->
eventList.add(event)
if (adapter.currentList.isEmpty())
adapter.submitList(eventList)
adapter.notifyItemInserted(eventList.size)
viewBinding.eventRv.scrollToPosition(eventList.size - 1)
}
if (it.error != null)
Toast.makeText(
requireActivity(),
it.error.toString(),
Toast.LENGTH_SHORT
)
.show()
}
}
}
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
viewModel.loadEvents()
}
}
}
override fun onDestroy() {
super.onDestroy()
_viewBinding = null
}
override fun onPause() {
super.onPause()
viewModel.removeUpdates()
}
}
class GamePagerAdapter(fragment: Fragment, private val match: Match) : FragmentStateAdapter(fragment) {
override fun createFragment(position: Int): Fragment {
val fragment =
when (position) {
0 -> {
val f = Roster()
f.arguments = Bundle().apply {
putParcelable("homeTeam", match.home)
putParcelable("awayTeam", match.away)
}
f
}
1 -> {
val f = GameInfo()
f.arguments = Bundle().apply {
putInt(ARG_OBJECT, position)
putString(ARG_MATCH_ID, match.id)
}
f
}
2 -> {
val f = TeamStat()
f.arguments = Bundle().apply {
putParcelable("homeTeam", match.home)
putParcelable("awayTeam", match.away)
}
f
}
else -> {
throw NoSuchElementException("")
}
}
return fragment
}
override fun getItemCount(): Int {
return 3
}
}
| 0 | Kotlin | 0 | 0 | 0c894fea21f565f45cc961510e97b6b1b4eb3d37 | 4,433 | ZGFiba | Apache License 2.0 |
android-common/src/main/kotlin/moe/feng/common/kt/ObjectsUtil.kt | fython | 115,638,922 | false | null | package moe.feng.common.kt
object ObjectsUtil {
fun isNull(obj: Any?): Boolean = obj == null
fun nonNull(obj: Any?): Boolean = obj != null
} | 0 | Kotlin | 1 | 10 | a7c78c1a5ceea35aab3637ec042eced5a05803e1 | 151 | NyanAndroidArch | MIT License |
smartcardreader/src/main/java/com/smartcardreader/CapturedImagesAdapter.kt | ocrsdkapp | 231,261,436 | false | null | package com.smartcardreader
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.li_image.view.*
class CapturedImagesAdapter(var list: ArrayList<String>,var preview : (String)->Unit,var delete : (String)->Unit) :
RecyclerView.Adapter<CapturedImagesAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.li_image, parent, false)
return ViewHolder(view)
}
override fun getItemCount() = list.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Glide.with(holder.itemView.context)
.load(list[position])
.into(holder.itemView.capturedImage)
holder.itemView.remove.setOnClickListener { delete.invoke(list[position]) }
holder.itemView.rootView.setOnClickListener { preview.invoke(list[position]) }
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
} | 0 | Kotlin | 3 | 2 | 8ae910384b7ed9f4ebe962f1013f80af4ef23c03 | 1,147 | ocr_sdk | MIT License |
app/src/main/java/com/android/sample/app/ui/DashboardFragment.kt | alirezaeiii | 450,895,998 | false | {"Kotlin": 41246} | package com.android.sample.app.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.fragment.findNavController
import com.android.sample.app.R
import com.android.sample.app.base.BaseFragment
import com.android.sample.app.base.BaseViewModel
import com.android.sample.app.domain.Dashboard
import com.android.sample.app.ui.theme.ComposeTheme
import com.android.sample.app.ui.common.composeView
import com.android.sample.app.viewmodel.DashboardViewModel
import org.koin.android.viewmodel.ext.android.viewModel
class DashboardFragment : BaseFragment<Dashboard>() {
override val viewModel: BaseViewModel<Dashboard> by viewModel(DashboardViewModel::class)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = composeView {
ComposeTheme {
Scaffold(
topBar = {
TopAppBar(
title = {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Text(text = stringResource(id = R.string.label_dashboard))
}
},
elevation = 8.dp,
modifier = Modifier.clip(
RoundedCornerShape(bottomStart = 18.dp, bottomEnd = 18.dp)
)
)
},
content = {
Content()
})
}
}
@Composable
override fun SuccessScreen(t: Dashboard) {
VerticalCollection(t) { link ->
val destination =
DashboardFragmentDirections.actionDashboardFragmentToSectionFragment(link)
findNavController().navigate(destination)
}
}
} | 0 | Kotlin | 1 | 0 | aa4d6c9b49f59c0b6ba1237f9035e2941f0f4716 | 2,546 | Koin-Compose | The Unlicense |
src/main/kotlin/com/onegravity/sudoku/model/Cell.kt | 1gravity | 407,597,760 | false | {"Kotlin": 148326} | package com.onegravity.sudoku.model
import java.util.*
/**
* A cell of a sudoku grid.
* <p>
* Holds:
* <ul>
* <li>The x and y coordinates (column/row) within the grid
* <li>The current value, or <code>0</code> if the cell is empty
* <li>The bitset of potential values for this cell (the candidates).
* </ul>
*/
class Cell(
val index: Int,
val block: Int,
var isGiven: Boolean = false,
) {
val col = index % 9
val row = index / 9
var value: Int = 0
set(newValue) {
if (newValue in 0..9) field = newValue else throw IllegalArgumentException("value must be between 0 and 9")
potentialValues.clear()
}
/**
* Returns true if no value has been set yet
*/
fun isEmpty() = value == 0
private val potentialValues = BitSet(9)
/**
* Get the potential values for this cell.
*
* The result is returned as a bitset. Each of the bit number 1 to 9 is set if the corresponding value is a
* potential value for this cell. Bit number <tt>0</tt> is not used and ignored.
*
* @return the potential values for this cell
*/
fun getPotentialValues() = potentialValues
/**
* Test whether the given value is a potential value for this cell.
*
* @param value the potential value to test, between 1 and 9, inclusive
*
* @return whether the given value is a potential value for this cell
*/
fun hasPotentialValue(value: Int) = potentialValues[value]
/**
* Add the given value as a potential value for this cell.
*
* @param value the value to add, between 1 and 9, inclusive
*/
fun addPotentialValue(value: Int) {
potentialValues[value] = true
}
/**
* Remove the given value from the potential values of this cell.
*
* @param value the value to remove, between 1 and 9, inclusive
*/
fun removePotentialValue(value: Int) {
potentialValues[value] = false
}
/**
* Remove the given valueS from the potential values of this cell.
*
* @param valuesToRemove the valueS to remove, between 1 and 9, inclusive
*/
fun removePotentialValues(valuesToRemove: BitSet) {
potentialValues.andNot(valuesToRemove)
}
/**
* Delete all potential values of this cell.
*/
fun clearPotentialValues() {
potentialValues.clear()
}
override fun toString() = "$col/$row: $value"
override fun equals(other: Any?) = when(other) {
is Cell -> index == other.index
else -> false
}
override fun hashCode() = index.hashCode()
}
| 0 | Kotlin | 0 | 1 | 4e8bfb119a57a101db4d873bf86cd5722105ebb3 | 2,634 | Dancing-Links-Kotlin | Apache License 2.0 |
src/main/kotlin/com/lykke/matching/engine/outgoing/messages/v2/events/common/CashOut.kt | MyJetWallet | 334,417,928 | true | {"Kotlin": 1903525, "Java": 39278} | package com.lykke.matching.engine.outgoing.messages.v2.events.common
import com.myjetwallet.messages.outgoing.grpc.OutgoingMessages
class CashOut(
val brokerId: String,
val accountId: String,
val walletId: String,
val assetId: String,
val volume: String,
val fees: List<Fee>?
) : EventPart<OutgoingMessages.CashOut.Builder> {
override fun createGeneratedMessageBuilder(): OutgoingMessages.CashOut.Builder {
val builder = OutgoingMessages.CashOut.newBuilder()
builder.setBrokerId(brokerId)
.setAccountId(accountId)
.setWalletId(walletId)
.setAssetId(assetId)
.volume = volume
fees?.forEach { fee ->
builder.addFees(fee.createGeneratedMessageBuilder())
}
return builder
}
} | 0 | Kotlin | 1 | 0 | fad1a43743bd7b833bfa4f1490da5e5350b992ff | 806 | MatchingEngine | MIT License |
domain/src/main/kotlin/com/ferelin/domain/useCases/notifyPrice/SetNotifyPriceUseCase.kt | NikitaFerelin | 339,103,168 | false | null | /*
* Copyright 2021 <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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ferelin.domain.useCases.notifyPrice
import com.ferelin.domain.repositories.NotifyPriceRepo
import com.ferelin.shared.NAMED_EXTERNAL_SCOPE
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Named
class SetNotifyPriceUseCase @Inject constructor(
private val notifyPriceRepo: NotifyPriceRepo,
@Named(NAMED_EXTERNAL_SCOPE) private val externalScope: CoroutineScope
) {
suspend fun set(notify: Boolean) {
externalScope.launch {
notifyPriceRepo.set(notify)
}
}
} | 0 | Kotlin | 3 | 30 | 18670da6124d0328b0d323b675d0bafdb4df45f6 | 1,176 | Android_Stock_Price | Apache License 2.0 |
src/main/kotlin/org/arend/psi/doc/ArendDocReferenceText.kt | JetBrains | 96,068,447 | false | {"Kotlin": 2655823, "Lex": 16187, "Java": 5894, "HTML": 2144, "CSS": 1108, "JavaScript": 713} | package org.arend.psi.doc
import com.intellij.lang.ASTNode
import org.arend.psi.ext.ArendCompositeElementImpl
class ArendDocReferenceText(node: ASTNode) : ArendCompositeElementImpl(node)
| 36 | Kotlin | 12 | 90 | 7a6608a2e44369e11c5baad3ef2928d6f9c971b2 | 189 | intellij-arend | Apache License 2.0 |
app/share/android/app/src/main/kotlin/com/example/share/MainActivity.kt | DahyeonWoo | 426,134,240 | false | {"Dart": 322320, "JavaScript": 145730, "Python": 84711, "Shell": 6223, "Kotlin": 2800, "Dockerfile": 1351, "Swift": 821, "Pug": 272, "CSS": 124, "Objective-C": 77, "HTML": 31} | package com.example.share // com.example.share는 앱에 맞게 수정해줘야 함
import android.content.Intent
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private var sharedData: String = ""
override fun onCreate(
savedInstanceState: Bundle?
) {
super.onCreate(savedInstanceState)
handleIntent()
}
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger,
"com.example.share").setMethodCallHandler { call, result ->
if (call.method == "getSharedData") {
handleIntent()
result.success(sharedData)
sharedData = ""
}
}
}
private fun handleIntent() {
// intent is a property of this activity
// Only process the intent if it's a send intent and it's of type 'text'
if (intent?.action == Intent.ACTION_SEND) {
if (intent.type == "text/plain") {
intent.getStringExtra(Intent.EXTRA_TEXT)?.let { intentData ->
sharedData = intentData
}
}
}
}
}
| 0 | Dart | 0 | 0 | a1d5e52e96d2100847d31800a5587ed9d8bad1cd | 1,384 | FindMap | Apache License 2.0 |
prime-router/src/main/kotlin/messages/ReportFileMessage.kt | CDCgov | 304,423,150 | false | null | package gov.cdc.prime.router.messages
import gov.cdc.prime.router.Topic
/**
* The report content message contains the content of a report that is kept in the service. This message
* is closely aligned with the report_file table.
*
* [reportId] is the UUID of the report.
* [schemaTopic] is the topic of the pipeline
* [schemaName] refers to the schema of the report
* [contentType] is the MIME content name. Usually,
* [content] is a JSON escaped string of the
* [origin] provides information about blob that the content came from
* [request] provides information about the request that created the message.
*/
class ReportFileMessage(
val reportId: String,
val schemaTopic: Topic,
val schemaName: String,
val contentType: String,
val content: String,
val origin: Origin? = null,
val request: Request? = null,
) {
data class Origin(
val bodyUrl: String = "",
val sendingOrg: String = "",
val sendingOrgClient: String = "",
val receivingOrg: String = "",
val receivingOrgSvc: String = "",
val indices: List<Int> = emptyList(),
val createdAt: String = "",
)
data class Request(
val reportId: String = "",
val receiverReportIndices: List<Int>? = emptyList(),
val messageID: String = "",
val senderReportIndices: Int?,
)
} | 978 | null | 39 | 71 | 81f5d3c284982ccdb7f24f36fc69fdd8fac2a919 | 1,371 | prime-reportstream | Creative Commons Zero v1.0 Universal |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/integration/ManageAttendanceRecordsJobIntegrationTest.kt | ministryofjustice | 533,838,017 | false | null | package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.integration
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.jdbc.Sql
import org.springframework.test.web.reactive.server.WebTestClient
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.ActivitySchedule
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.AttendanceStatus
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.ActivityRepository
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.AttendanceRepository
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.events.OutboundEventsPublisher
import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.events.OutboundHMPPSDomainEvent
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
@TestPropertySource(
properties = [
"feature.events.sns.enabled=true",
"feature.event.activities.prisoner.attendance-created=true",
"feature.event.activities.prisoner.attendance-amended=true",
"feature.event.activities.prisoner.attendance-expired=true",
],
)
class ManageAttendanceRecordsJobIntegrationTest : IntegrationTestBase() {
@MockBean
private lateinit var eventsPublisher: OutboundEventsPublisher
private val eventCaptor = argumentCaptor<OutboundHMPPSDomainEvent>()
@Autowired
private lateinit var attendanceRepository: AttendanceRepository
@Autowired
private lateinit var activityRepository: ActivityRepository
@Sql("classpath:test_data/seed-activity-id-4.sql")
@Test
fun `Four attendance records are created, 2 for Maths level 1 AM and 2 for Maths Level 1 PM and four create events are emitted`() {
assertThat(attendanceRepository.count()).isZero
with(activityRepository.findById(4).orElseThrow()) {
assertThat(description).isEqualTo("Maths Level 1")
assertThat(schedules()).hasSize(2)
with(schedules().findByDescription("Maths AM")) {
assertThat(allocations()).hasSize(2)
assertThat(instances()).hasSize(1)
assertThat(instances().first().attendances).isEmpty()
}
with(schedules().findByDescription("Maths PM")) {
assertThat(allocations()).hasSize(2)
assertThat(instances()).hasSize(1)
assertThat(instances().first().attendances).isEmpty()
}
}
webTestClient.manageAttendanceRecords()
with(activityRepository.findById(4).orElseThrow()) {
with(schedules().findByDescription("Maths AM")) {
assertThat(instances().first().attendances).hasSize(2)
}
with(schedules().findByDescription("Maths PM")) {
assertThat(instances().first().attendances).hasSize(2)
}
}
assertThat(attendanceRepository.count()).isEqualTo(4)
verify(eventsPublisher, times(4)).send(eventCaptor.capture())
eventCaptor.allValues.map {
assertThat(it.eventType).isEqualTo("activities.prisoner.attendance-created")
assertThat(it.occurredAt).isCloseTo(LocalDateTime.now(), Assertions.within(60, ChronoUnit.SECONDS))
assertThat(it.description).isEqualTo("A prisoner attendance has been created in the activities management service")
}
}
@Sql("classpath:test_data/seed-activity-id-4.sql")
@Test
fun `Multiple calls on same day does not result in duplicate attendances`() {
assertThat(attendanceRepository.count()).isZero
webTestClient.manageAttendanceRecords()
webTestClient.manageAttendanceRecords()
assertThat(attendanceRepository.count()).isEqualTo(4)
}
@Sql("classpath:test_data/seed-activity-id-5.sql")
@Test
fun `No attendance records are created for gym induction AM when attendance not required on activity`() {
assertThat(attendanceRepository.count()).isZero
with(activityRepository.findById(5).orElseThrow()) {
assertThat(description).isEqualTo("Gym induction")
assertThat(schedules()).hasSize(1)
with(schedules().findByDescription("Gym induction AM")) {
assertThat(allocations()).hasSize(2)
assertThat(instances()).hasSize(1)
assertThat(instances().first().attendances).isEmpty()
}
}
webTestClient.manageAttendanceRecords()
with(activityRepository.findById(5).orElseThrow()) {
with(schedules().findByDescription("Gym induction AM")) {
assertThat(instances().first().attendances).isEmpty()
}
}
assertThat(attendanceRepository.count()).isZero
}
@Sql("classpath:test_data/seed-attendances-yesterdays-completed.sql")
@Test
fun `Yesterdays completed attendance records remain in status COMPLETED and no sync events are emitted`() {
val yesterday = LocalDate.now().minusDays(1)
attendanceRepository.findAll().forEach {
assertThat(it.status()).isEqualTo(AttendanceStatus.COMPLETED)
assertThat(it.scheduledInstance.sessionDate).isEqualTo(yesterday)
}
webTestClient.manageAttendanceRecordsWithExpiry()
attendanceRepository.findAll().forEach {
assertThat(it.status()).isEqualTo(AttendanceStatus.COMPLETED)
}
verifyNoInteractions(eventsPublisher)
}
@Sql("classpath:test_data/seed-attendances-yesterdays-waiting.sql")
@Test
fun `Yesterdays waiting attendance records emit an expired sync event and remain in WAITING status`() {
val yesterday = LocalDate.now().minusDays(1)
attendanceRepository.findAll().forEach {
assertThat(it.status()).isEqualTo(AttendanceStatus.WAITING)
assertThat(it.scheduledInstance.sessionDate).isEqualTo(yesterday)
}
webTestClient.manageAttendanceRecordsWithExpiry()
attendanceRepository.findAll().forEach {
assertThat(it.status()).isEqualTo(AttendanceStatus.WAITING)
}
verify(eventsPublisher).send(eventCaptor.capture())
eventCaptor.allValues.map {
assertThat(it.eventType).isEqualTo("activities.prisoner.attendance-expired")
assertThat(it.occurredAt).isCloseTo(LocalDateTime.now(), Assertions.within(60, ChronoUnit.SECONDS))
assertThat(it.description).isEqualTo("An unmarked prisoner attendance has been expired in the activities management service")
}
}
@Sql("classpath:test_data/seed-attendances-two-days-old-waiting.sql")
@Test
fun `Two day old waiting attendance records do not emit an expired sync event`() {
val twoDaysAgo = LocalDate.now().minusDays(2)
attendanceRepository.findAll().forEach {
assertThat(it.status()).isEqualTo(AttendanceStatus.WAITING)
assertThat(it.scheduledInstance.sessionDate).isEqualTo(twoDaysAgo)
}
webTestClient.manageAttendanceRecordsWithExpiry()
attendanceRepository.findAll().forEach {
assertThat(it.status()).isEqualTo(AttendanceStatus.WAITING)
}
verifyNoInteractions(eventsPublisher)
}
@Sql("classpath:test_data/seed-attendances-for-today.sql")
@Test
fun `Attendance records for today will not emit an expired sync event - too early`() {
val today = LocalDate.now()
attendanceRepository.findAll().forEach {
assertThat(it.status()).isIn(AttendanceStatus.WAITING, AttendanceStatus.COMPLETED)
assertThat(it.scheduledInstance.sessionDate).isEqualTo(today)
}
webTestClient.manageAttendanceRecordsWithExpiry()
attendanceRepository.findAll().forEach {
assertThat(it.status()).isIn(AttendanceStatus.WAITING, AttendanceStatus.COMPLETED)
}
verifyNoInteractions(eventsPublisher)
}
private fun List<ActivitySchedule>.findByDescription(description: String) =
first { it.description.uppercase() == description.uppercase() }
private fun WebTestClient.manageAttendanceRecords() {
post()
.uri("/job/manage-attendance-records")
.accept(MediaType.TEXT_PLAIN)
.exchange()
.expectStatus().isCreated
Thread.sleep(1000)
}
private fun WebTestClient.manageAttendanceRecordsWithExpiry() {
post()
.uri("/job/manage-attendance-records?withExpiry=true")
.accept(MediaType.TEXT_PLAIN)
.exchange()
.expectStatus().isCreated
Thread.sleep(1000)
}
}
| 8 | Kotlin | 0 | 1 | 91047f3afed4397efa1861f9037db08952f95260 | 8,529 | hmpps-activities-management-api | MIT License |
kaddi-dsl/src/test/kotlin/audio/rabid/kaddi/Example.kt | rabidaudio | 221,611,149 | false | {"Kotlin": 55565} | package audio.rabid.kaddi
import audio.rabid.kaddi.dsl.*
object Example {
interface LoggerEndpoint {
fun handleLog(message: String)
}
class Logger(val endpoints: List<LoggerEndpoint>) {
fun log(message: String) {
for (endpoint in endpoints) {
endpoint.handleLog(message)
}
}
}
val LoggingModule = module("Logging") {
declareSetBinding<LoggerEndpoint>()
bind<Logger>().with {
Logger(endpoints = setInstance<LoggerEndpoint>().toList())
}
}
interface IDatabase
class Database : IDatabase, ScopeClosable {
var isClosed = false
override fun onScopeClose() {
isClosed = true
}
}
class DatabaseProvider : Provider<IDatabase> {
override fun get(): IDatabase = Database()
}
class ALoggerEndpoint : LoggerEndpoint {
override fun handleLog(message: String) {
// handle
}
}
val DataModule = module("Data") {
import(LoggingModule)
bind<IDatabase>().withSingleton(DatabaseProvider())
bindIntoSet<LoggerEndpoint>().with { ALoggerEndpoint() }
}
class Application {
fun onApplicationCreate() {
Kaddi.createScope(this, AppModule)
}
}
val AppModule = module("App") {
import(LoggingModule)
import(DataModule)
bind<String>("AppName").toInstance("MyApp")
}
class Activity1(val application: Application) {
val viewModel by inject<Activity1ViewModel>()
val logger by inject<Logger>()
fun onCreate() {
Kaddi.getScope(application)
.createChildScope(this, Activity1Module)
.inject(this)
logger.log("foo")
}
fun onDestroy() {
Kaddi.closeScope(this)
}
}
class Activity1ViewModel(val database: IDatabase, val appName: String)
val Activity1Module = module("Activity1") {
require<IDatabase>()
require<String>("AppName")
bind<Activity1ViewModel>().withSingleton {
Activity1ViewModel(
database = instance(),
appName = instance("AppName")
)
}
}
class Fragment {
val viewModel by inject<FragmentViewModel>()
fun onAttach(activity: Any) {
Kaddi.getScope(activity)
.createChildScope(this, FragmentModule)
.inject(this)
}
fun onDetach() {
Kaddi.closeScope(this)
}
}
class FragmentViewModel(val logger: Logger)
val FragmentModule = module("Fragment") {
require<Logger>()
bind<FragmentViewModel>().withSingleton {
FragmentViewModel(logger = instance())
}
}
class Activity2ViewModel(val logger: Logger, val database: IDatabase)
val Activity2Module = module("Activity2") {
require<Logger>()
require<IDatabase>()
bind<Activity2ViewModel>().withSingleton {
Activity2ViewModel(
logger = instance(),
database = instance()
)
}
}
class Activity2(val application: Application) {
val viewModel by inject<Activity2ViewModel>()
fun onCreate() {
Kaddi.getScope(application)
.createChildScope(this, Activity2Module)
.inject(this)
}
fun onDestroy() {
Kaddi.closeScope(this)
}
}
}
| 0 | Kotlin | 0 | 0 | 295e065f91ce86d640bd688b63061090a23b7998 | 3,602 | kaddi | Apache License 2.0 |
presentation/src/main/java/appus/software/githubusers/presentation/views/base/BaseActivity.kt | appus-studio | 180,989,176 | false | null | package appus.software.githubusers.presentation.views.base
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.NavController
import appus.software.githubusers.BR
import appus.software.githubusers.presentation.views.base.model.NavigationModel
import appus.software.githubusers.presentation.views.base.model.ToastModel
import org.koin.androidx.viewmodel.ext.android.viewModelByClass
import kotlin.reflect.KClass
abstract class BaseActivity<D : ViewDataBinding, ViewModelType : BaseViewModel>(clazz: KClass<ViewModelType>) :
AppCompatActivity(), ViewInterface, BaseView {
lateinit var viewDataBinding: D
open val vm: ViewModelType by viewModelByClass(clazz)
private var mLoader: View? = null
protected lateinit var navController: NavController
/**
* Override for set binding variable
*
* @return variable id
*/
val bindingViewModelId: Int = BR.vm
/**
* @return layout resource id
*/
@get:LayoutRes
abstract val layoutId: Int
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewDataBinding = DataBindingUtil.setContentView(this, layoutId)
viewDataBinding.lifecycleOwner = this
performDataBinding(viewDataBinding)
lifecycle.addObserver(vm)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
attachViews()
initViews(savedInstanceState)
super.onPostCreate(savedInstanceState)
}
protected fun initViews(savedInstanceState: Bundle?) {
}
protected open fun attachViews() {
}
/**
* @param viewDataBinding ViewDataBinding data of a screen
*/
protected fun performDataBinding(viewDataBinding: D) {
viewDataBinding.setVariable(bindingViewModelId, vm)
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(vm)
}
/**
* Show toast message
* @param toastModel Model with settings for toast
*/
override fun showToast(toastModel: ToastModel) {
val message: String? = if (toastModel.idResMessage != null) {
getString(toastModel.idResMessage!!)
} else {
toastModel.message
}
if (!message.isNullOrEmpty()) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
/**
* Screen navigation
* @param navModel Model with settings for navController
*/
override fun navigateTo(navModel: NavigationModel) {
}
}
interface ViewInterface : LifecycleOwner | 0 | Kotlin | 0 | 1 | 72b630dbaffe7e2d6c08a81ac48d551f8578b627 | 2,836 | top-github-contributors-android | Apache License 2.0 |
src/main/java/com/mvv/gui/javafx/winOS.kt | odisseylm | 679,732,600 | false | {"Kotlin": 1311124, "CSS": 32895, "Java": 6651} | package com.mvv.gui.javafx
import com.mvv.gui.util.findReflectionField
import com.mvv.win.UseWindowDarkMode
import javafx.stage.Window
import org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS
/*
import com.sun.jna.Library
import com.sun.jna.PointerType
import com.sun.jna.platform.win32.WinDef
import javafx.stage.Window
import java.lang.annotation.Native
fun getNativeHandleForStage(stage: Stage): WinDef.HWND? {
try {
val getPeer: Method = Window::class.java.getDeclaredMethod("getPeer", null)
getPeer.isAccessible = true
val tkStage = getPeer.invoke(stage)
val getRawHandle = tkStage.javaClass.getMethod("getRawHandle")
getRawHandle.isAccessible = true
val pointer: Pointer = Pointer(getRawHandle.invoke(tkStage) as Long)
return HWND(pointer)
} catch (ex: Exception) {
System.err.println("Unable to determine native handle for window")
return null
}
}
fun setDarkMode(stage: Stage, darkMode: Boolean) {
val hwnd: Any = FXWinUtil.getNativeHandleForStage(stage)
val dwmapi: Any = Dwmapi.INSTANCE
val darkModeRef: WinDef.BOOLByReference = BOOLByReference(BOOL(darkMode))
dwmapi.DwmSetWindowAttribute(hwnd, 20, darkModeRef, Native.getNativeSize(WinDef.BOOLByReference::class.java))
forceRedrawOfWindowTitleBar(stage)
}
private fun forceRedrawOfWindowTitleBar(stage: Stage) {
val maximized = stage.isMaximized
stage.isMaximized = !maximized
stage.isMaximized = maximized
}
interface Dwmapi : Library {
fun DwmSetWindowAttribute(hwnd: WinDef.HWND?, dwAttribute: Int, pvAttribute: PointerType?, cbAttribute: Int): Int
companion object {
val INSTANCE: Dwmapi = Native.load("dwmapi", Dwmapi::class.java)
}
}
FXWinUtil.setDarkMode(stage, true);
*/
val Window.handle: Long? get() {
val wnd = this
// this (javafx.stage.Stage)
// -> peer (com.sun.javafx.tk.quantum.WindowStage)
// -> platformWindow (com.sun.glass.ui.win.WinWindow)
// -> private long ptr;
// com.sun.javafx.tk.quantum.WindowStage
val peer = wnd.findReflectionField("peer", "impl_peer", "peer_impl")?.get(wnd) ?: return null
// com.sun.glass.ui.win.WinWindow
val winWnd = peer.findReflectionField("platformWindow")?.get(peer) ?: return null
// long
//val hWnd = winWnd.findReflectionField("ptr", "handle", "hWnd")?.get(winWnd) as Long?
val hWnd = (winWnd as com.sun.glass.ui.Window).rawHandle // .nativeHandle
return hWnd
}
fun setDarkTitle(wnd: Window): Boolean {
if (!IS_OS_WINDOWS) return false
val hWnd = wnd.handle
println("### hWnd: ${hWnd?.toString(16)}")
if (hWnd == null) {
return false
}
UseWindowDarkMode(hWnd)
return true
}
| 0 | Kotlin | 0 | 0 | 288fa12db9e895b2a445dd5e1eb7e15449876277 | 2,762 | learn-words | Creative Commons Attribution 3.0 Unported |
buildSrc/src/main/kotlin/Versions.kt | h4rdc0m | 300,855,749 | true | {"Kotlin": 440791, "JavaScript": 1700, "CSS": 1372, "HTML": 670} | object Versions {
const val KOTLIN_JS_WRAPPERS = "pre.110-kotlin-1.3.72"
const val REACT_VERSION = "16.13.1"
}
| 0 | null | 0 | 0 | da38c43490d7578e2d51747ac2373d86aa34f2e4 | 119 | kotlin-react-bootstrap | MIT License |
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/ui/model/ConsumptionPresentationStyle.kt | ryanw-mobile | 794,752,204 | false | {"Kotlin": 518481, "Swift": 693} | /*
* Copyright (c) 2024. Ryan Wong
* https://github.com/ryanw-mobile
* Sponsored by RW MobiMedia UK Limited
*
*/
package com.rwmobi.kunigami.ui.model
import androidx.compose.runtime.Immutable
import com.rwmobi.kunigami.domain.model.consumption.ConsumptionDataGroup
import kunigami.composeapp.generated.resources.Res
import kunigami.composeapp.generated.resources.presentation_style_day_half_hourly
import kunigami.composeapp.generated.resources.presentation_style_month_thirty_days
import kunigami.composeapp.generated.resources.presentation_style_month_weeks
import kunigami.composeapp.generated.resources.presentation_style_week_seven_days
import kunigami.composeapp.generated.resources.presentation_style_year_twelve_months
import org.jetbrains.compose.resources.StringResource
@Immutable
enum class ConsumptionPresentationStyle(val stringResource: StringResource) {
DAY_HALF_HOURLY(stringResource = Res.string.presentation_style_day_half_hourly),
WEEK_SEVEN_DAYS(stringResource = Res.string.presentation_style_week_seven_days),
MONTH_WEEKS(stringResource = Res.string.presentation_style_month_weeks),
MONTH_THIRTY_DAYS(stringResource = Res.string.presentation_style_month_thirty_days),
YEAR_TWELVE_MONTHS(stringResource = Res.string.presentation_style_year_twelve_months),
;
/***
* UI uses interprets the grouping differently. This is to map to the Enum that the API expects.
*/
fun getConsumptionDataGroup(): ConsumptionDataGroup {
return when (this) {
DAY_HALF_HOURLY -> ConsumptionDataGroup.HALF_HOURLY
WEEK_SEVEN_DAYS -> ConsumptionDataGroup.DAY
MONTH_WEEKS -> ConsumptionDataGroup.WEEK
MONTH_THIRTY_DAYS -> ConsumptionDataGroup.DAY
YEAR_TWELVE_MONTHS -> ConsumptionDataGroup.MONTH
}
}
}
| 24 | Kotlin | 0 | 2 | 241e0ea08e92d663e8c9fb2732627dc054e24db6 | 1,827 | OctoMeter | MIT License |
src/main/kotlin/io/mahdibohloul/kpringmediator/core/Exceptions.kt | mahdibohloul | 410,815,414 | false | {"Kotlin": 32862} | package io.mahdibohloul.kpringmediator.core
/**
* Basic exception type of the Kpring MediatR
*
* @author <NAME>
* @param message Exception message
*/
open class KpringMediatorException(message: String?) : RuntimeException(message)
/**
* Exception thrown when there is not a [RequestHandler] available for a [Request]
*
* @author <NAME>
*/
class NoRequestHandlerException(message: String?) : KpringMediatorException(message)
/**
* Exception thrown when there is an attempt to register a [RequestHandler] for a
* [Request] that already has a [RequestHandler] registered.
*
* @author <NAME>
*/
class DuplicateRequestHandlerRegistrationException(message: String?) : KpringMediatorException(message)
/**
* Exception thrown when there are no [NotificationHandler]s available for an [Notification]
*
* @author <NAME>
*/
class NoNotificationHandlersException(message: String?) : KpringMediatorException(message)
/**
* Exception thrown when there is not a [CommandHandler] available for a [Command]
*
* @author <NAME>
*/
class NoCommandHandlerException(message: String?) : KpringMediatorException(message)
/**
* Exception thrown when there is an attempt to register a [CommandHandler] for a
* [Command] that already has a [CommandHandler] registered.
*
* @author <NAME>
*/
class DuplicateCommandHandlerRegistrationException(message: String?) : KpringMediatorException(message) | 0 | Kotlin | 1 | 5 | fe1814899cb720ff6b67e0053500a9377024ed91 | 1,404 | Kpring-mediatR | MIT License |
android/src/main/java/com/chrynan/video/di/module/fragment/UserContentFragmentModule.kt | chRyNaN | 174,161,260 | false | null | package com.chrynan.video.di.module.fragment
import com.chrynan.video.ui.view.UserContentView
import com.chrynan.video.ui.fragment.UserContentFragment
import dagger.Binds
import dagger.Module
@Module
internal abstract class UserContentFragmentModule {
@Binds
abstract fun bindUserContentView(fragment: UserContentFragment): UserContentView
} | 0 | Kotlin | 0 | 8 | 63456dcfdd57dbee9ff02b2155b7e1ec5761db81 | 352 | Video | Apache License 2.0 |
app/src/main/java/org/p2p/wallet/history/repository/local/db/entities/embedded/TransactionTypeEntity.kt | p2p-org | 306,035,988 | false | {"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252} | package org.p2p.wallet.history.repository.local.db.entities.embedded
import androidx.room.TypeConverter
enum class TransactionTypeEntity(val typeStr: String) {
UNKNOWN("unknown"),
SWAP("swap"),
TRANSFER("transfer"),
TRANSFER_CHECKED("transferChecked"),
REN_BTC_TRANSFER("transfer"),
CREATE_ACCOUNT("create"),
CLOSE_ACCOUNT("closeAccount");
object Converter {
@TypeConverter
fun toEntity(typeStr: String): TransactionTypeEntity = enumValueOf(typeStr)
@TypeConverter
fun fromEntity(value: TransactionTypeEntity): String = value.typeStr
}
}
| 8 | Kotlin | 18 | 34 | d091e18b7d88c936b7c6c627f4fec96bcf4a0356 | 610 | key-app-android | MIT License |
work/work-runtime/src/main/java/androidx/work/ExperimentalConfigurationApi.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work
/**
* Annotation indicating experimental API for new WorkManager's Configuration APIs.
*
* These APIs allow fine grained tuning WorkManager's behavior. However, full effects of these
* flags on OS health and WorkManager's throughput aren't fully known and currently are being
* explored. After the research either the best default value for a flag will be chosen and then
* associated API will be removed or the guidance on how to choose a value depending on app's
* specifics will developed and then associated API will be promoted to stable.
*
* As a result these APIs annotated with `ExperimentalConfigurationApi` requires opt-in
*/
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY,
AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.CLASS)
@RequiresOptIn(level = RequiresOptIn.Level.WARNING)
annotation class ExperimentalConfigurationApi
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 1,547 | androidx | Apache License 2.0 |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/features/PixelGrabber.kt | XaverianTeamRobotics | 356,899,269 | false | {"Java Properties": 2, "PowerShell": 2, "XML": 25, "Shell": 3, "Gradle": 7, "Markdown": 6, "Batchfile": 1, "Text": 4, "Ignore List": 1, "Java": 206, "CODEOWNERS": 1, "YAML": 3, "Kotlin": 157} | package org.firstinspires.ftc.teamcode.features
import org.firstinspires.ftc.teamcode.internals.features.Buildable
import org.firstinspires.ftc.teamcode.internals.features.Feature
import org.firstinspires.ftc.teamcode.internals.hardware.Devices
/**
* This controls the pixel grabber.
*
*
* Connections: Uses the right servo in port 0, the left servo in port 1, and a controller.
*
*
* Controls: Use the right bumper to close the grabber or the left bumper to open it.
*/
class PixelGrabber : Feature(), Buildable {
var homePos0: Double = 70.0
var homePos1: Double = 30.0
var closePos0: Double = 62.5
var closePos1: Double = 41.5
override fun build() {
manualClose()
}
override fun loop() {
if (Devices.controller1.rightBumper) {
manualClose()
}
if (Devices.controller1.leftBumper) {
manualOpen()
}
}
private fun manualOpen() {
Devices.servo1.position = homePos1
Devices.servo0.position = homePos0
}
private fun manualClose() {
Devices.servo1.position = closePos1
Devices.servo0.position = closePos0
}
}
| 1 | null | 1 | 1 | 349cadebeacc12b05476b3f7ca557916be253cd7 | 1,161 | FtcRobotController | BSD 3-Clause Clear License |
server/src/main/kotlin/vr/Main.kt | tlaukkan | 62,936,064 | false | {"Gradle": 3, "Text": 2, "Ignore List": 1, "YAML": 1, "Markdown": 1, "Kotlin": 108, "INI": 1, "HTML": 2, "Wavefront Object": 4, "COLLADA": 1, "JavaScript": 6, "Java": 2, "JSON": 156} | package vr
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import logger
import org.apache.commons.io.FileUtils
import vr.config.ServerConfig
import vr.config.ServersConfig
import vr.network.NetworkServer
import vr.network.model.DataVector3
import vr.network.model.LightFieldNode
import vr.network.model.PrimitiveNode
import vr.server.VrServer
import vr.storage.IdentityStorage
import java.io.File
import java.nio.charset.Charset
import java.util.*
import java.util.logging.Logger
import javax.vecmath.AxisAngle4d
import javax.vecmath.Quat4d
val IDENTITY_STORE = IdentityStorage()
private val log = Logger.getLogger("vr.main")
fun main(args : Array<String>) {
var servers = configureServers(".")
val refreshTimeMillis = 300L
var startTimeMillis = System.currentTimeMillis()
while (true) {
updateCellPrimeNodes(servers, startTimeMillis)
Thread.sleep(refreshTimeMillis)
}
}
fun configureServers(path: String) : Map<String, VrServer> {
val string = FileUtils.readFileToString(File("$path/servers.yaml"), Charset.forName("UTF-8"))
val mapper = ObjectMapper(YAMLFactory())
val serversConfig = mapper.readValue(string, ServersConfig::class.java)
val servers: MutableMap<String, VrServer> = mutableMapOf()
for (serverConfig in serversConfig.servers) {
log.info("Starting server ${serverConfig.name} at ${serverConfig.uri}")
val server = VrServer(serverConfig.uri)
// Configure server cells and neighbouring cells
server.configureCells(serverConfig)
// Load server cell contents
server.load(path)
// Startup server
server.startup()
// Store server to servers map.
servers[serverConfig.name] = server
}
return servers
}
private fun updateCellPrimeNodes(servers: Map<String, VrServer>, startTimeMillis: Long) {
val timeMillis = System.currentTimeMillis() - startTimeMillis
val angle = (timeMillis / 20000.0) * 2 * Math.PI
val axisAngle = AxisAngle4d(0.0, 1.0, 0.0, angle)
val orientation = Quat4d()
orientation.set(axisAngle)
for (server in servers.values) {
for (cell in server.networkServer.getCells()) {
if (cell.remote) {
continue
}
cell.primeNode.orientation.x = orientation.x
cell.primeNode.orientation.y = orientation.y
cell.primeNode.orientation.z = orientation.z
cell.primeNode.orientation.w = orientation.w
cell.primeNode.scale.x = 0.1
cell.primeNode.scale.y = 0.1
cell.primeNode.scale.z = 0.1
server.networkServer.processReceivedNodes(mutableListOf(cell.primeNode))
}
}
} | 0 | JavaScript | 0 | 1 | 4067f653eef50e93aeaa7a5171709e6eb9dee005 | 2,779 | kotlin-web-vr | MIT License |
src/main/kotlin/me/zeroeightsix/waypoints/impl/screen/NewWaypointScreen.kt | zeroeightysix | 254,099,521 | false | {"Gradle": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 2, "JSON": 3, "Kotlin": 15} | package me.zeroeightsix.waypoints.impl.screen
import me.zeroeightsix.waypoints.api.WaypointRenderer
import me.zeroeightsix.waypoints.api.Waypoints
import me.zeroeightsix.waypoints.impl.WaypointImpl
import net.minecraft.client.MinecraftClient
import net.minecraft.text.TranslatableText
import net.minecraft.util.math.Vec3d
import org.lwjgl.glfw.GLFW
import spinnery.client.BaseScreen
import spinnery.client.TextRenderer
import spinnery.widget.*
import spinnery.widget.api.Position
import spinnery.widget.api.Size
import spinnery.widget.api.WLayoutElement
import spinnery.widget.api.WPositioned
import kotlin.math.roundToInt
class NewWaypointScreen : BaseScreen() {
private fun Position.add(x: Int, y: Int): Position = add(x, y, 0)
private fun WLayoutElement.lower(yOffset: Int): Position = Position.ofBottomLeft(this).add(0, yOffset)
private fun WAbstractTextEditor.active(active: Boolean = true) = setActive<WAbstractTextEditor>(active)
private fun WAbstractWidget.nextTo(xOffset: Int): Position = Position.ofTopRight(this).add(xOffset, 0, 0)
private fun WAbstractTextEditor.tabNext(next: WAbstractTextEditor, lamda: (WAbstractTextEditor, Int, Int, Int) -> Unit = {_,_,_,_ -> }) = setOnKeyPressed<WAbstractTextEditor> { widget, keyPressed, character, keyModifier ->
if (keyPressed == GLFW.GLFW_KEY_TAB) {
future = {
active(false)
next.active()
}
} else {
lamda(widget, keyPressed, character, keyModifier)
}
}
private var future: () -> Unit = {};
init {
val panel = `interface`.createChild(
{ WPanel() },
Position.ORIGIN,
Size.of(200, 108)
).setOnAlign<WPanel> { it.center() }
panel.center()
val label = panel.createChild(
{ WStaticText() },
Position.of(panel).add(6, 8)
).setText<WStaticText>(TranslatableText("gui.waypoints.new_waypoint.label_new"))
val nameField = panel.createChild(
{ WTextField() },
label.lower(8),
Size.of(200 - 6 * 2, 16)
).active()
val createButtonText = TranslatableText("gui.waypoints.new_waypoint.create_button")
val createButtonSize = Size.of(TextRenderer.width(createButtonText) + 6, 16)
val createButton = panel.createChild(
{ WButton() },
Position.ofTopRight(panel).add(-(6 + createButtonSize.width), 6),
createButtonSize
).setLabel<WButton>(createButtonText)
val xLabel = panel.createChild(
{ WCenteredText() },
nameField.lower(10),
Size.of(0, 16)
).setText<WStaticText>("X")
val yLabel = panel.createChild(
{ WCenteredText() },
xLabel.lower(8),
Size.of(0, 16)
).setText<WStaticText>("Y")
val zLabel = panel.createChild(
{ WCenteredText() },
yLabel.lower(8),
Size.of(0, 16)
).setText<WStaticText>("Z")
val xField = panel.createChild(
{ WNumberField() },
xLabel.nextTo(12),
Size.of(60, 16)
).setText<WNumberField>(MinecraftClient.getInstance().player!!.blockPos.x.toString())
val yField = panel.createChild(
{ WNumberField() },
yLabel.nextTo(12),
Size.of(60, 16)
).setText<WNumberField>(MinecraftClient.getInstance().player!!.eyeY.roundToInt().toString())
val zField = panel.createChild(
{ WNumberField() },
zLabel.nextTo(12),
Size.of(60, 16)
).setText<WNumberField>(MinecraftClient.getInstance().player!!.blockPos.z.toString())
val onComplete = {
val name = nameField.text
val x = xField.text.toDouble() + .5
val y = yField.text.toDouble()
val z = zField.text.toDouble() + .5
val pos = Vec3d(x, y, z)
Waypoints.accessor.addWaypoint(
WaypointImpl(pos, name, WaypointRenderer.default)
)
onClose()
}
createButton.setOnMouseClicked<WButton> { _, _, _, _ -> onComplete() }
// Tab order
nameField.tabNext(xField) { _, keyPressed, _, _ ->
if (keyPressed == GLFW.GLFW_KEY_ENTER) {
onComplete()
}
}
xField.tabNext(yField)
yField.tabNext(zField)
zField.tabNext(nameField)
}
override fun keyPressed(keyCode: Int, character: Int, keyModifier: Int): Boolean {
return super.keyPressed(keyCode, character, keyModifier).also {
future()
future = {}
}
}
}
| 1 | null | 1 | 1 | d95b602229ec01cbfa8cffb29763e4804ce9c693 | 4,720 | fabric-waypoints | Creative Commons Zero v1.0 Universal |
app/src/main/java/de/circuitco/bellbox/listfrags/PushCategoryFragment.kt | somehibs | 204,929,236 | false | null | package de.circuitco.bellbox.listfrags
import android.annotation.SuppressLint
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import de.circuitco.bellbox.BellboxFragment
import de.circuitco.bellbox.MainActivity
import de.circuitco.bellbox.R
import de.circuitco.bellbox.model.AppDatabase
import de.circuitco.bellbox.service.PushService
import kotlinx.android.synthetic.main.bells.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
@SuppressLint("SetTextI18n")
class PushCategoryFragment : BellboxFragment(), OnCategoryClick, Observer<Long> {
override fun onChanged(t: Long?) {
refresh()
}
override fun getBarTitle(): String = "Inbox"
override fun click(category: String) {
(activity as MainActivity).setFrag(PushFragment.new(category))
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.bells, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
PushService.changed.observe(this, this)
list.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
}
}
override fun refresh() {
super.refresh()
// Refresh from the server
GlobalScope.launch {
refreshFromDatabase()
}
}
private fun refreshFromDatabase() {
val senderMap = HashMap<String, Long>()
val senders = AppDatabase.getDatabase(context).pushDao().findSenders()
for (sender in senders) {
if (sender == null) {
continue
}
val count = AppDatabase.getDatabase(context).pushDao().countBySender(sender)
senderMap[sender] = count
}
val adapter = PushCategoryListAdapter(senders, senderMap, this)
activity?.runOnUiThread {
list.adapter = adapter
}
}
}
interface OnCategoryClick {
fun click(category: String)
}
class PushCategoryListAdapter(
private val senders: List<String>,
private val map: Map<String, Long>,
private val click :OnCategoryClick
) : RecyclerView.Adapter<PushCategoryViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PushCategoryViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.bell_item, parent, false)
return PushCategoryViewHolder(view, click)
}
override fun getItemCount(): Int {
return map.size
}
override fun onBindViewHolder(holder: PushCategoryViewHolder, position: Int) {
val thisName = senders[position]
val thisObject = map[thisName]
holder.bind(thisName, thisObject)
}
}
data class PushCategoryViewHolder(var view: View,
var clickParent: OnCategoryClick,
var name: TextView? = view.findViewById(R.id.name),
var type: TextView? = view.findViewById(R.id.type),
var key: TextView? = view.findViewById(R.id.key)
) : RecyclerView.ViewHolder(view), View.OnClickListener {
var sender = ""
override fun onClick(v: View?) {
clickParent.click(sender)
}
fun bind(sender: String, size: Long?) {
this.sender = sender
name?.text = sender
type?.text = "${size.toString()} push notifications"
view.setOnClickListener(this)
}
}
| 1 | null | 1 | 1 | e4ba8a49547eebe933648a787e3c311a5692e0d6 | 3,841 | bellbox-android-client | BSD Zero Clause License |
idea/idea-completion/testData/basic/multifile/StaticMembersOfNotImportedClassFromKotlin/StaticMembersOfNotImportedClassFromKotlin.dependency.kt | JakeWharton | 99,388,807 | true | null | package foo
class Bar {
companion object {
fun bfun() {}
val bval = 99
const val bconst = 100
}
class FooBar {
}
}
// ALLOW_AST_ACCESS | 0 | Kotlin | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 178 | kotlin | Apache License 2.0 |
cache/src/main/kotlin/org/brainail/everboxing/lingo/cache/db/dao/BaseDao.kt | brainail | 106,741,862 | 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 org.brainail.everboxing.lingo.cache.db.dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy.IGNORE
import androidx.room.OnConflictStrategy.REPLACE
import androidx.room.Update
interface BaseDao<T> {
@Insert(onConflict = IGNORE)
fun insert(obj: T): Long
@Insert(onConflict = IGNORE)
fun insert(vararg obj: T)
@Insert(onConflict = IGNORE)
fun insert(obj: List<T>)
@Insert(onConflict = REPLACE)
fun insertOrRecreate(obj: List<T>)
@Update(onConflict = REPLACE)
fun updateOrRecreate(obj: T): Int
@Delete
fun delete(obj: T)
}
| 6 | null | 1 | 2 | d71cf6dec0c0c7ba4d80666869b4c91f60a599f2 | 1,220 | .lingo | Apache License 2.0 |
app/src/main/kotlin/eldp/robotminediffuser/data/CloseClawCommand.kt | ysuo85 | 97,416,205 | false | {"Gradle": 3, "XML": 11, "Java Properties": 5, "Shell": 2, "Text": 1, "Ignore List": 2, "Batchfile": 2, "Markdown": 1, "Proguard": 1, "Kotlin": 20, "Java": 3} | package eldp.robotminediffuser.data
/**
* Created by mattdarc on 7/22/17.
*/
data class CloseClawCommand (val close: Boolean)
| 1 | null | 1 | 1 | 1d6ca8c0bfa6ea17a39c781d738840dd41bb5ddf | 129 | RobotMineDiffuser | MIT License |
bbfgradle/tmp/results/JVM-Xuse-ir/BACKEND_bdogeyc_FILE.kt | DaniilStepanov | 346,008,310 | false | null | // Bug happens on JVM -Xuse-ir
// IGNORE_BACKEND_FIR: JVM_IR
// FILE: tmp0.kt
fun n_ui_ub( x: Int,a: UByte,b: UByte ) = x !in a..b
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 134 | kotlinWithFuzzer | Apache License 2.0 |
thisboot/src/main/kotlin/com/brageast/blog/thisboot/config/SecurityConfig.kt | chenmoand | 208,778,754 | false | {"YAML": 3, "JSON with Comments": 2, "JSON": 5, "Text": 1, "Ignore List": 3, "Markdown": 11, "HTML": 5, "HTTP": 1, "JavaScript": 11, "TSX": 50, "XML": 1, "Less": 6, "Batchfile": 1, "Shell": 1, "Maven POM": 1, "INI": 1, "Java": 2, "Kotlin": 26} | package com.brageast.blog.thisboot.config
import com.brageast.blog.thisboot.annotation.EnableAuthenticationManager
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
import org.springframework.security.config.web.server.ServerHttpSecurity
import org.springframework.security.web.server.SecurityWebFilterChain
@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
@EnableAuthenticationManager
class SecurityConfig {
/**
* web安全配置
*
* @param http
* @return https://docs.spring.io/spring-boot/docs/2.2.0.RELEASE/reference/htmlsingle/#boot-features-security-webflux
*/
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain = http.run {
// csrf 与 Thymeleaf不太兼容
csrf().disable()
formLogin().loginPage("/login")
httpBasic().disable()
// 通过注解方式来进行权限验证
authorizeExchange()
/*.matchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll()*/
.pathMatchers("/**")
.permitAll()
build()
}
} | 9 | TypeScript | 1 | 2 | 0819b24e15843546d0b2d338ad5673b3901dfd4d | 1,356 | thisme | MIT License |
library/src/main/java/io/nyris/camera/CameraView.kt | nyris | 136,636,657 | false | {"Java": 113046, "Kotlin": 34644, "C++": 344} | package io.nyris.camera
import android.content.Context
import android.os.Build
import android.util.AttributeSet
/**
* CameraView.kt - Class view that extend BaseCameraView for targeting recognition based styleable parameters
*
* @author <NAME>
* Created by nyris GmbH
* Copyright © 2018 nyris GmbH. All rights reserved.
*/
class CameraView : BaseCameraView {
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
if (isInEditMode) {
mCallbacks = null
return
}
// Attributes
val a = context.obtainStyledAttributes(attrs, R.styleable.CameraView, defStyleAttr,
R.style.Widget_CameraView)
typeRecognition = a.getInt(R.styleable.CameraView_recognition, 0)
mCallbacks = CallbackBridge()
// Internal setup
val preview = createPreviewImpl(context)
mImpl = when {
Build.VERSION.SDK_INT < 21 -> cameraBelow21(typeRecognition, preview)
Build.VERSION.SDK_INT < 23 -> cameraAbove21Low23(typeRecognition, preview, context)
else -> cameraAbove23(typeRecognition, preview, context)
}
mAdjustViewBounds = a.getBoolean(R.styleable.CameraView_android_adjustViewBounds, false)
facing = a.getInt(R.styleable.CameraView_facing, FACING_BACK)
val aspectRatio = a.getString(R.styleable.CameraView_aspectRatio)
if (aspectRatio != null) {
setAspectRatio(AspectRatio.parse(aspectRatio))
} else {
setAspectRatio(Constants.DEFAULT_ASPECT_RATIO)
}
autoFocus = a.getBoolean(R.styleable.CameraView_autoFocus, true)
flash = a.getInt(R.styleable.CameraView_flash, Constants.FLASH_AUTO)
isSaveImage = a.getBoolean(R.styleable.CameraView_saveImage, false)
takenPictureWidth = a.getInt(R.styleable.CameraView_imageWidth, 512)
takenPictureHeight = a.getInt(R.styleable.CameraView_imageHeight, 512)
a.recycle()
updateFocusMarkerView(preview)
}
private fun cameraBelow21(type: Int, preview: PreviewImpl): CameraViewImpl {
return when (type) {
0 //none
-> Camera1(mCallbacks, preview)
1 //barcode
-> Camera1ZBar(mCallbacks, preview)
else -> Camera1(mCallbacks, preview)
}
}
private fun cameraAbove21Low23(type: Int, preview: PreviewImpl, context: Context): CameraViewImpl {
return when (type) {
0 //none
-> Camera2(mCallbacks, preview, context)
1 //barcode
-> Camera2ZBar(mCallbacks, preview, context)
else -> Camera2(mCallbacks, preview, context)
}
}
private fun cameraAbove23(type: Int, preview: PreviewImpl, context: Context): CameraViewImpl {
return when (type) {
0 //none
-> Camera2Api23(mCallbacks, preview, context)
1 //barcode
-> Camera2ZBarApi23(mCallbacks, preview, context)
else -> Camera2Api23(mCallbacks, preview, context)
}
}
} | 0 | Java | 1 | 2 | 446c5bd0560908cb56bef91bfe7af34998f38d42 | 3,258 | Camera.Android | Apache License 2.0 |
src/test/kotlin/g0601_0700/s0638_shopping_offers/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0601_0700.s0638_shopping_offers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun shoppingOffers() {
assertThat(
Solution()
.shoppingOffers(
listOf(2, 5),
listOf(listOf(3, 0, 5), listOf(1, 2, 10)),
listOf(3, 2)
),
equalTo(14)
)
}
@Test
fun shoppingOffers2() {
assertThat(
Solution()
.shoppingOffers(
listOf(2, 3, 4),
listOf(listOf(1, 1, 0, 4), listOf(2, 2, 1, 9)),
listOf(1, 2, 1)
),
equalTo(11)
)
}
}
| 0 | Kotlin | 20 | 43 | e8b08d4a512f037e40e358b078c0a091e691d88f | 812 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/shared/ageing/environment/FoodEnvironment.kt | theNamskov | 417,602,469 | false | {"Kotlin": 10236, "Assembly": 222} | package shared.ageing.environment
import shared.ageing.action.Action
import shared.ageing.action.ForageAction
import shared.ageing.action.HuntAction
import shared.ageing.action.NoAction
import shared.ageing.actor.Actor
import shared.ageing.percept.Percept
import utility.Helper
class FoodEnvironment(vararg ags : Actor) : Environment(*ags) {
val huntOptions : List<String> = listOf("ak)nf3m", "pr3ko", "p)nk)", "bayla", "akok)", "nantwie", "akyekyere")
var scores : MutableMap<Actor, Int> = mutableMapOf()
var animal : String? = null
init {
ags.forEach { scores.put(it, 0) }
}
override fun processAction(agent: Actor, act: Action) {
when(act) {
is ForageAction -> scores.put(agent, scores.getValue(agent) + 1)
is HuntAction -> scores.put(agent, scores.getValue(agent) + 2)
is NoAction -> scores.put(agent, scores.getValue(agent))
}
}
override fun sense(agent: Actor) {
if(animal != null) {
agent.perceive(Percept("animal", animal!!))
}
else
agent.perceive()
}
override fun step() {
animal = if(Helper.generateRandomDouble(0, 1) > 0.5) huntOptions[Helper.generateRandomInt(0, huntOptions.size)] else null
super.step()
}
} | 0 | Kotlin | 0 | 1 | 7ad2a09ef48b702c6f22f5b7a3293a878c913074 | 1,297 | dotkt | MIT License |
sdk-scrapper/src/main/kotlin/io/github/wulkanowy/sdk/scrapper/interceptor/StudentAndParentInterceptor.kt | dominik-korsa | 237,057,001 | true | {"Kotlin": 509705, "HTML": 128700, "Shell": 505} | package io.github.wulkanowy.sdk.scrapper.interceptor
import okhttp3.Interceptor
import okhttp3.Response
import java.net.CookieManager
import java.net.HttpCookie
import java.net.URI
class StudentAndParentInterceptor(
private val cookies: CookieManager,
private val schema: String,
private val host: String,
private val diaryId: Int,
private val studentId: Int,
private val schoolYear: Int
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
arrayOf(
arrayOf("idBiezacyDziennik", diaryId),
arrayOf("idBiezacyUczen", studentId),
arrayOf("idBiezacyDziennikPrzedszkole", 0),
arrayOf("biezacyRokSzkolny", schoolYear)
).forEach { cookie ->
arrayOf("opiekun", "uczen").forEach { module ->
HttpCookie(cookie[0].toString(), cookie[1].toString()).let {
it.path = "/"
it.domain = "uonetplus-$module.$host"
cookies.cookieStore.add(URI("$schema://${it.domain}"), it)
}
}
}
return chain.proceed(chain.request().newBuilder().build())
}
}
| 0 | Kotlin | 0 | 0 | 2d2b5176e6b3d5e5eb6b812441c1af740f26eeb5 | 1,181 | sdk | Apache License 2.0 |
domain/induction/src/testFixtures/kotlin/uk/gov/justice/digital/hmpps/educationandworkplanapi/domain/induction/dto/CreatePreviousWorkExperiencesDtoBuilder.kt | ministryofjustice | 653,598,082 | false | {"Kotlin": 603881, "Mustache": 3118, "Dockerfile": 1346} | package uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.induction.dto
import uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.induction.WorkExperience
import uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.induction.aValidWorkExperience
fun aValidCreatePreviousWorkExperiencesDto(
experiences: List<WorkExperience> = listOf(aValidWorkExperience()),
prisonId: String = "BXI",
) =
CreatePreviousWorkExperiencesDto(
experiences = experiences,
prisonId = prisonId,
)
| 1 | Kotlin | 0 | 2 | 95ca727cfdde32bc66348dc697440952751deee0 | 516 | hmpps-education-and-work-plan-api | MIT License |
flowbinding-viewpager2/src/androidTest/java/reactivecircus/flowbinding/viewpager2/ViewPager2PageScrollStateChangedFlowTest.kt | codacy-badger | 202,851,772 | true | {"Kotlin": 16801, "Shell": 909} | package reactivecircus.flowbinding.viewpager2
import androidx.test.filters.LargeTest
import androidx.viewpager2.widget.ViewPager2
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.cancel
import org.junit.Test
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
import reactivecircus.flowbinding.viewpager2.test.R
@LargeTest
class ViewPager2PageScrollStateChangedFlowTest {
@Test
fun pageScrollStateChanges_swipe() {
launchTest<ViewPager2Fragment> {
val recorder = FlowRecorder<Int>(testScope)
getViewById<ViewPager2>(R.id.viewPager)
.pageScrollStateChanges()
.recordWith(recorder)
recorder.assertNoMoreValues()
swipeLeftOnView(R.id.viewPager)
assertThat(recorder.takeValue()).isEqualTo(ViewPager2.SCROLL_STATE_DRAGGING)
assertThat(recorder.takeValue()).isEqualTo(ViewPager2.SCROLL_STATE_SETTLING)
assertThat(recorder.takeValue()).isEqualTo(ViewPager2.SCROLL_STATE_IDLE)
recorder.assertNoMoreValues()
testScope.cancel()
swipeRightOnView(R.id.viewPager)
recorder.assertNoMoreValues()
}
}
@Test
fun pageScrollStateChanges_programmatic() {
launchTest<ViewPager2Fragment> {
val recorder = FlowRecorder<Int>(testScope)
val viewPager = getViewById<ViewPager2>(R.id.viewPager)
viewPager.pageScrollStateChanges().recordWith(recorder)
recorder.assertNoMoreValues()
viewPager.currentItem = 1
// SCROLL_STATE_DRAGGING state is not emitted for programmatic page change
assertThat(recorder.takeValue()).isEqualTo(ViewPager2.SCROLL_STATE_SETTLING)
assertThat(recorder.takeValue()).isEqualTo(ViewPager2.SCROLL_STATE_IDLE)
recorder.assertNoMoreValues()
testScope.cancel()
viewPager.currentItem = 0
recorder.assertNoMoreValues()
}
}
}
| 0 | Kotlin | 0 | 0 | 53aabeeae99ad6d5a4759ac9c4d1a07254879e21 | 2,126 | FlowBinding | Apache License 2.0 |
app/src/main/java/io/github/tonnyl/mango/shot/ShotContract.kt | LoveAndroid01 | 99,331,552 | true | {"Kotlin": 176451, "HTML": 27029} | package io.github.tonnyl.mango.shot
import io.github.tonnyl.mango.data.Shot
import io.github.tonnyl.mango.data.User
import io.github.tonnyl.mango.mvp.BasePresenter
import io.github.tonnyl.mango.mvp.BaseView
/**
* Created by lizhaotailang on 2017/6/28.
*/
interface ShotContract {
interface View : BaseView<Presenter> {
fun showMessage(message: String?)
fun setLikeStatus(like: Boolean)
fun updateLikeCount(count: Int)
fun show(shot: Shot)
fun navigateToUserProfile(user: User)
fun navigateToComments(shot: Shot)
fun navigateToLikes(shot: Shot)
}
interface Presenter : BasePresenter {
fun toggleLike()
fun navigateToUserProfile()
fun navigateToComments()
fun navigateToLikes()
}
} | 0 | Kotlin | 0 | 0 | 2398034f0de3e44a07fab660bc1bac0dd5d42945 | 803 | Mango | MIT License |
data/src/main/kotlin/com/alfresco/content/data/ResponsePaging.kt | asksasasa83 | 370,693,203 | true | {"Kotlin": 385930, "JavaScript": 17131, "CSS": 15164, "HTML": 1854, "Shell": 735} | package com.alfresco.content.data
data class ResponsePaging(
val entries: List<Entry>,
val pagination: Pagination
) {
companion object {
fun with(raw: com.alfresco.content.models.NodeChildAssociationPaging): ResponsePaging {
return ResponsePaging(
raw.list?.entries?.map { Entry.with(it.entry) } ?: emptyList(),
Pagination.with(raw.list!!.pagination!!)
)
}
fun with(raw: com.alfresco.content.models.ResultSetPaging): ResponsePaging {
return ResponsePaging(
raw.list?.entries?.map { Entry.with(it.entry) } ?: emptyList(),
Pagination.with(raw.list!!.pagination!!)
)
}
fun with(raw: com.alfresco.content.models.SitePaging): ResponsePaging {
return ResponsePaging(
raw.list.entries.map { Entry.with(it.entry) },
Pagination.with(raw.list.pagination)
)
}
fun with(raw: com.alfresco.content.models.FavoritePaging): ResponsePaging {
return ResponsePaging(
raw.list.entries.map { Entry.with(it.entry) },
Pagination.with(raw.list.pagination)
)
}
fun with(raw: com.alfresco.content.models.SiteRolePaging): ResponsePaging {
return ResponsePaging(
raw.list.entries.map { Entry.with(it.entry) },
Pagination.with(raw.list.pagination)
)
}
fun with(raw: com.alfresco.content.models.SharedLinkPaging): ResponsePaging {
return ResponsePaging(
raw.list.entries.map { Entry.with(it.entry) },
Pagination.with(raw.list.pagination)
)
}
fun with(raw: com.alfresco.content.models.DeletedNodesPaging): ResponsePaging {
return ResponsePaging(
raw.list?.entries?.map { Entry.with(it.entry!!) } ?: emptyList(),
Pagination.with(raw.list!!.pagination!!)
)
}
}
}
| 0 | null | 0 | 0 | 774b0997e62995e597633316f1a0b9799c198210 | 2,057 | alfresco-mobile-workspace-android | Apache License 2.0 |
themes/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/themes/intui/standalone/IntUiGlobalMetrics.kt | JetBrains | 440,164,967 | false | null | package org.jetbrains.jewel.themes.intui.standalone
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.runtime.Immutable
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import org.jetbrains.jewel.GlobalMetrics
@Immutable
data class IntUiGlobalMetrics(
override val outlineWidth: Dp = 2.dp,
override val outlineCornerSize: CornerSize = CornerSize(3.dp),
) : GlobalMetrics
| 25 | Kotlin | 12 | 357 | 0bf6a272c62bd56bb26d95d54883bcefbfc4e954 | 428 | jewel | Apache License 2.0 |
sentinel/src/main/kotlin/com/infinum/sentinel/ui/bundles/details/BundleDetailsAdapter.kt | infinum | 257,115,400 | false | {"Kotlin": 526915, "HTML": 3350, "Groovy": 1211} | package com.infinum.sentinel.ui.bundles.details
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import com.infinum.sentinel.data.models.memory.bundles.BundleTree
import com.infinum.sentinel.databinding.SentinelItemBundleKeyBinding
internal class BundleDetailsAdapter(
private val parentSize: Int
) : ListAdapter<BundleTree, BundleDetailsViewHolder>(BundleDetailsDiffUtil()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BundleDetailsViewHolder =
BundleDetailsViewHolder(
SentinelItemBundleKeyBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
override fun onBindViewHolder(holder: BundleDetailsViewHolder, position: Int) =
holder.bind(getItem(position), parentSize)
override fun onViewRecycled(holder: BundleDetailsViewHolder) {
holder.unbind()
super.onViewRecycled(holder)
}
}
| 0 | Kotlin | 1 | 38 | 2ff478612c708804f9e71b09f3488e6cb6bb308b | 1,024 | android-sentinel | Apache License 2.0 |
f2-dsl/f2-dsl-function/src/commonMain/kotlin/f2/dsl/fnc/operators/groupBy.kt | komune-io | 746,765,045 | false | {"Kotlin": 221733, "Java": 155444, "Gherkin": 24181, "Makefile": 1677, "JavaScript": 1459, "Dockerfile": 963, "CSS": 102} | package f2.dsl.fnc.operators
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
/**
* Extension function to group elements of a Flow by a specified key.
*
* @param keySelector A function to extract the key for each element.
* @return A Flow emitting pairs of keys and corresponding flows of elements.
*/
fun <T, K> Flow<T>.groupBy(keySelector: (T) -> K): Flow<Pair<K, Flow<T>>> = channelFlow {
val groups = mutableMapOf<K, Channel<T>>()
// Launch a coroutine to collect the original flow
launch {
collect { value ->
val key = keySelector(value)
val groupChannel = groups.getOrPut(key) {
Channel<T>(Channel.BUFFERED).also { channel ->
// For each new group, send a new flow to the downstream collector
launch {
send(key to channel.consumeAsFlow())
}
}
}
groupChannel.send(value)
}
// Close all channels after the original flow collection is complete
groups.values.forEach { it.close() }
}
}
| 1 | Kotlin | 0 | 0 | e3fd9920265d65b179759cb5eab1b3f31cea4407 | 1,259 | fixers-f2 | Apache License 2.0 |
SecondTempleTimer/src/commonMain/kotlin/sternbach/software/kosherkotlin/hebrewcalendar/HebrewLocalDate.kt | kdroidFilter | 849,781,239 | false | {"Kotlin": 814129} | package sternbach.software.kosherkotlin.hebrewcalendar
import sternbach.software.kosherkotlin.hebrewcalendar.JewishDate.Companion.daysInJewishYear
import sternbach.software.kosherkotlin.hebrewcalendar.JewishDate.Companion.isJewishLeapYear
import kotlinx.datetime.*
import kotlin.time.Duration.Companion.days
/**
* A class representing a Hebrew local date. Hebrew analog to [java.time.LocalDate] or [kotlinx.datetime.LocalDate]
* Although the Hebrew year actually starts in [HebrewMonth.TISHREI], the choice was made to assign [HebrewMonth.NISSAN]
* with a value of 1. This may be because the year is colloquially said to start in Nissan (in accordance with the
* opinion Maseches <NAME> (TODO include source) that the world was created in Nissan).
* **Note:** this class considers the Gregorian calendar to start at year 0, in accordance with ISO-8601.
* @param year the Hebrew year Ano Mundi, e.g. 5783 (2023 Gregorian)
* @param dayOfMonth the day of the month. This is a value between 1 and 30. Leap years can change the upper-bound of this number.
* @param month the Hebrew month. This is a value between 1 and 13. The value of 13 represents Adar II on a leap year.
* */
data class HebrewLocalDate(
val year: Long,
val month: HebrewMonth,
val dayOfMonth: Int
) : Comparable<HebrewLocalDate> {
init {
require(year != 0L) { "year must not be 0 - year was skipped" }
// require(year > 0) { "year must be positive: $year" } // leaving this out to make the calendar proleptic
require(dayOfMonth in 1..30) { "dayOfMonth must be between 1 and 30: $dayOfMonth" }
if(month == HebrewMonth.ADAR_II) require(year.isJewishLeapYear) { "$year was not leap year - month cannot be set to $month" }
val daysInJewishMonth = JewishDate.getDaysInJewishMonth(month, year)
require(daysInJewishMonth >= dayOfMonth) { "Cannot set dayOfMonth to $dayOfMonth; $month only had $daysInJewishMonth in the year $year" }
}
constructor(year: Int, month: HebrewMonth, dayOfMonth: Int) : this(year.toLong(), month, dayOfMonth)
//-----------------------------------------------------------------------
/**
* Compares this date to another date.
*
*
* The comparison is primarily based on the date, from earliest to latest.
* It is "consistent with equals", as defined by [Comparable].
*
* @param other the other date to compare to
* @return the comparator value, negative if less, positive if greater
*/
override fun compareTo(other: HebrewLocalDate): Int {
var cmp = year - other.year
if (cmp == 0L) {
cmp = (
HebrewMonth.getTishreiBasedValue(
month.value,
year
) -
HebrewMonth.getTishreiBasedValue(other.month.value, other.year)
).toLong()
if (cmp == 0L) {
cmp = (dayOfMonth - other.dayOfMonth).toLong()
}
}
return cmp.toInt()
}
/**
* Returns this object with the [dayOfMonth] set to the given [newDayOfMonth].
*
* **Note:** This method does not change the month or year (e.g. passing in a value of 32 does not increment the month).
* */
fun withDayOfMonth(newDayOfMonth: Int) = copy(dayOfMonth = newDayOfMonth)
/**
* Returns this object with the [month] set to the given [newMonth].
*
* **Note:** This method does not change the day or year (e.g. if the [dayOfMonth] is 30 and [newMonth] only has 29 days, [dayOfMonth] will remain 30).
* */
fun withMonth(newMonth: HebrewMonth) = copy(month = newMonth)
/**
*
* Returns this object with the [year] set to the given [newYear].
*
* **Note:** This method does not change the day or month (e.g. if the [month] was the leap month [HebrewMonth.ADAR_II], and [newYear] is not a leap year, the month will remain [HebrewMonth.ADAR_II]).
* */
fun withYear(newYear: Long) = copy(year = newYear)
fun withYear(newYear: Int) = copy(year = newYear.toLong())
/**
* Returns the absolute date of Jewish date. ND+ER
*
* @param year
* the Jewish year. The year can't be negative
* @param month
* the Jewish month starting with Nisan. Nisan expects a value of 1 etc till Adar with a value of 12. For
* a leap year, 13 will be the expected value for Adar II. Use the constants [HebrewMonth.NISSAN]
* etc.
* @param dayOfMonth
* the Jewish day of month. valid values are 1-30. If the day of month is set to 30 for a month that only
* has 29 days, the day will be set as 29.
* @return the absolute date of the Jewish date.
*/
fun toJewishEpochDays(): Long =
// add elapsed days this year + Days in prior years + Days elapsed before absolute year 1
JewishDate.getDaysSinceStartOfJewishYear(year, month, dayOfMonth) +
JewishDate.getJewishCalendarElapsedDays(year) +
JEWISH_EPOCH
val isJewishLeapYear get() = year.isJewishLeapYear
/**
* Returns a copy of this [HebrewLocalDate] with the specified number of days added.
*
*
* This method adds the specified amount to the days field incrementing the
* month and year fields as necessary to ensure the result remains valid.
* The result is only invalid if the maximum/minimum year is exceeded.
*
*
* For example, 2008-12-31 plus one day would result in 2009-01-01.
*
*
* This instance is immutable and unaffected by this method call.
*
* @param daysToAdd the days to add, may be negative
* @return a [HebrewLocalDate] based on this date with the days added, not null
* @throws DateTimeException if the result exceeds the supported date range //TODO
*/
fun plusDays(days: Long): HebrewLocalDate {
var daysLeft = days
var newDayOfMonth = dayOfMonth + days
var newMonth = month
var newYear = year
while (daysLeft > 0) {
val daysInMonth = getNumDaysInHebrewMonth(newMonth, newYear)
daysLeft -= daysInMonth
if (newDayOfMonth > daysInMonth) {
val nextMonthInYear = newMonth.getNextMonthInYear(newYear)
newMonth = if (nextMonthInYear == null) {
newYear++
HebrewMonth.TISHREI
} else {
nextMonthInYear
}
newDayOfMonth -= daysInMonth
} else break
}
return HebrewLocalDate(newYear, newMonth, newDayOfMonth.toInt())
}
/**
* Computes the Gregorian [LocalDate] of a given [HebrewLocalDate].
* **Note:** this class considers the Gregorian calendar to start at year 0, in accordance with ISO-8601.
*/
fun toLocalDateGregorian(): LocalDate = toPairOfHebrewAndGregorianLocalDate(targetHebrewDate = this).second
companion object {
/**
* Computes the [HebrewLocalDate] of a given Gregorian date.
* @param this the gregorian date to convert to a [HebrewLocalDate]
*/
fun LocalDate.withYear(year: Int): LocalDate = LocalDate(year, month, dayOfMonth)
fun LocalDate.withMonth(month: Month): LocalDate = LocalDate(year, month, dayOfMonth)
fun LocalDate.withDayOfMonth(dayOfMonth: Int): LocalDate = LocalDate(year, month, dayOfMonth)
fun LocalDate.toHebrewDate(): HebrewLocalDate =
toPairOfHebrewAndGregorianLocalDate(targetGregorianDate = this).first
/**
* Computes the [HebrewLocalDate] of a given Gregorian date.
* @param this the gregorian date to convert to a [HebrewLocalDate]
*/
internal fun toPairOfHebrewAndGregorianLocalDate(
targetGregorianDate: LocalDate? = null,
targetHebrewDate: HebrewLocalDate? = null,
): Pair<HebrewLocalDate, LocalDate> {
/*
* The algorithm for converting a Gregorian date to a hebrew date is as follows:
* Let targetGregorianDate = date that client wants to convert to hebrew date.
* Let currentGregorianDate = the intermediate representation of the gregorian date which will be mutated until equal to targetGregorianDate
* Let currentHebrewDate = the intermediate representation of the hebrew date which will be mutated until currentGregorianDate is equal to targetGregorianDate
* Let hebrewStartingPoint = the beginning of the inception of the hebrew calendar
* Let gregorianStartingPoint = the known corresponding Gregorian date to hebrewStartingPoint.
* 1. Init variables:
* a. hebrewStartingPoint = Tishrei 1, 1
* b. gregorianStartingPoint = September 7, 3761 B.C.E.
* c. currentHebrewDate = hebrewStartingPoint
* d. currentGregorianDate = gregorianStartingPoint
* 2. If gregorianStartingPoint is equal to targetGregorianDate: return hebrewStartingPoint.
* 3. If gregorianStartingPoint is before targetGregorianDate:
* a. while(currentGregorianDate.year != targetGregorianDate.year):
* i. Let numDaysInHebrewYear = getNumDaysInHebrewYear(currentHebrewDate.year) //accounts for leap years
* ii. Let nextHebrewNewYear = currentGregorianDate.plusDays(numDaysInHebrewYear)
* iii. if(nextHebrewNewYear is after targetGregorianDate): break //we've overshot the target because it is between now and the next new year
* iv. else:
* 1. currentGregorianDate = nextHebrewNewYear
* 2. currentHebrewDate.year += 1
* b. while(currentGregorianDate.month != targetGregorianDate.month):
* i. Let numDaysInHebrewMonth = getNumDaysInHebrewMonth(currentHebrewDate.month)
* ii. Let nextHebrewNewMonth = currentGregorianDate.plusDays(numDaysInHebrewMonth)
* iii. if(nextHebrewNewMonth is after targetGregorianDate): break //we've overshot the target because it is between now and the next first-of-the-month
* iv. else:
* 1. currentGregorianDate = nextHebrewNewYear
* 2. currentHebrewDate.month += 1
* // currentHebrewDate is at the first day of the month of targetGregorianDate's hebrew equivalent.
* c. Let numDaysLeft = targetGregorianDate.dayOfMonth - currentGregorianDate.dayOfMonth
* d. let numDaysInHebrewMonth = getNumDaysInHebrewMonth(currentHebrewDate.month)
* e. if(numDaysLeft <= numDaysInHebrewMonth) currentHebrewDate.dayOfMonth += numDaysLeft //currentHebrewDate.dayOfMonth was 1
* f. else: //target is next month (e.g. numDaysLeft = 30 but numDaysInHebrewMonth = 29
* i. currentHebrewDate.month += 1
* ii. currentHebrewDate.dayOfMonth = numDaysLeft - numDaysInHebrewMonth + 1 //+1 because we did not start at 0, so we need to add the first day
* 4. If gregorianStartingPoint is after targetGregorianDate: //wants to compute the hebrew date of a Gregorian date prior to the inception of the Hebrew calendar
* i. Repeat step 3, but subtract instead of add.
* */
if (STARTING_DATE_GREGORIAN == targetGregorianDate || STARTING_DATE_HEBREW == targetHebrewDate) return STARTING_DATE_HEBREW to STARTING_DATE_GREGORIAN
require((targetGregorianDate != null) xor (targetHebrewDate != null)) { "Target date must not be null, and only one target can be chosen." }
//ensure target after start so we don't have to deal with negative numbers and walking backwards
if (targetGregorianDate != null) require(
targetGregorianDate >= STARTING_DATE_GREGORIAN
) { "Target date ($targetGregorianDate) must be after $STARTING_DATE_GREGORIAN ($STARTING_DATE_HEBREW). This requirement will hopefully be removed in a future release." }
else require(
targetHebrewDate!! >= STARTING_DATE_HEBREW
) { "Target date ($targetHebrewDate) must be after $STARTING_DATE_HEBREW ($STARTING_DATE_GREGORIAN). This requirement will hopefully be removed in a future release." }
/*if(targetGregorianDate != null){
val daysUntilTarget = STARTING_DATE_GREGORIAN.daysUntil(targetGregorianDate).toLong()
val hebrewDate = STARTING_DATE_HEBREW.plusDays(daysUntilTarget)
return hebrewDate to targetGregorianDate
} else {
}*/
var currentHebrewDate = STARTING_DATE_HEBREW
val tz = TimeZone.UTC
var currentGregorianDateInstant =
STARTING_DATE_GREGORIAN.atStartOfDayIn(tz) //+ 1.days //+1 because we don't want to mutate the STARTING_DATE_GREGORIAN
var currentGregorianDateTime = currentGregorianDateInstant.toLocalDateTime(tz)
val targetGregorianDateInstant = targetGregorianDate?.atStartOfDayIn(tz)
if (targetGregorianDate != null && STARTING_DATE_GREGORIAN > targetGregorianDate) { //STARTING_DATE_GREGORIAN > this - i.e. want to compute the hebrew date of a Gregorian date prior to the inception of the hebrew calendar
throw IllegalArgumentException("Cannot compute dates before the inception of the Hebrew calendar: $STARTING_DATE_GREGORIAN Gregorian/$STARTING_DATE_HEBREW. If you have a reason you want to do this, please submit a feature request on GitHub.")
}
while (
if (targetGregorianDate != null) currentGregorianDateTime.date.year != targetGregorianDate.year
else currentHebrewDate.year != targetHebrewDate!!.year
) {
if (currentGregorianDateTime.date.year == 0) { //if we're at the beginning of the Gregorian calendar, we need to skip year 0 - kotlinx-datetime/ISO-8601 uses year 0, but people normally don't - the world went from -1 BCE to 1 CE, not 0
val timeInYear1 = LocalDateTime(
LocalDate(
currentGregorianDateTime.date.year + 1,
currentGregorianDateTime.date.month,
currentGregorianDateTime.date.dayOfMonth
), currentGregorianDateTime.time
)
if (
(targetGregorianDate != null && timeInYear1.date > targetGregorianDate)
) { //we would overshoot the target because target is between the current date (in year 0) and the corresponding date in year 1 (LocalDate(1, month, day))
break // move forward the months and days, correcting for year
} else {
currentGregorianDateInstant = timeInYear1.toInstant(tz)
currentGregorianDateTime = timeInYear1
}
/*println("Was year 0 (gdate = $currentGregorianDateTime, hdate = $currentHebrewDate), jumping to ${STARTING_DATE_HEBREW.month} of year 1")
var gregorianMonth = currentGregorianDateTime.date.month
while(currentGregorianDateTime.date.year == 0 || currentHebrewDate.month != STARTING_DATE_HEBREW.month) {
println("Current hebrew date: $currentHebrewDate, current gregorian date: $currentGregorianDateTime")
val lastDayOfGregorianMonth =
JewishDate.getLastDayOfGregorianMonth(gregorianMonth.value, currentGregorianDateTime.year).toLong()
val sameMonth = gregorianMonth.value == currentGregorianDateTime.date.monthNumber
val daysToAdd =
if (sameMonth) lastDayOfGregorianMonth - currentGregorianDateTime.date.dayOfMonth*//*currentDayOfGregorianMonth*//*
else lastDayOfGregorianMonth
println("Days to add: $daysToAdd (same month: $sameMonth)")
currentHebrewDate = currentHebrewDate.plusDays(
daysToAdd
)
currentGregorianDateInstant += lastDayOfGregorianMonth.days
currentGregorianDateTime = currentGregorianDateInstant.toLocalDateTime(tz)
gregorianMonth = currentGregorianDateTime.date.month
}*/
continue
}
val daysInYear = getNumDaysInHebrewYear(currentHebrewDate.year) //accounts for leap years
//if(currentGregorianDate.year == 0) currentGregorianDate = LocalDate(1, currentGregorianDate.monthNumber, currentGregorianDate.dayOfMonth)
val newHebrewYear = currentHebrewDate.withYear(currentHebrewDate.year + 1)
val newStartOfHebrewYear = currentGregorianDateInstant + daysInYear.days
if (
if (targetGregorianDate != null) newStartOfHebrewYear > targetGregorianDateInstant!!
else newHebrewYear > targetHebrewDate!!
) break //overshot, don't keep adding. Could have overshot because the date could be between the two Rosh Hashanahs.
currentGregorianDateInstant = newStartOfHebrewYear
currentGregorianDateTime = currentGregorianDateInstant.toLocalDateTime(tz)
currentHebrewDate = newHebrewYear
}
//year is either right, and now we only need to worry about the month and dayOfMonth,
// or target is between current and current plus 1 year, but crosses the year boundary
// (e.g. current is last day of month, and target is 1st day of next month).
while (
if (targetGregorianDate != null) currentGregorianDateTime.month != targetGregorianDate.month || currentGregorianDateTime.year != targetGregorianDate.year
else currentHebrewDate.month != targetHebrewDate!!.month || currentHebrewDate.year != targetHebrewDate.year
) {
val daysInMonth = getNumDaysInHebrewMonth(
currentHebrewDate.month,
currentHebrewDate.year
)
val gregorianDateOfNextRoshChodesh = currentGregorianDateInstant + daysInMonth.days
val nextMonth = currentHebrewDate.month.getNextMonthInYear(currentHebrewDate.year)
val newHebrewDate =
if (nextMonth == null/*cross year boundary*/) currentHebrewDate.withMonth(HebrewMonth.TISHREI)
.withYear(currentHebrewDate.year + 1)
else currentHebrewDate.withMonth(nextMonth)
if (
if (targetGregorianDate != null) gregorianDateOfNextRoshChodesh > targetGregorianDateInstant!!
else newHebrewDate > targetHebrewDate!!
) {
break
} //overshot, don't keep adding. Could have overshot because the date could be between the two months
currentGregorianDateInstant = gregorianDateOfNextRoshChodesh
currentGregorianDateTime = currentGregorianDateInstant.toLocalDateTime(tz)
currentHebrewDate = newHebrewDate
}
//month is either right, and now we only need to worry about the dayOfMonth,
// or target is between current and current plus 1 month but crosses the month boundary
// (e.g. current is last day of month, and target is 1st day of next month).
if (currentGregorianDateInstant == targetGregorianDateInstant) return currentHebrewDate to currentGregorianDateTime.date // if day is already right, return
// currentHebrewDate is at the first day of the month of targetGregorianDate's hebrew equivalent month.
val hebrewMonthIsCorrect by lazy { targetHebrewDate!!.month == currentHebrewDate.month }
val numDaysLeftToAdd =
if (targetGregorianDate != null) (targetGregorianDateInstant!! - currentGregorianDateInstant).inWholeDays.toInt()
else {
if (hebrewMonthIsCorrect) targetHebrewDate!!.dayOfMonth - currentHebrewDate.dayOfMonth
else targetHebrewDate!!.dayOfMonth + getNumDaysInHebrewMonth(
targetHebrewDate.month,
targetHebrewDate.year
)
}
val numDaysInHebrewMonth = getNumDaysInHebrewMonth(currentHebrewDate.month, currentHebrewDate.year)
currentHebrewDate = if (numDaysLeftToAdd
/*TODO what if this is equal to numDaysInHebrewMonth? 1 (current day) + 30 (num days) = 31...*/
< numDaysInHebrewMonth
) currentHebrewDate.withDayOfMonth(
(numDaysLeftToAdd + 1/*started on day 1, so need to add that*/)
//.coerceAtMost(numDaysInHebrewMonth/*don't go over the max days in the month*/)
)
else { //target is next month (e.g. numDaysLeft = 30 but numDaysInHebrewMonth = 29)
val nextMonth = currentHebrewDate.month.getNextMonthInYear(currentHebrewDate.year)
if (nextMonth == null) {
HebrewLocalDate(
currentHebrewDate.year + 1,
HebrewMonth.TISHREI,
(numDaysLeftToAdd + 1/*started on day 1, so need to add that*/) - numDaysInHebrewMonth
)
} else currentHebrewDate
.withMonth(nextMonth)
.withDayOfMonth((numDaysLeftToAdd + 1/*started on day 1, so need to add that*/) - numDaysInHebrewMonth)
}
currentGregorianDateInstant += numDaysLeftToAdd.days/*don't need to account for month because datetime library will do the math*/
currentGregorianDateTime = currentGregorianDateInstant.toLocalDateTime(tz)
return currentHebrewDate to currentGregorianDateTime.date
}
fun getNumDaysInHebrewYear(year: Long): Int = year.daysInJewishYear
fun getNumDaysInHebrewMonth(month: HebrewMonth, year: Long): Int = JewishDate.getDaysInJewishMonth(month, year)
/**
* the Jewish epoch using the RD (Rata Die/Fixed Date or Reingold Dershowitz) day used in Calendrical Calculations.
* Day 1 is January 1, 0001 Gregorian
*/
const val JEWISH_EPOCH = -1_373_429
/**
* The start of the Hebrew calendar. Used as a reference point for converting between
* Gregorian and Hebrew dates.
* This currently starts at <NAME> of Gregorian year 1 so as not to deal with year 0 (1 B.C.E in kotlinx-datetime).
* Certain edge cases related to year zero were not handled correctly by the library.
* TODO reimplement to handle those cases.
* */
internal val STARTING_DATE_HEBREW = HebrewLocalDate(3762, HebrewMonth.TISHREI, 1)
/**
* @see STARTING_DATE_HEBREW; Does not account for The Gregorian Reformation.
* */
internal val STARTING_DATE_GREGORIAN = LocalDate(1, Month.SEPTEMBER, 6)
}
}
| 0 | Kotlin | 0 | 0 | 577cd4818376400b4acc0f580ef19def3bf9e8d9 | 23,405 | SecondTempleTimerLibrary | Apache License 2.0 |
app/src/main/java/com/gsm/bee_assistant_android/retrofit/repository/UserRepository.kt | Im-Tae | 265,436,336 | false | null | package com.gsm.bee_assistant_android.retrofit.repository
import com.gsm.bee_assistant_android.retrofit.domain.classroom.ClassroomTokenUpdate
import com.gsm.bee_assistant_android.retrofit.domain.user.SchoolInfoUpdate
import com.gsm.bee_assistant_android.retrofit.domain.user.UserInfo
import com.gsm.bee_assistant_android.retrofit.domain.user.UserToken
import com.gsm.bee_assistant_android.retrofit.network.UserApi
import com.gsm.bee_assistant_android.utils.NetworkUtil
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.Call
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class UserRepository @Inject constructor(
private val userApi: UserApi,
private val networkStatus: NetworkUtil
){
fun updateClassroomToken(classroomTokenUpdate: ClassroomTokenUpdate): Single<UserToken> =
userApi.updateClassroomToken(classroomTokenUpdate)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.retryWhen {
Flowable.interval(3, TimeUnit.SECONDS)
.onBackpressureBuffer()
.retryUntil {
if (networkStatus.networkInfo())
return@retryUntil true
false
}
}
fun getUserToken(email: String): Single<UserToken> =
userApi.getUserToken(email)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.retryWhen {
Flowable.interval(3, TimeUnit.SECONDS)
.onBackpressureBuffer()
.retryUntil {
if(networkStatus.networkInfo())
return@retryUntil true
false
}
}
fun getUserInfo(token: String): Single<UserInfo> =
userApi.getUserInfo(token)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.retryWhen {
Flowable.interval(3, TimeUnit.SECONDS)
.onBackpressureBuffer()
.retryUntil {
if(networkStatus.networkInfo())
return@retryUntil true
false
}
}
fun updateSchoolInfo(schoolInfoUpdate: SchoolInfoUpdate): Call<UserToken> =
userApi.updateSchoolInfo(schoolInfoUpdate)
} | 0 | Kotlin | 1 | 0 | 28457fdecdc1935e1d97b5a8ac0de6fdff7fbaf4 | 2,595 | Bee-Android | Apache License 2.0 |
app/src/main/java/com/xiaocydx/sample/extension/GCSavedStates.kt | xiaocydx | 460,257,515 | false | null | package com.xiaocydx.sample.extension
import androidx.collection.LongSparseArray
import androidx.collection.keyIterator
import androidx.viewpager2.adapter.FragmentStateAdapter
import java.lang.reflect.Field
/**
* 清除`mSavedStates`保存的无效Fragment状态
*
* [FragmentStateAdapter]销毁Fragment时,
* 若还包含item,则会将Fragment状态保存到成员属性`mSavedStates`,
* 后面滚动回item重新创建Fragment时,通过`mSavedStates`保存的Fragment状态恢复视图状态。
* 但是存在一个逻辑漏洞,若保存Fragment状态后,不再滚动回item,
* 而是移除item(例如整体刷新),则`mSavedStates`保存的Fragment状态不会被清除。
* 对于频繁移除item并且是常驻首页的ViewPager2页面来说,
* 这个逻辑漏洞可能会导致无效Fragment状态堆积,需要考虑在合适的时机,
* 通过反射清除`mSavedStates`保存的无效Fragment状态。
*/
fun FragmentStateAdapter.gcSavedStates() {
val mSavedStatesField: Field = runCatching {
FragmentStateAdapter::class.java.getDeclaredField("mSavedStates")
}.getOrNull() ?: return
mSavedStatesField.isAccessible = true
val mSavedStates = mSavedStatesField.get(this) as? LongSparseArray<*> ?: return
for (itemId in mSavedStates.keys()) {
if (!containsItem(itemId)) mSavedStates.remove(itemId)
}
}
private fun LongSparseArray<*>.keys(): LongArray {
var index = 0
val keys = LongArray(size())
for (key in keyIterator()) {
keys[index] = key
index++
}
return keys
} | 0 | Kotlin | 0 | 7 | 7283f04892a84661ff82f33eed377da2cc015874 | 1,253 | CXRV | Apache License 2.0 |
app/src/main/java/com/danisbana/danisbanaapp/domain/usecase/ValidateRepeatedPassword.kt | burhancabiroglu | 598,760,819 | false | null | package com.danisbana.danisbanaapp.domain.usecase
class ValidateRepeatedPassword {
fun execute(password: String, repeatedPassword: String): ValidationResult {
if(password != repeatedPassword) {
return ValidationResult(
successful = false,
errorMessage = "Parolalar eşleşmiyor"
)
}
return ValidationResult(
successful = true
)
}
} | 0 | Kotlin | 0 | 0 | 50cb4466f3dfcdb42d430b8cb6afc63526d53d43 | 439 | PsychologistCounselorApp | Creative Commons Zero v1.0 Universal |
presentation/src/main/java/com/yapp/growth/presentation/model/TimeType.kt | YAPP-Github | 475,724,938 | false | {"Kotlin": 517158} | package com.yapp.growth.presentation.model
import com.yapp.growth.presentation.R
enum class TimeType(val timeStringResId: Int) {
AM_12(R.string.create_plan_time_range_time_option_am_12),
AM_01(R.string.create_plan_time_range_time_option_am_01),
AM_02(R.string.create_plan_time_range_time_option_am_02),
AM_03(R.string.create_plan_time_range_time_option_am_03),
AM_04(R.string.create_plan_time_range_time_option_am_04),
AM_05(R.string.create_plan_time_range_time_option_am_05),
AM_06(R.string.create_plan_time_range_time_option_am_06),
AM_07(R.string.create_plan_time_range_time_option_am_07),
AM_08(R.string.create_plan_time_range_time_option_am_08),
AM_09(R.string.create_plan_time_range_time_option_am_09),
AM_10(R.string.create_plan_time_range_time_option_am_10),
AM_11(R.string.create_plan_time_range_time_option_am_11),
PM_12(R.string.create_plan_time_range_time_option_pm_12),
PM_01(R.string.create_plan_time_range_time_option_pm_01),
PM_02(R.string.create_plan_time_range_time_option_pm_02),
PM_03(R.string.create_plan_time_range_time_option_pm_03),
PM_04(R.string.create_plan_time_range_time_option_pm_04),
PM_05(R.string.create_plan_time_range_time_option_pm_05),
PM_06(R.string.create_plan_time_range_time_option_pm_06),
PM_07(R.string.create_plan_time_range_time_option_pm_07),
PM_08(R.string.create_plan_time_range_time_option_pm_08),
PM_09(R.string.create_plan_time_range_time_option_pm_09),
PM_10(R.string.create_plan_time_range_time_option_pm_10),
PM_11(R.string.create_plan_time_range_time_option_pm_11),
}
| 6 | Kotlin | 0 | 43 | 1dfc20bd4631567ea35def8d2fcb8414139c490d | 1,621 | 20th-Android-Team-1-FE | Apache License 2.0 |
presentation/src/main/java/com/yapp/growth/presentation/model/TimeType.kt | YAPP-Github | 475,724,938 | false | {"Kotlin": 517158} | package com.yapp.growth.presentation.model
import com.yapp.growth.presentation.R
enum class TimeType(val timeStringResId: Int) {
AM_12(R.string.create_plan_time_range_time_option_am_12),
AM_01(R.string.create_plan_time_range_time_option_am_01),
AM_02(R.string.create_plan_time_range_time_option_am_02),
AM_03(R.string.create_plan_time_range_time_option_am_03),
AM_04(R.string.create_plan_time_range_time_option_am_04),
AM_05(R.string.create_plan_time_range_time_option_am_05),
AM_06(R.string.create_plan_time_range_time_option_am_06),
AM_07(R.string.create_plan_time_range_time_option_am_07),
AM_08(R.string.create_plan_time_range_time_option_am_08),
AM_09(R.string.create_plan_time_range_time_option_am_09),
AM_10(R.string.create_plan_time_range_time_option_am_10),
AM_11(R.string.create_plan_time_range_time_option_am_11),
PM_12(R.string.create_plan_time_range_time_option_pm_12),
PM_01(R.string.create_plan_time_range_time_option_pm_01),
PM_02(R.string.create_plan_time_range_time_option_pm_02),
PM_03(R.string.create_plan_time_range_time_option_pm_03),
PM_04(R.string.create_plan_time_range_time_option_pm_04),
PM_05(R.string.create_plan_time_range_time_option_pm_05),
PM_06(R.string.create_plan_time_range_time_option_pm_06),
PM_07(R.string.create_plan_time_range_time_option_pm_07),
PM_08(R.string.create_plan_time_range_time_option_pm_08),
PM_09(R.string.create_plan_time_range_time_option_pm_09),
PM_10(R.string.create_plan_time_range_time_option_pm_10),
PM_11(R.string.create_plan_time_range_time_option_pm_11),
}
| 6 | Kotlin | 0 | 43 | 1dfc20bd4631567ea35def8d2fcb8414139c490d | 1,621 | 20th-Android-Team-1-FE | Apache License 2.0 |
app/src/main/java/com/example/cloudmoniter/Utils.kt | Y-Theta | 500,710,879 | false | null | package com.example.cloudmoniter
import java.security.InvalidKeyException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
class Utils {
companion object {
val UnitDic = mapOf(
1 to "B",
1.shl(1) to "KB",
1.shl(2) to "MB",
1.shl(3) to "GB",
)
fun GetFriendlyByte(byte: Long, digit: Int?): String {
var unit = 1;
val adigit = if (digit == null) 1024f else digit.toFloat();
var num = byte.toFloat();
while (num / adigit > 1) {
num /= adigit;
unit = unit.shl(1);
}
var unitstr = "B";
if (UnitDic.containsKey(unit))
unitstr = UnitDic[unit]!!;
return "${Math.round(num * 100) / 100f}$unitstr";
}
fun hmac256(key: ByteArray?, msg: String): ByteArray? {
try {
val hashingAlgorithm = "HmacSHA256" //or "HmacSHA1", "HmacSHA512"
val bytes = hmac(hashingAlgorithm, key, msg.toByteArray())
return bytes;
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
return null;
}
@Throws(NoSuchAlgorithmException::class, InvalidKeyException::class)
fun hmac(algorithm: String?, key: ByteArray?, message: ByteArray?): ByteArray {
val mac = Mac.getInstance(algorithm)
mac.init(SecretKeySpec(key, algorithm))
return mac.doFinal(message)
}
fun sha256Hex(password: String): String? {
return try {
var digest: MessageDigest? = null
try {
digest = MessageDigest.getInstance("SHA-256")
} catch (e1: NoSuchAlgorithmException) {
e1.printStackTrace()
}
digest!!.reset()
bin2hex(digest.digest(password.toByteArray()))
} catch (ignored: java.lang.Exception) {
null
}
}
fun bin2hex(data: ByteArray): String? {
val hex = java.lang.StringBuilder(data.size * 2)
for (b in data) hex.append(String.format("%02x", b.toInt() and 0xFF))
return hex.toString()
}
}
constructor() {
}
} | 0 | Kotlin | 0 | 0 | b0646faf8e6ea6e0ef7f0e4371adff7cc8d062a1 | 2,434 | android-wear-moniter | MIT License |
app/src/main/java/com/naftarozklad/repo/models/Subgroup.kt | bshvets8 | 115,192,251 | false | null | package com.naftarozklad.repo.models
import com.naftarozklad.R
import com.naftarozklad.utils.resolveString
/**
* Created by bohdan on 10/7/17
*/
enum class Subgroup(val id: Int, val description: String) {
COMMON(0, ""),
FIRST(1, resolveString(R.string.lbl_first_subgroup)),
SECOND(2, resolveString(R.string.lbl_second_subgroup))
} | 0 | Kotlin | 0 | 0 | 1cfa23ba5ea09539f684bdecee22c445a1d2e00d | 338 | NaftaRozkladAndroid | MIT License |
domain/src/main/java/com/patrykkosieradzki/ryanairandroidchallenge/domain/model/FlightSearchFilters.kt | k0siara | 364,285,487 | false | null | package com.patrykkosieradzki.ryanairandroidchallenge.domain.model
open class FlightSearchFilters(
open val dateOut: String,
open val originCode: String,
open val destinationCode: String,
open val adults: Int,
open val teens: Int,
open val children: Int
)
| 0 | Kotlin | 0 | 0 | 3dee0f436cce6ebac5ba0d5f6818b2818be736c0 | 281 | RyanairAndroidChallenge | Apache License 2.0 |
domain/src/main/java/com/cerminnovations/domain/model/Genre.kt | mbobiosio | 324,425,383 | false | null | package com.cerminnovations.domain.model
/**
* @Author <NAME>
* https://linktr.ee/mbobiosio
*/
data class Genre(
val id: Int,
val name: String
)
| 0 | Kotlin | 3 | 7 | 07270aa17f45edabfb6792fd529c212e1c585ce4 | 157 | MoviesBoard | MIT License |
pulumi-orca/src/main/kotlin/io/armory/plugin/stage/pulumi/Context.kt | danielpeach | 269,748,938 | true | {"Kotlin": 16427, "TypeScript": 5987, "JavaScript": 303, "CSS": 69} | package io.armory.plugin.stage.pulumi
import io.armory.plugin.stage.pulumi.exception.SimpleStageException
/**
* Context is used within the stage itself and returned to the Orca pipeline execution.
*/
data class Context(var exception: SimpleStageException? = null)
| 0 | null | 0 | 0 | 3030b6f4493986056c4a8a9a7ded3d24871e7fb5 | 268 | pulumi-plugin | Apache License 2.0 |
betfair/src/main/kotlin/com/prince/betfair/betfair/betting/entities/market/MarketDescription.kt | rinkledink | 359,216,810 | false | null | package com.prince.betfair.betfair.betting.entities.market
import com.prince.betfair.betfair.betting.enums.market.MarketBettingType
import java.util.*
/**
* Market definition
*
* @property persistenceEnabled: (required) If 'true' the market supports 'Keep' bets if the market is to be turned
* in-play
* @property bspMarket: (required) If 'true' the market supports Betfair SP betting
* @property marketTime: (required) The market start time. This is the scheduled start time of the market e.g. horse
* race or football match etc.
* @property suspendTime: (required) The market suspend time. This is the next time the market will be suspended for
* betting and is normally the same as the marketTime.
* @property settleTime: settled time
* @property bettingType: (required) See MarketBettingType
* @property turnInPlayEnabled: (required) If 'true' the market is set to turn in-play
* @property marketType: (required) Market base type
* @property regulator: (required) The market regulator. Value include “GIBRALTAR REGULATOR" (.com), MR_ESP (Betfair.es
* markets), MR_IT (Betfair.it). GIBRALTAR REGULATOR = MR_INT in the Stream API
* @property marketBaseRate: (required) The commission rate applicable to the market
* @property discountAllowed: (required) Indicates whether or not the user's discount rate is taken into account on this
* market. If ‘false’ all users will be charged the same commission rate, regardless of discount rate.
* @property wallet: The wallet to which the market belongs.
* @property rules: The market rules.
* @property rulesHasDate: Indicates whether rules have a date included.
* @property eachWayDivisor: The divisor is returned for the marketType EACH_WAY only and refers to the fraction of the
* win odds at which the place portion of an each way bet is settled
* @property clarifications: Any additional information regarding the market
* @property lineRangeInfo: Line range info for line markets
* @property raceType: An external identifier of a race type
* @property priceLadderDescription: Details about the price ladder in use for this market.
*/
data class MarketDescription(
val persistenceEnabled: Boolean,
val bspMarket: Boolean,
val marketTime: Date,
val suspendTime: Date,
val settleTime: Date,
val bettingType: MarketBettingType,
val turnInPlayEnabled: Boolean,
val marketType: String,
val regulator: String,
val marketBaseRate: Double,
val discountAllowed: Boolean,
val wallet: String,
val rules: String,
val rulesHasDate: Boolean,
val eachWayDivisor: Double,
val clarifications: String,
val lineRangeInfo: MarketLineRangeInfo,
val raceType: String,
val priceLadderDescription: PriceLadderDescription
)
| 0 | Kotlin | 0 | 0 | 41a78b8bb8d20fc8567290b986b06017caeb83bc | 2,754 | Kotlin-Betfair-API | MIT License |
app/src/commonMain/kotlin/de/jonasbroeckmann/nav/utils/Stat.kt | Jojo4GH | 833,423,037 | false | {"Kotlin": 61265, "Shell": 11260, "Batchfile": 233} | package de.jonasbroeckmann.nav.utils
import kotlinx.datetime.Instant
import kotlinx.io.files.Path
fun Path.stat(): Stat = stat(this)
expect fun stat(path: Path): Stat
data class Stat(
val deviceId: ULong,
val serialNumber: ULong,
val mode: Mode,
val userId: UInt,
val groupId: UInt,
val size: Long,
val lastAccessTime: Instant,
val lastModificationTime: Instant,
val lastStatusChangeTime: Instant
) {
data class Mode(
val isBlockDevice: Boolean,
val isCharacterDevice: Boolean,
val isPipe: Boolean,
val isRegularFile: Boolean,
val isDirectory: Boolean,
val isSymbolicLink: Boolean,
val isSocket: Boolean,
val user: Permissions,
val group: Permissions,
val others: Permissions
) {
data class Permissions(
val canRead: Boolean,
val canWrite: Boolean,
val canExecute: Boolean
)
}
}
infix fun UInt.mask(mask: Int): Boolean = (this and mask.toUInt()) != 0u
infix fun UShort.mask(mask: Int): Boolean = (this.toUInt() and mask.toUInt()) != 0u
infix fun UInt.bit(i: Int): Boolean = ((this shr i) and 1u) != 0u
fun Int.fullBinary(): String = (0..<Int.SIZE_BITS)
.reversed()
.map { (this ushr it) and 1 }
.joinToString("")
| 0 | Kotlin | 0 | 4 | da2ff78324854d043c1ffcb9274fd63becb89594 | 1,315 | nav | MIT License |
pluginApi/src/main/java/com/su/mediabox/pluginapi/components/IRankListComponent.kt | ADP-P-P | 464,030,820 | true | {"Kotlin": 26613} | package com.su.mediabox.pluginapi.components
import com.su.mediabox.pluginapi.been.AnimeCoverBean
import com.su.mediabox.pluginapi.been.PageNumberBean
/**
* 获取排行榜界面Tab数据组件
*/
interface IRankListComponent : IBaseComponent {
/**
* 获取排行榜列表数据
*
* @param partUrl 页面部分url,不为null
* @return Pair,不可为null
* List<AnimeCoverBean>:排行榜列表数据List,不为null
* PageNumberBean:下一页数据地址Bean,可为null,为空则没有下一页
*/
suspend fun getRankListData(partUrl: String): Pair<List<AnimeCoverBean>, PageNumberBean?>
} | 0 | Kotlin | 0 | 0 | dcaf9faa2dae5f189d2de39c28f0a1b3f2254949 | 526 | MediaBoxPlugin | Apache License 2.0 |
src/main/kotlin/com/sergeysav/algovis/structures/BSTStructure.kt | SergeySave | 146,689,965 | false | null | package com.sergeysav.algovis.structures
import com.sergeysav.algovis.Delayer
import com.sergeysav.algovis.Drawer
import com.sergeysav.algovis.algorithms.bst.AddAlgorithm
import com.sergeysav.algovis.algorithms.bst.RemoveAlgorithmPredecessor
import com.sergeysav.algovis.algorithms.bst.RemoveAlgorithmSuccessor
import com.sergeysav.algovis.toThe
import kotlin.math.max
/**
* @author sergeys
*
* @constructor Creates a new BSTStructure
*/
class BSTStructure: Structure() {
val delayer = Delayer()
override val algorithms: List<AlgorithmReference> = listOf(
AR("Add", listOf(Param("value"))) { params -> AddAlgorithm(this, params[0]) },
AR("Remove (Predecessor)", listOf(Param("value"))) { params ->
RemoveAlgorithmPredecessor(this, params[0])
},
AR("Remove (Successor)", listOf(Param("value"))) { params -> RemoveAlgorithmSuccessor(this, params[0]) }
)
override val initializationConditions: List<InitializationCondition> = listOf(
ic("Empty") {
root = null
},
ic("Balanced") {
root = Node(0).apply {
left = Node(-10).apply {
left = Node(-20)
right = Node(-5)
}
right = Node(10).apply {
left = Node(5)
right = Node(20)
}
}
},
ic("Degenerate") {
root = Node(0).apply {
right = Node(10).apply {
right = Node(20).apply {
right = Node(30)
}
}
}
}
)
override var initialized: Boolean = false
override fun initDraw(drawer: Drawer) {
drawer.width = (2 toThe (height + 1)) * 4
drawer.height = (3 + height) * 4 - 2 // height + 1 + 2
drawer.beginDraw()
}
override fun draw(drawer: Drawer) {
root?.drawTree(drawer, 0, drawer.width, 4, null)
}
private fun Node.drawTree(drawer: Drawer, left: Int, right: Int, y: Int, parentX: Int?) {
val pos = (left + right) / 2
this.x = pos
this.y = y
if (parentX != null) {
drawer.line(pos, y, parentX, y - 2)
}
this.left?.drawTree(drawer, left, pos, y + 4, pos)
this.right?.drawTree(drawer, pos, right, y + 4, pos)
this.draw(drawer, 0)
}
var root: Node? = null
val height: Int
get() {
return root?.height ?: -1
}
private fun ic(name: String, func: (Int) -> Unit) = IC(name) {
func(it)
initialized = true
}
inner class Node(var data: Int) {
var left: Node? = null
var right: Node? = null
var x: Int = 0
var y: Int = 0
val height: Int
get() {
return max(left?.height ?: -1, right?.height ?: -1) + 1
}
suspend fun setLeft(node: Node?) {
left = node
delayer.doDelay(delayMillis)
}
suspend fun setRight(node: Node?) {
right = node
delayer.doDelay(delayMillis)
}
suspend fun getLeft(): Node? {
delayer.doDelay(delayMillis)
return left
}
suspend fun getRight(): Node? {
delayer.doDelay(delayMillis)
return right
}
fun draw(drawer: Drawer, color: Int) {
drawer.fill(color, x - 1, y, 2, 2)
drawer.text(data.toString(), x - 1, y, 2, 2)
}
}
} | 0 | Kotlin | 0 | 0 | 34452944b6ff8648c7f2844999287a4d1d0f08e6 | 3,822 | Algovis | MIT License |
libnavui-maps/src/test/java/com/mapbox/navigation/ui/maps/util/LimitedQueueTest.kt | mapbox | 87,455,763 | false | {"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624} | package com.mapbox.navigation.ui.maps.util
import org.junit.Assert.assertEquals
import org.junit.Test
internal class LimitedQueueTest {
@Test
fun add() {
val queue = LimitedQueue<Int>(3)
queue.add(1)
checkQueue(listOf(1), queue)
queue.add(2)
checkQueue(listOf(1, 2), queue)
queue.add(3)
checkQueue(listOf(1, 2, 3), queue)
queue.add(4)
checkQueue(listOf(2, 3, 4), queue)
queue.clear()
checkQueue(emptyList(), queue)
queue.add(1)
checkQueue(listOf(1), queue)
}
private fun checkQueue(expected: List<Int>, queue: LimitedQueue<Int>) {
val actual = mutableListOf<Int>()
queue.forEach { actual.add(it) }
assertEquals(expected, actual)
}
}
| 508 | Kotlin | 318 | 621 | 88163ae3d7e34948369d6945d5b78a72bdd68d7c | 791 | mapbox-navigation-android | Apache License 2.0 |
core-kotlin-modules/core-kotlin-numbers-2/src/test/kotlin/com/baeldung/decimalformat/DecimalFormatUnitTest.kt | Baeldung | 260,481,121 | false | {"Kotlin": 1855665, "Java": 48276, "HTML": 4883, "Dockerfile": 292} | package com.baeldung.decimalformat
import org.junit.Test
import java.math.BigDecimal
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.text.NumberFormat
import java.util.*
import kotlin.test.assertFalse
fun formatDoubleUsingFormat(num: Double): String {
return "%.8f".format(Locale.US, num)
}
fun formatUsingBigDecimal(num: Double): String {
return BigDecimal.valueOf(num).toPlainString()
}
fun formatUsingString(num: Double): String {
return String.format(Locale.US, "%.6f", num)
}
fun formatUsingNumberFormat(num: Double): String {
val numberFormat = NumberFormat.getInstance(Locale.US)
numberFormat.maximumFractionDigits = 8
return numberFormat.format(num)
}
fun formatUsingDecimalFormat(num: Double): String {
val symbols = DecimalFormatSymbols(Locale.US)
val df = DecimalFormat("#.###############", symbols)
return df.format(num)
}
class DecimalFormatUnitTest {
@Test
fun `format double using format method`() {
val num = 0.000123456789
val result = formatDoubleUsingFormat(num)
assertFalse(result.contains("E"))
}
@Test
fun `format double using bigdecimal method`() {
val num: Double = 0.000123456789
val result = formatUsingBigDecimal(num)
assertFalse(result.contains("E"))
}
@Test
fun `format double using DecimalFormat method`() {
val num: Double = 0.000123456789
val result = formatUsingDecimalFormat(num)
assertFalse(result.contains("E"))
}
@Test
fun `format double using String method`() {
val num: Double = 0.000123456789
val result = formatUsingString(num)
assertFalse(result.contains("E"))
}
@Test
fun `format double using NumberFormat method`() {
val num: Double = 0.000123456789
val result = formatUsingNumberFormat(num)
assertFalse(result.contains("E"))
}
} | 14 | Kotlin | 294 | 465 | f1ef5d5ded3f7ddc647f1b6119f211068f704577 | 1,934 | kotlin-tutorials | MIT License |
src/main/kotlin/com/mineinabyss/guiy/inventory/GuiyOwner.kt | MineInAbyss | 417,169,083 | false | {"Kotlin": 122298} | package com.mineinabyss.guiy.inventory
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.Snapshot
import com.mineinabyss.guiy.layout.LayoutNode
import com.mineinabyss.guiy.modifiers.click.ClickScope
import com.mineinabyss.guiy.modifiers.Constraints
import com.mineinabyss.guiy.modifiers.drag.DragScope
import com.mineinabyss.guiy.nodes.GuiyNodeApplier
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
val LocalClickHandler: ProvidableCompositionLocal<ClickHandler> =
staticCompositionLocalOf { error("No provider for local click handler") }
val LocalCanvas: ProvidableCompositionLocal<GuiyCanvas?> =
staticCompositionLocalOf { null }
val LocalGuiyOwner: ProvidableCompositionLocal<GuiyOwner> =
staticCompositionLocalOf { error("No provider for GuiyOwner") }
data class ClickResult(
val cancelBukkitEvent: Boolean? = null,
) {
fun mergeWith(other: ClickResult) = ClickResult(
// Prioritize true > false > null
cancelBukkitEvent = (cancelBukkitEvent ?: other.cancelBukkitEvent)?.or(other.cancelBukkitEvent ?: false)
)
}
interface ClickHandler {
fun processClick(scope: ClickScope): ClickResult
fun processDrag(scope: DragScope)
}
@GuiyUIScopeMarker
class GuiyOwner : CoroutineScope {
var hasFrameWaiters = false
val clock = BroadcastFrameClock { hasFrameWaiters = true }
val composeScope = CoroutineScope(Dispatchers.Default) + clock
override val coroutineContext: CoroutineContext = composeScope.coroutineContext
private val rootNode = LayoutNode()
var running = false
private val recomposer = Recomposer(coroutineContext)
private val composition = Composition(GuiyNodeApplier(rootNode), recomposer)
var applyScheduled = false
val snapshotHandle = Snapshot.registerGlobalWriteObserver {
if (!applyScheduled) {
applyScheduled = true
composeScope.launch {
applyScheduled = false
Snapshot.sendApplyNotifications()
}
}
}
var exitScheduled = false
fun exit() {
exitScheduled = true
}
fun start(content: @Composable () -> Unit) {
!running || return
running = true
GuiyScopeManager.scopes += composeScope
launch {
recomposer.runRecomposeAndApplyChanges()
}
launch {
setContent(content)
while (!exitScheduled) {
// Bukkit.getScheduler().scheduleSyncRepeatingTask(guiyPlugin, {
if (hasFrameWaiters) {
hasFrameWaiters = false
clock.sendFrame(System.nanoTime()) // Frame time value is not used by Compose runtime.
rootNode.measure(Constraints())
rootNode.render()
}
delay(50)
}
running = false
recomposer.close()
snapshotHandle.dispose()
composition.dispose()
composeScope.cancel()
}
}
private fun setContent(content: @Composable () -> Unit) {
hasFrameWaiters = true
composition.setContent {
CompositionLocalProvider(LocalClickHandler provides object : ClickHandler {
override fun processClick(scope: ClickScope): ClickResult {
val slot = scope.slot
val width = rootNode.width
return rootNode.children.fold(ClickResult()) { acc, node ->
val w = node.width
val x = if (w == 0) 0 else slot % width
val y = if (w == 0) 0 else slot / width
acc.mergeWith(rootNode.processClick(scope, x, y))
}
}
override fun processDrag(scope: DragScope) {
rootNode.processDrag(scope)
}
}) {
content()
}
}
}
}
fun guiy(
content: @Composable () -> Unit
): GuiyOwner {
return GuiyOwner().apply {
start {
GuiyCompositionLocal(this) {
content()
}
}
}
}
@Composable
fun GuiyCompositionLocal(owner: GuiyOwner, content: @Composable () -> Unit) {
CompositionLocalProvider(
LocalGuiyOwner provides owner
) {
content()
}
}
| 0 | Kotlin | 1 | 37 | bb349827b7a5ea5fb97a4e33e7a979c38377efa2 | 4,406 | guiy-compose | MIT License |
app/src/main/java/dev/johnoreilly/fantasypremierleague/presentation/players/playerDetails/PlayerDetailsView.kt | joreilly | 332,307,418 | false | {"Jupyter Notebook": 389587, "Kotlin": 105304, "Makefile": 43005, "Swift": 11386} | @file:OptIn(ExperimentalMaterial3Api::class)
package dev.johnoreilly.fantasypremierleague.presentation.players.playerDetails
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import dev.johnoreilly.common.domain.entities.Player
import dev.johnoreilly.common.ui.PlayerDetailsViewShared
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlayerDetailsView(player: Player, popBackStack: () -> Unit) {
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(text = player.name)
},
navigationIcon = {
IconButton(onClick = { popBackStack() }) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
}
}
)
}) {
Column(Modifier.padding(it)) {
PlayerDetailsViewShared(player)
}
}
}
| 12 | Jupyter Notebook | 38 | 340 | 3d73617136adc418205eca9165145ced5ff05f00 | 1,452 | FantasyPremierLeague | Apache License 2.0 |
app/src/main/java/com/example/android/marsphotos/ui/foodCustomer/FoodCustomerListAdapter.kt | vietcong00 | 510,071,138 | false | {"Kotlin": 142265, "Java": 47905} | package com.example.android.marsphotos.ui.foodCustomer
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.marsphotos.data.constant.TYPE_DISH_LIST
import com.example.android.marsphotos.data.db.entity.FoodItem
import com.example.android.marsphotos.databinding.ListItemFoodCustomerBinding
class FoodListAdapter internal constructor(
private val viewModel: FoodViewModel,
private val itemFoodCanceledListener: ItemFoodCanceledListener,
) :
ListAdapter<FoodItem, FoodListAdapter.ViewHolder>(UserInfoDiffCallback()) {
class ViewHolder(private val binding: ListItemFoodCustomerBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(
viewModel: FoodViewModel,
item: FoodItem,
position: Int,
itemCanceledListener: ItemFoodCanceledListener
) {
binding.viewmodel = viewModel
binding.foodItem = item
binding.index = position
binding.itemFoodCanceledListener = itemCanceledListener
if(viewModel.foodListType == TYPE_DISH_LIST.foodRequests) {
binding.rightSwipe.visibility = View.VISIBLE
} else{
binding.rightSwipe.visibility = View.GONE
}
binding.executePendingBindings()
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(viewModel, getItem(position), position, itemFoodCanceledListener)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ListItemFoodCustomerBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding)
}
}
class UserInfoDiffCallback : DiffUtil.ItemCallback<FoodItem>() {
override fun areItemsTheSame(
oldItem: FoodItem,
newItem: FoodItem
): Boolean {
return oldItem.food.id === newItem.food.id && oldItem.billingId === newItem.billingId && oldItem.updatedAt === oldItem.updatedAt
}
@SuppressLint("DiffUtilEquals")
override fun areContentsTheSame(
oldItem: FoodItem,
newItem: FoodItem
): Boolean {
return oldItem.note === newItem.note
}
}
class ItemFoodCanceledListener(val clickListener: (index : Int) -> Unit) {
fun canceled(index : Int) = clickListener(index)
} | 0 | Kotlin | 0 | 0 | b5f5fb61ed28009cc932dc2ffbeaf5b89dbae7a4 | 2,632 | DATN-mobile-app | Apache License 2.0 |
sdk/src/main/java/io/customer/sdk/api/interceptors/HeadersInterceptor.kt | customerio | 355,691,391 | false | null | package io.customer.sdk.api.interceptors
import android.util.Base64
import io.customer.sdk.CustomerIO
import okhttp3.Interceptor
import okhttp3.Response
import java.nio.charset.StandardCharsets
internal class HeadersInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val token by lazy { "Basic ${getBasicAuthHeaderString()}" }
val userAgent by lazy { CustomerIO.instance().store.deviceStore.buildUserAgent() }
val request = chain.request()
.newBuilder()
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Authorization", token)
.addHeader("User-Agent", userAgent)
.build()
return chain.proceed(request)
}
private fun getBasicAuthHeaderString(): String {
val apiKey = CustomerIO.instance().config.apiKey
val siteId = CustomerIO.instance().config.siteId
val rawHeader = "$siteId:$apiKey"
return Base64.encodeToString(rawHeader.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
}
}
| 6 | Kotlin | 2 | 0 | a1399dc9f9b2f3c3291f0041d2acab7805588be2 | 1,088 | customerio-android | MIT License |
ktor-api/src/main/kotlin/de/featureide/service/models/ConfigurationFile.kt | OBDDimal | 500,464,865 | false | null | package de.featureide.service.models
import de.featureide.service.models.ConvertedFiles.autoIncrement
import org.jetbrains.exposed.sql.Table
data class ConfigurationFile(
val id: Int,
val name: String,
val algorithm: String,
val t: Int,
val limit: Int,
val content: String,
)
object ConfigurationFiles : Table() {
val id = integer("id").autoIncrement()
val name = varchar("name", 4096)
val algorithm = varchar("algorithm", 4096)
val t = integer("t")
val limit = integer("limit")
val content = text("content")
override val primaryKey = PrimaryKey(id)
} | 0 | Kotlin | 0 | 0 | fb7e62d711de4a3864d51c6ca6ed6345ed9655c9 | 607 | FeatureIDE-Service | MIT License |
src/test/kotlin/no/nav/amt/deltaker/bff/deltaker/api/model/InnholdDtoTest.kt | navikt | 701,285,451 | false | {"Kotlin": 401616, "PLpgSQL": 635, "Dockerfile": 173} | package no.nav.amt.deltaker.bff.deltaker.api.model
import io.kotest.matchers.shouldBe
import no.nav.amt.deltaker.bff.deltakerliste.tiltakstype.Innholdselement
import no.nav.amt.deltaker.bff.deltakerliste.tiltakstype.annetInnholdselement
import no.nav.amt.deltaker.bff.utils.data.TestData
import org.junit.Test
class InnholdDtoTest {
@Test
fun testFinnValgtInnhold() {
val innholdselement = Innholdselement("Type", "type")
val deltaker = TestData.lagDeltaker(
deltakerliste = TestData.lagDeltakerliste(
tiltak = TestData.lagTiltakstype(
innhold = TestData.lagDeltakerRegistreringInnhold(
innholdselementer = listOf(innholdselement, annetInnholdselement),
),
),
),
)
val annetBeskrivelse = "annet må ha en beskrivelse"
val valgtInnhold = finnValgtInnhold(
innhold = listOf(
InnholdDto(innholdselement.innholdskode, null),
InnholdDto(annetInnholdselement.innholdskode, annetBeskrivelse),
),
deltaker = deltaker,
)
valgtInnhold shouldBe listOf(
innholdselement.toInnhold(true),
annetInnholdselement.toInnhold(true, annetBeskrivelse),
)
}
}
| 1 | Kotlin | 0 | 0 | 7963da306b83804ebaa226fcab4c93565f14f5bf | 1,328 | amt-deltaker-bff | MIT License |
src/main/java/io/dotanuki/burster/burst10.kt | ubiratansoares | 144,885,208 | false | null | package io.dotanuki.burster
fun <A, B, C, D, E, F, G, H, I, J> using(block: Buster10<A, B, C, D, E, F, G, H, I, J>.() -> Unit) =
Buster10<A, B, C, D, E, F, G, H, I, J>().apply { block() }.execute()
class Buster10<A, B, C, D, E, F, G, H, I, J> {
private val container by lazy { Bullets10<A, B, C, D, E, F, G, H, I, J>() }
private var target: ((A, B, C, D, E, F, G, H, I, J) -> Unit)? = null
fun burst(block: Bullets10<A, B, C, D, E, F, G, H, I, J>.() -> Unit) {
container.apply { block() }
}
fun thenWith(assertion: (A, B, C, D, E, F, G, H, I, J) -> Unit) {
target = assertion
}
internal fun execute() = with(container.bullets) {
if (isEmpty()) throw BursterError.NoValues
forEach {
target
?.invoke(it.a, it.b, it.c, it.d, it.e, it.f, it.g, it.h, it.i, it.j)
?: throw BursterError.NoTarget
}
}
}
class Bullets10<A, B, C, D, E, F, G, H, I, J> {
internal val bullets = mutableListOf<T10<A, B, C, D, E, F, G, H, I, J>>()
fun values(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J) {
bullets += T10(a, b, c, d, e, f, g, h, i, j)
}
} | 0 | Kotlin | 0 | 1 | 35c8d22b3ae8b4a357cbb33c2d3b0d3ec3f09cf3 | 1,187 | burster | MIT License |
consumer/src/main/kotlin/streams/kafka/KafkaEventSink.kt | soumikroy80 | 245,561,439 | true | {"Kotlin": 628209, "Python": 4123} | package streams.kafka
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.neo4j.kernel.configuration.Config
import org.neo4j.kernel.internal.GraphDatabaseAPI
import org.neo4j.logging.Log
import streams.StreamsEventConsumer
import streams.StreamsEventConsumerFactory
import streams.StreamsEventSink
import streams.StreamsEventSinkQueryExecution
import streams.StreamsSinkConfiguration
import streams.StreamsSinkConfigurationConstants
import streams.StreamsTopicService
import streams.service.errors.ErrorService
import streams.service.errors.KafkaErrorService
import streams.utils.KafkaValidationUtils.getInvalidTopicsError
import streams.utils.Neo4jUtils
import streams.utils.StreamsUtils
import java.util.concurrent.TimeUnit
class KafkaEventSink(private val config: Config,
private val queryExecution: StreamsEventSinkQueryExecution,
private val streamsTopicService: StreamsTopicService,
private val log: Log,
private val db: GraphDatabaseAPI): StreamsEventSink(config, queryExecution, streamsTopicService, log, db) {
private lateinit var eventConsumer: StreamsEventConsumer
private lateinit var job: Job
override val streamsConfigMap = config.raw.filterKeys {
it.startsWith("kafka.") || (it.startsWith("streams.") && !it.startsWith("streams.sink.topic.cypher."))
}.toMap()
override val mappingKeys = mapOf(
"zookeeper" to "kafka.zookeeper.connect",
"broker" to "kafka.${ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG}",
"from" to "kafka.${ConsumerConfig.AUTO_OFFSET_RESET_CONFIG}",
"autoCommit" to "kafka.${ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG}",
"keyDeserializer" to "kafka.${ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG}",
"valueDeserializer" to "kafka.${ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG}",
"schemaRegistryUrl" to "kafka.schema.registry.url",
"groupId" to "kafka.${ConsumerConfig.GROUP_ID_CONFIG}")
override fun getEventConsumerFactory(): StreamsEventConsumerFactory {
return object: StreamsEventConsumerFactory() {
override fun createStreamsEventConsumer(config: Map<String, String>, log: Log): StreamsEventConsumer {
val kafkaConfig = KafkaSinkConfiguration.from(config)
val errorService = KafkaErrorService(kafkaConfig.asProperties(), ErrorService.ErrorConfig.from(kafkaConfig.streamsSinkConfiguration.errorConfig),{ s, e -> log.error(s,e as Throwable)})
return if (kafkaConfig.enableAutoCommit) {
KafkaAutoCommitEventConsumer(kafkaConfig, log, errorService)
} else {
KafkaManualCommitEventConsumer(kafkaConfig, log, errorService)
}
}
}
}
override fun start() { // TODO move to the abstract class
val streamsConfig = StreamsSinkConfiguration.from(config)
val topics = streamsTopicService.getTopics()
val isWriteableInstance = Neo4jUtils.isWriteableInstance(db)
if (!streamsConfig.enabled) {
if (topics.isNotEmpty() && isWriteableInstance) {
log.warn("You configured the following topics: $topics, in order to make the Sink work please set the `${StreamsSinkConfigurationConstants.STREAMS_CONFIG_PREFIX}${StreamsSinkConfigurationConstants.ENABLED}` to `true`")
}
return
}
log.info("Starting the Kafka Sink")
this.eventConsumer = getEventConsumerFactory()
.createStreamsEventConsumer(config.raw, log)
.withTopics(topics)
this.eventConsumer.start()
this.job = createJob()
if (isWriteableInstance) {
if (log.isDebugEnabled) {
streamsTopicService.getAll().forEach {
log.debug("Subscribed topics for type ${it.key} are: ${it.value}")
}
} else {
log.info("Subscribed topics: $topics")
}
}
log.info("Kafka Sink started")
}
override fun stop() = runBlocking { // TODO move to the abstract class
log.info("Stopping Kafka Sink daemon Job")
try {
job.cancelAndJoin()
log.info("Kafka Sink daemon Job stopped")
} catch (e : UninitializedPropertyAccessException) { /* ignoring this one only */ }
}
private fun createJob(): Job {
log.info("Creating Sink daemon Job")
return GlobalScope.launch(Dispatchers.IO) { // TODO improve exception management
try {
while (isActive) {
val timeMillis = if (Neo4jUtils.isWriteableInstance(db)) {
eventConsumer.read { topic, data ->
if (log.isDebugEnabled) {
log.debug("Reading data from topic $topic")
}
queryExecution.writeForTopic(topic, data)
}
TimeUnit.SECONDS.toMillis(1)
} else {
val timeMillis = TimeUnit.MINUTES.toMillis(5)
if (log.isDebugEnabled) {
log.debug("Not in a writeable instance, new check in $timeMillis millis")
}
timeMillis
}
delay(timeMillis)
}
eventConsumer.stop()
} catch (e: Throwable) {
val message = e.message ?: "Generic error, please check the stack trace: "
log.error(message, e)
eventConsumer.stop()
}
}
}
override fun printInvalidTopics() {
StreamsUtils.ignoreExceptions({
if (eventConsumer.invalidTopics().isNotEmpty()) {
log.warn(getInvalidTopicsError(eventConsumer.invalidTopics()))
}
}, UninitializedPropertyAccessException::class.java)
}
}
| 0 | Kotlin | 0 | 0 | b5b004c7df6b0c80041cc705915ed41d4e8d3243 | 6,372 | neo4j-streams | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/linear/Useredit.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.linear
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
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 moe.tlaster.icons.vuesax.vuesaxicons.LinearGroup
public val LinearGroup.Useredit: ImageVector
get() {
if (_useredit != null) {
return _useredit!!
}
_useredit = Builder(name = "Useredit", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 12.0f)
curveTo(14.7614f, 12.0f, 17.0f, 9.7614f, 17.0f, 7.0f)
curveTo(17.0f, 4.2386f, 14.7614f, 2.0f, 12.0f, 2.0f)
curveTo(9.2386f, 2.0f, 7.0f, 4.2386f, 7.0f, 7.0f)
curveTo(7.0f, 9.7614f, 9.2386f, 12.0f, 12.0f, 12.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(19.2101f, 15.74f)
lineTo(15.67f, 19.2801f)
curveTo(15.53f, 19.4201f, 15.4f, 19.68f, 15.37f, 19.87f)
lineTo(15.18f, 21.22f)
curveTo(15.11f, 21.71f, 15.45f, 22.05f, 15.94f, 21.98f)
lineTo(17.29f, 21.79f)
curveTo(17.48f, 21.76f, 17.75f, 21.63f, 17.88f, 21.49f)
lineTo(21.42f, 17.95f)
curveTo(22.03f, 17.34f, 22.32f, 16.63f, 21.42f, 15.73f)
curveTo(20.53f, 14.84f, 19.8201f, 15.13f, 19.2101f, 15.74f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.7001f, 16.25f)
curveTo(19.0001f, 17.33f, 19.84f, 18.17f, 20.92f, 18.47f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(3.4099f, 22.0f)
curveTo(3.4099f, 18.13f, 7.2599f, 15.0f, 11.9999f, 15.0f)
curveTo(13.0399f, 15.0f, 14.0399f, 15.15f, 14.9699f, 15.43f)
}
}
.build()
return _useredit!!
}
private var _useredit: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 3,465 | VuesaxIcons | MIT License |
src/main/kotlin/srsm/data/Foto.kt | simonorono | 635,535,182 | false | null | /*
* Copyright 2016 Sociedad Religiosa Servidores de María
*
* 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 srsm.data
import org.jdbi.v3.core.mapper.RowMapper
import org.jdbi.v3.core.statement.StatementContext
import org.jdbi.v3.sqlobject.config.RegisterRowMapper
import org.jdbi.v3.sqlobject.statement.SqlQuery
import srsm.model.Servidor
import java.sql.ResultSet
class FotoMapper : RowMapper<ByteArray> {
override fun map(rs: ResultSet, ctx: StatementContext): ByteArray {
return rs.getBytes("foto")
}
}
@RegisterRowMapper(FotoMapper::class)
interface FotoDAO {
@SqlQuery("")
fun hasFoto(s: Servidor): Boolean
}
| 0 | Kotlin | 0 | 0 | 80f0ff77529ee29eed664bbb74d2ad4b52d03ab3 | 1,164 | SRSM | Apache License 2.0 |
app/src/main/java/com/example/ranich/ui/component/cardItem/PersonalCard.kt | NoraHeithur | 791,614,008 | false | {"Kotlin": 164741} | package com.example.ranich.ui.component.cardItem
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.material.icons.outlined.Phone
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.text.font.FontWeight
import com.example.ranich.R
import com.example.ranich.domain.model.Contact
import com.example.ranich.ui.component.card.CardType
import com.example.ranich.ui.component.text.RobotoText
import com.example.ranich.ui.theme.Color_On_Surface
import com.example.ranich.ui.theme.Color_Primary
@Composable
fun PersonalCard(
modifier: Modifier,
contact: Contact,
) {
Column(
modifier = modifier.padding(all = dimensionResource(id = R.dimen.margin_padding_16))
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Icon(
modifier = modifier,
imageVector = if (contact.cardType == CardType.ADDRESS) {
Icons.Outlined.LocationOn
} else {
Icons.Outlined.Phone
},
tint = Color_On_Surface,
contentDescription = null
)
Spacer(modifier = modifier.width(dimensionResource(id = R.dimen.margin_padding_8)))
RobotoText(
modifier = modifier,
text = contact.cardType.toString(),
color = Color_On_Surface
)
}
Spacer(modifier = modifier.width(dimensionResource(id = R.dimen.margin_padding_8)))
RobotoText(
modifier = modifier
.padding(
start = dimensionResource(id = R.dimen.margin_padding_32),
top = dimensionResource(id = R.dimen.margin_padding_8)
),
text = if (contact.cardType == CardType.ADDRESS) {
contact.name
} else {
contact.contactNumber
},
color = Color_Primary,
weight = FontWeight.Bold
)
if (contact.cardType == CardType.ADDRESS) {
RobotoText(
modifier = modifier
.padding(
start = dimensionResource(id = R.dimen.margin_padding_32),
top = dimensionResource(id = R.dimen.margin_padding_8)
),
text = contact.relationship,
color = Color_On_Surface,
maxLines = Int.MAX_VALUE
)
}
}
} | 0 | Kotlin | 0 | 0 | 1bf6fe606862a7d29d2598f60d9abe89fba2b572 | 2,977 | Ranich | MIT License |
app/src/main/kotlin/com/hyosakura/imagehub/entity/relation/FolderWithFolder.kt | android-app-development-course | 416,623,247 | false | null | package com.hyosakura.imagehub.entity.relation
import androidx.room.Embedded
import androidx.room.Relation
import com.hyosakura.imagehub.entity.FolderEntity
data class FolderWithFolder(
@field:Embedded val folder: FolderEntity,
@field:Relation(
parentColumn = "folderId",
entityColumn = "parentId"
)
val childDirs: List<FolderEntity>
)
| 0 | Kotlin | 0 | 0 | a944c49b1e6afc24fb76c922d94c398297ecfa49 | 370 | 2021autumn-B5-ImageHub | MIT License |
examples/src/tl/ton/validatorsession/ValidatorSessionStats.kt | andreypfau | 719,064,910 | false | {"Kotlin": 62259} | // This file is generated by TLGenerator.kt
// Do not edit manually!
package tl.ton.validatorsession
import io.github.andreypfau.tl.serialization.Base64ByteStringSerializer
import io.github.andreypfau.tl.serialization.TLCombinatorId
import io.github.andreypfau.tl.serialization.TLFixedSize
import kotlin.jvm.JvmName
import kotlinx.io.bytestring.ByteString
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import tl.ton.tonnode.TonNodeBlockId
@Serializable
@SerialName("validatorSession.stats")
@TLCombinatorId(0x684D5A8F)
public data class ValidatorSessionStats(
@get:JvmName("id")
public val id: TonNodeBlockId,
@get:JvmName("timestamp")
public val timestamp: Long,
@TLFixedSize(value = 32)
@get:JvmName("self")
public val self: @Serializable(Base64ByteStringSerializer::class) ByteString,
@TLFixedSize(value = 32)
@get:JvmName("creator")
public val creator: @Serializable(Base64ByteStringSerializer::class) ByteString,
@SerialName("total_validators")
@get:JvmName("totalValidators")
public val totalValidators: Int,
@SerialName("total_weight")
@get:JvmName("totalWeight")
public val totalWeight: Long,
@get:JvmName("signatures")
public val signatures: Int,
@SerialName("signatures_weight")
@get:JvmName("signaturesWeight")
public val signaturesWeight: Long,
@SerialName("approve_signatures")
@get:JvmName("approveSignatures")
public val approveSignatures: Int,
@SerialName("approve_signatures_weight")
@get:JvmName("approveSignaturesWeight")
public val approveSignaturesWeight: Long,
@SerialName("first_round")
@get:JvmName("firstRound")
public val firstRound: Int,
@get:JvmName("rounds")
public val rounds: List<ValidatorSessionStatsRound>,
) {
public companion object
}
| 0 | Kotlin | 0 | 1 | 11f05ad1f977235e3e360cd6f6ada6f26993208e | 1,841 | tl-kotlin | MIT License |
hardware/src/main/java/hmju/tracking/hardware/HardwareTrackingModel.kt | sieunju | 487,008,552 | false | {"Kotlin": 106420} | package hmju.tracking.hardware
import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
import android.bluetooth.le.ScanResult
import android.nfc.tech.Ndef
import android.os.Build
import android.os.SystemClock
import androidx.core.util.forEach
import androidx.core.util.isNotEmpty
import hmju.tracking.model.ChildModel
import hmju.tracking.model.ContentsModel
import hmju.tracking.model.SummaryModel
import hmju.tracking.model.TitleModel
import hmju.tracking.model.TrackingModel
import java.text.SimpleDateFormat
import java.util.Locale
@SuppressLint("MissingPermission")
class HardwareTrackingModel : TrackingModel {
companion object {
private val dateFmt: SimpleDateFormat by lazy {
SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault())
}
}
constructor(
data: ScanResult
) {
setSummary(initSummary(data))
setReqModels(initReqModels(data))
}
constructor(gatt: BluetoothGatt) {
setSummary(initSummary(gatt))
setReqModels(initReqModels(gatt))
}
constructor(
gatt: BluetoothGatt,
byteArray: ByteArray
) {
setSummary(initSummary(gatt))
setReqModels(initReqModels(gatt))
setResModels(initResModels(byteArray))
}
constructor(ndef: Ndef) {
setSummary(initSummary(ndef))
setReqModels(initReqModels(ndef))
}
/**
* init Summary Bluetooth Advertising Type
* @param data BLE ADV Data
*/
private fun initSummary(data: ScanResult): SummaryModel {
val bootTimeMillis = System.currentTimeMillis() - SystemClock.elapsedRealtime()
val device = data.device
return SummaryModel(
colorHexCode = "#367CEE",
titleList = listOf(
"🛜BLE",
"Advertising",
dateFmt.format(bootTimeMillis + (data.timestampNanos / 1_000_000L))
),
contentsList = listOf(
if (!device.name.isNullOrEmpty()) device.name else "Empty Name",
device.address,
"${data.rssi}dBm"
)
)
}
private fun initSummary(data: BluetoothGatt): SummaryModel {
val device = data.device
return SummaryModel(
colorHexCode = "#367CEE",
titleList = listOf(
"🛜BLE",
"Connect",
dateFmt.format(System.currentTimeMillis())
),
contentsList = listOf(
if (!device.name.isNullOrEmpty()) device.name else "Empty Name",
device.address,
"-"
)
)
}
private fun initSummary(data: Ndef): SummaryModel {
return SummaryModel(
colorHexCode = "#FFC619",
titleList = listOf(
"🏷️NFC",
"Tag",
dateFmt.format(System.currentTimeMillis())
),
contentsList = listOf(
data.type,
"${data.maxSize}",
"-"
)
)
}
/**
* Ble Advertising Data
* @param data BLE ADV Data
*/
private fun initReqModels(
data: ScanResult
): List<ChildModel> {
val list = mutableListOf<ChildModel>()
val device = data.device
list.add(TitleModel(hexCode = "#C62828", text = "[Device]"))
if (!device.name.isNullOrEmpty()) {
list.add(ContentsModel(text = "Name:${device.name}"))
}
list.add(ContentsModel(hexCode = "#222222", text = device.address))
when (device.type) {
BluetoothDevice.DEVICE_TYPE_LE -> "Low Energy"
BluetoothDevice.DEVICE_TYPE_DUAL -> "Dual Mode"
BluetoothDevice.DEVICE_TYPE_CLASSIC -> "Classic"
BluetoothDevice.DEVICE_TYPE_UNKNOWN -> "Unknown"
else -> "Invalid"
}.run { list.add(ContentsModel(hexCode = "#222222", text = "Device type:${this}")) }
list.add(ContentsModel(hexCode = "#222222", text = "📶${data.rssi}dBm"))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val phy = when (data.primaryPhy) {
BluetoothDevice.PHY_LE_1M -> "LE 1M"
BluetoothDevice.PHY_LE_2M -> "LE 2M"
BluetoothDevice.PHY_LE_CODED -> "LE Coded"
else -> "Unknown"
}
list.add(ContentsModel(hexCode = "#222222", text = "Phy:${phy}"))
list.add(ContentsModel(text = "Connectable:${data.isConnectable}"))
}
val scanRecord = data.scanRecord
if (scanRecord != null) {
if (!scanRecord.serviceUuids.isNullOrEmpty()) {
list.add(TitleModel("#C62828", "[UUID]"))
scanRecord.serviceUuids.forEach {
list.add(ContentsModel(hexCode = "#222222", text = it.uuid.toString()))
}
}
if (scanRecord.manufacturerSpecificData.isNotEmpty()) {
list.add(TitleModel("#C62828", "[Manufacture]"))
scanRecord.manufacturerSpecificData.forEach { key, value ->
ContentsModel(
hexCode = "#222222",
text = "ID:${String.format("0x%04X", key)}"
).run { list.add(this) }
ContentsModel(
hexCode = "#222222",
text = value.joinToString { String.format("%02X", it) }
).run { list.add(this) }
}
}
}
return list
}
private fun initReqModels(
gatt: BluetoothGatt
): List<ChildModel> {
val list = mutableListOf<ChildModel>()
val device = gatt.device
list.add(TitleModel("#C62828", "[Device]"))
if (!device.name.isNullOrEmpty()) {
list.add(ContentsModel(text = "Name:${device.name}"))
}
list.add(ContentsModel(hexCode = "#222222", text = device.address))
when (device.type) {
BluetoothDevice.DEVICE_TYPE_LE -> "Low Energy"
BluetoothDevice.DEVICE_TYPE_DUAL -> "Dual Mode"
BluetoothDevice.DEVICE_TYPE_CLASSIC -> "Classic"
BluetoothDevice.DEVICE_TYPE_UNKNOWN -> "Unknown"
else -> "Invalid"
}.run { list.add(ContentsModel(hexCode = "#222222", text = "DeviceType\n${this}")) }
if (!gatt.services.isNullOrEmpty()) {
gatt.services.forEach { service ->
list.add(TitleModel("#C62828", "Service: ${service.uuid}"))
when (service.type) {
BluetoothGattService.SERVICE_TYPE_PRIMARY -> "PRIMARY"
BluetoothGattService.SERVICE_TYPE_SECONDARY -> "SECONDARY"
else -> "Unknown Type"
}.run { list.add(ContentsModel(hexCode = "#222222", text = "ServiceType: $this")) }
service.characteristics.forEach { characteristic ->
val str = StringBuilder("Characteristic")
str.appendLine("\t${characteristic.uuid}")
when (characteristic.writeType) {
BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT -> "DEFAULT"
BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE -> "NO_RESPONSE"
BluetoothGattCharacteristic.WRITE_TYPE_SIGNED -> "SIG"
else -> "Unknown"
}.run { str.appendLine("WriteType: $this") }
if (!characteristic.descriptors.isNullOrEmpty()) {
str.appendLine("Descriptors")
characteristic.descriptors.forEach { descriptor ->
str.appendLine("\t${descriptor.uuid}")
}
}
characteristic.properties.also { properties ->
str.append("Properties:")
val propertyList = mutableListOf<String>()
if (properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0) {
propertyList.add("NOTIFICATION")
}
if (properties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0) {
propertyList.add("INDICATE")
}
if (properties and BluetoothGattCharacteristic.PROPERTY_READ != 0) {
propertyList.add("READ")
}
if (properties and BluetoothGattCharacteristic.PROPERTY_WRITE != 0) {
propertyList.add("WRITE")
}
str.appendLine(propertyList.joinToString(", "))
}
list.add(TitleModel("#222222", str))
}
}
}
return list
}
private fun initReqModels(
data: Ndef
): List<ChildModel> {
val list = mutableListOf<ChildModel>()
ContentsModel(
hexCode = "#222222",
text = "Type: ${data.type}"
).run { list.add(this) }
ContentsModel(
hexCode = "#222222",
text = "Size: ${data.maxSize}"
).run { list.add(this) }
val records = data.ndefMessage?.records
if (records != null) {
TitleModel(
hexCode = "#C62828",
text = "[RAW]"
).run { list.add(this) }
val payload = records[0].payload
ContentsModel(
hexCode = "#222222",
text = payload.joinToString { String.format("%02X", it) }
).run { list.add(this) }
}
val cacheRecords = data.cachedNdefMessage?.records
if (cacheRecords != null) {
TitleModel(
hexCode = "#C62828",
text = "[Cache RAW]"
).run { list.add(this) }
val payload = cacheRecords[0].payload
ContentsModel(
hexCode = "#222222",
text = payload.joinToString { String.format("%02X", it) }
).run { list.add(this) }
}
return list
}
private fun initResModels(
bytes: ByteArray
): List<ChildModel> {
val list = mutableListOf<ChildModel>()
list.add(TitleModel(hexCode = "#C62828", text = "[${bytes.size} Bytes]"))
ContentsModel(
hexCode = "#222222",
text = bytes.joinToString { String.format("%02X", it) }
).run { list.add(this) }
return list
}
} | 0 | Kotlin | 1 | 8 | 30dbbf11f7405bf6a5d4e7bfe34b2b1a95047ed7 | 10,796 | httptracking | MIT License |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DSolveValue.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: DSolveValue
*
* Full name: System`DSolveValue
*
* DSolveValue[eqn, expr, x] gives the value of expr determined by a symbolic solution to the ordinary differential equation eqn with independent variable x.
* DSolveValue[eqn, expr, {x, x , x }] uses a symbolic solution for x between x and x .
* min max min max
* DSolveValue[{eqn , eqn , …}, expr, …] uses a symbolic solution for a list of differential equations.
* 1 2
* DSolveValue[eqn, expr, {x , x , …}] uses a solution for the partial differential equation eqn.
* 1 2
* DSolveValue[eqn, expr, {x , x , …} ∈ Ω] uses a solution of the partial differential equation eqn over the region Ω.
* Usage: 1 2
*
* Assumptions :> $Assumptions
* DependentVariables -> Automatic
* DiscreteVariables -> {}
* GeneratedParameters -> C
* Options: Method -> Automatic
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/DSolveValue
* Documentation: web: http://reference.wolfram.com/language/ref/DSolveValue.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun dSolveValue(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("DSolveValue", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 2,039 | mathemagika | Apache License 2.0 |
app/src/main/java/io/curity/haapidemo/utils/FocusChangeListener.kt | curityio | 298,594,142 | false | null | package io.curity.haapidemo.utils
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.core.content.ContextCompat
class FocusChangeListener: View.OnFocusChangeListener {
private fun hideKeyboard(view: View) {
val inputMethodManager: InputMethodManager = ContextCompat.getSystemService(
view.context,
InputMethodManager::class.java
)!!
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
override fun onFocusChange(v: View, hasFocus: Boolean) {
if (!hasFocus) {
hideKeyboard(v)
}
}
} | 0 | Kotlin | 0 | 0 | 6abb398157a6e0841323cf3f61e00b5f15bb5d87 | 631 | android-haapi-demo-app | Apache License 2.0 |
app/src/main/kotlin/com/faltenreich/skeletonlayout/logic/RecyclerViewListItem.kt | ema987 | 175,460,231 | true | {"Kotlin": 35753, "Java": 1330} | package com.faltenreich.skeletonlayout.logic
import android.support.annotation.DrawableRes
import android.support.annotation.StringRes
data class RecyclerViewListItem(
@StringRes val titleResId: Int,
@StringRes val descriptionResId: Int,
@DrawableRes val avatarResId: Int,
@DrawableRes val wallpaperResId: Int
) | 0 | Kotlin | 0 | 0 | a9b843b7f45b3831379f6f34a0a5cce9fabcebf8 | 345 | SkeletonLayout | Apache License 2.0 |
feature/spell/domain/src/commonMain/kotlin/com/nesterov/veld/domain/usecases/FetchSpellListUseCase.kt | anaesthez | 793,406,212 | false | {"Kotlin": 213315, "Ruby": 1684, "Swift": 522, "HTML": 275} | package com.nesterov.veld.domain.usecases
import com.nesterov.veld.common.RequestResult
import com.nesterov.veld.domain.SpellRepository
import com.nesterov.veld.domain.model.SpellDomainModel
class FetchSpellListUseCase(private val repository: SpellRepository) {
suspend operator fun invoke(): RequestResult<List<SpellDomainModel>> = repository.fetchSpellList()
} | 0 | Kotlin | 0 | 0 | 36fa1319b81c41939105b9af03066d960d3ad6ac | 368 | veld | MIT License |
src/main/kotlin/me/cunzai/plugin/customeconomy/database/MySQLHandler.kt | EmptyIrony | 850,999,878 | false | {"Kotlin": 24840} | package me.cunzai.plugin.customeconomy.database
import me.cunzai.plugin.customeconomy.config.ConfigLoader
import me.cunzai.plugin.customeconomy.data.PlayerClaimData
import me.cunzai.plugin.customeconomy.misc.getLastAndNextExecutionTime
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import taboolib.common.platform.event.SubscribeEvent
import taboolib.common.platform.function.submit
import taboolib.common.platform.function.submitAsync
import taboolib.module.configuration.Config
import taboolib.module.configuration.Configuration
import taboolib.module.database.*
import java.time.ZoneId
object MySQLHandler {
@Config("database.yml")
lateinit var config: Configuration
private val host by lazy {
config.getHost("mysql")
}
val datasource by lazy {
host.createDataSource()
}
val tables = HashMap<String, Table<Host<SQL>, SQL>>()
val claimTables = HashMap<String, Table<Host<SQL>, SQL>>()
fun init() {
tables.clear()
for (economyName in ConfigLoader.knownEconomyType) {
tables[economyName] = Table("economy_${economyName}", host) {
add {
id()
}
add ("player_name"){
type(ColumnTypeSQL.VARCHAR, 64) {
options(ColumnOptionSQL.KEY)
}
}
add("value") {
type(ColumnTypeSQL.INT)
}
add("last_refresh_at") {
type(ColumnTypeSQL.BIGINT)
}
}.apply {
workspace(datasource) {
createTable(checkExists = true)
}.run()
}
claimTables[economyName] = Table("economy_claim_${economyName}", host) {
add {
id()
}
add("player_name") {
type(ColumnTypeSQL.VARCHAR, 64) {
options(ColumnOptionSQL.KEY)
}
}
add("last_refresh_at") {
type(ColumnTypeSQL.BIGINT)
}
add("claim_data") {
type(ColumnTypeSQL.TEXT)
}
}.apply {
workspace(datasource) {
createTable(checkExists = true)
}.run()
}
}
}
fun getValue(name: String, economyName: String): Int? {
val table = tables[economyName] ?: return null
return table.workspace(datasource) {
select {
where {
("player_name" eq name)
}
}
}.firstOrNull {
val cron = ConfigLoader.economyCleanCron[name]
if (cron != null) {
val refreshedAt = getLong("last_refresh_at")
val lastCleanTime = cron.getLastAndNextExecutionTime().first
val lastCleanTimestamp = lastCleanTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
if (lastCleanTimestamp > refreshedAt) {
table.workspace(datasource) {
update {
set("value", 0)
set("last_refresh_at", System.currentTimeMillis())
where {
"player_name" eq name
}
}
}.run()
return@firstOrNull 0
}
}
return@firstOrNull getInt("value")
} ?: run {
table.workspace(datasource) {
insert("player_name", "value", "last_refresh_at") {
value(name, 0, System.currentTimeMillis())
}
}.run()
0
}
}
fun setValue(name: String, economyName: String, value: Int) {
val table = tables[economyName] ?: return
// refresh first
getValue(name, economyName)
table.workspace(datasource) {
update {
set("value", value)
set("last_refresh_at", System.currentTimeMillis())
where {
"player_name" eq name
}
}
}.run()
}
@SubscribeEvent
fun e(e: PlayerJoinEvent) {
val player = e.player
submitAsync {
for (economyType in ConfigLoader.economyCleanCron.keys) {
val table = claimTables[economyType] ?: continue
val data = table.workspace(datasource) {
select {
where {
"player_name" eq player.name
}
}
}.firstOrNull {
val lastRefresh = getLong("last_refresh_at")
val claimData = getString("claim_data")
val data = PlayerClaimData(player.name, economyType)
val split = claimData?.split(";")
data.lastRefresh = lastRefresh
if (split?.isNotEmpty() == true) {
data.claimed += split.toSet()
}
data
} ?: run {
table.workspace(datasource) {
insert("player_name", "last_refresh_at") {
value(player.name, System.currentTimeMillis())
}
}.run()
PlayerClaimData(player.name, economyType).apply {
lastRefresh = System.currentTimeMillis()
}
}
if (!player.isOnline) {
return@submitAsync
}
PlayerClaimData.cache.getOrPut(player.name) {
HashMap()
}[economyType] = data
}
}
}
fun PlayerClaimData.save() {
val table = claimTables[economyType] ?: return
table.workspace(datasource) {
update {
set("last_refresh_at", System.currentTimeMillis())
set("claim_data", claimed.joinToString(";"))
where {
"player_name" eq playerName
}
}
}.run()
}
@SubscribeEvent
fun e(e: PlayerQuitEvent) {
PlayerClaimData.cache.remove(e.player.name)
}
} | 0 | Kotlin | 0 | 0 | 786c3688b267e7ee66aab589155e4a4188a6e7ae | 6,583 | CustomEconomy | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/bradyaiello/fiveespells/di/RepositoryModule.kt | brady-aiello | 315,797,176 | false | null | package com.bradyaiello.fiveespells.di
import android.content.Context
import com.bradyaiello.fiveespells.Database
import com.bradyaiello.fiveespells.repository.SpellRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
object RepositoryModule {
@Singleton
@Provides
fun provideSpellRepository(
@ApplicationContext context: Context,
spellDatabase: Database,
): SpellRepository = SpellRepository(
context, spellDatabase
)
} | 0 | Kotlin | 0 | 0 | 4d75095e8142631f62fe324f5fa0f130b6deeb30 | 680 | FiveESpells | MIT License |
src/main/kotlin/com/github/w0819/game/uhc/recipes/ApprenticeSword.kt | dolphin2410-archive | 421,782,870 | true | {"Kotlin": 152472} | package com.github.w0819.game.uhc.recipes
import com.github.w0819.game.util.Item
import com.github.w0819.game.util.uhc.UHCRecipe
import org.bukkit.Material
import org.bukkit.NamespacedKey
class ApprenticeSword: UHCRecipe(
NamespacedKey.minecraft("apprentice_sword"),
Item.apprentice_Sword
) {
init {
shape(
" 1 ",
" 2 ",
" 1 "
)
setIngredient('1', Material.REDSTONE_BLOCK)
setIngredient('2', Material.IRON_SWORD)
}
} | 0 | Kotlin | 0 | 0 | a31b2a8f49f86250568a328ab9272adcc8896887 | 502 | UHC_System | MIT License |
app/src/main/java/com/oyamo/kontributor/domain/use_case/GetUserRepos.kt | oyamo | 542,380,740 | false | {"Kotlin": 93759} | package com.oyamo.kontributor.domain.use_case
import com.oyamo.kontributor.domain.model.Repo
import com.oyamo.kontributor.domain.repository.UserRepository
import com.oyamo.kontributor.util.Resource
import kotlinx.coroutines.flow.Flow
class GetUserRepos(private val userRepository: UserRepository) {
suspend operator fun invoke(username: String): Flow<Resource<List<Repo>>> {
return userRepository.getUserRepos(username)
}
} | 0 | Kotlin | 0 | 0 | 750fc7a25df267f2322d9e6eb38666e4a8906e9a | 441 | Kontributors | Apache License 2.0 |
src/test/resources/test-compile-data/jvm/kotlin-web-site/kotlin-tour-collections/482d5a5110b4d39d7886e0944ba418d7.6.kt | JetBrains | 219,478,945 | false | {"Kotlin": 489501, "Dockerfile": 2244, "Shell": 290} | fun main() {
//sampleStart
val shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
// Add "pentagon" to the list
shapes.add("pentagon")
println(shapes)
// [triangle, square, circle, pentagon]
// Remove the first "pentagon" from the list
shapes.remove("pentagon")
println(shapes)
// [triangle, square, circle]
//sampleEnd
} | 28 | Kotlin | 73 | 248 | ac53213b767d07f49fa48c5d99fedeb499b9b934 | 390 | kotlin-compiler-server | Apache License 2.0 |
components/ledger/ledger-utxo-flow/src/main/kotlin/net/corda/ledger/utxo/impl/token/selection/factories/TokenUpdateParameters.kt | corda | 346,070,752 | false | {"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.ledger.utxo.impl.token.selection.factories
import net.corda.v5.ledger.utxo.token.selection.ClaimedToken
// HACK: This class has been added for testing will be removed by CORE-5722 (ledger integration)
data class TokenUpdateParameters(
val newTokens: List<ClaimedToken>,
val consumedTokens: List<ClaimedToken>
)
| 14 | Kotlin | 27 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 339 | corda-runtime-os | Apache License 2.0 |
apps/android/app/src/androidTest/java/express/copter/cleverrc/ExampleInstrumentedTest.kt | CopterExpress | 76,990,241 | false | {"C++": 143020, "Python": 123476, "JavaScript": 104083, "Shell": 33075, "CMake": 23171, "HTML": 22511, "CSS": 7125, "Swift": 5299, "Kotlin": 3710, "C": 501, "Ruby": 316} | package express.copter.cleverrc
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("express.copter.cleverrc", appContext.packageName)
}
}
| 16 | C++ | 262 | 402 | 687041d571207bae6a36c268d43a65d73331ed9a | 648 | clover | MIT License |
client/src/commonTest/kotlin/serialize/analytics/TestABTestStatus.kt | algolia | 153,273,215 | false | null | package serialize.analytics
import com.algolia.search.model.analytics.ABTestStatus
import com.algolia.search.serialize.KeyActive
import com.algolia.search.serialize.KeyExpired
import com.algolia.search.serialize.KeyFailed
import com.algolia.search.serialize.KeyStopped
import kotlinx.serialization.json.JsonPrimitive
import serialize.TestSerializer
internal class TestABTestStatus : TestSerializer<ABTestStatus>(ABTestStatus) {
override val items = listOf(
ABTestStatus.Active to JsonPrimitive(KeyActive),
ABTestStatus.Stopped to JsonPrimitive(KeyStopped),
ABTestStatus.Expired to JsonPrimitive(KeyExpired),
ABTestStatus.Failed to JsonPrimitive(KeyFailed)
)
}
| 8 | Kotlin | 11 | 43 | 1e538208c9aa109653f334ecd22a8205e294c5c1 | 703 | algoliasearch-client-kotlin | MIT License |
src/test/kotlin/com/igorwojda/integer/power/challenge.kt | melomg | 425,247,471 | true | {"Kotlin": 218207} | package com.igorwojda.integer.power
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
private fun power(base: Int, exponent: Int): Int {
if (exponent == 0) {
return 1
}
var result = 1
repeat(exponent.downTo(1).count()) {
result *= base
}
return result
}
private class Test {
@Test
fun `power 2^1 returns 2`() {
power(2, 1) shouldBeEqualTo 2
}
@Test
fun `power 2^2 returns 2`() {
power(2, 2) shouldBeEqualTo 4
}
@Test
fun `power 2^3 returns 8`() {
power(2, 3) shouldBeEqualTo 8
}
@Test
fun `power 3^4 returns 81`() {
power(3, 4) shouldBeEqualTo 81
}
}
| 0 | Kotlin | 0 | 0 | 00b1103a121639557325b8907b9e9e5a6e5ef156 | 706 | kotlin-coding-challenges | MIT License |
app/src/main/java/com/sam/githubsearch/di/NetworkModule.kt | samir-sayyed | 727,823,513 | false | {"Kotlin": 24356} | package com.sam.githubsearch.di
import com.sam.githubsearch.data.api.GitHubSearchService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
object NetworkModule {
private const val BASE_URL = "https://api.github.com/"
@Singleton
@Provides
fun provideHttpClient(): OkHttpClient{
return OkHttpClient.Builder()
.build()
}
@Singleton
@Provides
fun providesRetrofit(httpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.client(httpClient)
.build()
}
@Singleton
@Provides
fun providesGitHubSearchServiceService(retrofit: Retrofit): GitHubSearchService {
return retrofit.create(GitHubSearchService::class.java)
}
} | 0 | Kotlin | 0 | 0 | a4bfb1afd66efe38539be0b91aedb74fe42f9e8e | 1,087 | Github-Search-App | MIT License |
responses/src/commonMain/kotlin/ru/krindra/vkkt/responses/market/MarketGetCommentsResponse.kt | krindra | 780,080,411 | false | {"Kotlin": 1336107} | package ru.krindra.vkkt.responses.market
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import ru.krindra.vkkt.objects.groups.GroupsGroupFull
import ru.krindra.vkkt.objects.users.UsersUserFull
import ru.krindra.vkkt.objects.wall.WallWallComment
import ru.krindra.vkkt.objects.market.*
/**
* @param count Total number
* @param items
* @param profiles List of users, available only if extended=true exists in query params
* @param groups List of groups, available only if extended=true exists in query params
*/
@Serializable
data class MarketGetCommentsResponse (
@SerialName("count") val count: Int,
@SerialName("items") val items: List<WallWallComment>,
@SerialName("groups") val groups: List<GroupsGroupFull>? = null,
@SerialName("profiles") val profiles: List<UsersUserFull>? = null,
)
| 0 | Kotlin | 0 | 1 | 58407ea02fc9d971f86702f3b822b33df65dd3be | 849 | VKKT | MIT License |
app/src/main/java/by/bsuir/luckymushroom/app/ui/activities/MainActivity.kt | AlexX333BY | 176,341,456 | false | null | package by.bsuir.luckymushroom.app.ui.activities
import android.Manifest
import android.app.Activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.support.design.widget.NavigationView
import android.support.v4.app.ActivityCompat
import android.support.v4.content.FileProvider
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import by.bsuir.luckymushroom.R
import by.bsuir.luckymushroom.app.ui.fragments.*
import by.bsuir.luckymushroom.app.viewmodels.AppViewModel
import by.bsuir.luckymushroom.app.viewmodels.UserViewModel
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.navigation_header.*
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener,
RecognitionFragment.OnClickListener,
LoginFragment.OnClickListener {
companion object {
val REQUEST_TAKE_PHOTO = 1
val REQUEST_GET_IMAGE = 2
val EXTRA_IMAGE = "Image"
val EXTRA_TEXT = "Text"
}
private lateinit var currentPhotoPath: String
private lateinit var recognitionFragment: RecognitionFragment
private lateinit var infoFragment: InfoFragment
private lateinit var model: AppViewModel
private lateinit var userModel: UserViewModel
var locationPermission: Boolean = false
private val isOldAndroidVersion: Boolean =
Build.VERSION.SDK_INT <= Build.VERSION_CODES.M
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
ActivityCompat.requestPermissions(
this, arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE
), 1
)
val logoutItem = navigationView.menu.findItem(R.id.nav_logout)
val historyItem = navigationView.menu.findItem(R.id.nav_history)
val loginItem = navigationView.menu.findItem(R.id.nav_login)
model = ViewModelProviders.of(this).get(AppViewModel::class.java)
userModel = ViewModelProviders.of(this).get(UserViewModel::class.java)
model.getIsLoading().observe(this, Observer {
it?.let {
if (it) {
fragment_content.visibility = View.INVISIBLE
progressBar.visibility = View.VISIBLE
} else {
progressBar.visibility = ProgressBar.INVISIBLE
fragment_content.visibility = View.VISIBLE
}
}
})
model.getIsRecognition().observe(this, Observer {
it?.let {
if (it)
model.launchRecognize()
}
})
model.getRecognitionResult().observe(this, Observer {
val recognizeResultText = it?.className ?: "not-recognized"
openRecognitionResultFragment(recognizeResultText)
})
userModel.getUser().observe(this, Observer {
if (it == null) {
logoutItem.isVisible = false
historyItem.isVisible = false
loginItem.isVisible = true
openLoginFragment()
} else {
logoutItem.isVisible = true
historyItem.isVisible = true
loginItem.isVisible = false
runMain()
}
textViewUserName.text =
it?.userCredentials?.userMail ?: "Mushroomer"
})
recognitionFragment = RecognitionFragment()
infoFragment = InfoFragment()
supportFragmentManager.beginTransaction()
.add(
R.id.fragment_content,
LoginFragment()
).commit()
initToggle()
findViewById<NavigationView>(
R.id.navigationView
).also { it.setNavigationItemSelectedListener(this) }
openLoginFragment()
}
override fun runMain() {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_content, recognitionFragment)
.commit()
drawerLayoutMain.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
model.launchRecognizerInit(assets)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
1 -> {
locationPermission =
(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
}
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_info -> {
val frag = supportFragmentManager.findFragmentById(
R.id.fragment_content
)
if (!(frag != null && frag is InfoFragment && frag.isVisible)) {
supportFragmentManager.beginTransaction().replace(
R.id.fragment_content, infoFragment
).addToBackStack(null).commit()
}
}
R.id.nav_recognition -> {
val frag = supportFragmentManager.findFragmentById(
R.id.fragment_content
)
if (!(frag != null && frag is RecognitionFragment && frag.isVisible)) {
supportFragmentManager.beginTransaction().replace(
R.id.fragment_content, recognitionFragment
).addToBackStack(null).commit()
}
}
R.id.nav_history -> {
val frag = supportFragmentManager.findFragmentById(
R.id.fragment_content
)
if (!(frag != null && frag is HistoryFragment && frag.isVisible)) {
supportFragmentManager.beginTransaction().replace(
R.id.fragment_content, HistoryFragment()
).addToBackStack(null).commit()
}
}
R.id.nav_logout -> {
userModel.launchLogOut()
}
R.id.nav_login -> {
openLoginFragment()
}
}
findViewById<DrawerLayout>(R.id.drawerLayoutMain).apply {
closeDrawer(GravityCompat.START)
}
return true
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
model.setIsRecognition(true)
} else if (requestCode == REQUEST_GET_IMAGE && resultCode == Activity.RESULT_OK) {
data?.let {
model.photoURI = getPath(it.data as Uri)!!
}
model.setIsRecognition(true)
}
}
private fun openLoginFragment() {
drawerLayoutMain.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
userModel.clearAuthError()
supportFragmentManager.beginTransaction()
.replace(
R.id.fragment_content,
LoginFragment()
).commit()
}
private fun getPath(uri: Uri): Uri? {
val projection: Array<String> = arrayOf(MediaStore.Images.Media.DATA)
val cursor: Cursor = if (!isOldAndroidVersion) {
val fileId = DocumentsContract.getDocumentId(uri)
val id = fileId.split(":")[1]
val selector = MediaStore.Images.Media._ID + "=?"
contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
selector, arrayOf(id), null
)
} else {
contentResolver.query(uri, projection, null, null, null)
}
var rez: Uri? = null
if (cursor.moveToFirst()) {
val columnIndex: Int =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
val filePath: String = cursor.getString(columnIndex)
rez = Uri.parse(filePath)
}
cursor.close()
return rez
}
@Throws(IOException::class)
private fun createImageFile(): File {
val timeStamp: String =
SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File =
getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_",
".jpg",
storageDir
).apply {
currentPhotoPath = absolutePath
}
}
private fun initToggle() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
val toggle = ActionBarDrawerToggle(
this, drawerLayoutMain, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
drawerLayoutMain.addDrawerListener(toggle)
toggle.syncState()
}
private fun openRecognitionResultFragment(recognizeResultText: String) {
val recognitionResultFragment =
RecognitionResultFragment()
Bundle().also {
it.putParcelable(
EXTRA_IMAGE, model.photoURI
)
it.putString(
EXTRA_TEXT, recognizeResultText
)
recognitionResultFragment.arguments = it
}
supportFragmentManager.beginTransaction()
.replace(
R.id.fragment_content, recognitionResultFragment
).addToBackStack(null).commit()
}
override fun pickUpFromGallery() {
Intent(Intent.ACTION_GET_CONTENT).also { getPictureIntent ->
getPictureIntent.addCategory(Intent.CATEGORY_OPENABLE)
getPictureIntent.type = "image/*"
startActivityForResult(
Intent.createChooser(getPictureIntent, "Select Picture"),
REQUEST_GET_IMAGE
)
}
}
override fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
takePictureIntent.addFlags(FLAG_GRANT_WRITE_URI_PERMISSION)
takePictureIntent.resolveActivity(packageManager)?.also {
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
val toast = Toast.makeText(
this,
"Уважаемый, ошибка ${ex.message}",
Toast.LENGTH_LONG
)
toast.show()
null
}
photoFile?.also {
model.photoURI =
if (!isOldAndroidVersion) FileProvider.getUriForFile(
this,
"by.bsuir.luckymushroom.fileprovider",
it
)
else Uri.fromFile(it)
takePictureIntent.putExtra(
MediaStore.EXTRA_OUTPUT,
model.photoURI
)
startActivityForResult(
takePictureIntent,
REQUEST_TAKE_PHOTO
)
}
}
}
}
}
| 3 | Kotlin | 1 | 1 | a3e4e53b9251ab23c61ad5a7f5a4a40a7c91eef8 | 12,284 | lucky-mushroom-android | MIT License |
app/src/test/java/com/nizarfadlan/storyu/presentation/ui/auth/AuthViewModelTest.kt | nizarfadlan | 797,397,406 | false | {"Kotlin": 148878} | package com.nizarfadlan.storyu.presentation.ui.auth
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import com.nizarfadlan.storyu.data.repository.AuthRepositoryImpl
import com.nizarfadlan.storyu.domain.common.ResultState
import com.nizarfadlan.storyu.utils.DummyData
import com.nizarfadlan.storyu.utils.MainDispatcherRule
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class AuthViewModelTest {
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
@get:Rule
var mainDispatcherRules = MainDispatcherRule()
@Mock
private lateinit var authRepositoryImpl: AuthRepositoryImpl
private lateinit var authViewModel: AuthViewModel
private val dummyEmail = DummyData.emailDummy()
private val dummyPassword = DummyData.passwordDummy()
private val dummyToken = DummyData.tokenDummy()
@Before
fun setUp() {
authRepositoryImpl = mock(authRepositoryImpl::class.java)
authViewModel = AuthViewModel(authRepositoryImpl)
}
@Test
fun `Sign in success and get result success`(): Unit = runTest {
val expectedResult = ResultState.Success(dummyToken)
val flowResult = flowOf(expectedResult)
`when`(authRepositoryImpl.signIn(dummyEmail, dummyPassword)).thenReturn(flowResult)
val observer = Observer<ResultState<String>> { resultState ->
assertNotNull(resultState)
assertTrue(resultState is ResultState.Success)
assertEquals(expectedResult, resultState)
assertEquals(dummyToken, (resultState as ResultState.Success).data)
}
val liveData = authViewModel.signIn(dummyEmail, dummyPassword)
try {
liveData.observeForever(observer)
verify(authRepositoryImpl).signIn(dummyEmail, dummyPassword)
} finally {
liveData.removeObserver(observer)
}
}
@Test
fun `Sign in success and get error result with Exception`(): Unit = runTest {
val expectedResult = ResultState.Error("Sign in failed")
val flowResult = flowOf(expectedResult)
`when`(authRepositoryImpl.signIn(dummyEmail, dummyPassword)).thenReturn(flowResult)
val observer = Observer<ResultState<String>> { resultState ->
assertNotNull(resultState)
assertTrue(resultState is ResultState.Error)
assertEquals(expectedResult, resultState)
}
val liveData = authViewModel.signIn(dummyEmail, dummyPassword)
try {
liveData.observeForever(observer)
verify(authRepositoryImpl).signIn(dummyEmail, dummyPassword)
} finally {
liveData.removeObserver(observer)
}
}
} | 0 | Kotlin | 0 | 0 | 1b92fd28aae3b8bb13e70854eb889f5a2269ae69 | 3,265 | StoryU | MIT License |
domain/useCases/src/main/java/com/example/usecases/ManageRecommendationNewsUseCase.kt | Abdallahx3x | 672,252,032 | false | {"Kotlin": 179589} | package com.example.usecases
import javax.inject.Inject
class ManageRecommendationNewsUseCase @Inject constructor(
private val newsHiveRepository: NewsHiveRepository
) {
suspend fun getRecommendationNews() = newsHiveRepository
.getLatestNews(
sort = SORT,
language = LANGUAGE
).drop(5).take(4).distinctBy { it.news.title }
suspend fun getAllRecommendationNews() = newsHiveRepository.getAllLatestNews(
sort = SORT,
language =LANGUAGE
)
companion object {
const val SORT = "published_desc"
const val LANGUAGE = "en"
}
} | 0 | Kotlin | 1 | 7 | 6a8e3157efabaa72fbd2419e03726f83e6b6107c | 617 | NewsHive | MIT License |
app/src/main/java/com/dteti/animapp/NotifyEightReceiver.kt | gladhtput | 414,054,833 | false | {"Kotlin": 47461} | package com.dteti.animapp
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.TaskStackBuilder
import com.dteti.animapp.dto.AnimeDetails
import com.dteti.animapp.usecases.AnimeUseCases
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.random.Random
class NotifyEightReceiver : BroadcastReceiver() {
@EntryPoint
@InstallIn(SingletonComponent::class)
interface BroadcastReceiverEntryPoint {
fun animeUseCases(): AnimeUseCases
}
override fun onReceive(context: Context?, intent: Intent?) {
val entryPoint = EntryPointAccessors.fromApplication(context, BroadcastReceiverEntryPoint::class.java)
Log.d("BCR", "fired")
GlobalScope.launch {
val useCases = entryPoint.animeUseCases()
var anime : AnimeDetails? = null
do {
anime = useCases.readAnimeById(Random.nextInt(0, 10000))
if (anime != null && (anime.ageRating.contains("R+") || anime.ageRating.contains("Rx"))) {
Log.d("BCR", "Unsafe for work anime found. retrying...")
anime = null
}
} while(anime == null)
val openDetailsIntent = Intent(context, DetailActivity::class.java).apply {
putExtra("animeId", anime.id.toString())
}
if (context != null) {
val pendingIntent : PendingIntent? = TaskStackBuilder.create(context).run {
addNextIntentWithParentStack(openDetailsIntent)
getPendingIntent(42, PendingIntent.FLAG_UPDATE_CURRENT)
}
/*val i = Intent(context,MainActivity::class.java)
intent!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val pendingIntent = PendingIntent.getActivity(context, 0, openDetailsIntent, 0)*/
val builder = NotificationCompat.Builder(context!!, "NotifyEightAM")
.setSmallIcon(R.drawable.ic_animapp)
.setContentTitle("Random Anime of the Day")
.setContentText("Tap here to receive your random anime of the day!")
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(123, builder.build())
Log.d("BCR", anime?.title ?: "none")
}
}
}
} | 0 | Kotlin | 1 | 1 | c9cebe8a93902a3ddf834bcedd193f7661155bb0 | 3,113 | papb-team6 | MIT License |
src/main/kotlin/org/knowledge4retail/rfid2gtin/Rfid2gtinApplication.kt | knowledge4retail | 577,469,863 | false | {"Kotlin": 7940, "Dockerfile": 620} | package org.knowledge4retail.rfid2gtin
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class Rfid2gtinApplication
fun main(args: Array<String>) {
runApplication<Rfid2gtinApplication>(*args)
{
}
}
| 0 | Kotlin | 0 | 0 | 8bf0b03f51cb18d92cfb2fef8b8f3bf6e0aec36d | 293 | k4r-rfid2gtin | MIT License |
orders/src/test/kotlin/com/lastminute/cdc/orders/OrdersApplicationTests.kt | gdipaolantonio | 192,891,873 | false | null | package com.lastminute.cdc.orders
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class OrdersApplicationTests {
@Test
fun contextLoads() {
}
}
| 4 | Kotlin | 0 | 1 | 8ca9d7a980d8501b24707ae11e9493e1f8ea0e77 | 323 | cdc-with-pact | Apache License 2.0 |
app/src/main/java/com/ape/apps/sample/baypilot/data/sharedprefs/SharedPreferencesManager.kt | google | 502,861,545 | false | null | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ape.apps.sample.baypilot.data.sharedprefs
import android.content.Context
import android.content.SharedPreferences
import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo
import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanType
class SharedPreferencesManager(context: Context) {
companion object {
private const val TAG = "BayPilotSharedPreferencesManager"
private const val SHARED_PREFS = "shared_prefs"
private const val KEY_IS_FIRST_RUN = "is_first_run"
private const val KEY_IMEI = "imei"
private const val KEY_CREDIT_PLAN_SAVED = "credit_plan_saved"
private const val KEY_VALID_CREDIT_PLAN = "valid_credit_plan"
private const val KEY_DEVICE_RELEASED = "device_released"
// Used to observe changes; creditPlanSaveId = lastCreditPlanSaveId + 1
const val KEY_CREDIT_PLAN_SAVE_ID = "credit_plan_save_id"
private const val KEY_TOTAL_AMOUNT = "total_amount"
private const val KEY_PAID_AMOUNT = "paid_amount"
private const val KEY_DUE_DATE = "due_date"
private const val KEY_NEXT_DUE_AMOUNT = "next_due_amount"
private const val KEY_PLAN_TYPE = "plan_type"
}
var sharedPreferences: SharedPreferences = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE)
fun isFirstRun(): Boolean = sharedPreferences.getBoolean(KEY_IS_FIRST_RUN, true)
fun writeFirstRun(firstRun: Boolean) = with(sharedPreferences.edit()) {
putBoolean(KEY_IS_FIRST_RUN, firstRun)
commit()
}
fun readIMEI(): String = sharedPreferences.getString(KEY_IMEI, "") ?: ""
fun writeIMEI(imei: String) = with(sharedPreferences.edit()) {
putString(KEY_IMEI, imei)
commit()
}
fun isCreditPlanSaved(): Boolean = sharedPreferences.getBoolean(KEY_CREDIT_PLAN_SAVED, false)
fun isValidCreditPlan(): Boolean = sharedPreferences.getBoolean(KEY_VALID_CREDIT_PLAN, false)
fun isDeviceReleased(): Boolean = sharedPreferences.getBoolean(KEY_DEVICE_RELEASED, false)
fun markDeviceReleased() = with(sharedPreferences.edit()) {
incrementCreditPlanSaveId()
putBoolean(KEY_DEVICE_RELEASED, true)
commit()
}
fun setCreditPlanInvalid() = with(sharedPreferences.edit()) {
incrementCreditPlanSaveId()
putBoolean(KEY_CREDIT_PLAN_SAVED, true)
putBoolean(KEY_VALID_CREDIT_PLAN, false)
commit()
}
fun readCreditPlan(): CreditPlanInfo? {
if (sharedPreferences.getBoolean(KEY_CREDIT_PLAN_SAVED, false).not()) return null
if (sharedPreferences.getBoolean(KEY_VALID_CREDIT_PLAN, false).not()) return null
return CreditPlanInfo(
sharedPreferences.getInt(KEY_TOTAL_AMOUNT, 0),
sharedPreferences.getInt(KEY_PAID_AMOUNT, 0),
sharedPreferences.getString(KEY_DUE_DATE, ""),
sharedPreferences.getInt(KEY_NEXT_DUE_AMOUNT, 0),
CreditPlanType.toCreditPlanType(sharedPreferences.getString(KEY_PLAN_TYPE, ""))
)
}
fun writeCreditPlan(creditPlanInfo: CreditPlanInfo) = with(sharedPreferences.edit()) {
incrementCreditPlanSaveId()
putBoolean(KEY_CREDIT_PLAN_SAVED, true)
putBoolean(KEY_VALID_CREDIT_PLAN, true)
putInt(KEY_TOTAL_AMOUNT, creditPlanInfo.totalAmount ?: 0)
putInt(KEY_PAID_AMOUNT, creditPlanInfo.totalPaidAmount ?: 0)
putString(KEY_DUE_DATE, creditPlanInfo.dueDate ?: "")
putInt(KEY_NEXT_DUE_AMOUNT, creditPlanInfo.nextDueAmount ?: 0)
putString(KEY_PLAN_TYPE, CreditPlanType.toString(creditPlanInfo.planType) ?: "")
commit()
}
// Used to observe changes; creditPlanSaveId = lastCreditPlanSaveId + 1
private fun SharedPreferences.Editor.incrementCreditPlanSaveId() {
putInt(KEY_CREDIT_PLAN_SAVE_ID, sharedPreferences.getInt(KEY_CREDIT_PLAN_SAVE_ID, 0) + 1)
}
} | 0 | Kotlin | 0 | 9 | 30b9c6886bd08b98e0468511233057e8750b7caa | 4,279 | kiosk-app-reference-implementation | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.